ngram listlengths 0 67.8k |
|---|
[
"python3 # -*- encoding=utf-8 -*- # description: # author:jack # create_time: 2018/7/2 from",
"# create_time: 2018/7/2 from dueros.directive.BaseDirective import BaseDirective class Stop(BaseDirective): \"\"\" VideoPlayer.Stop指令 详见文档:https://dueros.baidu.com/didp/doc/dueros-bot-platform/dbp-custom/videoplayer_markdown#VideoPlayer.Stop%E6%8C%87%E4%BB%A4 \"\"\"",
"-*- # description: # author:jack # create_time: 2018/7/2 from dueros.directive.BaseDirective import BaseDirective class",
"create_time: 2018/7/2 from dueros.directive.BaseDirective import BaseDirective class Stop(BaseDirective): \"\"\" VideoPlayer.Stop指令 详见文档:https://dueros.baidu.com/didp/doc/dueros-bot-platform/dbp-custom/videoplayer_markdown#VideoPlayer.Stop%E6%8C%87%E4%BB%A4 \"\"\" def",
"description: # author:jack # create_time: 2018/7/2 from dueros.directive.BaseDirective import BaseDirective class Stop(BaseDirective): \"\"\"",
"-*- encoding=utf-8 -*- # description: # author:jack # create_time: 2018/7/2 from dueros.directive.BaseDirective import",
"2018/7/2 from dueros.directive.BaseDirective import BaseDirective class Stop(BaseDirective): \"\"\" VideoPlayer.Stop指令 详见文档:https://dueros.baidu.com/didp/doc/dueros-bot-platform/dbp-custom/videoplayer_markdown#VideoPlayer.Stop%E6%8C%87%E4%BB%A4 \"\"\" def __init__(self):",
"dueros.directive.BaseDirective import BaseDirective class Stop(BaseDirective): \"\"\" VideoPlayer.Stop指令 详见文档:https://dueros.baidu.com/didp/doc/dueros-bot-platform/dbp-custom/videoplayer_markdown#VideoPlayer.Stop%E6%8C%87%E4%BB%A4 \"\"\" def __init__(self): super(Stop, self).__init__('VideoPlayer.Stop')",
"# author:jack # create_time: 2018/7/2 from dueros.directive.BaseDirective import BaseDirective class Stop(BaseDirective): \"\"\" VideoPlayer.Stop指令",
"#!/usr/bin/env python3 # -*- encoding=utf-8 -*- # description: # author:jack # create_time: 2018/7/2",
"author:jack # create_time: 2018/7/2 from dueros.directive.BaseDirective import BaseDirective class Stop(BaseDirective): \"\"\" VideoPlayer.Stop指令 详见文档:https://dueros.baidu.com/didp/doc/dueros-bot-platform/dbp-custom/videoplayer_markdown#VideoPlayer.Stop%E6%8C%87%E4%BB%A4",
"encoding=utf-8 -*- # description: # author:jack # create_time: 2018/7/2 from dueros.directive.BaseDirective import BaseDirective",
"# description: # author:jack # create_time: 2018/7/2 from dueros.directive.BaseDirective import BaseDirective class Stop(BaseDirective):",
"from dueros.directive.BaseDirective import BaseDirective class Stop(BaseDirective): \"\"\" VideoPlayer.Stop指令 详见文档:https://dueros.baidu.com/didp/doc/dueros-bot-platform/dbp-custom/videoplayer_markdown#VideoPlayer.Stop%E6%8C%87%E4%BB%A4 \"\"\" def __init__(self): super(Stop,",
"# -*- encoding=utf-8 -*- # description: # author:jack # create_time: 2018/7/2 from dueros.directive.BaseDirective"
] |
[
"# simple addition program a = 20 b = 20 print(\"The sum is",
"addition program a = 20 b = 20 print(\"The sum is \", a+b)",
"<reponame>Suvradippaul/actions<gh_stars>0 # simple addition program a = 20 b = 20 print(\"The sum",
"simple addition program a = 20 b = 20 print(\"The sum is \","
] |
[
"-*- coding: utf-8 -*- \"\"\"Asynchronous Python client for the Meppel Afvalkalender API.\"\"\" from",
"utf-8 -*- \"\"\"Asynchronous Python client for the Meppel Afvalkalender API.\"\"\" from .const import",
"WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, ) from .meppel_afvalkalender import ( # noqa MeppelAfvalkalender, MeppelAfvalkalenderAddressError,",
"( # noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, ) from .meppel_afvalkalender import ( #",
".const import ( # noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, ) from .meppel_afvalkalender import",
"client for the Meppel Afvalkalender API.\"\"\" from .const import ( # noqa WASTE_TYPE_NON_RECYCLABLE,",
"coding: utf-8 -*- \"\"\"Asynchronous Python client for the Meppel Afvalkalender API.\"\"\" from .const",
"API.\"\"\" from .const import ( # noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, ) from",
"# -*- coding: utf-8 -*- \"\"\"Asynchronous Python client for the Meppel Afvalkalender API.\"\"\"",
"from .const import ( # noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, ) from .meppel_afvalkalender",
"Python client for the Meppel Afvalkalender API.\"\"\" from .const import ( # noqa",
"the Meppel Afvalkalender API.\"\"\" from .const import ( # noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER,",
"Meppel Afvalkalender API.\"\"\" from .const import ( # noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC,",
"WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, ) from .meppel_afvalkalender import ( # noqa MeppelAfvalkalender, MeppelAfvalkalenderAddressError, MeppelAfvalkalenderConnectionError, MeppelAfvalkalenderError,",
"Afvalkalender API.\"\"\" from .const import ( # noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, )",
"noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, ) from .meppel_afvalkalender import ( # noqa MeppelAfvalkalender,",
"\"\"\"Asynchronous Python client for the Meppel Afvalkalender API.\"\"\" from .const import ( #",
"# noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, ) from .meppel_afvalkalender import ( # noqa",
"-*- \"\"\"Asynchronous Python client for the Meppel Afvalkalender API.\"\"\" from .const import (",
"WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, ) from .meppel_afvalkalender import ( # noqa MeppelAfvalkalender, MeppelAfvalkalenderAddressError, MeppelAfvalkalenderConnectionError,",
"for the Meppel Afvalkalender API.\"\"\" from .const import ( # noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC,",
"WASTE_TYPE_PLASTIC, ) from .meppel_afvalkalender import ( # noqa MeppelAfvalkalender, MeppelAfvalkalenderAddressError, MeppelAfvalkalenderConnectionError, MeppelAfvalkalenderError, )",
"import ( # noqa WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, ) from .meppel_afvalkalender import ("
] |
[
"exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return True return False",
"!= codeIndex: #代码里面找到plist return True else: exportJsonIndex = checkInDataList(plistFileName, exportJsonDataList, False) # plist",
"= checkInDataList(picName, fntDataList, False) if -1 != fntIndex: # fnt => code fntName",
"return True return False #=============================================================== # @brief 查找没用的图片 # @params picPath 要查找的图片路径 #",
"import shutil global g_cnt g_cnt = 0 def getCnt(): global g_cnt g_cnt =",
"0 def getCnt(): global g_cnt g_cnt = g_cnt + 1 return g_cnt #===================================",
"在代码里面处理 #========================== def handleInCode(picIndex, picNameList, codeDataList): picName = picNameList[picIndex][0] index = checkInDataList(picName, codeDataList,",
"-1 != csdIndex: fileName = csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(fileName[:-1]+\"b\",",
"\"/\"==preCh or \">\"==preCh: return index return -1 #========================== # @brief 处理没有用的文件 #========================== def",
"#========================== def handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): picName = picNameList[picIndex][0] #pic => fnt",
"picNameList.append([fileName, prePath]) return picNameList # print(\"read PicNameList ok\") #=============================================== # @brief 读取文件目录下某个后缀的数据到列表里面 #===============================================",
"== fielSuffixName: f = open(prePath+\"/\"+fileName, \"rb\") data = f.read() # saveToList.append([data, fileName, prePath+\"/\"+fileName])",
"# plist => code if -1 != codeIndex: #代码里面找到plist return True else: exportJsonIndex",
"pass # plist, exportJson elif handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): pass # fnt",
"def handleNotFoundFile(filePathList): for fileInfo in filePathList: fileName = fileInfo[0] filePath = fileInfo[1] if",
"读取所有图片到列表里面 #=================================== def readPicNameList(picPath): picNameList = [] for prePath, folderList, fileNameList in os.walk(picPath):",
"=> code # (4) # 1. png => fnt, fnt => code #",
"# @brief 查找没用的图片 # @params picPath 要查找的图片路径 # codePath 要查找的代码路径 # csdPath 要查找的csd路径(只有csd才能用来查询,csb不行)",
"in os.walk(filePath): for fileName in fileNameList: # fielSuffixName = fileName[-3:] fielSuffixName = fileName[-n:]",
"fntIndex = checkInDataList(picName, fntDataList, False) if -1 != fntIndex: # fnt => code",
"#=================================== def checkInDataList(keyword, dataList, show):#, n): # 各种情况如下: # csd: <FileData Type=\"Normal\" Path=\"Res/abc.png\"",
"(1)\" (2)' (3)/ (4)> for index in range(0, len(dataList)): fileInfo = dataList[index] findIndex",
"(3)/ (4)> for index in range(0, len(dataList)): fileInfo = dataList[index] findIndex = fileInfo[0].find(keyword)",
"= checkInDataList(picName, csdDataList, False) if -1 != csdIndex: fileName = csdDataList[csdIndex][1] # csd",
"#========================== # @brief 在fnt里面处理 #========================== def handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): picName =",
"handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): picName = picNameList[picIndex][0] #pic => fnt fntIndex =",
"for picIndex in range(0, len(picNameList)): # code if handleInCode(picIndex, picNameList, codeDataList): pass #",
"查找没用的图片 # @params picPath 要查找的图片路径 # codePath 要查找的代码路径 # csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) # plist",
"handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): pass # fnt elif handleInFnt(picIndex, picNameList, fntDataList, csdDataList,",
"if -1 != plistIndex: plistFileName = plistDataList[plistIndex][1] codeIndex = checkInDataList(plistFileName, codeDataList, False) #",
"return False #========================== # @brief 在plist里面处理 #========================== def handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList):",
"# csd => code codeIndex = checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex:",
"checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(), picName, csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([ (picName,",
"plist => code # 2. png => plist, plist => ExportJson, ExportJson =>",
"(csdFileName, csdDataList[csdIndex][2])]) return True return False #=============================================================== # @brief 查找没用的图片 # @params picPath",
"findIndex = fileInfo[0].find(keyword) if -1 != findIndex: preCh = fileInfo[0][findIndex-1] if '\"'==preCh or",
"checkInDataList(picName, fntDataList, False) if -1 != fntIndex: # fnt => code fntName =",
"<gh_stars>0 # -*- coding:utf-8 -*- #===================================== # 通过分析所有代码,找出没有用到的图片 # 没有用的图片资源主要有如下3种情况: # (1)png =>",
"getCnt(): global g_cnt g_cnt = g_cnt + 1 return g_cnt #=================================== # @brief",
"False) if -1 != plistIndex: plistFileName = plistDataList[plistIndex][1] codeIndex = checkInDataList(plistFileName, codeDataList, False)",
"#fnt => csd csdIndex = checkInDataList(fntName, csdDataList, False) if -1 != csdIndex: csdFileName",
"picNameList, codeDataList): pass # csd elif handleInCsd(picIndex, picNameList, csdDataList, codeDataList): pass # plist,",
"os import shutil global g_cnt g_cnt = 0 def getCnt(): global g_cnt g_cnt",
"handleInCsd(picIndex, picNameList, csdDataList, codeDataList): pass # plist, exportJson elif handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList,",
"code: [\"abc\"] = \"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\") # plist: <key>abc.png</key> # # 规律如下: #",
"handleInCsd(picIndex, picNameList, csdDataList,codeDataList): picName = picNameList[picIndex][0] #pic => csd csdIndex = checkInDataList(picName, csdDataList,",
"-1 != exportJsonIndex: exportJsonFileName = exportJsonDataList[exportJsonIndex][1] codeIndex = checkInDataList(exportJsonFileName, codeDataList, False) # exportJston",
"= readFileDataToList(fntPath, \"fnt\") exportJsonDataList = readFileDataToList(fntPath, \"ExportJson\") for picIndex in range(0, len(picNameList)): #",
"csd => code #===================================== import os import shutil global g_cnt g_cnt = 0",
"checkInDataList(plistFileName, exportJsonDataList, False) # plist = > exportJston if -1 != exportJsonIndex: exportJsonFileName",
"len(picNameList)): # code if handleInCode(picIndex, picNameList, codeDataList): pass # csd elif handleInCsd(picIndex, picNameList,",
"fnt=>csd, csd => code #===================================== import os import shutil global g_cnt g_cnt =",
"filePath = fileInfo[1] if not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #========================== # @brief 在代码里面处理",
"plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return True return False #========================== # @brief 在fnt里面处理 #========================== def",
"g_cnt = g_cnt + 1 return g_cnt #=================================== # @brief 读取所有图片到列表里面 #=================================== def",
"= checkInDataList(plistFileName, exportJsonDataList, False) # plist = > exportJston if -1 != exportJsonIndex:",
"False) if -1 != fntIndex: # fnt => code fntName = fntDataList[fntIndex][1] codeIndex",
"=> code codeIndex = checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(), picName,",
"picIndex in range(0, len(picNameList)): # code if handleInCode(picIndex, picNameList, codeDataList): pass # csd",
"picName = picNameList[picIndex][0] #pic => plist plistIndex = checkInDataList(picName, plistDataList, False) if -1",
"codeIndex: #代码里面找到plist return True else: exportJsonIndex = checkInDataList(plistFileName, exportJsonDataList, False) # plist =",
"handleNotFoundFile(filePathList): for fileInfo in filePathList: fileName = fileInfo[0] filePath = fileInfo[1] if not",
"= checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(), picName, csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([",
"codeDataList): pass # plist, exportJson elif handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): pass #",
"== codeIndex: print(getCnt(), picName, plistFileName, exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName,",
"shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #========================== # @brief 在代码里面处理 #========================== def handleInCode(picIndex, picNameList, codeDataList): picName =",
"csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(fileName[:-1]+\"b\", codeDataList, False) if -1 ==",
"= checkInDataList(picName, codeDataList, False) return -1!=index #========================== # @brief 在csd里面处理 #========================== def handleInCsd(picIndex,",
"\"lua\") csdDataList = readFileDataToList(csdPath, \"csd\") plistDataList = readFileDataToList(plistPath,\"plist\") fntDataList = readFileDataToList(fntPath, \"fnt\") exportJsonDataList",
"picNameList[picIndex][0] #pic => csd csdIndex = checkInDataList(picName, csdDataList, False) if -1 != csdIndex:",
"or \"jpg\" == suffixName: picNameList.append([fileName, prePath]) return picNameList # print(\"read PicNameList ok\") #===============================================",
"pass # fnt elif handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): pass if \"__main__\" ==",
"fileName in fileNameList: suffixName = fileName[-3:] if \"png\" == suffixName or \"jpg\" ==",
"@brief 在代码里面处理 #========================== def handleInCode(picIndex, picNameList, codeDataList): picName = picNameList[picIndex][0] index = checkInDataList(picName,",
"@brief 查找没用的图片 # @params picPath 要查找的图片路径 # codePath 要查找的代码路径 # csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) #",
"#========================== # @brief 在plist里面处理 #========================== def handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): picName =",
"in fileNameList: suffixName = fileName[-3:] if \"png\" == suffixName or \"jpg\" == suffixName:",
"return -1 #========================== # @brief 处理没有用的文件 #========================== def handleNotFoundFile(filePathList): for fileInfo in filePathList:",
"#========================== # @brief 在csd里面处理 #========================== def handleInCsd(picIndex, picNameList, csdDataList,codeDataList): picName = picNameList[picIndex][0] #pic",
"if -1 != findIndex: preCh = fileInfo[0][findIndex-1] if '\"'==preCh or \"'\"==preCh or \"/\"==preCh",
"-1 != codeIndex: return True else: #fnt => csd csdIndex = checkInDataList(fntName, csdDataList,",
"= checkInDataList(exportJsonFileName, codeDataList, False) # exportJston => code if -1 == codeIndex: print(getCnt(),",
"for fileName in fileNameList: # fielSuffixName = fileName[-3:] fielSuffixName = fileName[-n:] if suffixName",
"plistIndex = checkInDataList(picName, plistDataList, False) if -1 != plistIndex: plistFileName = plistDataList[plistIndex][1] codeIndex",
"print(getCnt(), picName, plistFileName, exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return",
"return False #========================== # @brief 在fnt里面处理 #========================== def handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList):",
"要查找的fnt路径 #=============================================================== def findNotUsePic(picPath, codePath, csdPath, plistPath, fntPath): picNameList = readPicNameList(picPath) codeDataList =",
"csd => code # (3) # 1. png => plist, plist => code",
"index in range(0, len(dataList)): fileInfo = dataList[index] findIndex = fileInfo[0].find(keyword) if -1 !=",
"(plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return True return False #========================== # @brief 在fnt里面处理 #==========================",
"folderList, fileNameList in os.walk(filePath): for fileName in fileNameList: # fielSuffixName = fileName[-3:] fielSuffixName",
"'\"'==preCh or \"'\"==preCh or \"/\"==preCh or \">\"==preCh: return index return -1 #========================== #",
"codeDataList): pass # fnt elif handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): pass if \"__main__\"",
"for prePath, folderList, fileNameList in os.walk(picPath): for fileName in fileNameList: suffixName = fileName[-3:]",
"/> # code: [\"abc\"] = \"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\") # plist: <key>abc.png</key> # #",
"= fileName[-3:] if \"png\" == suffixName or \"jpg\" == suffixName: picNameList.append([fileName, prePath]) return",
"code codeIndex = checkInDataList(fileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(), picName, fileName,",
"!= plistIndex: plistFileName = plistDataList[plistIndex][1] codeIndex = checkInDataList(plistFileName, codeDataList, False) # plist =>",
"exportJson elif handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): pass # fnt elif handleInFnt(picIndex, picNameList,",
"= \"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\") # plist: <key>abc.png</key> # # 规律如下: # (1)\" (2)'",
"for index in range(0, len(dataList)): fileInfo = dataList[index] findIndex = fileInfo[0].find(keyword) if -1",
"@brief 读取文件目录下某个后缀的数据到列表里面 #=============================================== def readFileDataToList(filePath, suffixName): n = len(suffixName) saveToList = [] for",
"fileName[-n:] if suffixName == fielSuffixName: f = open(prePath+\"/\"+fileName, \"rb\") data = f.read() #",
"fielSuffixName = fileName[-3:] fielSuffixName = fileName[-n:] if suffixName == fielSuffixName: f = open(prePath+\"/\"+fileName,",
"plist => code if -1 != codeIndex: #代码里面找到plist return True else: exportJsonIndex =",
"[] for prePath, folderList, fileNameList in os.walk(filePath): for fileName in fileNameList: # fielSuffixName",
"codeIndex = checkInDataList(plistFileName, codeDataList, False) # plist => code if -1 != codeIndex:",
"=> fnt, fnt => code # 2. png => fnt, fnt=>csd, csd =>",
"# (2)png => csd, csd => code # (3) # 1. png =>",
"suffixName): n = len(suffixName) saveToList = [] for prePath, folderList, fileNameList in os.walk(filePath):",
"codeDataList, False) # plist => code if -1 != codeIndex: #代码里面找到plist return True",
"True return False #=============================================================== # @brief 查找没用的图片 # @params picPath 要查找的图片路径 # codePath",
"cc.Sprite:create(\"res/abc/abc.png\") # plist: <key>abc.png</key> # # 规律如下: # (1)\" (2)' (3)/ (4)> for",
"fnt, fnt=>csd, csd => code #===================================== import os import shutil global g_cnt g_cnt",
"show):#, n): # 各种情况如下: # csd: <FileData Type=\"Normal\" Path=\"Res/abc.png\" /> # code: [\"abc\"]",
"def readPicNameList(picPath): picNameList = [] for prePath, folderList, fileNameList in os.walk(picPath): for fileName",
"csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])]) return True return False #=============================================================== #",
"=> code # 2. png => fnt, fnt=>csd, csd => code #===================================== import",
"picNameList, fntDataList, csdDataList, codeDataList): picName = picNameList[picIndex][0] #pic => fnt fntIndex = checkInDataList(picName,",
"exportJsonDataList, False) # plist = > exportJston if -1 != exportJsonIndex: exportJsonFileName =",
"plist plistIndex = checkInDataList(picName, plistDataList, False) if -1 != plistIndex: plistFileName = plistDataList[plistIndex][1]",
"\"needdelete/\"+filePath+\"/\"+fileName) #========================== # @brief 在代码里面处理 #========================== def handleInCode(picIndex, picNameList, codeDataList): picName = picNameList[picIndex][0]",
"picNameList, plistDataList, exportJsonDataList, codeDataList): picName = picNameList[picIndex][0] #pic => plist plistIndex = checkInDataList(picName,",
"plist 要查找的plist路径 # fntPath 要查找的fnt路径 #=============================================================== def findNotUsePic(picPath, codePath, csdPath, plistPath, fntPath): picNameList",
"# fielSuffixName = fileName[-3:] fielSuffixName = fileName[-n:] if suffixName == fielSuffixName: f =",
"os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #========================== # @brief 在代码里面处理 #========================== def handleInCode(picIndex, picNameList, codeDataList):",
"codeDataList): picName = picNameList[picIndex][0] index = checkInDataList(picName, codeDataList, False) return -1!=index #========================== #",
"csdIndex = checkInDataList(fntName, csdDataList, False) if -1 != csdIndex: csdFileName = csdDataList[csdIndex][1] #",
"(picName, picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return True return False #========================== # @brief",
"plistFileName, exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return True return",
"return g_cnt #=================================== # @brief 读取所有图片到列表里面 #=================================== def readPicNameList(picPath): picNameList = [] for",
"code fntName = fntDataList[fntIndex][1] codeIndex = checkInDataList(fntName, codeDataList, False) if -1 != codeIndex:",
"#========================== # @brief 处理没有用的文件 #========================== def handleNotFoundFile(filePathList): for fileInfo in filePathList: fileName =",
"os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #========================== # @brief 在代码里面处理 #========================== def handleInCode(picIndex, picNameList, codeDataList): picName",
"1. png => fnt, fnt => code # 2. png => fnt, fnt=>csd,",
"!= findIndex: preCh = fileInfo[0][findIndex-1] if '\"'==preCh or \"'\"==preCh or \"/\"==preCh or \">\"==preCh:",
"csdDataList[csdIndex][2])]) return True return False #=============================================================== # @brief 查找没用的图片 # @params picPath 要查找的图片路径",
"fileName in fileNameList: # fielSuffixName = fileName[-3:] fielSuffixName = fileName[-n:] if suffixName ==",
"fileInfo in filePathList: fileName = fileInfo[0] filePath = fileInfo[1] if not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath)",
"在plist里面处理 #========================== def handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): picName = picNameList[picIndex][0] #pic =>",
"False) # plist = > exportJston if -1 != exportJsonIndex: exportJsonFileName = exportJsonDataList[exportJsonIndex][1]",
"# 各种情况如下: # csd: <FileData Type=\"Normal\" Path=\"Res/abc.png\" /> # code: [\"abc\"] = \"abc.png\",",
"# fnt elif handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): pass if \"__main__\" == __name__:",
"return picNameList # print(\"read PicNameList ok\") #=============================================== # @brief 读取文件目录下某个后缀的数据到列表里面 #=============================================== def readFileDataToList(filePath,",
"picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])]) return True return False #========================== # @brief 在plist里面处理 #========================== def",
"fntDataList, csdDataList, codeDataList): picName = picNameList[picIndex][0] #pic => fnt fntIndex = checkInDataList(picName, fntDataList,",
"(1)png => code # (2)png => csd, csd => code # (3) #",
"codeIndex = checkInDataList(fntName, codeDataList, False) if -1 != codeIndex: return True else: #fnt",
"# plist 要查找的plist路径 # fntPath 要查找的fnt路径 #=============================================================== def findNotUsePic(picPath, codePath, csdPath, plistPath, fntPath):",
"in fileNameList: # fielSuffixName = fileName[-3:] fielSuffixName = fileName[-n:] if suffixName == fielSuffixName:",
"readFileDataToList(csdPath, \"csd\") plistDataList = readFileDataToList(plistPath,\"plist\") fntDataList = readFileDataToList(fntPath, \"fnt\") exportJsonDataList = readFileDataToList(fntPath, \"ExportJson\")",
"picName, csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])]) return True return False #===============================================================",
"picNameList, csdDataList, codeDataList): pass # plist, exportJson elif handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList):",
"False #========================== # @brief 在fnt里面处理 #========================== def handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): picName",
"def handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): picName = picNameList[picIndex][0] #pic => fnt fntIndex",
"code codeIndex = checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(), picName, csdFileName,",
"# fntPath 要查找的fnt路径 #=============================================================== def findNotUsePic(picPath, codePath, csdPath, plistPath, fntPath): picNameList = readPicNameList(picPath)",
"global g_cnt g_cnt = g_cnt + 1 return g_cnt #=================================== # @brief 读取所有图片到列表里面",
"# code if handleInCode(picIndex, picNameList, codeDataList): pass # csd elif handleInCsd(picIndex, picNameList, csdDataList,",
"= checkInDataList(fntName, codeDataList, False) if -1 != codeIndex: return True else: #fnt =>",
"= checkInDataList(plistFileName, codeDataList, False) # plist => code if -1 != codeIndex: #代码里面找到plist",
"code if -1 == codeIndex: print(getCnt(), picName, plistFileName, exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([ (picName, picNameList[picIndex][1]),",
"=> code #===================================== import os import shutil global g_cnt g_cnt = 0 def",
"codeIndex = checkInDataList(fileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(), picName, fileName, \"pic=>csd\")",
"#=============================================================== # @brief 查找没用的图片 # @params picPath 要查找的图片路径 # codePath 要查找的代码路径 # csdPath",
"= 0 def getCnt(): global g_cnt g_cnt = g_cnt + 1 return g_cnt",
"plist: <key>abc.png</key> # # 规律如下: # (1)\" (2)' (3)/ (4)> for index in",
"codeIndex: return True else: #fnt => csd csdIndex = checkInDataList(fntName, csdDataList, False) if",
"\"csd\") plistDataList = readFileDataToList(plistPath,\"plist\") fntDataList = readFileDataToList(fntPath, \"fnt\") exportJsonDataList = readFileDataToList(fntPath, \"ExportJson\") for",
"fileName[-3:] if \"png\" == suffixName or \"jpg\" == suffixName: picNameList.append([fileName, prePath]) return picNameList",
"def findNotUsePic(picPath, codePath, csdPath, plistPath, fntPath): picNameList = readPicNameList(picPath) codeDataList = readFileDataToList(codePath, \"lua\")",
"#===================================== import os import shutil global g_cnt g_cnt = 0 def getCnt(): global",
"#pic => fnt fntIndex = checkInDataList(picName, fntDataList, False) if -1 != fntIndex: #",
"code #===================================== import os import shutil global g_cnt g_cnt = 0 def getCnt():",
"fileName = csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(fileName[:-1]+\"b\", codeDataList, False) if",
"def checkInDataList(keyword, dataList, show):#, n): # 各种情况如下: # csd: <FileData Type=\"Normal\" Path=\"Res/abc.png\" />",
"> exportJston if -1 != exportJsonIndex: exportJsonFileName = exportJsonDataList[exportJsonIndex][1] codeIndex = checkInDataList(exportJsonFileName, codeDataList,",
"(3) # 1. png => plist, plist => code # 2. png =>",
"(2)png => csd, csd => code # (3) # 1. png => plist,",
"# print(\"read PicNameList ok\") #=============================================== # @brief 读取文件目录下某个后缀的数据到列表里面 #=============================================== def readFileDataToList(filePath, suffixName): n",
"True else: #fnt => csd csdIndex = checkInDataList(fntName, csdDataList, False) if -1 !=",
"picName = picNameList[picIndex][0] index = checkInDataList(picName, codeDataList, False) return -1!=index #========================== # @brief",
"= readPicNameList(picPath) codeDataList = readFileDataToList(codePath, \"lua\") csdDataList = readFileDataToList(csdPath, \"csd\") plistDataList = readFileDataToList(plistPath,\"plist\")",
"#=================================== def readPicNameList(picPath): picNameList = [] for prePath, folderList, fileNameList in os.walk(picPath): for",
"fntName = fntDataList[fntIndex][1] codeIndex = checkInDataList(fntName, codeDataList, False) if -1 != codeIndex: return",
"# 没有用的图片资源主要有如下3种情况: # (1)png => code # (2)png => csd, csd => code",
"n): # 各种情况如下: # csd: <FileData Type=\"Normal\" Path=\"Res/abc.png\" /> # code: [\"abc\"] =",
"csdIndex: csdFileName = csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False)",
"return index return -1 #========================== # @brief 处理没有用的文件 #========================== def handleNotFoundFile(filePathList): for fileInfo",
"checkInDataList(picName, codeDataList, False) return -1!=index #========================== # @brief 在csd里面处理 #========================== def handleInCsd(picIndex, picNameList,",
"处理没有用的文件 #========================== def handleNotFoundFile(filePathList): for fileInfo in filePathList: fileName = fileInfo[0] filePath =",
"-1 != plistIndex: plistFileName = plistDataList[plistIndex][1] codeIndex = checkInDataList(plistFileName, codeDataList, False) # plist",
"readFileDataToList(filePath, suffixName): n = len(suffixName) saveToList = [] for prePath, folderList, fileNameList in",
"通过分析所有代码,找出没有用到的图片 # 没有用的图片资源主要有如下3种情况: # (1)png => code # (2)png => csd, csd =>",
"plistDataList, False) if -1 != plistIndex: plistFileName = plistDataList[plistIndex][1] codeIndex = checkInDataList(plistFileName, codeDataList,",
"!= csdIndex: csdFileName = csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(csdFileName[:-1]+\"b\", codeDataList,",
"= > exportJston if -1 != exportJsonIndex: exportJsonFileName = exportJsonDataList[exportJsonIndex][1] codeIndex = checkInDataList(exportJsonFileName,",
"csd csdIndex = checkInDataList(fntName, csdDataList, False) if -1 != csdIndex: csdFileName = csdDataList[csdIndex][1]",
"# @brief 在数据列表里面检查 #=================================== def checkInDataList(keyword, dataList, show):#, n): # 各种情况如下: # csd:",
"# # 规律如下: # (1)\" (2)' (3)/ (4)> for index in range(0, len(dataList)):",
"for fileName in fileNameList: suffixName = fileName[-3:] if \"png\" == suffixName or \"jpg\"",
"-1 == codeIndex: print(getCnt(), picName, fileName, \"pic=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])]) return",
"code # (4) # 1. png => fnt, fnt => code # 2.",
"fntDataList, csdDataList, codeDataList): pass if \"__main__\" == __name__: findNotUsePic(\"./src\", \"./src\", \"./ccs_pro\", \"./src\", \"./src\")",
"csdDataList[csdIndex][2])]) return True return False #========================== # @brief 在plist里面处理 #========================== def handleInPlist(picIndex, picNameList,",
"code # 2. png => fnt, fnt=>csd, csd => code #===================================== import os",
"False) # exportJston => code if -1 == codeIndex: print(getCnt(), picName, plistFileName, exportJsonFileName,",
"saveToList.append([data, fileName, prePath+\"/\"+fileName]) saveToList.append([data, fileName, prePath]) f.close() return saveToList #=================================== # @brief 在数据列表里面检查",
"= picNameList[picIndex][0] #pic => plist plistIndex = checkInDataList(picName, plistDataList, False) if -1 !=",
"# saveToList.append([data, fileName, prePath+\"/\"+fileName]) saveToList.append([data, fileName, prePath]) f.close() return saveToList #=================================== # @brief",
"1. png => plist, plist => code # 2. png => plist, plist",
"codeIndex: print(getCnt(), picName, csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])]) return True return",
"csdIndex: fileName = csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(fileName[:-1]+\"b\", codeDataList, False)",
"csdDataList,codeDataList): picName = picNameList[picIndex][0] #pic => csd csdIndex = checkInDataList(picName, csdDataList, False) if",
"suffixName = fileName[-3:] if \"png\" == suffixName or \"jpg\" == suffixName: picNameList.append([fileName, prePath])",
"# fnt => code fntName = fntDataList[fntIndex][1] codeIndex = checkInDataList(fntName, codeDataList, False) if",
"要查找的plist路径 # fntPath 要查找的fnt路径 #=============================================================== def findNotUsePic(picPath, codePath, csdPath, plistPath, fntPath): picNameList =",
"#=============================================================== def findNotUsePic(picPath, codePath, csdPath, plistPath, fntPath): picNameList = readPicNameList(picPath) codeDataList = readFileDataToList(codePath,",
"g_cnt + 1 return g_cnt #=================================== # @brief 读取所有图片到列表里面 #=================================== def readPicNameList(picPath): picNameList",
"range(0, len(picNameList)): # code if handleInCode(picIndex, picNameList, codeDataList): pass # csd elif handleInCsd(picIndex,",
"fielSuffixName = fileName[-n:] if suffixName == fielSuffixName: f = open(prePath+\"/\"+fileName, \"rb\") data =",
"= fileInfo[0] filePath = fileInfo[1] if not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #========================== #",
"f.read() # saveToList.append([data, fileName, prePath+\"/\"+fileName]) saveToList.append([data, fileName, prePath]) f.close() return saveToList #=================================== #",
"PicNameList ok\") #=============================================== # @brief 读取文件目录下某个后缀的数据到列表里面 #=============================================== def readFileDataToList(filePath, suffixName): n = len(suffixName)",
"fileName, prePath+\"/\"+fileName]) saveToList.append([data, fileName, prePath]) f.close() return saveToList #=================================== # @brief 在数据列表里面检查 #===================================",
"preCh = fileInfo[0][findIndex-1] if '\"'==preCh or \"'\"==preCh or \"/\"==preCh or \">\"==preCh: return index",
"plist, plist => ExportJson, ExportJson => code # (4) # 1. png =>",
"g_cnt g_cnt = g_cnt + 1 return g_cnt #=================================== # @brief 读取所有图片到列表里面 #===================================",
"codeDataList): picName = picNameList[picIndex][0] #pic => plist plistIndex = checkInDataList(picName, plistDataList, False) if",
"open(prePath+\"/\"+fileName, \"rb\") data = f.read() # saveToList.append([data, fileName, prePath+\"/\"+fileName]) saveToList.append([data, fileName, prePath]) f.close()",
"return True return False #========================== # @brief 在plist里面处理 #========================== def handleInPlist(picIndex, picNameList, plistDataList,",
"# -*- coding:utf-8 -*- #===================================== # 通过分析所有代码,找出没有用到的图片 # 没有用的图片资源主要有如下3种情况: # (1)png => code",
"=> plist, plist => ExportJson, ExportJson => code # (4) # 1. png",
"(4) # 1. png => fnt, fnt => code # 2. png =>",
"def handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): picName = picNameList[picIndex][0] #pic => plist plistIndex",
"codeDataList): pass # csd elif handleInCsd(picIndex, picNameList, csdDataList, codeDataList): pass # plist, exportJson",
"各种情况如下: # csd: <FileData Type=\"Normal\" Path=\"Res/abc.png\" /> # code: [\"abc\"] = \"abc.png\", #",
"=> code if -1 == codeIndex: print(getCnt(), picName, plistFileName, exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([ (picName,",
"Path=\"Res/abc.png\" /> # code: [\"abc\"] = \"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\") # plist: <key>abc.png</key> #",
"!= csdIndex: fileName = csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(fileName[:-1]+\"b\", codeDataList,",
"else: #fnt => csd csdIndex = checkInDataList(fntName, csdDataList, False) if -1 != csdIndex:",
"picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return True return False #========================== # @brief 在fnt里面处理",
"for fileInfo in filePathList: fileName = fileInfo[0] filePath = fileInfo[1] if not os.path.exists(\"needdelete/\"+filePath):",
"# 规律如下: # (1)\" (2)' (3)/ (4)> for index in range(0, len(dataList)): fileInfo",
"=> code # (3) # 1. png => plist, plist => code #",
"png => plist, plist => code # 2. png => plist, plist =>",
"fileNameList: suffixName = fileName[-3:] if \"png\" == suffixName or \"jpg\" == suffixName: picNameList.append([fileName,",
"plist => ExportJson, ExportJson => code # (4) # 1. png => fnt,",
"True return False #========================== # @brief 在plist里面处理 #========================== def handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList,",
"# csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) # plist 要查找的plist路径 # fntPath 要查找的fnt路径 #=============================================================== def findNotUsePic(picPath, codePath,",
"False) if -1 == codeIndex: print(getCnt(), picName, fileName, \"pic=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (fileName,",
"prePath]) return picNameList # print(\"read PicNameList ok\") #=============================================== # @brief 读取文件目录下某个后缀的数据到列表里面 #=============================================== def",
"picNameList[picIndex][0] #pic => fnt fntIndex = checkInDataList(picName, fntDataList, False) if -1 != fntIndex:",
"f.close() return saveToList #=================================== # @brief 在数据列表里面检查 #=================================== def checkInDataList(keyword, dataList, show):#, n):",
"\"pic=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])]) return True return False #========================== # @brief",
"# 1. png => fnt, fnt => code # 2. png => fnt,",
"f = open(prePath+\"/\"+fileName, \"rb\") data = f.read() # saveToList.append([data, fileName, prePath+\"/\"+fileName]) saveToList.append([data, fileName,",
"= readFileDataToList(plistPath,\"plist\") fntDataList = readFileDataToList(fntPath, \"fnt\") exportJsonDataList = readFileDataToList(fntPath, \"ExportJson\") for picIndex in",
"False #========================== # @brief 在plist里面处理 #========================== def handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): picName",
"import os import shutil global g_cnt g_cnt = 0 def getCnt(): global g_cnt",
"if suffixName == fielSuffixName: f = open(prePath+\"/\"+fileName, \"rb\") data = f.read() # saveToList.append([data,",
"# csd => code codeIndex = checkInDataList(fileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex:",
"fnt elif handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): pass if \"__main__\" == __name__: findNotUsePic(\"./src\",",
"-*- #===================================== # 通过分析所有代码,找出没有用到的图片 # 没有用的图片资源主要有如下3种情况: # (1)png => code # (2)png =>",
"= csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(fileName[:-1]+\"b\", codeDataList, False) if -1",
"-1 != codeIndex: #代码里面找到plist return True else: exportJsonIndex = checkInDataList(plistFileName, exportJsonDataList, False) #",
"exportJsonFileName = exportJsonDataList[exportJsonIndex][1] codeIndex = checkInDataList(exportJsonFileName, codeDataList, False) # exportJston => code if",
"csdDataList = readFileDataToList(csdPath, \"csd\") plistDataList = readFileDataToList(plistPath,\"plist\") fntDataList = readFileDataToList(fntPath, \"fnt\") exportJsonDataList =",
"# (1)\" (2)' (3)/ (4)> for index in range(0, len(dataList)): fileInfo = dataList[index]",
"readFileDataToList(fntPath, \"ExportJson\") for picIndex in range(0, len(picNameList)): # code if handleInCode(picIndex, picNameList, codeDataList):",
"return False #=============================================================== # @brief 查找没用的图片 # @params picPath 要查找的图片路径 # codePath 要查找的代码路径",
"csd => code codeIndex = checkInDataList(fileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(),",
"# @brief 读取文件目录下某个后缀的数据到列表里面 #=============================================== def readFileDataToList(filePath, suffixName): n = len(suffixName) saveToList = []",
"\"pic=>plist=>json\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return True return False #==========================",
"picPath 要查找的图片路径 # codePath 要查找的代码路径 # csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) # plist 要查找的plist路径 # fntPath",
"fntDataList, False) if -1 != fntIndex: # fnt => code fntName = fntDataList[fntIndex][1]",
"-1 == codeIndex: print(getCnt(), picName, plistFileName, exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]),",
"@brief 在csd里面处理 #========================== def handleInCsd(picIndex, picNameList, csdDataList,codeDataList): picName = picNameList[picIndex][0] #pic => csd",
"=> code codeIndex = checkInDataList(fileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(), picName,",
"codePath 要查找的代码路径 # csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) # plist 要查找的plist路径 # fntPath 要查找的fnt路径 #=============================================================== def",
"prePath+\"/\"+fileName]) saveToList.append([data, fileName, prePath]) f.close() return saveToList #=================================== # @brief 在数据列表里面检查 #=================================== def",
"csdDataList, codeDataList): pass if \"__main__\" == __name__: findNotUsePic(\"./src\", \"./src\", \"./ccs_pro\", \"./src\", \"./src\") print(\"ok\")",
"在数据列表里面检查 #=================================== def checkInDataList(keyword, dataList, show):#, n): # 各种情况如下: # csd: <FileData Type=\"Normal\"",
"plist = > exportJston if -1 != exportJsonIndex: exportJsonFileName = exportJsonDataList[exportJsonIndex][1] codeIndex =",
"if -1 != exportJsonIndex: exportJsonFileName = exportJsonDataList[exportJsonIndex][1] codeIndex = checkInDataList(exportJsonFileName, codeDataList, False) #",
"picName = picNameList[picIndex][0] #pic => csd csdIndex = checkInDataList(picName, csdDataList, False) if -1",
"@brief 处理没有用的文件 #========================== def handleNotFoundFile(filePathList): for fileInfo in filePathList: fileName = fileInfo[0] filePath",
"range(0, len(dataList)): fileInfo = dataList[index] findIndex = fileInfo[0].find(keyword) if -1 != findIndex: preCh",
"for prePath, folderList, fileNameList in os.walk(filePath): for fileName in fileNameList: # fielSuffixName =",
"\"fnt\") exportJsonDataList = readFileDataToList(fntPath, \"ExportJson\") for picIndex in range(0, len(picNameList)): # code if",
"plist, exportJson elif handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): pass # fnt elif handleInFnt(picIndex,",
"fnt fntIndex = checkInDataList(picName, fntDataList, False) if -1 != fntIndex: # fnt =>",
"checkInDataList(plistFileName, codeDataList, False) # plist => code if -1 != codeIndex: #代码里面找到plist return",
"[\"abc\"] = \"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\") # plist: <key>abc.png</key> # # 规律如下: # (1)\"",
"= picNameList[picIndex][0] #pic => csd csdIndex = checkInDataList(picName, csdDataList, False) if -1 !=",
"handleNotFoundFile([ (picName, picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])]) return True return False #=============================================================== # @brief 查找没用的图片",
"readFileDataToList(fntPath, \"fnt\") exportJsonDataList = readFileDataToList(fntPath, \"ExportJson\") for picIndex in range(0, len(picNameList)): # code",
"codeDataList): picName = picNameList[picIndex][0] #pic => fnt fntIndex = checkInDataList(picName, fntDataList, False) if",
"要查找的csd路径(只有csd才能用来查询,csb不行) # plist 要查找的plist路径 # fntPath 要查找的fnt路径 #=============================================================== def findNotUsePic(picPath, codePath, csdPath, plistPath,",
"n = len(suffixName) saveToList = [] for prePath, folderList, fileNameList in os.walk(filePath): for",
"#=============================================== def readFileDataToList(filePath, suffixName): n = len(suffixName) saveToList = [] for prePath, folderList,",
"要查找的代码路径 # csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) # plist 要查找的plist路径 # fntPath 要查找的fnt路径 #=============================================================== def findNotUsePic(picPath,",
"=> code fntName = fntDataList[fntIndex][1] codeIndex = checkInDataList(fntName, codeDataList, False) if -1 !=",
"fielSuffixName: f = open(prePath+\"/\"+fileName, \"rb\") data = f.read() # saveToList.append([data, fileName, prePath+\"/\"+fileName]) saveToList.append([data,",
"# plist = > exportJston if -1 != exportJsonIndex: exportJsonFileName = exportJsonDataList[exportJsonIndex][1] codeIndex",
"fileNameList in os.walk(filePath): for fileName in fileNameList: # fielSuffixName = fileName[-3:] fielSuffixName =",
"fntPath 要查找的fnt路径 #=============================================================== def findNotUsePic(picPath, codePath, csdPath, plistPath, fntPath): picNameList = readPicNameList(picPath) codeDataList",
"= dataList[index] findIndex = fileInfo[0].find(keyword) if -1 != findIndex: preCh = fileInfo[0][findIndex-1] if",
"if -1 != codeIndex: #代码里面找到plist return True else: exportJsonIndex = checkInDataList(plistFileName, exportJsonDataList, False)",
"exportJston if -1 != exportJsonIndex: exportJsonFileName = exportJsonDataList[exportJsonIndex][1] codeIndex = checkInDataList(exportJsonFileName, codeDataList, False)",
"return True return False #========================== # @brief 在fnt里面处理 #========================== def handleInFnt(picIndex, picNameList, fntDataList,",
"= checkInDataList(fntName, csdDataList, False) if -1 != csdIndex: csdFileName = csdDataList[csdIndex][1] # csd",
"elif handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): pass if \"__main__\" == __name__: findNotUsePic(\"./src\", \"./src\",",
"plistDataList, exportJsonDataList, codeDataList): pass # fnt elif handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): pass",
"if \"png\" == suffixName or \"jpg\" == suffixName: picNameList.append([fileName, prePath]) return picNameList #",
"fntPath): picNameList = readPicNameList(picPath) codeDataList = readFileDataToList(codePath, \"lua\") csdDataList = readFileDataToList(csdPath, \"csd\") plistDataList",
"picNameList = [] for prePath, folderList, fileNameList in os.walk(picPath): for fileName in fileNameList:",
"plist, plist => code # 2. png => plist, plist => ExportJson, ExportJson",
"(4)> for index in range(0, len(dataList)): fileInfo = dataList[index] findIndex = fileInfo[0].find(keyword) if",
"picName = picNameList[picIndex][0] #pic => fnt fntIndex = checkInDataList(picName, fntDataList, False) if -1",
"or \">\"==preCh: return index return -1 #========================== # @brief 处理没有用的文件 #========================== def handleNotFoundFile(filePathList):",
"# (4) # 1. png => fnt, fnt => code # 2. png",
"# exportJston => code if -1 == codeIndex: print(getCnt(), picName, plistFileName, exportJsonFileName, \"pic=>plist=>json\")",
"if '\"'==preCh or \"'\"==preCh or \"/\"==preCh or \">\"==preCh: return index return -1 #==========================",
"png => fnt, fnt => code # 2. png => fnt, fnt=>csd, csd",
"readFileDataToList(plistPath,\"plist\") fntDataList = readFileDataToList(fntPath, \"fnt\") exportJsonDataList = readFileDataToList(fntPath, \"ExportJson\") for picIndex in range(0,",
"def readFileDataToList(filePath, suffixName): n = len(suffixName) saveToList = [] for prePath, folderList, fileNameList",
"codeDataList, False) return -1!=index #========================== # @brief 在csd里面处理 #========================== def handleInCsd(picIndex, picNameList, csdDataList,codeDataList):",
"csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) # plist 要查找的plist路径 # fntPath 要查找的fnt路径 #=============================================================== def findNotUsePic(picPath, codePath, csdPath,",
"ExportJson, ExportJson => code # (4) # 1. png => fnt, fnt =>",
"(2)' (3)/ (4)> for index in range(0, len(dataList)): fileInfo = dataList[index] findIndex =",
"#=============================================== # @brief 读取文件目录下某个后缀的数据到列表里面 #=============================================== def readFileDataToList(filePath, suffixName): n = len(suffixName) saveToList =",
"if -1 != codeIndex: return True else: #fnt => csd csdIndex = checkInDataList(fntName,",
"codeIndex: print(getCnt(), picName, plistFileName, exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])])",
"g_cnt g_cnt = 0 def getCnt(): global g_cnt g_cnt = g_cnt + 1",
"@brief 在plist里面处理 #========================== def handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): picName = picNameList[picIndex][0] #pic",
"elif handleInCsd(picIndex, picNameList, csdDataList, codeDataList): pass # plist, exportJson elif handleInPlist(picIndex, picNameList, plistDataList,",
"codeDataList, False) if -1 == codeIndex: print(getCnt(), picName, csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]),",
"#=================================== # @brief 在数据列表里面检查 #=================================== def checkInDataList(keyword, dataList, show):#, n): # 各种情况如下: #",
"codeDataList, False) if -1 == codeIndex: print(getCnt(), picName, fileName, \"pic=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]),",
"True else: exportJsonIndex = checkInDataList(plistFileName, exportJsonDataList, False) # plist = > exportJston if",
"exportJsonIndex = checkInDataList(plistFileName, exportJsonDataList, False) # plist = > exportJston if -1 !=",
"-*- coding:utf-8 -*- #===================================== # 通过分析所有代码,找出没有用到的图片 # 没有用的图片资源主要有如下3种情况: # (1)png => code #",
"= fileName[-n:] if suffixName == fielSuffixName: f = open(prePath+\"/\"+fileName, \"rb\") data = f.read()",
"规律如下: # (1)\" (2)' (3)/ (4)> for index in range(0, len(dataList)): fileInfo =",
"return saveToList #=================================== # @brief 在数据列表里面检查 #=================================== def checkInDataList(keyword, dataList, show):#, n): #",
"#========================== def handleInCsd(picIndex, picNameList, csdDataList,codeDataList): picName = picNameList[picIndex][0] #pic => csd csdIndex =",
"if -1 != fntIndex: # fnt => code fntName = fntDataList[fntIndex][1] codeIndex =",
"csd => code codeIndex = checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(),",
"csd: <FileData Type=\"Normal\" Path=\"Res/abc.png\" /> # code: [\"abc\"] = \"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\") #",
"<FileData Type=\"Normal\" Path=\"Res/abc.png\" /> # code: [\"abc\"] = \"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\") # plist:",
"csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False) if -1 ==",
"checkInDataList(picName, csdDataList, False) if -1 != csdIndex: fileName = csdDataList[csdIndex][1] # csd =>",
"要查找的图片路径 # codePath 要查找的代码路径 # csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) # plist 要查找的plist路径 # fntPath 要查找的fnt路径",
"= [] for prePath, folderList, fileNameList in os.walk(picPath): for fileName in fileNameList: suffixName",
"= readFileDataToList(codePath, \"lua\") csdDataList = readFileDataToList(csdPath, \"csd\") plistDataList = readFileDataToList(plistPath,\"plist\") fntDataList = readFileDataToList(fntPath,",
"handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): picName = picNameList[picIndex][0] #pic => plist plistIndex =",
"= [] for prePath, folderList, fileNameList in os.walk(filePath): for fileName in fileNameList: #",
"# (3) # 1. png => plist, plist => code # 2. png",
"# @params picPath 要查找的图片路径 # codePath 要查找的代码路径 # csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) # plist 要查找的plist路径",
"readPicNameList(picPath) codeDataList = readFileDataToList(codePath, \"lua\") csdDataList = readFileDataToList(csdPath, \"csd\") plistDataList = readFileDataToList(plistPath,\"plist\") fntDataList",
"checkInDataList(fileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(), picName, fileName, \"pic=>csd\") handleNotFoundFile([ (picName,",
"=> fnt, fnt=>csd, csd => code #===================================== import os import shutil global g_cnt",
"Type=\"Normal\" Path=\"Res/abc.png\" /> # code: [\"abc\"] = \"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\") # plist: <key>abc.png</key>",
"handleNotFoundFile([ (picName, picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])]) return True return False #========================== # @brief 在plist里面处理",
"在csd里面处理 #========================== def handleInCsd(picIndex, picNameList, csdDataList,codeDataList): picName = picNameList[picIndex][0] #pic => csd csdIndex",
"in range(0, len(dataList)): fileInfo = dataList[index] findIndex = fileInfo[0].find(keyword) if -1 != findIndex:",
"dataList[index] findIndex = fileInfo[0].find(keyword) if -1 != findIndex: preCh = fileInfo[0][findIndex-1] if '\"'==preCh",
"picNameList = readPicNameList(picPath) codeDataList = readFileDataToList(codePath, \"lua\") csdDataList = readFileDataToList(csdPath, \"csd\") plistDataList =",
"code # (2)png => csd, csd => code # (3) # 1. png",
"# @brief 在plist里面处理 #========================== def handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): picName = picNameList[picIndex][0]",
"读取文件目录下某个后缀的数据到列表里面 #=============================================== def readFileDataToList(filePath, suffixName): n = len(suffixName) saveToList = [] for prePath,",
"False) if -1 != csdIndex: fileName = csdDataList[csdIndex][1] # csd => code codeIndex",
"fnt, fnt => code # 2. png => fnt, fnt=>csd, csd => code",
"picNameList # print(\"read PicNameList ok\") #=============================================== # @brief 读取文件目录下某个后缀的数据到列表里面 #=============================================== def readFileDataToList(filePath, suffixName):",
"fileName[-3:] fielSuffixName = fileName[-n:] if suffixName == fielSuffixName: f = open(prePath+\"/\"+fileName, \"rb\") data",
"if -1 != csdIndex: csdFileName = csdDataList[csdIndex][1] # csd => code codeIndex =",
"2. png => plist, plist => ExportJson, ExportJson => code # (4) #",
"csdFileName = csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False) if",
"csd elif handleInCsd(picIndex, picNameList, csdDataList, codeDataList): pass # plist, exportJson elif handleInPlist(picIndex, picNameList,",
"= f.read() # saveToList.append([data, fileName, prePath+\"/\"+fileName]) saveToList.append([data, fileName, prePath]) f.close() return saveToList #===================================",
"csdIndex = checkInDataList(picName, csdDataList, False) if -1 != csdIndex: fileName = csdDataList[csdIndex][1] #",
"\">\"==preCh: return index return -1 #========================== # @brief 处理没有用的文件 #========================== def handleNotFoundFile(filePathList): for",
"exportJsonDataList[exportJsonIndex][1] codeIndex = checkInDataList(exportJsonFileName, codeDataList, False) # exportJston => code if -1 ==",
"=> csd csdIndex = checkInDataList(fntName, csdDataList, False) if -1 != csdIndex: csdFileName =",
"\"ExportJson\") for picIndex in range(0, len(picNameList)): # code if handleInCode(picIndex, picNameList, codeDataList): pass",
"= len(suffixName) saveToList = [] for prePath, folderList, fileNameList in os.walk(filePath): for fileName",
"= checkInDataList(picName, plistDataList, False) if -1 != plistIndex: plistFileName = plistDataList[plistIndex][1] codeIndex =",
"in filePathList: fileName = fileInfo[0] filePath = fileInfo[1] if not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName,",
"-1 #========================== # @brief 处理没有用的文件 #========================== def handleNotFoundFile(filePathList): for fileInfo in filePathList: fileName",
"= picNameList[picIndex][0] #pic => fnt fntIndex = checkInDataList(picName, fntDataList, False) if -1 !=",
"(picName, picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])]) return True return False #=============================================================== # @brief 查找没用的图片 #",
"data = f.read() # saveToList.append([data, fileName, prePath+\"/\"+fileName]) saveToList.append([data, fileName, prePath]) f.close() return saveToList",
"=> plist, plist => code # 2. png => plist, plist => ExportJson,",
"def handleInCode(picIndex, picNameList, codeDataList): picName = picNameList[picIndex][0] index = checkInDataList(picName, codeDataList, False) return",
"if -1 != csdIndex: fileName = csdDataList[csdIndex][1] # csd => code codeIndex =",
"not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #========================== # @brief 在代码里面处理 #========================== def handleInCode(picIndex, picNameList,",
"coding:utf-8 -*- #===================================== # 通过分析所有代码,找出没有用到的图片 # 没有用的图片资源主要有如下3种情况: # (1)png => code # (2)png",
"handleInCode(picIndex, picNameList, codeDataList): picName = picNameList[picIndex][0] index = checkInDataList(picName, codeDataList, False) return -1!=index",
"[] for prePath, folderList, fileNameList in os.walk(picPath): for fileName in fileNameList: suffixName =",
"(picName, picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])]) return True return False #========================== # @brief 在plist里面处理 #==========================",
"# plist, exportJson elif handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): pass # fnt elif",
"codeIndex = checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(), picName, csdFileName, \"pic=>fnt=>csd\")",
"saveToList.append([data, fileName, prePath]) f.close() return saveToList #=================================== # @brief 在数据列表里面检查 #=================================== def checkInDataList(keyword,",
"if handleInCode(picIndex, picNameList, codeDataList): pass # csd elif handleInCsd(picIndex, picNameList, csdDataList, codeDataList): pass",
"exportJsonDataList, codeDataList): pass # fnt elif handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): pass if",
"False) if -1 != csdIndex: csdFileName = csdDataList[csdIndex][1] # csd => code codeIndex",
"if not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #========================== # @brief 在代码里面处理 #========================== def handleInCode(picIndex,",
"picNameList, codeDataList): picName = picNameList[picIndex][0] index = checkInDataList(picName, codeDataList, False) return -1!=index #==========================",
"== suffixName: picNameList.append([fileName, prePath]) return picNameList # print(\"read PicNameList ok\") #=============================================== # @brief",
"fileName, prePath]) f.close() return saveToList #=================================== # @brief 在数据列表里面检查 #=================================== def checkInDataList(keyword, dataList,",
"# cc.Sprite:create(\"res/abc/abc.png\") # plist: <key>abc.png</key> # # 规律如下: # (1)\" (2)' (3)/ (4)>",
"checkInDataList(keyword, dataList, show):#, n): # 各种情况如下: # csd: <FileData Type=\"Normal\" Path=\"Res/abc.png\" /> #",
"csdDataList, False) if -1 != csdIndex: fileName = csdDataList[csdIndex][1] # csd => code",
"csd csdIndex = checkInDataList(picName, csdDataList, False) if -1 != csdIndex: fileName = csdDataList[csdIndex][1]",
"fnt => code fntName = fntDataList[fntIndex][1] codeIndex = checkInDataList(fntName, codeDataList, False) if -1",
"csdDataList, False) if -1 != csdIndex: csdFileName = csdDataList[csdIndex][1] # csd => code",
"fileInfo[0][findIndex-1] if '\"'==preCh or \"'\"==preCh or \"/\"==preCh or \">\"==preCh: return index return -1",
"\"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\") # plist: <key>abc.png</key> # # 规律如下: # (1)\" (2)' (3)/",
"# @brief 读取所有图片到列表里面 #=================================== def readPicNameList(picPath): picNameList = [] for prePath, folderList, fileNameList",
"fileName, \"pic=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])]) return True return False #========================== #",
"return -1!=index #========================== # @brief 在csd里面处理 #========================== def handleInCsd(picIndex, picNameList, csdDataList,codeDataList): picName =",
"def getCnt(): global g_cnt g_cnt = g_cnt + 1 return g_cnt #=================================== #",
"len(suffixName) saveToList = [] for prePath, folderList, fileNameList in os.walk(filePath): for fileName in",
"#========================== def handleInCode(picIndex, picNameList, codeDataList): picName = picNameList[picIndex][0] index = checkInDataList(picName, codeDataList, False)",
"@params picPath 要查找的图片路径 # codePath 要查找的代码路径 # csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) # plist 要查找的plist路径 #",
"index = checkInDataList(picName, codeDataList, False) return -1!=index #========================== # @brief 在csd里面处理 #========================== def",
"== codeIndex: print(getCnt(), picName, csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])]) return True",
"-1 != csdIndex: csdFileName = csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(csdFileName[:-1]+\"b\",",
"<key>abc.png</key> # # 规律如下: # (1)\" (2)' (3)/ (4)> for index in range(0,",
"plistIndex: plistFileName = plistDataList[plistIndex][1] codeIndex = checkInDataList(plistFileName, codeDataList, False) # plist => code",
"= fileInfo[0][findIndex-1] if '\"'==preCh or \"'\"==preCh or \"/\"==preCh or \">\"==preCh: return index return",
"=> code # (2)png => csd, csd => code # (3) # 1.",
"in range(0, len(picNameList)): # code if handleInCode(picIndex, picNameList, codeDataList): pass # csd elif",
"def handleInCsd(picIndex, picNameList, csdDataList,codeDataList): picName = picNameList[picIndex][0] #pic => csd csdIndex = checkInDataList(picName,",
"= fileInfo[0].find(keyword) if -1 != findIndex: preCh = fileInfo[0][findIndex-1] if '\"'==preCh or \"'\"==preCh",
"= csdDataList[csdIndex][1] # csd => code codeIndex = checkInDataList(csdFileName[:-1]+\"b\", codeDataList, False) if -1",
"在fnt里面处理 #========================== def handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): picName = picNameList[picIndex][0] #pic =>",
"-1 != findIndex: preCh = fileInfo[0][findIndex-1] if '\"'==preCh or \"'\"==preCh or \"/\"==preCh or",
"fntDataList = readFileDataToList(fntPath, \"fnt\") exportJsonDataList = readFileDataToList(fntPath, \"ExportJson\") for picIndex in range(0, len(picNameList)):",
"os.walk(picPath): for fileName in fileNameList: suffixName = fileName[-3:] if \"png\" == suffixName or",
"picName, fileName, \"pic=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])]) return True return False #==========================",
"#=================================== # @brief 读取所有图片到列表里面 #=================================== def readPicNameList(picPath): picNameList = [] for prePath, folderList,",
"shutil global g_cnt g_cnt = 0 def getCnt(): global g_cnt g_cnt = g_cnt",
"csdPath, plistPath, fntPath): picNameList = readPicNameList(picPath) codeDataList = readFileDataToList(codePath, \"lua\") csdDataList = readFileDataToList(csdPath,",
"-1 != fntIndex: # fnt => code fntName = fntDataList[fntIndex][1] codeIndex = checkInDataList(fntName,",
"findNotUsePic(picPath, codePath, csdPath, plistPath, fntPath): picNameList = readPicNameList(picPath) codeDataList = readFileDataToList(codePath, \"lua\") csdDataList",
"plistPath, fntPath): picNameList = readPicNameList(picPath) codeDataList = readFileDataToList(codePath, \"lua\") csdDataList = readFileDataToList(csdPath, \"csd\")",
"+ 1 return g_cnt #=================================== # @brief 读取所有图片到列表里面 #=================================== def readPicNameList(picPath): picNameList =",
"picNameList[picIndex][0] index = checkInDataList(picName, codeDataList, False) return -1!=index #========================== # @brief 在csd里面处理 #==========================",
"#pic => plist plistIndex = checkInDataList(picName, plistDataList, False) if -1 != plistIndex: plistFileName",
"fntIndex: # fnt => code fntName = fntDataList[fntIndex][1] codeIndex = checkInDataList(fntName, codeDataList, False)",
"saveToList #=================================== # @brief 在数据列表里面检查 #=================================== def checkInDataList(keyword, dataList, show):#, n): # 各种情况如下:",
"suffixName: picNameList.append([fileName, prePath]) return picNameList # print(\"read PicNameList ok\") #=============================================== # @brief 读取文件目录下某个后缀的数据到列表里面",
"= readFileDataToList(fntPath, \"ExportJson\") for picIndex in range(0, len(picNameList)): # code if handleInCode(picIndex, picNameList,",
"= readFileDataToList(csdPath, \"csd\") plistDataList = readFileDataToList(plistPath,\"plist\") fntDataList = readFileDataToList(fntPath, \"fnt\") exportJsonDataList = readFileDataToList(fntPath,",
"fileNameList in os.walk(picPath): for fileName in fileNameList: suffixName = fileName[-3:] if \"png\" ==",
"exportJsonDataList[exportJsonIndex][2])]) return True return False #========================== # @brief 在fnt里面处理 #========================== def handleInFnt(picIndex, picNameList,",
"#========================== def handleNotFoundFile(filePathList): for fileInfo in filePathList: fileName = fileInfo[0] filePath = fileInfo[1]",
"codeDataList, False) # exportJston => code if -1 == codeIndex: print(getCnt(), picName, plistFileName,",
"plistFileName = plistDataList[plistIndex][1] codeIndex = checkInDataList(plistFileName, codeDataList, False) # plist => code if",
"codeIndex = checkInDataList(exportJsonFileName, codeDataList, False) # exportJston => code if -1 == codeIndex:",
"= open(prePath+\"/\"+fileName, \"rb\") data = f.read() # saveToList.append([data, fileName, prePath+\"/\"+fileName]) saveToList.append([data, fileName, prePath])",
"没有用的图片资源主要有如下3种情况: # (1)png => code # (2)png => csd, csd => code #",
"picNameList, fntDataList, csdDataList, codeDataList): pass if \"__main__\" == __name__: findNotUsePic(\"./src\", \"./src\", \"./ccs_pro\", \"./src\",",
"fileInfo[0] filePath = fileInfo[1] if not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #========================== # @brief",
"codeDataList = readFileDataToList(codePath, \"lua\") csdDataList = readFileDataToList(csdPath, \"csd\") plistDataList = readFileDataToList(plistPath,\"plist\") fntDataList =",
"fileInfo[0].find(keyword) if -1 != findIndex: preCh = fileInfo[0][findIndex-1] if '\"'==preCh or \"'\"==preCh or",
"code if handleInCode(picIndex, picNameList, codeDataList): pass # csd elif handleInCsd(picIndex, picNameList, csdDataList, codeDataList):",
"fnt => code # 2. png => fnt, fnt=>csd, csd => code #=====================================",
"# @brief 在csd里面处理 #========================== def handleInCsd(picIndex, picNameList, csdDataList,codeDataList): picName = picNameList[picIndex][0] #pic =>",
"2. png => fnt, fnt=>csd, csd => code #===================================== import os import shutil",
"else: exportJsonIndex = checkInDataList(plistFileName, exportJsonDataList, False) # plist = > exportJston if -1",
"saveToList = [] for prePath, folderList, fileNameList in os.walk(filePath): for fileName in fileNameList:",
"# @brief 在fnt里面处理 #========================== def handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): picName = picNameList[picIndex][0]",
"fileInfo = dataList[index] findIndex = fileInfo[0].find(keyword) if -1 != findIndex: preCh = fileInfo[0][findIndex-1]",
"handleInCode(picIndex, picNameList, codeDataList): pass # csd elif handleInCsd(picIndex, picNameList, csdDataList, codeDataList): pass #",
"code if -1 != codeIndex: #代码里面找到plist return True else: exportJsonIndex = checkInDataList(plistFileName, exportJsonDataList,",
"plistDataList = readFileDataToList(plistPath,\"plist\") fntDataList = readFileDataToList(fntPath, \"fnt\") exportJsonDataList = readFileDataToList(fntPath, \"ExportJson\") for picIndex",
"readFileDataToList(codePath, \"lua\") csdDataList = readFileDataToList(csdPath, \"csd\") plistDataList = readFileDataToList(plistPath,\"plist\") fntDataList = readFileDataToList(fntPath, \"fnt\")",
"pass # csd elif handleInCsd(picIndex, picNameList, csdDataList, codeDataList): pass # plist, exportJson elif",
"checkInDataList(fntName, csdDataList, False) if -1 != csdIndex: csdFileName = csdDataList[csdIndex][1] # csd =>",
"(fileName, csdDataList[csdIndex][2])]) return True return False #========================== # @brief 在plist里面处理 #========================== def handleInPlist(picIndex,",
"csd, csd => code # (3) # 1. png => plist, plist =>",
"os.walk(filePath): for fileName in fileNameList: # fielSuffixName = fileName[-3:] fielSuffixName = fileName[-n:] if",
"if -1 == codeIndex: print(getCnt(), picName, fileName, \"pic=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])])",
"exportJsonIndex: exportJsonFileName = exportJsonDataList[exportJsonIndex][1] codeIndex = checkInDataList(exportJsonFileName, codeDataList, False) # exportJston => code",
"# code: [\"abc\"] = \"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\") # plist: <key>abc.png</key> # # 规律如下:",
"-1 == codeIndex: print(getCnt(), picName, csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])]) return",
"# 2. png => plist, plist => ExportJson, ExportJson => code # (4)",
"or \"/\"==preCh or \">\"==preCh: return index return -1 #========================== # @brief 处理没有用的文件 #==========================",
"\"rb\") data = f.read() # saveToList.append([data, fileName, prePath+\"/\"+fileName]) saveToList.append([data, fileName, prePath]) f.close() return",
"ok\") #=============================================== # @brief 读取文件目录下某个后缀的数据到列表里面 #=============================================== def readFileDataToList(filePath, suffixName): n = len(suffixName) saveToList",
"= g_cnt + 1 return g_cnt #=================================== # @brief 读取所有图片到列表里面 #=================================== def readPicNameList(picPath):",
"\"pic=>fnt=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])]) return True return False #=============================================================== # @brief",
"fileName = fileInfo[0] filePath = fileInfo[1] if not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #==========================",
"folderList, fileNameList in os.walk(picPath): for fileName in fileNameList: suffixName = fileName[-3:] if \"png\"",
"=> code if -1 != codeIndex: #代码里面找到plist return True else: exportJsonIndex = checkInDataList(plistFileName,",
"return True else: exportJsonIndex = checkInDataList(plistFileName, exportJsonDataList, False) # plist = > exportJston",
"prePath]) f.close() return saveToList #=================================== # @brief 在数据列表里面检查 #=================================== def checkInDataList(keyword, dataList, show):#,",
"#pic => csd csdIndex = checkInDataList(picName, csdDataList, False) if -1 != csdIndex: fileName",
"if -1 == codeIndex: print(getCnt(), picName, plistFileName, exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (plistFileName,",
"!= exportJsonIndex: exportJsonFileName = exportJsonDataList[exportJsonIndex][1] codeIndex = checkInDataList(exportJsonFileName, codeDataList, False) # exportJston =>",
"=> csd csdIndex = checkInDataList(picName, csdDataList, False) if -1 != csdIndex: fileName =",
"codePath, csdPath, plistPath, fntPath): picNameList = readPicNameList(picPath) codeDataList = readFileDataToList(codePath, \"lua\") csdDataList =",
"!= fntIndex: # fnt => code fntName = fntDataList[fntIndex][1] codeIndex = checkInDataList(fntName, codeDataList,",
"# @brief 处理没有用的文件 #========================== def handleNotFoundFile(filePathList): for fileInfo in filePathList: fileName = fileInfo[0]",
"fntDataList[fntIndex][1] codeIndex = checkInDataList(fntName, codeDataList, False) if -1 != codeIndex: return True else:",
"print(getCnt(), picName, fileName, \"pic=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])]) return True return False",
"png => plist, plist => ExportJson, ExportJson => code # (4) # 1.",
"= fileName[-3:] fielSuffixName = fileName[-n:] if suffixName == fielSuffixName: f = open(prePath+\"/\"+fileName, \"rb\")",
"@brief 在fnt里面处理 #========================== def handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): picName = picNameList[picIndex][0] #pic",
"csdDataList, codeDataList): picName = picNameList[picIndex][0] #pic => fnt fntIndex = checkInDataList(picName, fntDataList, False)",
"# csd: <FileData Type=\"Normal\" Path=\"Res/abc.png\" /> # code: [\"abc\"] = \"abc.png\", # cc.Sprite:create(\"res/abc/abc.png\")",
"(exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return True return False #========================== # @brief 在fnt里面处理 #========================== def handleInFnt(picIndex,",
"codeIndex: print(getCnt(), picName, fileName, \"pic=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])]) return True return",
"=> plist plistIndex = checkInDataList(picName, plistDataList, False) if -1 != plistIndex: plistFileName =",
"prePath, folderList, fileNameList in os.walk(filePath): for fileName in fileNameList: # fielSuffixName = fileName[-3:]",
"fileNameList: # fielSuffixName = fileName[-3:] fielSuffixName = fileName[-n:] if suffixName == fielSuffixName: f",
"checkInDataList(exportJsonFileName, codeDataList, False) # exportJston => code if -1 == codeIndex: print(getCnt(), picName,",
"dataList, show):#, n): # 各种情况如下: # csd: <FileData Type=\"Normal\" Path=\"Res/abc.png\" /> # code:",
"elif handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): pass # fnt elif handleInFnt(picIndex, picNameList, fntDataList,",
"suffixName == fielSuffixName: f = open(prePath+\"/\"+fileName, \"rb\") data = f.read() # saveToList.append([data, fileName,",
"code # 2. png => plist, plist => ExportJson, ExportJson => code #",
"global g_cnt g_cnt = 0 def getCnt(): global g_cnt g_cnt = g_cnt +",
"@brief 在数据列表里面检查 #=================================== def checkInDataList(keyword, dataList, show):#, n): # 各种情况如下: # csd: <FileData",
"@brief 读取所有图片到列表里面 #=================================== def readPicNameList(picPath): picNameList = [] for prePath, folderList, fileNameList in",
"== suffixName or \"jpg\" == suffixName: picNameList.append([fileName, prePath]) return picNameList # print(\"read PicNameList",
"# codePath 要查找的代码路径 # csdPath 要查找的csd路径(只有csd才能用来查询,csb不行) # plist 要查找的plist路径 # fntPath 要查找的fnt路径 #===============================================================",
"= checkInDataList(fileName[:-1]+\"b\", codeDataList, False) if -1 == codeIndex: print(getCnt(), picName, fileName, \"pic=>csd\") handleNotFoundFile([",
"plistDataList, exportJsonDataList, codeDataList): picName = picNameList[picIndex][0] #pic => plist plistIndex = checkInDataList(picName, plistDataList,",
"png => fnt, fnt=>csd, csd => code #===================================== import os import shutil global",
"False) return -1!=index #========================== # @brief 在csd里面处理 #========================== def handleInCsd(picIndex, picNameList, csdDataList,codeDataList): picName",
"plistDataList[plistIndex][1] codeIndex = checkInDataList(plistFileName, codeDataList, False) # plist => code if -1 !=",
"prePath, folderList, fileNameList in os.walk(picPath): for fileName in fileNameList: suffixName = fileName[-3:] if",
"suffixName or \"jpg\" == suffixName: picNameList.append([fileName, prePath]) return picNameList # print(\"read PicNameList ok\")",
"codeDataList, False) if -1 != codeIndex: return True else: #fnt => csd csdIndex",
"1 return g_cnt #=================================== # @brief 读取所有图片到列表里面 #=================================== def readPicNameList(picPath): picNameList = []",
"= exportJsonDataList[exportJsonIndex][1] codeIndex = checkInDataList(exportJsonFileName, codeDataList, False) # exportJston => code if -1",
"#===================================== # 通过分析所有代码,找出没有用到的图片 # 没有用的图片资源主要有如下3种情况: # (1)png => code # (2)png => csd,",
"picName, plistFileName, exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return True",
"print(getCnt(), picName, csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])]) return True return False",
"or \"'\"==preCh or \"/\"==preCh or \">\"==preCh: return index return -1 #========================== # @brief",
"= fileInfo[1] if not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #========================== # @brief 在代码里面处理 #==========================",
"True return False #========================== # @brief 在fnt里面处理 #========================== def handleInFnt(picIndex, picNameList, fntDataList, csdDataList,",
"=> code # 2. png => plist, plist => ExportJson, ExportJson => code",
"in os.walk(picPath): for fileName in fileNameList: suffixName = fileName[-3:] if \"png\" == suffixName",
"checkInDataList(picName, plistDataList, False) if -1 != plistIndex: plistFileName = plistDataList[plistIndex][1] codeIndex = checkInDataList(plistFileName,",
"handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList): pass if \"__main__\" == __name__: findNotUsePic(\"./src\", \"./src\", \"./ccs_pro\",",
"# 1. png => plist, plist => code # 2. png => plist,",
"index return -1 #========================== # @brief 处理没有用的文件 #========================== def handleNotFoundFile(filePathList): for fileInfo in",
"=> csd, csd => code # (3) # 1. png => plist, plist",
"csdDataList, codeDataList): pass # plist, exportJson elif handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): pass",
"readPicNameList(picPath): picNameList = [] for prePath, folderList, fileNameList in os.walk(picPath): for fileName in",
"= fntDataList[fntIndex][1] codeIndex = checkInDataList(fntName, codeDataList, False) if -1 != codeIndex: return True",
"picNameList, csdDataList,codeDataList): picName = picNameList[picIndex][0] #pic => csd csdIndex = checkInDataList(picName, csdDataList, False)",
"findIndex: preCh = fileInfo[0][findIndex-1] if '\"'==preCh or \"'\"==preCh or \"/\"==preCh or \">\"==preCh: return",
"\"jpg\" == suffixName: picNameList.append([fileName, prePath]) return picNameList # print(\"read PicNameList ok\") #=============================================== #",
"return True else: #fnt => csd csdIndex = checkInDataList(fntName, csdDataList, False) if -1",
"exportJsonDataList = readFileDataToList(fntPath, \"ExportJson\") for picIndex in range(0, len(picNameList)): # code if handleInCode(picIndex,",
"# csd elif handleInCsd(picIndex, picNameList, csdDataList, codeDataList): pass # plist, exportJson elif handleInPlist(picIndex,",
"-1!=index #========================== # @brief 在csd里面处理 #========================== def handleInCsd(picIndex, picNameList, csdDataList,codeDataList): picName = picNameList[picIndex][0]",
"=> fnt fntIndex = checkInDataList(picName, fntDataList, False) if -1 != fntIndex: # fnt",
"ExportJson => code # (4) # 1. png => fnt, fnt => code",
"\"png\" == suffixName or \"jpg\" == suffixName: picNameList.append([fileName, prePath]) return picNameList # print(\"read",
"# 2. png => fnt, fnt=>csd, csd => code #===================================== import os import",
"# 通过分析所有代码,找出没有用到的图片 # 没有用的图片资源主要有如下3种情况: # (1)png => code # (2)png => csd, csd",
"#========================== # @brief 在代码里面处理 #========================== def handleInCode(picIndex, picNameList, codeDataList): picName = picNameList[picIndex][0] index",
"fileInfo[1] if not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName) #========================== # @brief 在代码里面处理 #========================== def",
"g_cnt = 0 def getCnt(): global g_cnt g_cnt = g_cnt + 1 return",
"== codeIndex: print(getCnt(), picName, fileName, \"pic=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (fileName, csdDataList[csdIndex][2])]) return True",
"= picNameList[picIndex][0] index = checkInDataList(picName, codeDataList, False) return -1!=index #========================== # @brief 在csd里面处理",
"# (1)png => code # (2)png => csd, csd => code # (3)",
"False #=============================================================== # @brief 查找没用的图片 # @params picPath 要查找的图片路径 # codePath 要查找的代码路径 #",
"=> ExportJson, ExportJson => code # (4) # 1. png => fnt, fnt",
"#========================== def handleInPlist(picIndex, picNameList, plistDataList, exportJsonDataList, codeDataList): picName = picNameList[picIndex][0] #pic => plist",
"#代码里面找到plist return True else: exportJsonIndex = checkInDataList(plistFileName, exportJsonDataList, False) # plist = >",
"= plistDataList[plistIndex][1] codeIndex = checkInDataList(plistFileName, codeDataList, False) # plist => code if -1",
"print(\"read PicNameList ok\") #=============================================== # @brief 读取文件目录下某个后缀的数据到列表里面 #=============================================== def readFileDataToList(filePath, suffixName): n =",
"False) if -1 != codeIndex: return True else: #fnt => csd csdIndex =",
"picNameList, plistDataList, exportJsonDataList, codeDataList): pass # fnt elif handleInFnt(picIndex, picNameList, fntDataList, csdDataList, codeDataList):",
"exportJston => code if -1 == codeIndex: print(getCnt(), picName, plistFileName, exportJsonFileName, \"pic=>plist=>json\") handleNotFoundFile([",
"checkInDataList(fntName, codeDataList, False) if -1 != codeIndex: return True else: #fnt => csd",
"g_cnt #=================================== # @brief 读取所有图片到列表里面 #=================================== def readPicNameList(picPath): picNameList = [] for prePath,",
"# @brief 在代码里面处理 #========================== def handleInCode(picIndex, picNameList, codeDataList): picName = picNameList[picIndex][0] index =",
"picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])]) return True return False #=============================================================== # @brief 查找没用的图片 # @params",
"exportJsonDataList, codeDataList): picName = picNameList[picIndex][0] #pic => plist plistIndex = checkInDataList(picName, plistDataList, False)",
"filePathList: fileName = fileInfo[0] filePath = fileInfo[1] if not os.path.exists(\"needdelete/\"+filePath): os.makedirs(\"needdelete/\"+filePath) shutil.copyfile(filePath+\"/\"+fileName, \"needdelete/\"+filePath+\"/\"+fileName)",
"False) # plist => code if -1 != codeIndex: #代码里面找到plist return True else:",
"if -1 == codeIndex: print(getCnt(), picName, csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (csdFileName, csdDataList[csdIndex][2])])",
"\"'\"==preCh or \"/\"==preCh or \">\"==preCh: return index return -1 #========================== # @brief 处理没有用的文件",
"picNameList[picIndex][0] #pic => plist plistIndex = checkInDataList(picName, plistDataList, False) if -1 != plistIndex:",
"code # (3) # 1. png => plist, plist => code # 2.",
"handleNotFoundFile([ (picName, picNameList[picIndex][1]), (plistFileName, plistDataList[plistIndex][2]), (exportJsonFileName, exportJsonDataList[exportJsonIndex][2])]) return True return False #========================== #",
"!= codeIndex: return True else: #fnt => csd csdIndex = checkInDataList(fntName, csdDataList, False)",
"False) if -1 == codeIndex: print(getCnt(), picName, csdFileName, \"pic=>fnt=>csd\") handleNotFoundFile([ (picName, picNameList[picIndex][1]), (csdFileName,",
"len(dataList)): fileInfo = dataList[index] findIndex = fileInfo[0].find(keyword) if -1 != findIndex: preCh =",
"# plist: <key>abc.png</key> # # 规律如下: # (1)\" (2)' (3)/ (4)> for index"
] |
[
"MAIN_REPORT.explain(message, priority, line, label=label) def gently(message, line=None, label='explain'): MAIN_REPORT.gently(message, line, label=label) def hide_correctness():",
"user. \"\"\" MAIN_REPORT.give_partial(value, message) def explain(message, priority='medium', line=None, label='explain'): MAIN_REPORT.explain(message, priority, line, label=label)",
"`value`. Optionally display a positive message too. Args: value (number): The number to",
"that the entire assignment is done. \"\"\" MAIN_REPORT.set_success() def compliment(message, line=None): \"\"\" Create",
"expected to work with a given Report, and only #: default to this",
"MAIN_REPORT = Report() def set_success(): \"\"\" Creates Successful feedback for the user, indicating",
"pedal.report.report import Report #: The global Report object. Meant to be used as",
"given Report, and only #: default to this Report when no others are",
"'suppress', 'log', 'debug', 'clear_report', 'get_all_feedback', 'MAIN_REPORT'] from pedal.report.report import Report #: The global",
"report object (MAIN_REPORT). \"\"\" __all__ = ['set_success', 'compliment', 'give_partial', 'explain', 'gently', 'hide_correctness', 'suppress',",
"to create their own Report. #: Of course, all APIs are expected to",
"\"\"\" __all__ = ['set_success', 'compliment', 'give_partial', 'explain', 'gently', 'hide_correctness', 'suppress', 'log', 'debug', 'clear_report',",
"line of code to reference. \"\"\" MAIN_REPORT.compliment(message, line) def give_partial(value, message=None): \"\"\" Increases",
"only #: default to this Report when no others are given. MAIN_REPORT =",
"work with a given Report, and only #: default to this Report when",
"'clear_report', 'get_all_feedback', 'MAIN_REPORT'] from pedal.report.report import Report #: The global Report object. Meant",
"indicating that the entire assignment is done. \"\"\" MAIN_REPORT.set_success() def compliment(message, line=None): \"\"\"",
"the user's score by. message (str): The message to display to the user.",
"a global report object (MAIN_REPORT). \"\"\" __all__ = ['set_success', 'compliment', 'give_partial', 'explain', 'gently',",
"Args: message (str): The message to display to the user. line (int): The",
"score by the `value`. Optionally display a positive message too. Args: value (number):",
"line=None, label='explain'): MAIN_REPORT.explain(message, priority, line, label=label) def gently(message, line=None, label='explain'): MAIN_REPORT.gently(message, line, label=label)",
"to work with a given Report, and only #: default to this Report",
"default singleton #: for any tool, so that instructors do not have to",
"feedback for the user, potentially on a specific line of code. Args: message",
"given. MAIN_REPORT = Report() def set_success(): \"\"\" Creates Successful feedback for the user,",
"line (int): The relevant line of code to reference. \"\"\" MAIN_REPORT.compliment(message, line) def",
"as a default singleton #: for any tool, so that instructors do not",
"'get_all_feedback', 'MAIN_REPORT'] from pedal.report.report import Report #: The global Report object. Meant to",
"a given Report, and only #: default to this Report when no others",
"message to display to the user. \"\"\" MAIN_REPORT.give_partial(value, message) def explain(message, priority='medium', line=None,",
"and only #: default to this Report when no others are given. MAIN_REPORT",
"message (str): The message to display to the user. line (int): The relevant",
"#: Of course, all APIs are expected to work with a given Report,",
"Meant to be used as a default singleton #: for any tool, so",
"feedback in a convenient way. Uses a global report object (MAIN_REPORT). \"\"\" __all__",
"to be used as a default singleton #: for any tool, so that",
"def compliment(message, line=None): \"\"\" Create a positive feedback for the user, potentially on",
"by. message (str): The message to display to the user. \"\"\" MAIN_REPORT.give_partial(value, message)",
"user's current score by the `value`. Optionally display a positive message too. Args:",
"by the `value`. Optionally display a positive message too. Args: value (number): The",
"are given. MAIN_REPORT = Report() def set_success(): \"\"\" Creates Successful feedback for the",
"do not have to create their own Report. #: Of course, all APIs",
"= Report() def set_success(): \"\"\" Creates Successful feedback for the user, indicating that",
"for the user, indicating that the entire assignment is done. \"\"\" MAIN_REPORT.set_success() def",
"user, indicating that the entire assignment is done. \"\"\" MAIN_REPORT.set_success() def compliment(message, line=None):",
"gently(message, line=None, label='explain'): MAIN_REPORT.gently(message, line, label=label) def hide_correctness(): MAIN_REPORT.hide_correctness() def suppress(category, label=True): MAIN_REPORT.suppress(category,",
"to this Report when no others are given. MAIN_REPORT = Report() def set_success():",
"'explain', 'gently', 'hide_correctness', 'suppress', 'log', 'debug', 'clear_report', 'get_all_feedback', 'MAIN_REPORT'] from pedal.report.report import Report",
"assignment is done. \"\"\" MAIN_REPORT.set_success() def compliment(message, line=None): \"\"\" Create a positive feedback",
"a default singleton #: for any tool, so that instructors do not have",
"for the user, potentially on a specific line of code. Args: message (str):",
"Args: value (number): The number to increase the user's score by. message (str):",
"message too. Args: value (number): The number to increase the user's score by.",
"own Report. #: Of course, all APIs are expected to work with a",
"tool, so that instructors do not have to create their own Report. #:",
"on a specific line of code. Args: message (str): The message to display",
"message=None): \"\"\" Increases the user's current score by the `value`. Optionally display a",
"in a convenient way. Uses a global report object (MAIN_REPORT). \"\"\" __all__ =",
"\"\"\" Imperative style commands for constructing feedback in a convenient way. Uses a",
"potentially on a specific line of code. Args: message (str): The message to",
"label) def log(message): MAIN_REPORT.log(message) def debug(message): MAIN_REPORT.debug(message) def clear_report(): MAIN_REPORT.clear() def get_all_feedback(): return",
"(MAIN_REPORT). \"\"\" __all__ = ['set_success', 'compliment', 'give_partial', 'explain', 'gently', 'hide_correctness', 'suppress', 'log', 'debug',",
"MAIN_REPORT.set_success() def compliment(message, line=None): \"\"\" Create a positive feedback for the user, potentially",
"Report. #: Of course, all APIs are expected to work with a given",
"compliment(message, line=None): \"\"\" Create a positive feedback for the user, potentially on a",
"to the user. \"\"\" MAIN_REPORT.give_partial(value, message) def explain(message, priority='medium', line=None, label='explain'): MAIN_REPORT.explain(message, priority,",
"relevant line of code to reference. \"\"\" MAIN_REPORT.compliment(message, line) def give_partial(value, message=None): \"\"\"",
"a positive message too. Args: value (number): The number to increase the user's",
"\"\"\" MAIN_REPORT.give_partial(value, message) def explain(message, priority='medium', line=None, label='explain'): MAIN_REPORT.explain(message, priority, line, label=label) def",
"a specific line of code. Args: message (str): The message to display to",
"The message to display to the user. line (int): The relevant line of",
"no others are given. MAIN_REPORT = Report() def set_success(): \"\"\" Creates Successful feedback",
"the user, potentially on a specific line of code. Args: message (str): The",
"\"\"\" Creates Successful feedback for the user, indicating that the entire assignment is",
"to display to the user. \"\"\" MAIN_REPORT.give_partial(value, message) def explain(message, priority='medium', line=None, label='explain'):",
"course, all APIs are expected to work with a given Report, and only",
"all APIs are expected to work with a given Report, and only #:",
"way. Uses a global report object (MAIN_REPORT). \"\"\" __all__ = ['set_success', 'compliment', 'give_partial',",
"display to the user. \"\"\" MAIN_REPORT.give_partial(value, message) def explain(message, priority='medium', line=None, label='explain'): MAIN_REPORT.explain(message,",
"label=label) def hide_correctness(): MAIN_REPORT.hide_correctness() def suppress(category, label=True): MAIN_REPORT.suppress(category, label) def log(message): MAIN_REPORT.log(message) def",
"singleton #: for any tool, so that instructors do not have to create",
"create their own Report. #: Of course, all APIs are expected to work",
"\"\"\" MAIN_REPORT.compliment(message, line) def give_partial(value, message=None): \"\"\" Increases the user's current score by",
"commands for constructing feedback in a convenient way. Uses a global report object",
"line, label=label) def gently(message, line=None, label='explain'): MAIN_REPORT.gently(message, line, label=label) def hide_correctness(): MAIN_REPORT.hide_correctness() def",
"\"\"\" Create a positive feedback for the user, potentially on a specific line",
"for constructing feedback in a convenient way. Uses a global report object (MAIN_REPORT).",
"from pedal.report.report import Report #: The global Report object. Meant to be used",
"__all__ = ['set_success', 'compliment', 'give_partial', 'explain', 'gently', 'hide_correctness', 'suppress', 'log', 'debug', 'clear_report', 'get_all_feedback',",
"line=None): \"\"\" Create a positive feedback for the user, potentially on a specific",
"The relevant line of code to reference. \"\"\" MAIN_REPORT.compliment(message, line) def give_partial(value, message=None):",
"user's score by. message (str): The message to display to the user. \"\"\"",
"explain(message, priority='medium', line=None, label='explain'): MAIN_REPORT.explain(message, priority, line, label=label) def gently(message, line=None, label='explain'): MAIN_REPORT.gently(message,",
"MAIN_REPORT.gently(message, line, label=label) def hide_correctness(): MAIN_REPORT.hide_correctness() def suppress(category, label=True): MAIN_REPORT.suppress(category, label) def log(message):",
"suppress(category, label=True): MAIN_REPORT.suppress(category, label) def log(message): MAIN_REPORT.log(message) def debug(message): MAIN_REPORT.debug(message) def clear_report(): MAIN_REPORT.clear()",
"positive feedback for the user, potentially on a specific line of code. Args:",
"Report, and only #: default to this Report when no others are given.",
"(int): The relevant line of code to reference. \"\"\" MAIN_REPORT.compliment(message, line) def give_partial(value,",
"reference. \"\"\" MAIN_REPORT.compliment(message, line) def give_partial(value, message=None): \"\"\" Increases the user's current score",
"'log', 'debug', 'clear_report', 'get_all_feedback', 'MAIN_REPORT'] from pedal.report.report import Report #: The global Report",
"line, label=label) def hide_correctness(): MAIN_REPORT.hide_correctness() def suppress(category, label=True): MAIN_REPORT.suppress(category, label) def log(message): MAIN_REPORT.log(message)",
"that instructors do not have to create their own Report. #: Of course,",
"style commands for constructing feedback in a convenient way. Uses a global report",
"Increases the user's current score by the `value`. Optionally display a positive message",
"def explain(message, priority='medium', line=None, label='explain'): MAIN_REPORT.explain(message, priority, line, label=label) def gently(message, line=None, label='explain'):",
"Report #: The global Report object. Meant to be used as a default",
"to the user. line (int): The relevant line of code to reference. \"\"\"",
"global report object (MAIN_REPORT). \"\"\" __all__ = ['set_success', 'compliment', 'give_partial', 'explain', 'gently', 'hide_correctness',",
"= ['set_success', 'compliment', 'give_partial', 'explain', 'gently', 'hide_correctness', 'suppress', 'log', 'debug', 'clear_report', 'get_all_feedback', 'MAIN_REPORT']",
"entire assignment is done. \"\"\" MAIN_REPORT.set_success() def compliment(message, line=None): \"\"\" Create a positive",
"MAIN_REPORT.compliment(message, line) def give_partial(value, message=None): \"\"\" Increases the user's current score by the",
"line=None, label='explain'): MAIN_REPORT.gently(message, line, label=label) def hide_correctness(): MAIN_REPORT.hide_correctness() def suppress(category, label=True): MAIN_REPORT.suppress(category, label)",
"label='explain'): MAIN_REPORT.gently(message, line, label=label) def hide_correctness(): MAIN_REPORT.hide_correctness() def suppress(category, label=True): MAIN_REPORT.suppress(category, label) def",
"user, potentially on a specific line of code. Args: message (str): The message",
"\"\"\" Increases the user's current score by the `value`. Optionally display a positive",
"#: for any tool, so that instructors do not have to create their",
"Report object. Meant to be used as a default singleton #: for any",
"of code. Args: message (str): The message to display to the user. line",
"priority='medium', line=None, label='explain'): MAIN_REPORT.explain(message, priority, line, label=label) def gently(message, line=None, label='explain'): MAIN_REPORT.gently(message, line,",
"label='explain'): MAIN_REPORT.explain(message, priority, line, label=label) def gently(message, line=None, label='explain'): MAIN_REPORT.gently(message, line, label=label) def",
"their own Report. #: Of course, all APIs are expected to work with",
"so that instructors do not have to create their own Report. #: Of",
"'debug', 'clear_report', 'get_all_feedback', 'MAIN_REPORT'] from pedal.report.report import Report #: The global Report object.",
"to increase the user's score by. message (str): The message to display to",
"number to increase the user's score by. message (str): The message to display",
"def suppress(category, label=True): MAIN_REPORT.suppress(category, label) def log(message): MAIN_REPORT.log(message) def debug(message): MAIN_REPORT.debug(message) def clear_report():",
"object (MAIN_REPORT). \"\"\" __all__ = ['set_success', 'compliment', 'give_partial', 'explain', 'gently', 'hide_correctness', 'suppress', 'log',",
"not have to create their own Report. #: Of course, all APIs are",
"global Report object. Meant to be used as a default singleton #: for",
"done. \"\"\" MAIN_REPORT.set_success() def compliment(message, line=None): \"\"\" Create a positive feedback for the",
"code. Args: message (str): The message to display to the user. line (int):",
"feedback for the user, indicating that the entire assignment is done. \"\"\" MAIN_REPORT.set_success()",
"Report() def set_success(): \"\"\" Creates Successful feedback for the user, indicating that the",
"for any tool, so that instructors do not have to create their own",
"value (number): The number to increase the user's score by. message (str): The",
"the entire assignment is done. \"\"\" MAIN_REPORT.set_success() def compliment(message, line=None): \"\"\" Create a",
"are expected to work with a given Report, and only #: default to",
"give_partial(value, message=None): \"\"\" Increases the user's current score by the `value`. Optionally display",
"constructing feedback in a convenient way. Uses a global report object (MAIN_REPORT). \"\"\"",
"line of code. Args: message (str): The message to display to the user.",
"the `value`. Optionally display a positive message too. Args: value (number): The number",
"The message to display to the user. \"\"\" MAIN_REPORT.give_partial(value, message) def explain(message, priority='medium',",
"a convenient way. Uses a global report object (MAIN_REPORT). \"\"\" __all__ = ['set_success',",
"code to reference. \"\"\" MAIN_REPORT.compliment(message, line) def give_partial(value, message=None): \"\"\" Increases the user's",
"positive message too. Args: value (number): The number to increase the user's score",
"def gently(message, line=None, label='explain'): MAIN_REPORT.gently(message, line, label=label) def hide_correctness(): MAIN_REPORT.hide_correctness() def suppress(category, label=True):",
"\"\"\" MAIN_REPORT.set_success() def compliment(message, line=None): \"\"\" Create a positive feedback for the user,",
"default to this Report when no others are given. MAIN_REPORT = Report() def",
"(number): The number to increase the user's score by. message (str): The message",
"this Report when no others are given. MAIN_REPORT = Report() def set_success(): \"\"\"",
"(str): The message to display to the user. \"\"\" MAIN_REPORT.give_partial(value, message) def explain(message,",
"APIs are expected to work with a given Report, and only #: default",
"'give_partial', 'explain', 'gently', 'hide_correctness', 'suppress', 'log', 'debug', 'clear_report', 'get_all_feedback', 'MAIN_REPORT'] from pedal.report.report import",
"<filename>src/lib/pedal/report/imperative.py<gh_stars>1-10 \"\"\" Imperative style commands for constructing feedback in a convenient way. Uses",
"'MAIN_REPORT'] from pedal.report.report import Report #: The global Report object. Meant to be",
"of code to reference. \"\"\" MAIN_REPORT.compliment(message, line) def give_partial(value, message=None): \"\"\" Increases the",
"hide_correctness(): MAIN_REPORT.hide_correctness() def suppress(category, label=True): MAIN_REPORT.suppress(category, label) def log(message): MAIN_REPORT.log(message) def debug(message): MAIN_REPORT.debug(message)",
"#: default to this Report when no others are given. MAIN_REPORT = Report()",
"be used as a default singleton #: for any tool, so that instructors",
"to reference. \"\"\" MAIN_REPORT.compliment(message, line) def give_partial(value, message=None): \"\"\" Increases the user's current",
"def hide_correctness(): MAIN_REPORT.hide_correctness() def suppress(category, label=True): MAIN_REPORT.suppress(category, label) def log(message): MAIN_REPORT.log(message) def debug(message):",
"Optionally display a positive message too. Args: value (number): The number to increase",
"a positive feedback for the user, potentially on a specific line of code.",
"others are given. MAIN_REPORT = Report() def set_success(): \"\"\" Creates Successful feedback for",
"object. Meant to be used as a default singleton #: for any tool,",
"too. Args: value (number): The number to increase the user's score by. message",
"message (str): The message to display to the user. \"\"\" MAIN_REPORT.give_partial(value, message) def",
"used as a default singleton #: for any tool, so that instructors do",
"'hide_correctness', 'suppress', 'log', 'debug', 'clear_report', 'get_all_feedback', 'MAIN_REPORT'] from pedal.report.report import Report #: The",
"message to display to the user. line (int): The relevant line of code",
"Imperative style commands for constructing feedback in a convenient way. Uses a global",
"label=True): MAIN_REPORT.suppress(category, label) def log(message): MAIN_REPORT.log(message) def debug(message): MAIN_REPORT.debug(message) def clear_report(): MAIN_REPORT.clear() def",
"The global Report object. Meant to be used as a default singleton #:",
"def log(message): MAIN_REPORT.log(message) def debug(message): MAIN_REPORT.debug(message) def clear_report(): MAIN_REPORT.clear() def get_all_feedback(): return MAIN_REPORT.feedback",
"Successful feedback for the user, indicating that the entire assignment is done. \"\"\"",
"the user, indicating that the entire assignment is done. \"\"\" MAIN_REPORT.set_success() def compliment(message,",
"score by. message (str): The message to display to the user. \"\"\" MAIN_REPORT.give_partial(value,",
"Creates Successful feedback for the user, indicating that the entire assignment is done.",
"the user. line (int): The relevant line of code to reference. \"\"\" MAIN_REPORT.compliment(message,",
"is done. \"\"\" MAIN_REPORT.set_success() def compliment(message, line=None): \"\"\" Create a positive feedback for",
"line) def give_partial(value, message=None): \"\"\" Increases the user's current score by the `value`.",
"['set_success', 'compliment', 'give_partial', 'explain', 'gently', 'hide_correctness', 'suppress', 'log', 'debug', 'clear_report', 'get_all_feedback', 'MAIN_REPORT'] from",
"#: The global Report object. Meant to be used as a default singleton",
"def give_partial(value, message=None): \"\"\" Increases the user's current score by the `value`. Optionally",
"the user. \"\"\" MAIN_REPORT.give_partial(value, message) def explain(message, priority='medium', line=None, label='explain'): MAIN_REPORT.explain(message, priority, line,",
"def set_success(): \"\"\" Creates Successful feedback for the user, indicating that the entire",
"any tool, so that instructors do not have to create their own Report.",
"current score by the `value`. Optionally display a positive message too. Args: value",
"'gently', 'hide_correctness', 'suppress', 'log', 'debug', 'clear_report', 'get_all_feedback', 'MAIN_REPORT'] from pedal.report.report import Report #:",
"increase the user's score by. message (str): The message to display to the",
"display to the user. line (int): The relevant line of code to reference.",
"specific line of code. Args: message (str): The message to display to the",
"Report when no others are given. MAIN_REPORT = Report() def set_success(): \"\"\" Creates",
"MAIN_REPORT.suppress(category, label) def log(message): MAIN_REPORT.log(message) def debug(message): MAIN_REPORT.debug(message) def clear_report(): MAIN_REPORT.clear() def get_all_feedback():",
"Of course, all APIs are expected to work with a given Report, and",
"Uses a global report object (MAIN_REPORT). \"\"\" __all__ = ['set_success', 'compliment', 'give_partial', 'explain',",
"MAIN_REPORT.give_partial(value, message) def explain(message, priority='medium', line=None, label='explain'): MAIN_REPORT.explain(message, priority, line, label=label) def gently(message,",
"set_success(): \"\"\" Creates Successful feedback for the user, indicating that the entire assignment",
"priority, line, label=label) def gently(message, line=None, label='explain'): MAIN_REPORT.gently(message, line, label=label) def hide_correctness(): MAIN_REPORT.hide_correctness()",
"with a given Report, and only #: default to this Report when no",
"(str): The message to display to the user. line (int): The relevant line",
"user. line (int): The relevant line of code to reference. \"\"\" MAIN_REPORT.compliment(message, line)",
"message) def explain(message, priority='medium', line=None, label='explain'): MAIN_REPORT.explain(message, priority, line, label=label) def gently(message, line=None,",
"when no others are given. MAIN_REPORT = Report() def set_success(): \"\"\" Creates Successful",
"display a positive message too. Args: value (number): The number to increase the",
"MAIN_REPORT.hide_correctness() def suppress(category, label=True): MAIN_REPORT.suppress(category, label) def log(message): MAIN_REPORT.log(message) def debug(message): MAIN_REPORT.debug(message) def",
"import Report #: The global Report object. Meant to be used as a",
"label=label) def gently(message, line=None, label='explain'): MAIN_REPORT.gently(message, line, label=label) def hide_correctness(): MAIN_REPORT.hide_correctness() def suppress(category,",
"the user's current score by the `value`. Optionally display a positive message too.",
"The number to increase the user's score by. message (str): The message to",
"instructors do not have to create their own Report. #: Of course, all",
"Create a positive feedback for the user, potentially on a specific line of",
"to display to the user. line (int): The relevant line of code to",
"convenient way. Uses a global report object (MAIN_REPORT). \"\"\" __all__ = ['set_success', 'compliment',",
"have to create their own Report. #: Of course, all APIs are expected",
"'compliment', 'give_partial', 'explain', 'gently', 'hide_correctness', 'suppress', 'log', 'debug', 'clear_report', 'get_all_feedback', 'MAIN_REPORT'] from pedal.report.report"
] |
[
"ANNOTATIONS AND FULL PATH TO THE PIPELINE BASE DIRECTORY (do not change) path_genome",
"path_star = \"/usr/local/bin/STAR\" path_htseq = \"/usr/bin/htseq-count\" path_samtools = \"/usr/local/bin/samtools\" path_cutadapt = \"/usr/local/bin/cutadapt\" #",
"--alignIntronMin 20 --alignIntronMax 1000000 --alignMatesGapMax 1000000\"} # ENVIRONMENT VARIABLES: # The following system",
"\"/usr/local/bin/samtools\" path_cutadapt = \"/usr/local/bin/cutadapt\" # STAR options (users can add their own options):",
"to add or overwrite # their current values. environment = {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\":",
"by aRNApipe in their system). path_trimgalore = \"/usr/local/bin/trim_galore\" path_bowtie2 = \"/usr/local/bin/bowtie2\" path_fastqc =",
"of this dict are used in the project config files to use the",
"\"/genomes_processed/#LABEL/genesets.gtf\" path_fasta = path_db + \"/genomes_processed/#LABEL/genome.fa\" annots = [path_db + \"/genomes_processed/#LABEL/genesets.refFlat\", path_db +",
"= \"/usr/local/bin/samtools\" path_cutadapt = \"/usr/local/bin/cutadapt\" # STAR options (users can add their own",
"# The following system environment variables are changed to add or overwrite #",
"# -*- coding: utf-8 -*- import sys import os # LIBRARY USED TO",
"AND FULL PATH TO THE PIPELINE BASE DIRECTORY (do not change) path_genome =",
"FOR IBM LSF WORKLOAD MANAGER (it uses 'sys_LSF.py') # - 'LOCAL' FOR SEQUENTIAL",
"SUBMIT JOBS: # - 'LSF' FOR IBM LSF WORKLOAD MANAGER (it uses 'sys_LSF.py')",
"\"/genomes_processed/#LABEL/STAR_genome\" path_annotation = path_db + \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta = path_db + \"/genomes_processed/#LABEL/genome.fa\" annots =",
"= path_db + \"/genomes_processed/#LABEL/genome.fa\" annots = [path_db + \"/genomes_processed/#LABEL/genesets.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/protein_coding.refFlat\", path_db",
"\"/usr/local/bin/cutadapt\" # STAR options (users can add their own options): # The keys",
"\"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS AND FULL PATH TO THE PIPELINE BASE DIRECTORY",
"FOLDER \"genomes_processed\" WHERE THE DIFFERENT GENOME BUILDS ARE STORED path_db = \"/share/\" path_code",
"changed to add or overwrite # their current values. environment = {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"],",
"used by aRNApipe in their system). path_trimgalore = \"/usr/local/bin/trim_galore\" path_bowtie2 = \"/usr/local/bin/bowtie2\" path_fastqc",
"OTHER WORKLOAD MANAGERS (it uses 'sys_OTHER.py') mode = \"OTHER\" # PATH TO THE",
"- 'LOCAL' FOR SEQUENTIAL RUN ON SINGLE MACHINE (it uses 'sys_single.py') # -",
"(it uses 'sys_single.py') # - 'OTHER' FOR LIBRARIES ADAPTED TO OTHER WORKLOAD MANAGERS",
"add their own options): # The keys of this dict are used in",
"STAR arguments within the corresponding dictionary values star_options = {\"default\": \"\", \"encode\": \"--outFilterType",
"LIBRARY USED TO SUBMIT JOBS: # - 'LSF' FOR IBM LSF WORKLOAD MANAGER",
"LIBRARIES ADAPTED TO OTHER WORKLOAD MANAGERS (it uses 'sys_OTHER.py') mode = \"OTHER\" #",
"options (users can add their own options): # The keys of this dict",
"20 --alignSJoverhangMin 8 --alignSJDBoverhangMin 1 --outFilterMismatchNmax 999 --outFilterMismatchNoverLmax 0.04 --alignIntronMin 20 --alignIntronMax 1000000",
"environment variables are changed to add or overwrite # their current values. environment",
"\"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} #",
"FULL PATH TO THE PIPELINE BASE DIRECTORY (do not change) path_genome = path_db",
"'sys_single.py') # - 'OTHER' FOR LIBRARIES ADAPTED TO OTHER WORKLOAD MANAGERS (it uses",
"The keys of this dict are used in the project config files to",
"to match # the current locations of the binaries used by aRNApipe in",
"files to use the # referenced STAR arguments within the corresponding dictionary values",
"MANAGER (it uses 'sys_LSF.py') # - 'LOCAL' FOR SEQUENTIAL RUN ON SINGLE MACHINE",
"-*- coding: utf-8 -*- import sys import os # LIBRARY USED TO SUBMIT",
"= path_db + \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta = path_db + \"/genomes_processed/#LABEL/genome.fa\" annots = [path_db +",
"\"/usr/local/FastQC/fastqc\" path_star = \"/usr/local/bin/STAR\" path_htseq = \"/usr/bin/htseq-count\" path_samtools = \"/usr/local/bin/samtools\" path_cutadapt = \"/usr/local/bin/cutadapt\"",
"\"/share/code/\" # FULL PATHS TO BINARIES USED BY aRNApipe (users must change these",
"can add their own options): # The keys of this dict are used",
"uses 'sys_OTHER.py') mode = \"OTHER\" # PATH TO THE FOLDER \"genomes_processed\" WHERE THE",
"the corresponding dictionary values star_options = {\"default\": \"\", \"encode\": \"--outFilterType BySJout --outFilterMultimapNmax 20",
"THE PIPELINE BASE DIRECTORY (do not change) path_genome = path_db + \"/genomes_processed/#LABEL/STAR_genome\" path_annotation",
"corresponding dictionary values star_options = {\"default\": \"\", \"encode\": \"--outFilterType BySJout --outFilterMultimapNmax 20 --alignSJoverhangMin",
"mode = \"OTHER\" # PATH TO THE FOLDER \"genomes_processed\" WHERE THE DIFFERENT GENOME",
"# LIBRARY USED TO SUBMIT JOBS: # - 'LSF' FOR IBM LSF WORKLOAD",
"(it uses 'sys_OTHER.py') mode = \"OTHER\" # PATH TO THE FOLDER \"genomes_processed\" WHERE",
"= \"/usr/local/bin/bowtie2\" path_fastqc = \"/usr/local/FastQC/fastqc\" path_star = \"/usr/local/bin/STAR\" path_htseq = \"/usr/bin/htseq-count\" path_samtools =",
"binaries used by aRNApipe in their system). path_trimgalore = \"/usr/local/bin/trim_galore\" path_bowtie2 = \"/usr/local/bin/bowtie2\"",
":[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS AND FULL PATH TO THE PIPELINE BASE DIRECTORY (do not",
"\"/usr/bin/htseq-count\" path_samtools = \"/usr/local/bin/samtools\" path_cutadapt = \"/usr/local/bin/cutadapt\" # STAR options (users can add",
"JOBS: # - 'LSF' FOR IBM LSF WORKLOAD MANAGER (it uses 'sys_LSF.py') #",
"'OTHER' FOR LIBRARIES ADAPTED TO OTHER WORKLOAD MANAGERS (it uses 'sys_OTHER.py') mode =",
"their own options): # The keys of this dict are used in the",
"WHERE THE DIFFERENT GENOME BUILDS ARE STORED path_db = \"/share/\" path_code = \"/share/code/\"",
"path_htseq = \"/usr/bin/htseq-count\" path_samtools = \"/usr/local/bin/samtools\" path_cutadapt = \"/usr/local/bin/cutadapt\" # STAR options (users",
"\"\", \"encode\": \"--outFilterType BySJout --outFilterMultimapNmax 20 --alignSJoverhangMin 8 --alignSJDBoverhangMin 1 --outFilterMismatchNmax 999 --outFilterMismatchNoverLmax",
"BySJout --outFilterMultimapNmax 20 --alignSJoverhangMin 8 --alignSJDBoverhangMin 1 --outFilterMismatchNmax 999 --outFilterMismatchNoverLmax 0.04 --alignIntronMin 20",
"values. environment = {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"],",
"in their system). path_trimgalore = \"/usr/local/bin/trim_galore\" path_bowtie2 = \"/usr/local/bin/bowtie2\" path_fastqc = \"/usr/local/FastQC/fastqc\" path_star",
"# \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]}",
"1000000\"} # ENVIRONMENT VARIABLES: # The following system environment variables are changed to",
"RUN ON SINGLE MACHINE (it uses 'sys_single.py') # - 'OTHER' FOR LIBRARIES ADAPTED",
"TO BINARIES USED BY aRNApipe (users must change these values to match #",
"these values to match # the current locations of the binaries used by",
"MACHINE (it uses 'sys_single.py') # - 'OTHER' FOR LIBRARIES ADAPTED TO OTHER WORKLOAD",
"ARE STORED path_db = \"/share/\" path_code = \"/share/code/\" # FULL PATHS TO BINARIES",
"--alignSJoverhangMin 8 --alignSJDBoverhangMin 1 --outFilterMismatchNmax 999 --outFilterMismatchNoverLmax 0.04 --alignIntronMin 20 --alignIntronMax 1000000 --alignMatesGapMax",
"must change these values to match # the current locations of the binaries",
"TO THE PIPELINE BASE DIRECTORY (do not change) path_genome = path_db + \"/genomes_processed/#LABEL/STAR_genome\"",
"path_db + \"/genomes_processed/#LABEL/genome.fa\" annots = [path_db + \"/genomes_processed/#LABEL/genesets.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/protein_coding.refFlat\", path_db +",
"variables are changed to add or overwrite # their current values. environment =",
"path_trimgalore = \"/usr/local/bin/trim_galore\" path_bowtie2 = \"/usr/local/bin/bowtie2\" path_fastqc = \"/usr/local/FastQC/fastqc\" path_star = \"/usr/local/bin/STAR\" path_htseq",
"\"encode\": \"--outFilterType BySJout --outFilterMultimapNmax 20 --alignSJoverhangMin 8 --alignSJDBoverhangMin 1 --outFilterMismatchNmax 999 --outFilterMismatchNoverLmax 0.04",
"= \"/usr/local/bin/cutadapt\" # STAR options (users can add their own options): # The",
"TO OTHER WORKLOAD MANAGERS (it uses 'sys_OTHER.py') mode = \"OTHER\" # PATH TO",
"use the # referenced STAR arguments within the corresponding dictionary values star_options =",
"in the project config files to use the # referenced STAR arguments within",
"annots = [path_db + \"/genomes_processed/#LABEL/genesets.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/protein_coding.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/rRNA.refFlat\"] nannots =",
"\"genomes_processed\" WHERE THE DIFFERENT GENOME BUILDS ARE STORED path_db = \"/share/\" path_code =",
"FOR SEQUENTIAL RUN ON SINGLE MACHINE (it uses 'sys_single.py') # - 'OTHER' FOR",
"GENOME BUILDS ARE STORED path_db = \"/share/\" path_code = \"/share/code/\" # FULL PATHS",
"current locations of the binaries used by aRNApipe in their system). path_trimgalore =",
"# - 'OTHER' FOR LIBRARIES ADAPTED TO OTHER WORKLOAD MANAGERS (it uses 'sys_OTHER.py')",
"= {\"default\": \"\", \"encode\": \"--outFilterType BySJout --outFilterMultimapNmax 20 --alignSJoverhangMin 8 --alignSJDBoverhangMin 1 --outFilterMismatchNmax",
"# the current locations of the binaries used by aRNApipe in their system).",
"999 --outFilterMismatchNoverLmax 0.04 --alignIntronMin 20 --alignIntronMax 1000000 --alignMatesGapMax 1000000\"} # ENVIRONMENT VARIABLES: #",
"FOR LIBRARIES ADAPTED TO OTHER WORKLOAD MANAGERS (it uses 'sys_OTHER.py') mode = \"OTHER\"",
"# STAR options (users can add their own options): # The keys of",
"[\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS AND FULL PATH TO THE PIPELINE",
"DIRECTORY (do not change) path_genome = path_db + \"/genomes_processed/#LABEL/STAR_genome\" path_annotation = path_db +",
"USED TO SUBMIT JOBS: # - 'LSF' FOR IBM LSF WORKLOAD MANAGER (it",
"SEQUENTIAL RUN ON SINGLE MACHINE (it uses 'sys_single.py') # - 'OTHER' FOR LIBRARIES",
"system environment variables are changed to add or overwrite # their current values.",
"(users must change these values to match # the current locations of the",
"project config files to use the # referenced STAR arguments within the corresponding",
"BUILDS ARE STORED path_db = \"/share/\" path_code = \"/share/code/\" # FULL PATHS TO",
"the # referenced STAR arguments within the corresponding dictionary values star_options = {\"default\":",
"= {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\":",
"{\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"],",
"\"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS AND FULL PATH TO THE PIPELINE BASE DIRECTORY (do",
"= \"OTHER\" # PATH TO THE FOLDER \"genomes_processed\" WHERE THE DIFFERENT GENOME BUILDS",
"MANAGERS (it uses 'sys_OTHER.py') mode = \"OTHER\" # PATH TO THE FOLDER \"genomes_processed\"",
"# - 'LSF' FOR IBM LSF WORKLOAD MANAGER (it uses 'sys_LSF.py') # -",
"the current locations of the binaries used by aRNApipe in their system). path_trimgalore",
"# The keys of this dict are used in the project config files",
"+ \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta = path_db + \"/genomes_processed/#LABEL/genome.fa\" annots = [path_db + \"/genomes_processed/#LABEL/genesets.refFlat\", path_db",
"aRNApipe in their system). path_trimgalore = \"/usr/local/bin/trim_galore\" path_bowtie2 = \"/usr/local/bin/bowtie2\" path_fastqc = \"/usr/local/FastQC/fastqc\"",
"[\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], #",
"system). path_trimgalore = \"/usr/local/bin/trim_galore\" path_bowtie2 = \"/usr/local/bin/bowtie2\" path_fastqc = \"/usr/local/FastQC/fastqc\" path_star = \"/usr/local/bin/STAR\"",
"# ANNOTATIONS AND FULL PATH TO THE PIPELINE BASE DIRECTORY (do not change)",
"1 --outFilterMismatchNmax 999 --outFilterMismatchNoverLmax 0.04 --alignIntronMin 20 --alignIntronMax 1000000 --alignMatesGapMax 1000000\"} # ENVIRONMENT",
"TO SUBMIT JOBS: # - 'LSF' FOR IBM LSF WORKLOAD MANAGER (it uses",
"= \"/usr/local/bin/STAR\" path_htseq = \"/usr/bin/htseq-count\" path_samtools = \"/usr/local/bin/samtools\" path_cutadapt = \"/usr/local/bin/cutadapt\" # STAR",
"path_genome = path_db + \"/genomes_processed/#LABEL/STAR_genome\" path_annotation = path_db + \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta = path_db",
"ENVIRONMENT VARIABLES: # The following system environment variables are changed to add or",
"import os # LIBRARY USED TO SUBMIT JOBS: # - 'LSF' FOR IBM",
"not change) path_genome = path_db + \"/genomes_processed/#LABEL/STAR_genome\" path_annotation = path_db + \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta",
"are changed to add or overwrite # their current values. environment = {\"JAVA_HOME\":",
"+ \"/genomes_processed/#LABEL/STAR_genome\" path_annotation = path_db + \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta = path_db + \"/genomes_processed/#LABEL/genome.fa\" annots",
"PIPELINE BASE DIRECTORY (do not change) path_genome = path_db + \"/genomes_processed/#LABEL/STAR_genome\" path_annotation =",
"coding: utf-8 -*- import sys import os # LIBRARY USED TO SUBMIT JOBS:",
"this dict are used in the project config files to use the #",
"(do not change) path_genome = path_db + \"/genomes_processed/#LABEL/STAR_genome\" path_annotation = path_db + \"/genomes_processed/#LABEL/genesets.gtf\"",
"arguments within the corresponding dictionary values star_options = {\"default\": \"\", \"encode\": \"--outFilterType BySJout",
"--alignIntronMax 1000000 --alignMatesGapMax 1000000\"} # ENVIRONMENT VARIABLES: # The following system environment variables",
"overwrite # their current values. environment = {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\":",
"environment = {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], #",
"own options): # The keys of this dict are used in the project",
"# their current values. environment = {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"],",
"path_annotation = path_db + \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta = path_db + \"/genomes_processed/#LABEL/genome.fa\" annots = [path_db",
"path_db = \"/share/\" path_code = \"/share/code/\" # FULL PATHS TO BINARIES USED BY",
"LSF WORKLOAD MANAGER (it uses 'sys_LSF.py') # - 'LOCAL' FOR SEQUENTIAL RUN ON",
"'sys_OTHER.py') mode = \"OTHER\" # PATH TO THE FOLDER \"genomes_processed\" WHERE THE DIFFERENT",
"THE FOLDER \"genomes_processed\" WHERE THE DIFFERENT GENOME BUILDS ARE STORED path_db = \"/share/\"",
"keys of this dict are used in the project config files to use",
"import sys import os # LIBRARY USED TO SUBMIT JOBS: # - 'LSF'",
"add or overwrite # their current values. environment = {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"],",
"- 'LSF' FOR IBM LSF WORKLOAD MANAGER (it uses 'sys_LSF.py') # - 'LOCAL'",
"os # LIBRARY USED TO SUBMIT JOBS: # - 'LSF' FOR IBM LSF",
"\"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS AND FULL",
"STORED path_db = \"/share/\" path_code = \"/share/code/\" # FULL PATHS TO BINARIES USED",
"= \"/usr/bin/htseq-count\" path_samtools = \"/usr/local/bin/samtools\" path_cutadapt = \"/usr/local/bin/cutadapt\" # STAR options (users can",
"the project config files to use the # referenced STAR arguments within the",
"IBM LSF WORKLOAD MANAGER (it uses 'sys_LSF.py') # - 'LOCAL' FOR SEQUENTIAL RUN",
"aRNApipe (users must change these values to match # the current locations of",
"# ENVIRONMENT VARIABLES: # The following system environment variables are changed to add",
"path_bowtie2 = \"/usr/local/bin/bowtie2\" path_fastqc = \"/usr/local/FastQC/fastqc\" path_star = \"/usr/local/bin/STAR\" path_htseq = \"/usr/bin/htseq-count\" path_samtools",
"(it uses 'sys_LSF.py') # - 'LOCAL' FOR SEQUENTIAL RUN ON SINGLE MACHINE (it",
"= \"/share/code/\" # FULL PATHS TO BINARIES USED BY aRNApipe (users must change",
"= [path_db + \"/genomes_processed/#LABEL/genesets.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/protein_coding.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/rRNA.refFlat\"] nannots = [\"general\",\"protein_coding\",\"ribosomal\"]",
"'sys_LSF.py') # - 'LOCAL' FOR SEQUENTIAL RUN ON SINGLE MACHINE (it uses 'sys_single.py')",
"to use the # referenced STAR arguments within the corresponding dictionary values star_options",
"\"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS AND FULL PATH TO THE",
"path_db + \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta = path_db + \"/genomes_processed/#LABEL/genome.fa\" annots = [path_db + \"/genomes_processed/#LABEL/genesets.refFlat\",",
"VARIABLES: # The following system environment variables are changed to add or overwrite",
"path_fastqc = \"/usr/local/FastQC/fastqc\" path_star = \"/usr/local/bin/STAR\" path_htseq = \"/usr/bin/htseq-count\" path_samtools = \"/usr/local/bin/samtools\" path_cutadapt",
"(users can add their own options): # The keys of this dict are",
"star_options = {\"default\": \"\", \"encode\": \"--outFilterType BySJout --outFilterMultimapNmax 20 --alignSJoverhangMin 8 --alignSJDBoverhangMin 1",
"uses 'sys_LSF.py') # - 'LOCAL' FOR SEQUENTIAL RUN ON SINGLE MACHINE (it uses",
"PATHS TO BINARIES USED BY aRNApipe (users must change these values to match",
"[\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\"",
"# referenced STAR arguments within the corresponding dictionary values star_options = {\"default\": \"\",",
"WORKLOAD MANAGER (it uses 'sys_LSF.py') # - 'LOCAL' FOR SEQUENTIAL RUN ON SINGLE",
"within the corresponding dictionary values star_options = {\"default\": \"\", \"encode\": \"--outFilterType BySJout --outFilterMultimapNmax",
"ADAPTED TO OTHER WORKLOAD MANAGERS (it uses 'sys_OTHER.py') mode = \"OTHER\" # PATH",
"SINGLE MACHINE (it uses 'sys_single.py') # - 'OTHER' FOR LIBRARIES ADAPTED TO OTHER",
"USED BY aRNApipe (users must change these values to match # the current",
"change) path_genome = path_db + \"/genomes_processed/#LABEL/STAR_genome\" path_annotation = path_db + \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta =",
"0.04 --alignIntronMin 20 --alignIntronMax 1000000 --alignMatesGapMax 1000000\"} # ENVIRONMENT VARIABLES: # The following",
"\"/usr/local/bin/bowtie2\" path_fastqc = \"/usr/local/FastQC/fastqc\" path_star = \"/usr/local/bin/STAR\" path_htseq = \"/usr/bin/htseq-count\" path_samtools = \"/usr/local/bin/samtools\"",
"match # the current locations of the binaries used by aRNApipe in their",
"--alignSJDBoverhangMin 1 --outFilterMismatchNmax 999 --outFilterMismatchNoverLmax 0.04 --alignIntronMin 20 --alignIntronMax 1000000 --alignMatesGapMax 1000000\"} #",
"= \"/usr/local/bin/trim_galore\" path_bowtie2 = \"/usr/local/bin/bowtie2\" path_fastqc = \"/usr/local/FastQC/fastqc\" path_star = \"/usr/local/bin/STAR\" path_htseq =",
"20 --alignIntronMax 1000000 --alignMatesGapMax 1000000\"} # ENVIRONMENT VARIABLES: # The following system environment",
"or overwrite # their current values. environment = {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], #",
"uses 'sys_single.py') # - 'OTHER' FOR LIBRARIES ADAPTED TO OTHER WORKLOAD MANAGERS (it",
"referenced STAR arguments within the corresponding dictionary values star_options = {\"default\": \"\", \"encode\":",
"--outFilterMismatchNoverLmax 0.04 --alignIntronMin 20 --alignIntronMax 1000000 --alignMatesGapMax 1000000\"} # ENVIRONMENT VARIABLES: # The",
"'LOCAL' FOR SEQUENTIAL RUN ON SINGLE MACHINE (it uses 'sys_single.py') # - 'OTHER'",
"\"/usr/local/bin/trim_galore\" path_bowtie2 = \"/usr/local/bin/bowtie2\" path_fastqc = \"/usr/local/FastQC/fastqc\" path_star = \"/usr/local/bin/STAR\" path_htseq = \"/usr/bin/htseq-count\"",
"--outFilterMultimapNmax 20 --alignSJoverhangMin 8 --alignSJDBoverhangMin 1 --outFilterMismatchNmax 999 --outFilterMismatchNoverLmax 0.04 --alignIntronMin 20 --alignIntronMax",
"change these values to match # the current locations of the binaries used",
"\"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"],",
"path_code = \"/share/code/\" # FULL PATHS TO BINARIES USED BY aRNApipe (users must",
"values to match # the current locations of the binaries used by aRNApipe",
"PATH TO THE FOLDER \"genomes_processed\" WHERE THE DIFFERENT GENOME BUILDS ARE STORED path_db",
"current values. environment = {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\":",
"locations of the binaries used by aRNApipe in their system). path_trimgalore = \"/usr/local/bin/trim_galore\"",
"+ \"/genomes_processed/#LABEL/genome.fa\" annots = [path_db + \"/genomes_processed/#LABEL/genesets.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/protein_coding.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/rRNA.refFlat\"]",
"# PATH TO THE FOLDER \"genomes_processed\" WHERE THE DIFFERENT GENOME BUILDS ARE STORED",
"'LSF' FOR IBM LSF WORKLOAD MANAGER (it uses 'sys_LSF.py') # - 'LOCAL' FOR",
"the binaries used by aRNApipe in their system). path_trimgalore = \"/usr/local/bin/trim_galore\" path_bowtie2 =",
"their system). path_trimgalore = \"/usr/local/bin/trim_galore\" path_bowtie2 = \"/usr/local/bin/bowtie2\" path_fastqc = \"/usr/local/FastQC/fastqc\" path_star =",
"1000000 --alignMatesGapMax 1000000\"} # ENVIRONMENT VARIABLES: # The following system environment variables are",
"\"/genomes_processed/#LABEL/genome.fa\" annots = [path_db + \"/genomes_processed/#LABEL/genesets.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/protein_coding.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/rRNA.refFlat\"] nannots",
"BASE DIRECTORY (do not change) path_genome = path_db + \"/genomes_processed/#LABEL/STAR_genome\" path_annotation = path_db",
"config files to use the # referenced STAR arguments within the corresponding dictionary",
"values star_options = {\"default\": \"\", \"encode\": \"--outFilterType BySJout --outFilterMultimapNmax 20 --alignSJoverhangMin 8 --alignSJDBoverhangMin",
"path_samtools = \"/usr/local/bin/samtools\" path_cutadapt = \"/usr/local/bin/cutadapt\" # STAR options (users can add their",
"BY aRNApipe (users must change these values to match # the current locations",
"FULL PATHS TO BINARIES USED BY aRNApipe (users must change these values to",
"path_fasta = path_db + \"/genomes_processed/#LABEL/genome.fa\" annots = [path_db + \"/genomes_processed/#LABEL/genesets.refFlat\", path_db + \"/genomes_processed/#LABEL/refFlats/protein_coding.refFlat\",",
"\"/share/\" path_code = \"/share/code/\" # FULL PATHS TO BINARIES USED BY aRNApipe (users",
"[\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS AND FULL PATH",
"STAR options (users can add their own options): # The keys of this",
"= \"/usr/local/FastQC/fastqc\" path_star = \"/usr/local/bin/STAR\" path_htseq = \"/usr/bin/htseq-count\" path_samtools = \"/usr/local/bin/samtools\" path_cutadapt =",
"[\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS",
"are used in the project config files to use the # referenced STAR",
"--alignMatesGapMax 1000000\"} # ENVIRONMENT VARIABLES: # The following system environment variables are changed",
"their current values. environment = {\"JAVA_HOME\": [\"/usr/java/jdk1.8.0_60/\",\"add\"], \"PYTHONPATH\": [\"/usr/lib64/python2.7/site-packages\",\"overwrite\"], # \"PATH\": [\"/gpfs/gpfs1/software/Python-2.7.2/bin\",\"add\"], #",
"= \"/share/\" path_code = \"/share/code/\" # FULL PATHS TO BINARIES USED BY aRNApipe",
"THE DIFFERENT GENOME BUILDS ARE STORED path_db = \"/share/\" path_code = \"/share/code/\" #",
"8 --alignSJDBoverhangMin 1 --outFilterMismatchNmax 999 --outFilterMismatchNoverLmax 0.04 --alignIntronMin 20 --alignIntronMax 1000000 --alignMatesGapMax 1000000\"}",
"{\"default\": \"\", \"encode\": \"--outFilterType BySJout --outFilterMultimapNmax 20 --alignSJoverhangMin 8 --alignSJDBoverhangMin 1 --outFilterMismatchNmax 999",
"# \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS AND FULL PATH TO THE PIPELINE BASE",
"sys import os # LIBRARY USED TO SUBMIT JOBS: # - 'LSF' FOR",
"\"OTHER\" # PATH TO THE FOLDER \"genomes_processed\" WHERE THE DIFFERENT GENOME BUILDS ARE",
"# \"PATH\": [\"/gpfs/gpfs1/software/bedtools2-2.20.0/bin\",\"add\"], # \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS AND",
"BINARIES USED BY aRNApipe (users must change these values to match # the",
"# - 'LOCAL' FOR SEQUENTIAL RUN ON SINGLE MACHINE (it uses 'sys_single.py') #",
"ON SINGLE MACHINE (it uses 'sys_single.py') # - 'OTHER' FOR LIBRARIES ADAPTED TO",
"DIFFERENT GENOME BUILDS ARE STORED path_db = \"/share/\" path_code = \"/share/code/\" # FULL",
"# \"PATH\": [\"/gpfs/gpfs1/software/samtools-1.2/bin\",\"add\"], # \"LD_LIBRARY_PATH\":[\"/gpfs/gpfs1/software/gcc-4.8.2/usr/lib64\",\"add\"], \"PERL5LIB\" :[\"/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1:/gpfs/gpfs1/software/perl-modules/lib/perl5/5.10.1/lib64/perl5\",\"add\"]} # ANNOTATIONS AND FULL PATH TO",
"utf-8 -*- import sys import os # LIBRARY USED TO SUBMIT JOBS: #",
"- 'OTHER' FOR LIBRARIES ADAPTED TO OTHER WORKLOAD MANAGERS (it uses 'sys_OTHER.py') mode",
"-*- import sys import os # LIBRARY USED TO SUBMIT JOBS: # -",
"of the binaries used by aRNApipe in their system). path_trimgalore = \"/usr/local/bin/trim_galore\" path_bowtie2",
"used in the project config files to use the # referenced STAR arguments",
"following system environment variables are changed to add or overwrite # their current",
"\"/usr/local/bin/STAR\" path_htseq = \"/usr/bin/htseq-count\" path_samtools = \"/usr/local/bin/samtools\" path_cutadapt = \"/usr/local/bin/cutadapt\" # STAR options",
"\"--outFilterType BySJout --outFilterMultimapNmax 20 --alignSJoverhangMin 8 --alignSJDBoverhangMin 1 --outFilterMismatchNmax 999 --outFilterMismatchNoverLmax 0.04 --alignIntronMin",
"options): # The keys of this dict are used in the project config",
"dictionary values star_options = {\"default\": \"\", \"encode\": \"--outFilterType BySJout --outFilterMultimapNmax 20 --alignSJoverhangMin 8",
"WORKLOAD MANAGERS (it uses 'sys_OTHER.py') mode = \"OTHER\" # PATH TO THE FOLDER",
"# FULL PATHS TO BINARIES USED BY aRNApipe (users must change these values",
"path_cutadapt = \"/usr/local/bin/cutadapt\" # STAR options (users can add their own options): #",
"The following system environment variables are changed to add or overwrite # their",
"PATH TO THE PIPELINE BASE DIRECTORY (do not change) path_genome = path_db +",
"dict are used in the project config files to use the # referenced",
"TO THE FOLDER \"genomes_processed\" WHERE THE DIFFERENT GENOME BUILDS ARE STORED path_db =",
"= path_db + \"/genomes_processed/#LABEL/STAR_genome\" path_annotation = path_db + \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta = path_db +",
"--outFilterMismatchNmax 999 --outFilterMismatchNoverLmax 0.04 --alignIntronMin 20 --alignIntronMax 1000000 --alignMatesGapMax 1000000\"} # ENVIRONMENT VARIABLES:",
"path_db + \"/genomes_processed/#LABEL/STAR_genome\" path_annotation = path_db + \"/genomes_processed/#LABEL/genesets.gtf\" path_fasta = path_db + \"/genomes_processed/#LABEL/genome.fa\""
] |
[] |
[
"tag: TG = DEFAULT_TAG) -> Any: store_key: SK = self.store_key(key, tag=tag) with self._lock:",
"serial_value: int = self.serialize(value + delta) self._cache[store_key] = serial_value self.visit_hook(store_key, VT_INCR) return serial_value",
"= Union[int, float] TG: Type = Optional[str] SK: Type = Tuple[Any, TG] Time:",
"False return True def _set(self, store_key: SK, value: Any, timeout=DEFAULT_TIMEOUT) -> bool: if",
"tag: TG = DEFAULT_TAG) -> Number: \"\"\" Will throed ValueError when the key",
"'key': key, 'store_key': store_key, 'store_value': self._cache[store_key], 'value': self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key] } def incr(self,",
"serial_value: Any = self.serialize(value) with self._lock: return self._set(store_key, serial_value, timeout) def get(self, key:",
"store_key: Any, vt: VT) -> NoReturn: if vt == VT_SET: self._cache.move_to_end(store_key, last=False) __delitem__",
"self._expire_info: Dict[SK, Any] = _expire_info.setdefault(self.name, {}) self._lock: LK = _locks.setdefault(self.name, self.LOCK()) def set(",
"ttl(self, key: Any, tag: TG) -> Time: store_key: Any = self.store_key(key, tag) if",
"the key value include stored key and serialized value. \"\"\" store_key: SK =",
"= self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) raise ValueError(\"Key '%s' not found\"",
"self.serialize(value) with self._lock: if self._has_expired(store_key): self._set(store_key, serial_value, timeout) return True return False def",
"TG = DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key, tag=tag) with self._lock: return",
"value. \"\"\" store_key: SK = self.store_key(key, tag) if not self._has_expired(store_key): return { 'key':",
"try: del self._cache[store_key] del self._expire_info[store_key] except KeyError: return False return True def _set(self,",
"with self._lock: self._cache.clear() self._expire_info.clear() return True def evict(self) -> NoReturn: if self.cull_size ==",
"self._cache: OrderedDict[SK, Any] = _caches.setdefault( self.name, OrderedDict() ) self._expire_info: Dict[SK, Any] = _expire_info.setdefault(self.name,",
"SK: return key, tag def restore_key(self, store_key: SK) -> SK: return store_key def",
"for keys and values are also relatively loose. It is entirely implemented by",
"key: str, tag: TG = DEFAULT_TAG) -> Optional[Dict[str, Any]]: \"\"\" Get the details",
"vt: VT) -> NoReturn: \"\"\"\"\"\" def fifo_hook_visit(self, store_key: Any, vt: VT) -> NoReturn:",
"60) >>> cache.set('name', 'venus') True >>> cache.get('name') 'venus' >>> cache.delete('name') True >>> cache.get('name')",
"whether the mutex takes effect depends on the lock type. \"\"\" store_key: SK",
"Optional[str] = DEFAULT_TAG ) -> bool: \"\"\" Realize the mutually exclusive operation of",
"1, tag: TG = DEFAULT_TAG) -> Number: \"\"\" Will throed ValueError when the",
"DEFAULT_TAG from cache3.utils import NullContext LK: Type = Union[NullContext, Lock] Number: Type =",
"VT_SET = 0 VT_GET = 1 VT_INCR = 2 _caches: Dict[Any, Any] =",
"lru_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: self._cache.move_to_end(store_key, last=False) def lfu_hook_visit(self, store_key: Any,",
"import DEFAULT_TIMEOUT, DEFAULT_TAG from cache3.utils import NullContext LK: Type = Union[NullContext, Lock] Number:",
"self.evict() self._cache[store_key] = value self.visit_hook(store_key, VT_SET) self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def __iter__(self)",
"key: str, default: Any = None, tag: TG = DEFAULT_TAG) -> Any: store_key:",
"get __setitem__ = set # Thread safe cache in memory class SafeCache(SimpleCache): LOCK:",
"returned \"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): return False",
"\"\"\" Realize the mutually exclusive operation of data through thread lock. but whether",
"List, Callable from cache3 import AbstractCache from cache3.setting import DEFAULT_TIMEOUT, DEFAULT_TAG from cache3.utils",
"``dict``, at the same time, it requirements for keys and values are also",
"self._lock: self._cache.clear() self._expire_info.clear() return True def evict(self) -> NoReturn: if self.cull_size == 0:",
"Type = Tuple[Any, TG] Time: Type = float VT: Type = int VH",
"'expire': self._expire_info[store_key] } def incr(self, key: str, delta: int = 1, tag: TG",
"return False self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def delete(self, key: str, tag: TG",
"self._lock: if self._has_expired(store_key): self._delete(store_key) return False return True def ttl(self, key: Any, tag:",
"if self.cull_size == 0: self._cache.clear() self._expire_info.clear() else: count = len(self._cache) // self.cull_size for",
"= float VT: Type = int VH = Callable[[Any, VT], NoReturn] VT_SET =",
"default: Any = None, tag: TG = DEFAULT_TAG) -> Any: store_key: SK =",
"def fifo_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: if vt == VT_SET: self._cache.move_to_end(store_key,",
"vt == VT_SET: self._cache.move_to_end(store_key, last=False) __delitem__ = delete __getitem__ = get __setitem__ =",
"str, tag: TG = DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key, tag=tag) with",
"# Thread unsafe cache in memory class SimpleCache(AbstractCache): \"\"\" Simple encapsulation of ``OrderedDict``,",
"be returned \"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): return",
"self._cache[store_key] = serial_value self.visit_hook(store_key, VT_INCR) return serial_value def has_key(self, key: str, tag: TG",
"= DEFAULT_TAG) -> Any: store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key):",
"False return True def ttl(self, key: Any, tag: TG) -> Time: store_key: Any",
"__len__(self) -> int: return len(self._cache) def lru_hook_visit(self, store_key: Any, vt: VT) -> NoReturn:",
"TG = DEFAULT_TAG) -> bool: \"\"\" Renew the key. When the key does",
"if self._has_expired(store_key): self._delete(store_key) raise ValueError(\"Key '%s' not found\" % key) value: Any =",
"__getitem__ = get __setitem__ = set # Thread safe cache in memory class",
"Callable from cache3 import AbstractCache from cache3.setting import DEFAULT_TIMEOUT, DEFAULT_TAG from cache3.utils import",
"VT_SET) self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def __iter__(self) -> Tuple[Any, ...]: for store_key",
"return True def ttl(self, key: Any, tag: TG) -> Time: store_key: Any =",
"Any = None, tag: TG = DEFAULT_TAG) -> Any: store_key: SK = self.store_key(key,",
"self._lock: if self._has_expired(store_key): self._set(store_key, serial_value, timeout) return True return False def touch(self, key:",
"inspect(self, key: str, tag: TG = DEFAULT_TAG) -> Optional[Dict[str, Any]]: \"\"\" Get the",
"DEFAULT_TAG ) -> bool: \"\"\" Realize the mutually exclusive operation of data through",
"serial_value def has_key(self, key: str, tag: TG = DEFAULT_TAG) -> bool: store_key: SK",
"= {} _locks: Dict[Any, Any] = {} # Thread unsafe cache in memory",
"False def touch(self, key: str, timeout: Number, tag: TG = DEFAULT_TAG) -> bool:",
"value: Any, timeout: float = DEFAULT_TIMEOUT, tag: Optional[str] = DEFAULT_TAG ) -> bool:",
"tag: TG = DEFAULT_TAG) -> Optional[Dict[str, Any]]: \"\"\" Get the details of the",
"Get the details of the key value include stored key and serialized value.",
"= DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key):",
"len(self) >= self.max_size: self.evict() self._cache[store_key] = value self.visit_hook(store_key, VT_SET) self._expire_info[store_key] = self.get_backend_timeout(timeout) return",
"return value def ex_set( self, key: str, value: Any, timeout: float = DEFAULT_TIMEOUT,",
"Any, vt: VT) -> NoReturn: \"\"\"\"\"\" def fifo_hook_visit(self, store_key: Any, vt: VT) ->",
"-*- coding: utf-8 -*- # DATE: 2021/7/24 # Author: <EMAIL> from collections import",
"Union, Optional, NoReturn, Tuple, List, Callable from cache3 import AbstractCache from cache3.setting import",
"return True def evict(self) -> NoReturn: if self.cull_size == 0: self._cache.clear() self._expire_info.clear() else:",
"\"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): return False self._expire_info[store_key]",
"-1.) return exp is not None and exp <= current() def _delete(self, store_key:",
"cache = SimpleCache('test_cache', 60) >>> cache.set('name', 'venus') True >>> cache.get('name') 'venus' >>> cache.delete('name')",
"DEFAULT_TAG) -> bool: \"\"\" Renew the key. When the key does not exist,",
"Type = int VH = Callable[[Any, VT], NoReturn] VT_SET = 0 VT_GET =",
"Tuple, List, Callable from cache3 import AbstractCache from cache3.setting import DEFAULT_TIMEOUT, DEFAULT_TAG from",
"get(self, key: str, default: Any = None, tag: TG = DEFAULT_TAG) -> Any:",
"operation of data through thread lock. but whether the mutex takes effect depends",
"Union[NullContext, Lock] Number: Type = Union[int, float] TG: Type = Optional[str] SK: Type",
"timeout: Number = DEFAULT_TIMEOUT, tag: TG = DEFAULT_TAG ) -> bool: store_key: SK",
"false will be returned \"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock: if",
"def inspect(self, key: str, tag: TG = DEFAULT_TAG) -> Optional[Dict[str, Any]]: \"\"\" Get",
"bool: try: del self._cache[store_key] del self._expire_info[store_key] except KeyError: return False return True def",
"return True def delete(self, key: str, tag: TG = DEFAULT_TAG) -> bool: store_key:",
"= SimpleCache('test_cache', 60) >>> cache.set('name', 'venus') True >>> cache.get('name') 'venus' >>> cache.delete('name') True",
"Lock from time import time as current from typing import Dict, Any, Type,",
"-> NoReturn: if vt == VT_SET: self._cache.move_to_end(store_key, last=False) __delitem__ = delete __getitem__ =",
"the key. When the key does not exist, false will be returned \"\"\"",
"= self._expire_info.get(store_key, -1.) return exp is not None and exp <= current() def",
"Tuple[Any, ...]: for store_key in reversed(self._cache.keys()): if not self._has_expired(store_key): key, tag = self.restore_key(store_key)",
"bool: with self._lock: self._cache.clear() self._expire_info.clear() return True def evict(self) -> NoReturn: if self.cull_size",
"None, tag: TG = DEFAULT_TAG) -> Any: store_key: SK = self.store_key(key, tag=tag) with",
"True def ttl(self, key: Any, tag: TG) -> Time: store_key: Any = self.store_key(key,",
"performance similar to that of a ``dict``, at the same time, it requirements",
"2 _caches: Dict[Any, Any] = {} _expire_info: Dict[Any, Any] = {} _locks: Dict[Any,",
"key, tag def restore_key(self, store_key: SK) -> SK: return store_key def _has_expired(self, store_key:",
"-> bool: store_key: SK = self.store_key(key, tag=tag) with self._lock: return self._delete(store_key) def inspect(self,",
"float = DEFAULT_TIMEOUT, tag: Optional[str] = DEFAULT_TAG ) -> bool: \"\"\" Realize the",
"Any] = {} _locks: Dict[Any, Any] = {} # Thread unsafe cache in",
"set( self, key: Any, value: Any, timeout: Number = DEFAULT_TIMEOUT, tag: TG =",
"exclusive operation of data through thread lock. but whether the mutex takes effect",
"values are also relatively loose. It is entirely implemented by memory, so use",
"store_key: SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock: if self._has_expired(store_key):",
"f'{self.evict_type}_hook_visit') # Attributes _name, _timeout from validate. self._cache: OrderedDict[SK, Any] = _caches.setdefault( self.name,",
"-> bool: with self._lock: self._cache.clear() self._expire_info.clear() return True def evict(self) -> NoReturn: if",
"tag: TG = DEFAULT_TAG ) -> bool: store_key: SK = self.store_key(key, tag=tag) serial_value:",
"if not self._has_expired(store_key): key, tag = self.restore_key(store_key) yield key, self.deserialize(self._cache[store_key]), tag def __len__(self)",
"def _has_expired(self, store_key: SK) -> bool: exp: float = self._expire_info.get(store_key, -1.) return exp",
"TG = DEFAULT_TAG) -> Number: \"\"\" Will throed ValueError when the key is",
"when the key is not existed. \"\"\" store_key: SK = self.store_key(key, tag=tag) with",
"<EMAIL> from collections import OrderedDict from threading import Lock from time import time",
"with self._lock: if self._has_expired(store_key): self._delete(store_key) return default value: Any = self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET)",
"= set # Thread safe cache in memory class SafeCache(SimpleCache): LOCK: LK =",
"NoReturn: if vt == VT_SET: self._cache.move_to_end(store_key, last=False) __delitem__ = delete __getitem__ = get",
"= None, tag: TG = DEFAULT_TAG) -> Any: store_key: SK = self.store_key(key, tag=tag)",
"_locks.setdefault(self.name, self.LOCK()) def set( self, key: Any, value: Any, timeout: Number = DEFAULT_TIMEOUT,",
"LK = _locks.setdefault(self.name, self.LOCK()) def set( self, key: Any, value: Any, timeout: Number",
"to that of a ``dict``, at the same time, it requirements for keys",
"key: str, delta: int = 1, tag: TG = DEFAULT_TAG) -> Number: \"\"\"",
"self.serialize(value) with self._lock: return self._set(store_key, serial_value, timeout) def get(self, key: str, default: Any",
"count = len(self._cache) // self.cull_size for i in range(count): store_key, _ = self._cache.popitem()",
"from collections import OrderedDict from threading import Lock from time import time as",
"SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): return False self._expire_info[store_key] = self.get_backend_timeout(timeout)",
"encapsulation of ``OrderedDict``, so it has a performance similar to that of a",
"in range(count): store_key, _ = self._cache.popitem() del self._expire_info[store_key] def store_key(self, key: Any, tag:",
"store_key: SK) -> bool: exp: float = self._expire_info.get(store_key, -1.) return exp is not",
"bool: \"\"\" Realize the mutually exclusive operation of data through thread lock. but",
"_caches: Dict[Any, Any] = {} _expire_info: Dict[Any, Any] = {} _locks: Dict[Any, Any]",
"store_key: SK = self.store_key(key, tag) if not self._has_expired(store_key): return { 'key': key, 'store_key':",
"'store_key': store_key, 'store_value': self._cache[store_key], 'value': self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key] } def incr(self, key: str,",
"DEFAULT_TAG) -> Optional[Dict[str, Any]]: \"\"\" Get the details of the key value include",
"also relatively loose. It is entirely implemented by memory, so use the required",
"from cache3 import AbstractCache from cache3.setting import DEFAULT_TIMEOUT, DEFAULT_TAG from cache3.utils import NullContext",
"self.visit_hook: VH = getattr(self, f'{self.evict_type}_hook_visit') # Attributes _name, _timeout from validate. self._cache: OrderedDict[SK,",
"current() def clear(self) -> bool: with self._lock: self._cache.clear() self._expire_info.clear() return True def evict(self)",
"self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): return False self._expire_info[store_key] = self.get_backend_timeout(timeout) return True",
"SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) raise ValueError(\"Key '%s' not",
"bool: exp: float = self._expire_info.get(store_key, -1.) return exp is not None and exp",
"vt: VT) -> NoReturn: if vt == VT_SET: self._cache.move_to_end(store_key, last=False) __delitem__ = delete",
"TG) -> Time: store_key: Any = self.store_key(key, tag) if self._has_expired(store_key): return -1 return",
"from validate. self._cache: OrderedDict[SK, Any] = _caches.setdefault( self.name, OrderedDict() ) self._expire_info: Dict[SK, Any]",
"TG = DEFAULT_TAG) -> Optional[Dict[str, Any]]: \"\"\" Get the details of the key",
"= self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock: if self._has_expired(store_key): self._set(store_key, serial_value,",
"key: str, value: Any, timeout: float = DEFAULT_TIMEOUT, tag: Optional[str] = DEFAULT_TAG )",
"store_key, _ = self._cache.popitem() del self._expire_info[store_key] def store_key(self, key: Any, tag: TG) ->",
"store_key: Any = self.store_key(key, tag) if self._has_expired(store_key): return -1 return self._expire_info[store_key] - current()",
"NoReturn: self._cache.move_to_end(store_key, last=False) def lfu_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: \"\"\"\"\"\" def",
"memory class SimpleCache(AbstractCache): \"\"\" Simple encapsulation of ``OrderedDict``, so it has a performance",
"self._has_expired(store_key): self._set(store_key, serial_value, timeout) return True return False def touch(self, key: str, timeout:",
"\"\"\" store_key: SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock: if",
"-> NoReturn: self._cache.move_to_end(store_key, last=False) def lfu_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: \"\"\"\"\"\"",
"mutually exclusive operation of data through thread lock. but whether the mutex takes",
"= self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return default value: Any =",
"Type = float VT: Type = int VH = Callable[[Any, VT], NoReturn] VT_SET",
"_caches.setdefault( self.name, OrderedDict() ) self._expire_info: Dict[SK, Any] = _expire_info.setdefault(self.name, {}) self._lock: LK =",
"in reversed(self._cache.keys()): if not self._has_expired(store_key): key, tag = self.restore_key(store_key) yield key, self.deserialize(self._cache[store_key]), tag",
"the required control capacity and expiration time to avoid wast memory. >>> cache",
"self._lock: return self._set(store_key, serial_value, timeout) def get(self, key: str, default: Any = None,",
"self.visit_hook(store_key, VT_INCR) return serial_value def has_key(self, key: str, tag: TG = DEFAULT_TAG) ->",
"Any = self.deserialize(self._cache[store_key]) serial_value: int = self.serialize(value + delta) self._cache[store_key] = serial_value self.visit_hook(store_key,",
"_has_expired(self, store_key: SK) -> bool: exp: float = self._expire_info.get(store_key, -1.) return exp is",
"Any, tag: TG) -> Time: store_key: Any = self.store_key(key, tag) if self._has_expired(store_key): return",
"self._lock: return self._delete(store_key) def inspect(self, key: str, tag: TG = DEFAULT_TAG) -> Optional[Dict[str,",
"bool: store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return False",
"store_key def _has_expired(self, store_key: SK) -> bool: exp: float = self._expire_info.get(store_key, -1.) return",
"value: Any, timeout=DEFAULT_TIMEOUT) -> bool: if self.timeout and len(self) >= self.max_size: self.evict() self._cache[store_key]",
"incr(self, key: str, delta: int = 1, tag: TG = DEFAULT_TAG) -> Number:",
"not self._has_expired(store_key): return { 'key': key, 'store_key': store_key, 'store_value': self._cache[store_key], 'value': self.deserialize(self._cache[store_key]), 'expire':",
"-> Tuple[Any, ...]: for store_key in reversed(self._cache.keys()): if not self._has_expired(store_key): key, tag =",
"it requirements for keys and values are also relatively loose. It is entirely",
"= 2 _caches: Dict[Any, Any] = {} _expire_info: Dict[Any, Any] = {} _locks:",
"value: Any, timeout: Number = DEFAULT_TIMEOUT, tag: TG = DEFAULT_TAG ) -> bool:",
"self._has_expired(store_key): key, tag = self.restore_key(store_key) yield key, self.deserialize(self._cache[store_key]), tag def __len__(self) -> int:",
"if self.timeout and len(self) >= self.max_size: self.evict() self._cache[store_key] = value self.visit_hook(store_key, VT_SET) self._expire_info[store_key]",
"key: Any, tag: TG) -> Time: store_key: Any = self.store_key(key, tag) if self._has_expired(store_key):",
"Any, timeout=DEFAULT_TIMEOUT) -> bool: if self.timeout and len(self) >= self.max_size: self.evict() self._cache[store_key] =",
"Number = DEFAULT_TIMEOUT, tag: TG = DEFAULT_TAG ) -> bool: store_key: SK =",
"= value self.visit_hook(store_key, VT_SET) self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def __iter__(self) -> Tuple[Any,",
"tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return False return True def ttl(self, key:",
"True def __iter__(self) -> Tuple[Any, ...]: for store_key in reversed(self._cache.keys()): if not self._has_expired(store_key):",
"= self._cache.popitem() del self._expire_info[store_key] def store_key(self, key: Any, tag: TG) -> SK: return",
"in memory class SimpleCache(AbstractCache): \"\"\" Simple encapsulation of ``OrderedDict``, so it has a",
"VT_SET: self._cache.move_to_end(store_key, last=False) __delitem__ = delete __getitem__ = get __setitem__ = set #",
"return default value: Any = self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET) return value def ex_set( self,",
"Any = self.serialize(value) with self._lock: return self._set(store_key, serial_value, timeout) def get(self, key: str,",
"'%s' not found\" % key) value: Any = self.deserialize(self._cache[store_key]) serial_value: int = self.serialize(value",
"and serialized value. \"\"\" store_key: SK = self.store_key(key, tag) if not self._has_expired(store_key): return",
"a ``dict``, at the same time, it requirements for keys and values are",
"threading import Lock from time import time as current from typing import Dict,",
"**kwargs) -> None: super(SimpleCache, self).__init__(*args, **kwargs) self.visit_hook: VH = getattr(self, f'{self.evict_type}_hook_visit') # Attributes",
"of ``OrderedDict``, so it has a performance similar to that of a ``dict``,",
"= self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): return False self._expire_info[store_key] = self.get_backend_timeout(timeout) return",
"'store_value': self._cache[store_key], 'value': self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key] } def incr(self, key: str, delta: int",
"exp <= current() def _delete(self, store_key: SK) -> bool: try: del self._cache[store_key] del",
"'male', 0) True >>> cache.get('gender') \"\"\" LOCK: LK = NullContext def __init__(self, *args,",
"thread lock. but whether the mutex takes effect depends on the lock type.",
"SK) -> bool: exp: float = self._expire_info.get(store_key, -1.) return exp is not None",
"import Dict, Any, Type, Union, Optional, NoReturn, Tuple, List, Callable from cache3 import",
"time import time as current from typing import Dict, Any, Type, Union, Optional,",
"at the same time, it requirements for keys and values are also relatively",
"tag: TG = DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key, tag=tag) with self._lock:",
"tag: Optional[str] = DEFAULT_TAG ) -> bool: \"\"\" Realize the mutually exclusive operation",
"if self._has_expired(store_key): self._set(store_key, serial_value, timeout) return True return False def touch(self, key: str,",
"= self.deserialize(self._cache[store_key]) serial_value: int = self.serialize(value + delta) self._cache[store_key] = serial_value self.visit_hook(store_key, VT_INCR)",
"mutex takes effect depends on the lock type. \"\"\" store_key: SK = self.store_key(key,",
">>> cache.set('gender', 'male', 0) True >>> cache.get('gender') \"\"\" LOCK: LK = NullContext def",
"__iter__(self) -> Tuple[Any, ...]: for store_key in reversed(self._cache.keys()): if not self._has_expired(store_key): key, tag",
"_expire_info.setdefault(self.name, {}) self._lock: LK = _locks.setdefault(self.name, self.LOCK()) def set( self, key: Any, value:",
"self._has_expired(store_key): return { 'key': key, 'store_key': store_key, 'store_value': self._cache[store_key], 'value': self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key]",
"range(count): store_key, _ = self._cache.popitem() del self._expire_info[store_key] def store_key(self, key: Any, tag: TG)",
"self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def delete(self, key: str, tag: TG = DEFAULT_TAG)",
"int VH = Callable[[Any, VT], NoReturn] VT_SET = 0 VT_GET = 1 VT_INCR",
"= self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return False return True def",
"del self._expire_info[store_key] except KeyError: return False return True def _set(self, store_key: SK, value:",
"LOCK: LK = NullContext def __init__(self, *args, **kwargs) -> None: super(SimpleCache, self).__init__(*args, **kwargs)",
"not self._has_expired(store_key): key, tag = self.restore_key(store_key) yield key, self.deserialize(self._cache[store_key]), tag def __len__(self) ->",
"timeout: float = DEFAULT_TIMEOUT, tag: Optional[str] = DEFAULT_TAG ) -> bool: \"\"\" Realize",
"self).__init__(*args, **kwargs) self.visit_hook: VH = getattr(self, f'{self.evict_type}_hook_visit') # Attributes _name, _timeout from validate.",
"self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock: return self._set(store_key, serial_value, timeout) def",
"delete(self, key: str, tag: TG = DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key,",
"= get __setitem__ = set # Thread safe cache in memory class SafeCache(SimpleCache):",
"raise ValueError(\"Key '%s' not found\" % key) value: Any = self.deserialize(self._cache[store_key]) serial_value: int",
"self._delete(store_key) raise ValueError(\"Key '%s' not found\" % key) value: Any = self.deserialize(self._cache[store_key]) serial_value:",
"== VT_SET: self._cache.move_to_end(store_key, last=False) __delitem__ = delete __getitem__ = get __setitem__ = set",
"True def _set(self, store_key: SK, value: Any, timeout=DEFAULT_TIMEOUT) -> bool: if self.timeout and",
"It is entirely implemented by memory, so use the required control capacity and",
"Number: \"\"\" Will throed ValueError when the key is not existed. \"\"\" store_key:",
"self._has_expired(store_key): self._delete(store_key) raise ValueError(\"Key '%s' not found\" % key) value: Any = self.deserialize(self._cache[store_key])",
"DEFAULT_TAG ) -> bool: store_key: SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value)",
"-> bool: exp: float = self._expire_info.get(store_key, -1.) return exp is not None and",
"Any] = {} # Thread unsafe cache in memory class SimpleCache(AbstractCache): \"\"\" Simple",
"not existed. \"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key)",
"store_key: Any, vt: VT) -> NoReturn: \"\"\"\"\"\" def fifo_hook_visit(self, store_key: Any, vt: VT)",
"self.get_backend_timeout(timeout) return True def __iter__(self) -> Tuple[Any, ...]: for store_key in reversed(self._cache.keys()): if",
"key value include stored key and serialized value. \"\"\" store_key: SK = self.store_key(key,",
"cache.set('gender', 'male', 0) True >>> cache.get('gender') \"\"\" LOCK: LK = NullContext def __init__(self,",
"vt: VT) -> NoReturn: self._cache.move_to_end(store_key, last=False) def lfu_hook_visit(self, store_key: Any, vt: VT) ->",
"through thread lock. but whether the mutex takes effect depends on the lock",
"VT) -> NoReturn: self._cache.move_to_end(store_key, last=False) def lfu_hook_visit(self, store_key: Any, vt: VT) -> NoReturn:",
"self._cache.popitem() del self._expire_info[store_key] def store_key(self, key: Any, tag: TG) -> SK: return key,",
"coding: utf-8 -*- # DATE: 2021/7/24 # Author: <EMAIL> from collections import OrderedDict",
"value: Any = self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET) return value def ex_set( self, key: str,",
"key) value: Any = self.deserialize(self._cache[store_key]) serial_value: int = self.serialize(value + delta) self._cache[store_key] =",
"key is not existed. \"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock: if",
"cache.delete('name') True >>> cache.get('name') >>> cache.set('gender', 'male', 0) True >>> cache.get('gender') \"\"\" LOCK:",
"DEFAULT_TAG) -> Any: store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key)",
"str, timeout: Number, tag: TG = DEFAULT_TAG) -> bool: \"\"\" Renew the key.",
"lock. but whether the mutex takes effect depends on the lock type. \"\"\"",
"return self._expire_info[store_key] - current() def clear(self) -> bool: with self._lock: self._cache.clear() self._expire_info.clear() return",
"but whether the mutex takes effect depends on the lock type. \"\"\" store_key:",
"-> bool: if self.timeout and len(self) >= self.max_size: self.evict() self._cache[store_key] = value self.visit_hook(store_key,",
"= self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock: return self._set(store_key, serial_value, timeout)",
"self._lock: if self._has_expired(store_key): self._delete(store_key) raise ValueError(\"Key '%s' not found\" % key) value: Any",
"Number, tag: TG = DEFAULT_TAG) -> bool: \"\"\" Renew the key. When the",
"Any, Type, Union, Optional, NoReturn, Tuple, List, Callable from cache3 import AbstractCache from",
"self._lock: LK = _locks.setdefault(self.name, self.LOCK()) def set( self, key: Any, value: Any, timeout:",
"self._cache.clear() self._expire_info.clear() return True def evict(self) -> NoReturn: if self.cull_size == 0: self._cache.clear()",
"self._has_expired(store_key): return False self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def delete(self, key: str, tag:",
"True def delete(self, key: str, tag: TG = DEFAULT_TAG) -> bool: store_key: SK",
"tag = self.restore_key(store_key) yield key, self.deserialize(self._cache[store_key]), tag def __len__(self) -> int: return len(self._cache)",
"return self._set(store_key, serial_value, timeout) def get(self, key: str, default: Any = None, tag:",
"self.visit_hook(store_key, VT_GET) return value def ex_set( self, key: str, value: Any, timeout: float",
"= int VH = Callable[[Any, VT], NoReturn] VT_SET = 0 VT_GET = 1",
"and expiration time to avoid wast memory. >>> cache = SimpleCache('test_cache', 60) >>>",
"delete __getitem__ = get __setitem__ = set # Thread safe cache in memory",
"capacity and expiration time to avoid wast memory. >>> cache = SimpleCache('test_cache', 60)",
"NoReturn] VT_SET = 0 VT_GET = 1 VT_INCR = 2 _caches: Dict[Any, Any]",
"wast memory. >>> cache = SimpleCache('test_cache', 60) >>> cache.set('name', 'venus') True >>> cache.get('name')",
"key: Any, value: Any, timeout: Number = DEFAULT_TIMEOUT, tag: TG = DEFAULT_TAG )",
"fifo_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: if vt == VT_SET: self._cache.move_to_end(store_key, last=False)",
"*args, **kwargs) -> None: super(SimpleCache, self).__init__(*args, **kwargs) self.visit_hook: VH = getattr(self, f'{self.evict_type}_hook_visit') #",
"float] TG: Type = Optional[str] SK: Type = Tuple[Any, TG] Time: Type =",
"exist, false will be returned \"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock:",
"last=False) def lfu_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: \"\"\"\"\"\" def fifo_hook_visit(self, store_key:",
"Dict[Any, Any] = {} _expire_info: Dict[Any, Any] = {} _locks: Dict[Any, Any] =",
"= self.serialize(value + delta) self._cache[store_key] = serial_value self.visit_hook(store_key, VT_INCR) return serial_value def has_key(self,",
"self._cache[store_key] del self._expire_info[store_key] except KeyError: return False return True def _set(self, store_key: SK,",
"len(self._cache) def lru_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: self._cache.move_to_end(store_key, last=False) def lfu_hook_visit(self,",
"keys and values are also relatively loose. It is entirely implemented by memory,",
"super(SimpleCache, self).__init__(*args, **kwargs) self.visit_hook: VH = getattr(self, f'{self.evict_type}_hook_visit') # Attributes _name, _timeout from",
"TG] Time: Type = float VT: Type = int VH = Callable[[Any, VT],",
"if not self._has_expired(store_key): return { 'key': key, 'store_key': store_key, 'store_value': self._cache[store_key], 'value': self.deserialize(self._cache[store_key]),",
"self._expire_info.clear() return True def evict(self) -> NoReturn: if self.cull_size == 0: self._cache.clear() self._expire_info.clear()",
"= DEFAULT_TIMEOUT, tag: TG = DEFAULT_TAG ) -> bool: store_key: SK = self.store_key(key,",
"-1 return self._expire_info[store_key] - current() def clear(self) -> bool: with self._lock: self._cache.clear() self._expire_info.clear()",
">>> cache.delete('name') True >>> cache.get('name') >>> cache.set('gender', 'male', 0) True >>> cache.get('gender') \"\"\"",
"_set(self, store_key: SK, value: Any, timeout=DEFAULT_TIMEOUT) -> bool: if self.timeout and len(self) >=",
"found\" % key) value: Any = self.deserialize(self._cache[store_key]) serial_value: int = self.serialize(value + delta)",
"= _locks.setdefault(self.name, self.LOCK()) def set( self, key: Any, value: Any, timeout: Number =",
"bool: store_key: SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock: return",
"0 VT_GET = 1 VT_INCR = 2 _caches: Dict[Any, Any] = {} _expire_info:",
"with self._lock: if self._has_expired(store_key): self._delete(store_key) raise ValueError(\"Key '%s' not found\" % key) value:",
"LK: Type = Union[NullContext, Lock] Number: Type = Union[int, float] TG: Type =",
"tag: TG) -> SK: return key, tag def restore_key(self, store_key: SK) -> SK:",
"-> int: return len(self._cache) def lru_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: self._cache.move_to_end(store_key,",
"SK, value: Any, timeout=DEFAULT_TIMEOUT) -> bool: if self.timeout and len(self) >= self.max_size: self.evict()",
"ValueError(\"Key '%s' not found\" % key) value: Any = self.deserialize(self._cache[store_key]) serial_value: int =",
"= serial_value self.visit_hook(store_key, VT_INCR) return serial_value def has_key(self, key: str, tag: TG =",
"\"\"\"\"\"\" def fifo_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: if vt == VT_SET:",
"control capacity and expiration time to avoid wast memory. >>> cache = SimpleCache('test_cache',",
"NoReturn: if self.cull_size == 0: self._cache.clear() self._expire_info.clear() else: count = len(self._cache) // self.cull_size",
"timeout) return True return False def touch(self, key: str, timeout: Number, tag: TG",
"the details of the key value include stored key and serialized value. \"\"\"",
"def delete(self, key: str, tag: TG = DEFAULT_TAG) -> bool: store_key: SK =",
"<= current() def _delete(self, store_key: SK) -> bool: try: del self._cache[store_key] del self._expire_info[store_key]",
"cache3 import AbstractCache from cache3.setting import DEFAULT_TIMEOUT, DEFAULT_TAG from cache3.utils import NullContext LK:",
"unsafe cache in memory class SimpleCache(AbstractCache): \"\"\" Simple encapsulation of ``OrderedDict``, so it",
"cache.get('name') 'venus' >>> cache.delete('name') True >>> cache.get('name') >>> cache.set('gender', 'male', 0) True >>>",
"TG = DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key, tag=tag) with self._lock: if",
"DEFAULT_TAG) -> Number: \"\"\" Will throed ValueError when the key is not existed.",
"key: str, tag: TG = DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key, tag=tag)",
"a performance similar to that of a ``dict``, at the same time, it",
"= DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key, tag=tag) with self._lock: return self._delete(store_key)",
"{} # Thread unsafe cache in memory class SimpleCache(AbstractCache): \"\"\" Simple encapsulation of",
"the mutex takes effect depends on the lock type. \"\"\" store_key: SK =",
"else: count = len(self._cache) // self.cull_size for i in range(count): store_key, _ =",
"DEFAULT_TIMEOUT, tag: TG = DEFAULT_TAG ) -> bool: store_key: SK = self.store_key(key, tag=tag)",
"SimpleCache(AbstractCache): \"\"\" Simple encapsulation of ``OrderedDict``, so it has a performance similar to",
"self._expire_info.clear() else: count = len(self._cache) // self.cull_size for i in range(count): store_key, _",
"True >>> cache.get('gender') \"\"\" LOCK: LK = NullContext def __init__(self, *args, **kwargs) ->",
"key does not exist, false will be returned \"\"\" store_key: SK = self.store_key(key,",
"-> SK: return store_key def _has_expired(self, store_key: SK) -> bool: exp: float =",
"def _delete(self, store_key: SK) -> bool: try: del self._cache[store_key] del self._expire_info[store_key] except KeyError:",
"= DEFAULT_TAG) -> Optional[Dict[str, Any]]: \"\"\" Get the details of the key value",
"0: self._cache.clear() self._expire_info.clear() else: count = len(self._cache) // self.cull_size for i in range(count):",
"True >>> cache.get('name') 'venus' >>> cache.delete('name') True >>> cache.get('name') >>> cache.set('gender', 'male', 0)",
"store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) raise ValueError(\"Key '%s'",
"DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key, tag=tag) with self._lock: return self._delete(store_key) def",
"= {} _expire_info: Dict[Any, Any] = {} _locks: Dict[Any, Any] = {} #",
"getattr(self, f'{self.evict_type}_hook_visit') # Attributes _name, _timeout from validate. self._cache: OrderedDict[SK, Any] = _caches.setdefault(",
"float VT: Type = int VH = Callable[[Any, VT], NoReturn] VT_SET = 0",
"i in range(count): store_key, _ = self._cache.popitem() del self._expire_info[store_key] def store_key(self, key: Any,",
"DEFAULT_TIMEOUT, DEFAULT_TAG from cache3.utils import NullContext LK: Type = Union[NullContext, Lock] Number: Type",
"def incr(self, key: str, delta: int = 1, tag: TG = DEFAULT_TAG) ->",
"VT], NoReturn] VT_SET = 0 VT_GET = 1 VT_INCR = 2 _caches: Dict[Any,",
"Realize the mutually exclusive operation of data through thread lock. but whether the",
"self.name, OrderedDict() ) self._expire_info: Dict[SK, Any] = _expire_info.setdefault(self.name, {}) self._lock: LK = _locks.setdefault(self.name,",
"timeout: Number, tag: TG = DEFAULT_TAG) -> bool: \"\"\" Renew the key. When",
"tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) raise ValueError(\"Key '%s' not found\" % key)",
"\"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) raise ValueError(\"Key",
">>> cache.get('name') >>> cache.set('gender', 'male', 0) True >>> cache.get('gender') \"\"\" LOCK: LK =",
"= DEFAULT_TAG) -> bool: \"\"\" Renew the key. When the key does not",
"// self.cull_size for i in range(count): store_key, _ = self._cache.popitem() del self._expire_info[store_key] def",
"= Callable[[Any, VT], NoReturn] VT_SET = 0 VT_GET = 1 VT_INCR = 2",
"with self._lock: if self._has_expired(store_key): return False self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def delete(self,",
"is not None and exp <= current() def _delete(self, store_key: SK) -> bool:",
"None and exp <= current() def _delete(self, store_key: SK) -> bool: try: del",
">>> cache.get('gender') \"\"\" LOCK: LK = NullContext def __init__(self, *args, **kwargs) -> None:",
"str, delta: int = 1, tag: TG = DEFAULT_TAG) -> Number: \"\"\" Will",
"store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return False return",
"timeout) def get(self, key: str, default: Any = None, tag: TG = DEFAULT_TAG)",
"cache in memory class SimpleCache(AbstractCache): \"\"\" Simple encapsulation of ``OrderedDict``, so it has",
"int: return len(self._cache) def lru_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: self._cache.move_to_end(store_key, last=False)",
"VT: Type = int VH = Callable[[Any, VT], NoReturn] VT_SET = 0 VT_GET",
"Time: Type = float VT: Type = int VH = Callable[[Any, VT], NoReturn]",
"str, value: Any, timeout: float = DEFAULT_TIMEOUT, tag: Optional[str] = DEFAULT_TAG ) ->",
"def _set(self, store_key: SK, value: Any, timeout=DEFAULT_TIMEOUT) -> bool: if self.timeout and len(self)",
"TG = DEFAULT_TAG) -> Any: store_key: SK = self.store_key(key, tag=tag) with self._lock: if",
"and len(self) >= self.max_size: self.evict() self._cache[store_key] = value self.visit_hook(store_key, VT_SET) self._expire_info[store_key] = self.get_backend_timeout(timeout)",
"-> SK: return key, tag def restore_key(self, store_key: SK) -> SK: return store_key",
"def __len__(self) -> int: return len(self._cache) def lru_hook_visit(self, store_key: Any, vt: VT) ->",
"def ttl(self, key: Any, tag: TG) -> Time: store_key: Any = self.store_key(key, tag)",
"if self._has_expired(store_key): return -1 return self._expire_info[store_key] - current() def clear(self) -> bool: with",
"store_key: Any, vt: VT) -> NoReturn: self._cache.move_to_end(store_key, last=False) def lfu_hook_visit(self, store_key: Any, vt:",
"Any, vt: VT) -> NoReturn: if vt == VT_SET: self._cache.move_to_end(store_key, last=False) __delitem__ =",
"lfu_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: \"\"\"\"\"\" def fifo_hook_visit(self, store_key: Any, vt:",
"required control capacity and expiration time to avoid wast memory. >>> cache =",
"cache3.utils import NullContext LK: Type = Union[NullContext, Lock] Number: Type = Union[int, float]",
"self._cache.move_to_end(store_key, last=False) __delitem__ = delete __getitem__ = get __setitem__ = set # Thread",
"{}) self._lock: LK = _locks.setdefault(self.name, self.LOCK()) def set( self, key: Any, value: Any,",
"NullContext def __init__(self, *args, **kwargs) -> None: super(SimpleCache, self).__init__(*args, **kwargs) self.visit_hook: VH =",
">>> cache.set('name', 'venus') True >>> cache.get('name') 'venus' >>> cache.delete('name') True >>> cache.get('name') >>>",
"ValueError when the key is not existed. \"\"\" store_key: SK = self.store_key(key, tag=tag)",
"data through thread lock. but whether the mutex takes effect depends on the",
"= DEFAULT_TIMEOUT, tag: Optional[str] = DEFAULT_TAG ) -> bool: \"\"\" Realize the mutually",
"-> bool: \"\"\" Renew the key. When the key does not exist, false",
"VT_INCR) return serial_value def has_key(self, key: str, tag: TG = DEFAULT_TAG) -> bool:",
"DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key)",
"exp is not None and exp <= current() def _delete(self, store_key: SK) ->",
"from typing import Dict, Any, Type, Union, Optional, NoReturn, Tuple, List, Callable from",
"True >>> cache.get('name') >>> cache.set('gender', 'male', 0) True >>> cache.get('gender') \"\"\" LOCK: LK",
"exp: float = self._expire_info.get(store_key, -1.) return exp is not None and exp <=",
"by memory, so use the required control capacity and expiration time to avoid",
"type. \"\"\" store_key: SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock:",
"self._has_expired(store_key): self._delete(store_key) return default value: Any = self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET) return value def",
"store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): return False self._expire_info[store_key] =",
"effect depends on the lock type. \"\"\" store_key: SK = self.store_key(key, tag=tag) serial_value:",
"tag) if self._has_expired(store_key): return -1 return self._expire_info[store_key] - current() def clear(self) -> bool:",
"self.restore_key(store_key) yield key, self.deserialize(self._cache[store_key]), tag def __len__(self) -> int: return len(self._cache) def lru_hook_visit(self,",
"expiration time to avoid wast memory. >>> cache = SimpleCache('test_cache', 60) >>> cache.set('name',",
"self._expire_info[store_key] except KeyError: return False return True def _set(self, store_key: SK, value: Any,",
"__setitem__ = set # Thread safe cache in memory class SafeCache(SimpleCache): LOCK: LK",
"+ delta) self._cache[store_key] = serial_value self.visit_hook(store_key, VT_INCR) return serial_value def has_key(self, key: str,",
"0) True >>> cache.get('gender') \"\"\" LOCK: LK = NullContext def __init__(self, *args, **kwargs)",
"#!/usr/bin/python # -*- coding: utf-8 -*- # DATE: 2021/7/24 # Author: <EMAIL> from",
"touch(self, key: str, timeout: Number, tag: TG = DEFAULT_TAG) -> bool: \"\"\" Renew",
"store_key: SK, value: Any, timeout=DEFAULT_TIMEOUT) -> bool: if self.timeout and len(self) >= self.max_size:",
"'venus') True >>> cache.get('name') 'venus' >>> cache.delete('name') True >>> cache.get('name') >>> cache.set('gender', 'male',",
"reversed(self._cache.keys()): if not self._has_expired(store_key): key, tag = self.restore_key(store_key) yield key, self.deserialize(self._cache[store_key]), tag def",
"OrderedDict from threading import Lock from time import time as current from typing",
"tag: TG = DEFAULT_TAG) -> bool: \"\"\" Renew the key. When the key",
"value: Any = self.deserialize(self._cache[store_key]) serial_value: int = self.serialize(value + delta) self._cache[store_key] = serial_value",
"True return False def touch(self, key: str, timeout: Number, tag: TG = DEFAULT_TAG)",
"def get(self, key: str, default: Any = None, tag: TG = DEFAULT_TAG) ->",
"from time import time as current from typing import Dict, Any, Type, Union,",
"= self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET) return value def ex_set( self, key: str, value: Any,",
"= 1, tag: TG = DEFAULT_TAG) -> Number: \"\"\" Will throed ValueError when",
"serial_value, timeout) def get(self, key: str, default: Any = None, tag: TG =",
"value include stored key and serialized value. \"\"\" store_key: SK = self.store_key(key, tag)",
"= delete __getitem__ = get __setitem__ = set # Thread safe cache in",
"self._lock: if self._has_expired(store_key): return False self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def delete(self, key:",
"-> Number: \"\"\" Will throed ValueError when the key is not existed. \"\"\"",
"-> Time: store_key: Any = self.store_key(key, tag) if self._has_expired(store_key): return -1 return self._expire_info[store_key]",
") self._expire_info: Dict[SK, Any] = _expire_info.setdefault(self.name, {}) self._lock: LK = _locks.setdefault(self.name, self.LOCK()) def",
"VT) -> NoReturn: if vt == VT_SET: self._cache.move_to_end(store_key, last=False) __delitem__ = delete __getitem__",
"_name, _timeout from validate. self._cache: OrderedDict[SK, Any] = _caches.setdefault( self.name, OrderedDict() ) self._expire_info:",
"relatively loose. It is entirely implemented by memory, so use the required control",
"avoid wast memory. >>> cache = SimpleCache('test_cache', 60) >>> cache.set('name', 'venus') True >>>",
"int = self.serialize(value + delta) self._cache[store_key] = serial_value self.visit_hook(store_key, VT_INCR) return serial_value def",
"return True def __iter__(self) -> Tuple[Any, ...]: for store_key in reversed(self._cache.keys()): if not",
"LK = NullContext def __init__(self, *args, **kwargs) -> None: super(SimpleCache, self).__init__(*args, **kwargs) self.visit_hook:",
"...]: for store_key in reversed(self._cache.keys()): if not self._has_expired(store_key): key, tag = self.restore_key(store_key) yield",
"time, it requirements for keys and values are also relatively loose. It is",
"store_key: SK) -> bool: try: del self._cache[store_key] del self._expire_info[store_key] except KeyError: return False",
"del self._cache[store_key] del self._expire_info[store_key] except KeyError: return False return True def _set(self, store_key:",
"Any = self.store_key(key, tag) if self._has_expired(store_key): return -1 return self._expire_info[store_key] - current() def",
"from threading import Lock from time import time as current from typing import",
"SK) -> SK: return store_key def _has_expired(self, store_key: SK) -> bool: exp: float",
"import time as current from typing import Dict, Any, Type, Union, Optional, NoReturn,",
"is not existed. \"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key):",
"- current() def clear(self) -> bool: with self._lock: self._cache.clear() self._expire_info.clear() return True def",
"cache3.setting import DEFAULT_TIMEOUT, DEFAULT_TAG from cache3.utils import NullContext LK: Type = Union[NullContext, Lock]",
"and values are also relatively loose. It is entirely implemented by memory, so",
"self._cache[store_key] = value self.visit_hook(store_key, VT_SET) self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def __iter__(self) ->",
"Any] = _expire_info.setdefault(self.name, {}) self._lock: LK = _locks.setdefault(self.name, self.LOCK()) def set( self, key:",
"= 1 VT_INCR = 2 _caches: Dict[Any, Any] = {} _expire_info: Dict[Any, Any]",
"int = 1, tag: TG = DEFAULT_TAG) -> Number: \"\"\" Will throed ValueError",
"Dict[Any, Any] = {} _locks: Dict[Any, Any] = {} # Thread unsafe cache",
"Any, vt: VT) -> NoReturn: self._cache.move_to_end(store_key, last=False) def lfu_hook_visit(self, store_key: Any, vt: VT)",
"Dict[Any, Any] = {} # Thread unsafe cache in memory class SimpleCache(AbstractCache): \"\"\"",
"is entirely implemented by memory, so use the required control capacity and expiration",
"TG) -> SK: return key, tag def restore_key(self, store_key: SK) -> SK: return",
"and exp <= current() def _delete(self, store_key: SK) -> bool: try: del self._cache[store_key]",
"import Lock from time import time as current from typing import Dict, Any,",
"Any] = _caches.setdefault( self.name, OrderedDict() ) self._expire_info: Dict[SK, Any] = _expire_info.setdefault(self.name, {}) self._lock:",
"from cache3.utils import NullContext LK: Type = Union[NullContext, Lock] Number: Type = Union[int,",
"tag def __len__(self) -> int: return len(self._cache) def lru_hook_visit(self, store_key: Any, vt: VT)",
"self._expire_info[store_key] - current() def clear(self) -> bool: with self._lock: self._cache.clear() self._expire_info.clear() return True",
"\"\"\" store_key: SK = self.store_key(key, tag) if not self._has_expired(store_key): return { 'key': key,",
"self._has_expired(store_key): return -1 return self._expire_info[store_key] - current() def clear(self) -> bool: with self._lock:",
"self._delete(store_key) return False return True def ttl(self, key: Any, tag: TG) -> Time:",
"VH = Callable[[Any, VT], NoReturn] VT_SET = 0 VT_GET = 1 VT_INCR =",
"memory. >>> cache = SimpleCache('test_cache', 60) >>> cache.set('name', 'venus') True >>> cache.get('name') 'venus'",
"the same time, it requirements for keys and values are also relatively loose.",
"utf-8 -*- # DATE: 2021/7/24 # Author: <EMAIL> from collections import OrderedDict from",
"Dict, Any, Type, Union, Optional, NoReturn, Tuple, List, Callable from cache3 import AbstractCache",
"self._set(store_key, serial_value, timeout) return True return False def touch(self, key: str, timeout: Number,",
"so it has a performance similar to that of a ``dict``, at the",
"return self._delete(store_key) def inspect(self, key: str, tag: TG = DEFAULT_TAG) -> Optional[Dict[str, Any]]:",
"def has_key(self, key: str, tag: TG = DEFAULT_TAG) -> bool: store_key: SK =",
"timeout=DEFAULT_TIMEOUT) -> bool: if self.timeout and len(self) >= self.max_size: self.evict() self._cache[store_key] = value",
"store_key: SK) -> SK: return store_key def _has_expired(self, store_key: SK) -> bool: exp:",
"self._cache.move_to_end(store_key, last=False) def lfu_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: \"\"\"\"\"\" def fifo_hook_visit(self,",
"value def ex_set( self, key: str, value: Any, timeout: float = DEFAULT_TIMEOUT, tag:",
"\"\"\" Simple encapsulation of ``OrderedDict``, so it has a performance similar to that",
"= DEFAULT_TAG) -> Number: \"\"\" Will throed ValueError when the key is not",
"self._has_expired(store_key): self._delete(store_key) return False return True def ttl(self, key: Any, tag: TG) ->",
"-> bool: \"\"\" Realize the mutually exclusive operation of data through thread lock.",
"Callable[[Any, VT], NoReturn] VT_SET = 0 VT_GET = 1 VT_INCR = 2 _caches:",
"return { 'key': key, 'store_key': store_key, 'store_value': self._cache[store_key], 'value': self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key] }",
"VT_GET = 1 VT_INCR = 2 _caches: Dict[Any, Any] = {} _expire_info: Dict[Any,",
"self.store_key(key, tag=tag) with self._lock: return self._delete(store_key) def inspect(self, key: str, tag: TG =",
"SimpleCache('test_cache', 60) >>> cache.set('name', 'venus') True >>> cache.get('name') 'venus' >>> cache.delete('name') True >>>",
"tag) if not self._has_expired(store_key): return { 'key': key, 'store_key': store_key, 'store_value': self._cache[store_key], 'value':",
"serial_value, timeout) return True return False def touch(self, key: str, timeout: Number, tag:",
"\"\"\" Get the details of the key value include stored key and serialized",
"= self.get_backend_timeout(timeout) return True def __iter__(self) -> Tuple[Any, ...]: for store_key in reversed(self._cache.keys()):",
"self.max_size: self.evict() self._cache[store_key] = value self.visit_hook(store_key, VT_SET) self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def",
">= self.max_size: self.evict() self._cache[store_key] = value self.visit_hook(store_key, VT_SET) self._expire_info[store_key] = self.get_backend_timeout(timeout) return True",
"lock type. \"\"\" store_key: SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with",
"key, 'store_key': store_key, 'store_value': self._cache[store_key], 'value': self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key] } def incr(self, key:",
"str, tag: TG = DEFAULT_TAG) -> Optional[Dict[str, Any]]: \"\"\" Get the details of",
"class SimpleCache(AbstractCache): \"\"\" Simple encapsulation of ``OrderedDict``, so it has a performance similar",
"for store_key in reversed(self._cache.keys()): if not self._has_expired(store_key): key, tag = self.restore_key(store_key) yield key,",
"1 VT_INCR = 2 _caches: Dict[Any, Any] = {} _expire_info: Dict[Any, Any] =",
"include stored key and serialized value. \"\"\" store_key: SK = self.store_key(key, tag) if",
"= Optional[str] SK: Type = Tuple[Any, TG] Time: Type = float VT: Type",
"throed ValueError when the key is not existed. \"\"\" store_key: SK = self.store_key(key,",
"True def evict(self) -> NoReturn: if self.cull_size == 0: self._cache.clear() self._expire_info.clear() else: count",
"import NullContext LK: Type = Union[NullContext, Lock] Number: Type = Union[int, float] TG:",
"of the key value include stored key and serialized value. \"\"\" store_key: SK",
"= _expire_info.setdefault(self.name, {}) self._lock: LK = _locks.setdefault(self.name, self.LOCK()) def set( self, key: Any,",
"Will throed ValueError when the key is not existed. \"\"\" store_key: SK =",
"== 0: self._cache.clear() self._expire_info.clear() else: count = len(self._cache) // self.cull_size for i in",
"# -*- coding: utf-8 -*- # DATE: 2021/7/24 # Author: <EMAIL> from collections",
"} def incr(self, key: str, delta: int = 1, tag: TG = DEFAULT_TAG)",
"if self._has_expired(store_key): self._delete(store_key) return False return True def ttl(self, key: Any, tag: TG)",
"for i in range(count): store_key, _ = self._cache.popitem() del self._expire_info[store_key] def store_key(self, key:",
"= Tuple[Any, TG] Time: Type = float VT: Type = int VH =",
"self.serialize(value + delta) self._cache[store_key] = serial_value self.visit_hook(store_key, VT_INCR) return serial_value def has_key(self, key:",
"return False def touch(self, key: str, timeout: Number, tag: TG = DEFAULT_TAG) ->",
"from cache3.setting import DEFAULT_TIMEOUT, DEFAULT_TAG from cache3.utils import NullContext LK: Type = Union[NullContext,",
"'venus' >>> cache.delete('name') True >>> cache.get('name') >>> cache.set('gender', 'male', 0) True >>> cache.get('gender')",
"del self._expire_info[store_key] def store_key(self, key: Any, tag: TG) -> SK: return key, tag",
"= DEFAULT_TAG ) -> bool: store_key: SK = self.store_key(key, tag=tag) serial_value: Any =",
"Type = Optional[str] SK: Type = Tuple[Any, TG] Time: Type = float VT:",
"-> None: super(SimpleCache, self).__init__(*args, **kwargs) self.visit_hook: VH = getattr(self, f'{self.evict_type}_hook_visit') # Attributes _name,",
"def __iter__(self) -> Tuple[Any, ...]: for store_key in reversed(self._cache.keys()): if not self._has_expired(store_key): key,",
"time to avoid wast memory. >>> cache = SimpleCache('test_cache', 60) >>> cache.set('name', 'venus')",
"if self._has_expired(store_key): self._delete(store_key) return default value: Any = self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET) return value",
"= self.serialize(value) with self._lock: if self._has_expired(store_key): self._set(store_key, serial_value, timeout) return True return False",
"self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key] } def incr(self, key: str, delta: int = 1, tag:",
"does not exist, false will be returned \"\"\" store_key: SK = self.store_key(key, tag=tag)",
"self.cull_size == 0: self._cache.clear() self._expire_info.clear() else: count = len(self._cache) // self.cull_size for i",
"of a ``dict``, at the same time, it requirements for keys and values",
"**kwargs) self.visit_hook: VH = getattr(self, f'{self.evict_type}_hook_visit') # Attributes _name, _timeout from validate. self._cache:",
"= self.restore_key(store_key) yield key, self.deserialize(self._cache[store_key]), tag def __len__(self) -> int: return len(self._cache) def",
"= getattr(self, f'{self.evict_type}_hook_visit') # Attributes _name, _timeout from validate. self._cache: OrderedDict[SK, Any] =",
"Any, tag: TG) -> SK: return key, tag def restore_key(self, store_key: SK) ->",
"KeyError: return False return True def _set(self, store_key: SK, value: Any, timeout=DEFAULT_TIMEOUT) ->",
"% key) value: Any = self.deserialize(self._cache[store_key]) serial_value: int = self.serialize(value + delta) self._cache[store_key]",
"it has a performance similar to that of a ``dict``, at the same",
"= NullContext def __init__(self, *args, **kwargs) -> None: super(SimpleCache, self).__init__(*args, **kwargs) self.visit_hook: VH",
"= DEFAULT_TAG ) -> bool: \"\"\" Realize the mutually exclusive operation of data",
"self._expire_info.get(store_key, -1.) return exp is not None and exp <= current() def _delete(self,",
"Type, Union, Optional, NoReturn, Tuple, List, Callable from cache3 import AbstractCache from cache3.setting",
"OrderedDict() ) self._expire_info: Dict[SK, Any] = _expire_info.setdefault(self.name, {}) self._lock: LK = _locks.setdefault(self.name, self.LOCK())",
"use the required control capacity and expiration time to avoid wast memory. >>>",
"self.deserialize(self._cache[store_key]) serial_value: int = self.serialize(value + delta) self._cache[store_key] = serial_value self.visit_hook(store_key, VT_INCR) return",
"def lru_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: self._cache.move_to_end(store_key, last=False) def lfu_hook_visit(self, store_key:",
"ex_set( self, key: str, value: Any, timeout: float = DEFAULT_TIMEOUT, tag: Optional[str] =",
"self.timeout and len(self) >= self.max_size: self.evict() self._cache[store_key] = value self.visit_hook(store_key, VT_SET) self._expire_info[store_key] =",
"Any, timeout: Number = DEFAULT_TIMEOUT, tag: TG = DEFAULT_TAG ) -> bool: store_key:",
"of data through thread lock. but whether the mutex takes effect depends on",
"store_key: SK = self.store_key(key, tag=tag) with self._lock: return self._delete(store_key) def inspect(self, key: str,",
"has a performance similar to that of a ``dict``, at the same time,",
"with self._lock: return self._set(store_key, serial_value, timeout) def get(self, key: str, default: Any =",
"= _caches.setdefault( self.name, OrderedDict() ) self._expire_info: Dict[SK, Any] = _expire_info.setdefault(self.name, {}) self._lock: LK",
"with self._lock: if self._has_expired(store_key): self._delete(store_key) return False return True def ttl(self, key: Any,",
"VT) -> NoReturn: \"\"\"\"\"\" def fifo_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: if",
"def ex_set( self, key: str, value: Any, timeout: float = DEFAULT_TIMEOUT, tag: Optional[str]",
"= self.store_key(key, tag=tag) with self._lock: return self._delete(store_key) def inspect(self, key: str, tag: TG",
"restore_key(self, store_key: SK) -> SK: return store_key def _has_expired(self, store_key: SK) -> bool:",
"Optional, NoReturn, Tuple, List, Callable from cache3 import AbstractCache from cache3.setting import DEFAULT_TIMEOUT,",
"Optional[Dict[str, Any]]: \"\"\" Get the details of the key value include stored key",
"store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return default value:",
"delta: int = 1, tag: TG = DEFAULT_TAG) -> Number: \"\"\" Will throed",
"bool: store_key: SK = self.store_key(key, tag=tag) with self._lock: return self._delete(store_key) def inspect(self, key:",
"self.LOCK()) def set( self, key: Any, value: Any, timeout: Number = DEFAULT_TIMEOUT, tag:",
"loose. It is entirely implemented by memory, so use the required control capacity",
"details of the key value include stored key and serialized value. \"\"\" store_key:",
"self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return default value: Any = self.deserialize(self._cache[store_key])",
"{ 'key': key, 'store_key': store_key, 'store_value': self._cache[store_key], 'value': self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key] } def",
"return store_key def _has_expired(self, store_key: SK) -> bool: exp: float = self._expire_info.get(store_key, -1.)",
"def restore_key(self, store_key: SK) -> SK: return store_key def _has_expired(self, store_key: SK) ->",
"key: str, timeout: Number, tag: TG = DEFAULT_TAG) -> bool: \"\"\" Renew the",
"= {} # Thread unsafe cache in memory class SimpleCache(AbstractCache): \"\"\" Simple encapsulation",
"self._lock: if self._has_expired(store_key): self._delete(store_key) return default value: Any = self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET) return",
"_locks: Dict[Any, Any] = {} # Thread unsafe cache in memory class SimpleCache(AbstractCache):",
"-> Any: store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return",
"self.store_key(key, tag) if not self._has_expired(store_key): return { 'key': key, 'store_key': store_key, 'store_value': self._cache[store_key],",
"NullContext LK: Type = Union[NullContext, Lock] Number: Type = Union[int, float] TG: Type",
"tag: TG) -> Time: store_key: Any = self.store_key(key, tag) if self._has_expired(store_key): return -1",
"with self._lock: if self._has_expired(store_key): self._set(store_key, serial_value, timeout) return True return False def touch(self,",
"the lock type. \"\"\" store_key: SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value)",
"_delete(self, store_key: SK) -> bool: try: del self._cache[store_key] del self._expire_info[store_key] except KeyError: return",
"SK = self.store_key(key, tag) if not self._has_expired(store_key): return { 'key': key, 'store_key': store_key,",
"= self.store_key(key, tag) if self._has_expired(store_key): return -1 return self._expire_info[store_key] - current() def clear(self)",
"value self.visit_hook(store_key, VT_SET) self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def __iter__(self) -> Tuple[Any, ...]:",
"def touch(self, key: str, timeout: Number, tag: TG = DEFAULT_TAG) -> bool: \"\"\"",
"Union[int, float] TG: Type = Optional[str] SK: Type = Tuple[Any, TG] Time: Type",
"None: super(SimpleCache, self).__init__(*args, **kwargs) self.visit_hook: VH = getattr(self, f'{self.evict_type}_hook_visit') # Attributes _name, _timeout",
"Author: <EMAIL> from collections import OrderedDict from threading import Lock from time import",
"{} _expire_info: Dict[Any, Any] = {} _locks: Dict[Any, Any] = {} # Thread",
">>> cache.get('name') 'venus' >>> cache.delete('name') True >>> cache.get('name') >>> cache.set('gender', 'male', 0) True",
"self._delete(store_key) return default value: Any = self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET) return value def ex_set(",
"DATE: 2021/7/24 # Author: <EMAIL> from collections import OrderedDict from threading import Lock",
"current from typing import Dict, Any, Type, Union, Optional, NoReturn, Tuple, List, Callable",
"requirements for keys and values are also relatively loose. It is entirely implemented",
"self.get_backend_timeout(timeout) return True def delete(self, key: str, tag: TG = DEFAULT_TAG) -> bool:",
"-> bool: store_key: SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock:",
"self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) raise ValueError(\"Key '%s' not found\" %",
"store_key(self, key: Any, tag: TG) -> SK: return key, tag def restore_key(self, store_key:",
"= self.serialize(value) with self._lock: return self._set(store_key, serial_value, timeout) def get(self, key: str, default:",
"__delitem__ = delete __getitem__ = get __setitem__ = set # Thread safe cache",
"= self.store_key(key, tag) if not self._has_expired(store_key): return { 'key': key, 'store_key': store_key, 'store_value':",
"serial_value: Any = self.serialize(value) with self._lock: if self._has_expired(store_key): self._set(store_key, serial_value, timeout) return True",
"self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def __iter__(self) -> Tuple[Any, ...]: for store_key in",
"# Author: <EMAIL> from collections import OrderedDict from threading import Lock from time",
"self._expire_info[store_key] } def incr(self, key: str, delta: int = 1, tag: TG =",
"self._expire_info[store_key] def store_key(self, key: Any, tag: TG) -> SK: return key, tag def",
"float = self._expire_info.get(store_key, -1.) return exp is not None and exp <= current()",
"with self._lock: return self._delete(store_key) def inspect(self, key: str, tag: TG = DEFAULT_TAG) ->",
"def lfu_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: \"\"\"\"\"\" def fifo_hook_visit(self, store_key: Any,",
"self.store_key(key, tag) if self._has_expired(store_key): return -1 return self._expire_info[store_key] - current() def clear(self) ->",
"store_key: SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock: return self._set(store_key,",
"When the key does not exist, false will be returned \"\"\" store_key: SK",
"= 0 VT_GET = 1 VT_INCR = 2 _caches: Dict[Any, Any] = {}",
"validate. self._cache: OrderedDict[SK, Any] = _caches.setdefault( self.name, OrderedDict() ) self._expire_info: Dict[SK, Any] =",
"= self.get_backend_timeout(timeout) return True def delete(self, key: str, tag: TG = DEFAULT_TAG) ->",
"-> NoReturn: \"\"\"\"\"\" def fifo_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: if vt",
"return key, tag def restore_key(self, store_key: SK) -> SK: return store_key def _has_expired(self,",
"typing import Dict, Any, Type, Union, Optional, NoReturn, Tuple, List, Callable from cache3",
"DEFAULT_TIMEOUT, tag: Optional[str] = DEFAULT_TAG ) -> bool: \"\"\" Realize the mutually exclusive",
"Optional[str] SK: Type = Tuple[Any, TG] Time: Type = float VT: Type =",
"tag def restore_key(self, store_key: SK) -> SK: return store_key def _has_expired(self, store_key: SK)",
"Number: Type = Union[int, float] TG: Type = Optional[str] SK: Type = Tuple[Any,",
") -> bool: store_key: SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with",
"# DATE: 2021/7/24 # Author: <EMAIL> from collections import OrderedDict from threading import",
"self.deserialize(self._cache[store_key]), tag def __len__(self) -> int: return len(self._cache) def lru_hook_visit(self, store_key: Any, vt:",
"bool: \"\"\" Renew the key. When the key does not exist, false will",
"key, tag = self.restore_key(store_key) yield key, self.deserialize(self._cache[store_key]), tag def __len__(self) -> int: return",
"__init__(self, *args, **kwargs) -> None: super(SimpleCache, self).__init__(*args, **kwargs) self.visit_hook: VH = getattr(self, f'{self.evict_type}_hook_visit')",
"Dict[SK, Any] = _expire_info.setdefault(self.name, {}) self._lock: LK = _locks.setdefault(self.name, self.LOCK()) def set( self,",
"clear(self) -> bool: with self._lock: self._cache.clear() self._expire_info.clear() return True def evict(self) -> NoReturn:",
"VT_GET) return value def ex_set( self, key: str, value: Any, timeout: float =",
"NoReturn: \"\"\"\"\"\" def fifo_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: if vt ==",
"time as current from typing import Dict, Any, Type, Union, Optional, NoReturn, Tuple,",
"-> bool: try: del self._cache[store_key] del self._expire_info[store_key] except KeyError: return False return True",
"as current from typing import Dict, Any, Type, Union, Optional, NoReturn, Tuple, List,",
"key, self.deserialize(self._cache[store_key]), tag def __len__(self) -> int: return len(self._cache) def lru_hook_visit(self, store_key: Any,",
"takes effect depends on the lock type. \"\"\" store_key: SK = self.store_key(key, tag=tag)",
"return -1 return self._expire_info[store_key] - current() def clear(self) -> bool: with self._lock: self._cache.clear()",
"Type = Union[NullContext, Lock] Number: Type = Union[int, float] TG: Type = Optional[str]",
">>> cache = SimpleCache('test_cache', 60) >>> cache.set('name', 'venus') True >>> cache.get('name') 'venus' >>>",
"existed. \"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) raise",
"return True return False def touch(self, key: str, timeout: Number, tag: TG =",
"VH = getattr(self, f'{self.evict_type}_hook_visit') # Attributes _name, _timeout from validate. self._cache: OrderedDict[SK, Any]",
"implemented by memory, so use the required control capacity and expiration time to",
"default value: Any = self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET) return value def ex_set( self, key:",
"= len(self._cache) // self.cull_size for i in range(count): store_key, _ = self._cache.popitem() del",
"SK) -> bool: try: del self._cache[store_key] del self._expire_info[store_key] except KeyError: return False return",
"def store_key(self, key: Any, tag: TG) -> SK: return key, tag def restore_key(self,",
"tag=tag) serial_value: Any = self.serialize(value) with self._lock: if self._has_expired(store_key): self._set(store_key, serial_value, timeout) return",
"Type = Union[int, float] TG: Type = Optional[str] SK: Type = Tuple[Any, TG]",
"-> NoReturn: if self.cull_size == 0: self._cache.clear() self._expire_info.clear() else: count = len(self._cache) //",
"-> Optional[Dict[str, Any]]: \"\"\" Get the details of the key value include stored",
"_ = self._cache.popitem() del self._expire_info[store_key] def store_key(self, key: Any, tag: TG) -> SK:",
"VT_INCR = 2 _caches: Dict[Any, Any] = {} _expire_info: Dict[Any, Any] = {}",
"def set( self, key: Any, value: Any, timeout: Number = DEFAULT_TIMEOUT, tag: TG",
"2021/7/24 # Author: <EMAIL> from collections import OrderedDict from threading import Lock from",
"Any: store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return default",
"str, default: Any = None, tag: TG = DEFAULT_TAG) -> Any: store_key: SK",
"TG: Type = Optional[str] SK: Type = Tuple[Any, TG] Time: Type = float",
"to avoid wast memory. >>> cache = SimpleCache('test_cache', 60) >>> cache.set('name', 'venus') True",
"False self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def delete(self, key: str, tag: TG =",
"self._set(store_key, serial_value, timeout) def get(self, key: str, default: Any = None, tag: TG",
"the key is not existed. \"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock:",
"_expire_info: Dict[Any, Any] = {} _locks: Dict[Any, Any] = {} # Thread unsafe",
"self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock: if self._has_expired(store_key): self._set(store_key, serial_value, timeout)",
"return False return True def _set(self, store_key: SK, value: Any, timeout=DEFAULT_TIMEOUT) -> bool:",
"serialized value. \"\"\" store_key: SK = self.store_key(key, tag) if not self._has_expired(store_key): return {",
"delta) self._cache[store_key] = serial_value self.visit_hook(store_key, VT_INCR) return serial_value def has_key(self, key: str, tag:",
"except KeyError: return False return True def _set(self, store_key: SK, value: Any, timeout=DEFAULT_TIMEOUT)",
"Any]]: \"\"\" Get the details of the key value include stored key and",
"so use the required control capacity and expiration time to avoid wast memory.",
"Any = self.serialize(value) with self._lock: if self._has_expired(store_key): self._set(store_key, serial_value, timeout) return True return",
"evict(self) -> NoReturn: if self.cull_size == 0: self._cache.clear() self._expire_info.clear() else: count = len(self._cache)",
"has_key(self, key: str, tag: TG = DEFAULT_TAG) -> bool: store_key: SK = self.store_key(key,",
"will be returned \"\"\" store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key):",
"SK: return store_key def _has_expired(self, store_key: SK) -> bool: exp: float = self._expire_info.get(store_key,",
"def __init__(self, *args, **kwargs) -> None: super(SimpleCache, self).__init__(*args, **kwargs) self.visit_hook: VH = getattr(self,",
"not found\" % key) value: Any = self.deserialize(self._cache[store_key]) serial_value: int = self.serialize(value +",
"Any = self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET) return value def ex_set( self, key: str, value:",
"SK = self.store_key(key, tag=tag) with self._lock: return self._delete(store_key) def inspect(self, key: str, tag:",
"self.visit_hook(store_key, VT_SET) self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def __iter__(self) -> Tuple[Any, ...]: for",
"stored key and serialized value. \"\"\" store_key: SK = self.store_key(key, tag) if not",
"yield key, self.deserialize(self._cache[store_key]), tag def __len__(self) -> int: return len(self._cache) def lru_hook_visit(self, store_key:",
"cache.get('name') >>> cache.set('gender', 'male', 0) True >>> cache.get('gender') \"\"\" LOCK: LK = NullContext",
"SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return False return True",
"cache.set('name', 'venus') True >>> cache.get('name') 'venus' >>> cache.delete('name') True >>> cache.get('name') >>> cache.set('gender',",
"\"\"\" Will throed ValueError when the key is not existed. \"\"\" store_key: SK",
"import AbstractCache from cache3.setting import DEFAULT_TIMEOUT, DEFAULT_TAG from cache3.utils import NullContext LK: Type",
"Attributes _name, _timeout from validate. self._cache: OrderedDict[SK, Any] = _caches.setdefault( self.name, OrderedDict() )",
"return len(self._cache) def lru_hook_visit(self, store_key: Any, vt: VT) -> NoReturn: self._cache.move_to_end(store_key, last=False) def",
"entirely implemented by memory, so use the required control capacity and expiration time",
"bool: if self.timeout and len(self) >= self.max_size: self.evict() self._cache[store_key] = value self.visit_hook(store_key, VT_SET)",
"Renew the key. When the key does not exist, false will be returned",
"NoReturn, Tuple, List, Callable from cache3 import AbstractCache from cache3.setting import DEFAULT_TIMEOUT, DEFAULT_TAG",
"TG = DEFAULT_TAG ) -> bool: store_key: SK = self.store_key(key, tag=tag) serial_value: Any",
"memory, so use the required control capacity and expiration time to avoid wast",
"self, key: str, value: Any, timeout: float = DEFAULT_TIMEOUT, tag: Optional[str] = DEFAULT_TAG",
"return exp is not None and exp <= current() def _delete(self, store_key: SK)",
"SK: Type = Tuple[Any, TG] Time: Type = float VT: Type = int",
"not None and exp <= current() def _delete(self, store_key: SK) -> bool: try:",
"store_key, 'store_value': self._cache[store_key], 'value': self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key] } def incr(self, key: str, delta:",
"Simple encapsulation of ``OrderedDict``, so it has a performance similar to that of",
"self._cache[store_key], 'value': self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key] } def incr(self, key: str, delta: int =",
"# Attributes _name, _timeout from validate. self._cache: OrderedDict[SK, Any] = _caches.setdefault( self.name, OrderedDict()",
"self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return False return True def ttl(self,",
"-> bool: store_key: SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return",
"store_key in reversed(self._cache.keys()): if not self._has_expired(store_key): key, tag = self.restore_key(store_key) yield key, self.deserialize(self._cache[store_key]),",
"``OrderedDict``, so it has a performance similar to that of a ``dict``, at",
"self._delete(store_key) def inspect(self, key: str, tag: TG = DEFAULT_TAG) -> Optional[Dict[str, Any]]: \"\"\"",
"set # Thread safe cache in memory class SafeCache(SimpleCache): LOCK: LK = Lock",
"tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return default value: Any = self.deserialize(self._cache[store_key]) self.visit_hook(store_key,",
"key. When the key does not exist, false will be returned \"\"\" store_key:",
"if self._has_expired(store_key): return False self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def delete(self, key: str,",
"self, key: Any, value: Any, timeout: Number = DEFAULT_TIMEOUT, tag: TG = DEFAULT_TAG",
"return serial_value def has_key(self, key: str, tag: TG = DEFAULT_TAG) -> bool: store_key:",
"len(self._cache) // self.cull_size for i in range(count): store_key, _ = self._cache.popitem() del self._expire_info[store_key]",
") -> bool: \"\"\" Realize the mutually exclusive operation of data through thread",
"OrderedDict[SK, Any] = _caches.setdefault( self.name, OrderedDict() ) self._expire_info: Dict[SK, Any] = _expire_info.setdefault(self.name, {})",
"Any, timeout: float = DEFAULT_TIMEOUT, tag: Optional[str] = DEFAULT_TAG ) -> bool: \"\"\"",
"self.cull_size for i in range(count): store_key, _ = self._cache.popitem() del self._expire_info[store_key] def store_key(self,",
"SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock: return self._set(store_key, serial_value,",
"= Union[NullContext, Lock] Number: Type = Union[int, float] TG: Type = Optional[str] SK:",
"on the lock type. \"\"\" store_key: SK = self.store_key(key, tag=tag) serial_value: Any =",
"if vt == VT_SET: self._cache.move_to_end(store_key, last=False) __delitem__ = delete __getitem__ = get __setitem__",
"AbstractCache from cache3.setting import DEFAULT_TIMEOUT, DEFAULT_TAG from cache3.utils import NullContext LK: Type =",
"\"\"\" Renew the key. When the key does not exist, false will be",
"-*- # DATE: 2021/7/24 # Author: <EMAIL> from collections import OrderedDict from threading",
"_timeout from validate. self._cache: OrderedDict[SK, Any] = _caches.setdefault( self.name, OrderedDict() ) self._expire_info: Dict[SK,",
"that of a ``dict``, at the same time, it requirements for keys and",
"{} _locks: Dict[Any, Any] = {} # Thread unsafe cache in memory class",
"tag=tag) serial_value: Any = self.serialize(value) with self._lock: return self._set(store_key, serial_value, timeout) def get(self,",
"cache.get('gender') \"\"\" LOCK: LK = NullContext def __init__(self, *args, **kwargs) -> None: super(SimpleCache,",
"return False return True def ttl(self, key: Any, tag: TG) -> Time: store_key:",
"are also relatively loose. It is entirely implemented by memory, so use the",
"current() def _delete(self, store_key: SK) -> bool: try: del self._cache[store_key] del self._expire_info[store_key] except",
"Time: store_key: Any = self.store_key(key, tag) if self._has_expired(store_key): return -1 return self._expire_info[store_key] -",
"serial_value self.visit_hook(store_key, VT_INCR) return serial_value def has_key(self, key: str, tag: TG = DEFAULT_TAG)",
"Tuple[Any, TG] Time: Type = float VT: Type = int VH = Callable[[Any,",
"Thread unsafe cache in memory class SimpleCache(AbstractCache): \"\"\" Simple encapsulation of ``OrderedDict``, so",
"collections import OrderedDict from threading import Lock from time import time as current",
"def clear(self) -> bool: with self._lock: self._cache.clear() self._expire_info.clear() return True def evict(self) ->",
"SK = self.store_key(key, tag=tag) serial_value: Any = self.serialize(value) with self._lock: if self._has_expired(store_key): self._set(store_key,",
"the key does not exist, false will be returned \"\"\" store_key: SK =",
"tag=tag) with self._lock: return self._delete(store_key) def inspect(self, key: str, tag: TG = DEFAULT_TAG)",
"'value': self.deserialize(self._cache[store_key]), 'expire': self._expire_info[store_key] } def incr(self, key: str, delta: int = 1,",
"tag=tag) with self._lock: if self._has_expired(store_key): return False self._expire_info[store_key] = self.get_backend_timeout(timeout) return True def",
"import OrderedDict from threading import Lock from time import time as current from",
"Lock] Number: Type = Union[int, float] TG: Type = Optional[str] SK: Type =",
"return True def _set(self, store_key: SK, value: Any, timeout=DEFAULT_TIMEOUT) -> bool: if self.timeout",
"the mutually exclusive operation of data through thread lock. but whether the mutex",
"Any] = {} _expire_info: Dict[Any, Any] = {} _locks: Dict[Any, Any] = {}",
"same time, it requirements for keys and values are also relatively loose. It",
"last=False) __delitem__ = delete __getitem__ = get __setitem__ = set # Thread safe",
"def evict(self) -> NoReturn: if self.cull_size == 0: self._cache.clear() self._expire_info.clear() else: count =",
"self._cache.clear() self._expire_info.clear() else: count = len(self._cache) // self.cull_size for i in range(count): store_key,",
"key and serialized value. \"\"\" store_key: SK = self.store_key(key, tag) if not self._has_expired(store_key):",
"\"\"\" LOCK: LK = NullContext def __init__(self, *args, **kwargs) -> None: super(SimpleCache, self).__init__(*args,",
"similar to that of a ``dict``, at the same time, it requirements for",
"self.deserialize(self._cache[store_key]) self.visit_hook(store_key, VT_GET) return value def ex_set( self, key: str, value: Any, timeout:",
"SK = self.store_key(key, tag=tag) with self._lock: if self._has_expired(store_key): self._delete(store_key) return default value: Any",
"not exist, false will be returned \"\"\" store_key: SK = self.store_key(key, tag=tag) with",
"Any, value: Any, timeout: Number = DEFAULT_TIMEOUT, tag: TG = DEFAULT_TAG ) ->",
"depends on the lock type. \"\"\" store_key: SK = self.store_key(key, tag=tag) serial_value: Any",
"key: Any, tag: TG) -> SK: return key, tag def restore_key(self, store_key: SK)"
] |
[
"= argparse.ArgumentParser(usage='python %(prog)s [options]', description='Implements pi estimators.') parser.add_argument('--n_samples', type=int, help='number of samples', required=True)",
"required=True) args = parser.parse_args() n_runs = args.n_runs n_samples = args.n_samples func = pi_estimator_markov_chain",
"plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std, label='mean $\\pm$ std') plt.axhline(y=np.pi, color='k', linestyle='--', label='$\\pi$') plt.ylim([np.pi-0.5, np.pi+0.5]) plt.xlim([0,",
"1.0: n_inside += 1 n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) return",
"+ dy if abs(xn) < 1.0 and abs(yn) < 1.0: x = xn",
"in range(n_runs): e = func(n_samples) runs.append(e) return np.mean(runs, axis=0), np.std(runs, axis=0) parser =",
"of runs', required=True) args = parser.parse_args() n_runs = args.n_runs n_samples = args.n_samples func",
"import argparse import numpy as np import matplotlib.pyplot as plt def pi_estimator(n_samples): est",
"in range(n_samples): x = np.random.uniform(0.0, 1.0) y = 4.0 * np.sqrt(1.0 - np.power(x,",
"e += (y - e) / (np.float(i) + 1.0) est.append(e) return np.array(est) def",
"dx yn = y + dy if abs(xn) < 1.0 and abs(yn) <",
"1.0) y = np.random.uniform(-1.0, 1.0) for i in range(n_samples): dx = np.random.uniform(-step, step)",
"run(n_runs, n_samples, func) plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std, label='mean $\\pm$ std') plt.axhline(y=np.pi, color='k', linestyle='--', label='$\\pi$')",
"= list() n_inside = 0; n_all = 0; n_accepted = 0 x =",
"0; n_all = 0; n_accepted = 0 x = np.random.uniform(-1.0, 1.0) y =",
"= list() e = 0.0 for i in range(n_samples): x = np.random.uniform(0.0, 1.0)",
"np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) dist = np.sqrt(np.power(x, 2) + np.power(y, 2))",
"xn y = yn n_accepted += 1 dist = np.sqrt(np.power(x, 2) + np.power(y,",
"e) / (np.float(i) + 1.0) est.append(e) return np.array(est) def pi_estimator_markov_chain(n_samples, step=0.1): est =",
"list() n_inside = 0; n_all = 0; n_accepted = 0 x = np.random.uniform(-1.0,",
"np.array(est) def pi_estimator_markov_chain(n_samples, step=0.1): est = list() n_inside = 0; n_all = 0;",
"range(n_samples): x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) dist = np.sqrt(np.power(x, 2)",
"1.0 and abs(yn) < 1.0: x = xn y = yn n_accepted +=",
"std = run(n_runs, n_samples, func) plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std, label='mean $\\pm$ std') plt.axhline(y=np.pi, color='k',",
"np.power(y, 2)) if dist <= 1.0: n_inside += 1 n_all += 1 est.append(4.0",
"range(n_runs): e = func(n_samples) runs.append(e) return np.mean(runs, axis=0), np.std(runs, axis=0) parser = argparse.ArgumentParser(usage='python",
"n_samples, func) plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std, label='mean $\\pm$ std') plt.axhline(y=np.pi, color='k', linestyle='--', label='$\\pi$') plt.ylim([np.pi-0.5,",
"= np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist <= 1.0: n_inside += 1",
"func): runs = [] for i in range(n_runs): e = func(n_samples) runs.append(e) return",
"<= 1.0: n_inside += 1 n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all))",
"parser.parse_args() n_runs = args.n_runs n_samples = args.n_samples func = pi_estimator_markov_chain mean, std =",
"[] for i in range(n_runs): e = func(n_samples) runs.append(e) return np.mean(runs, axis=0), np.std(runs,",
"est = list() n_inside = 0; n_all = 0 for i in range(n_samples):",
"np.float(n_all)) return np.array(est) def pi_estimator_integral(n_samples): est = list() e = 0.0 for i",
"for i in range(n_samples): x = np.random.uniform(0.0, 1.0) y = 4.0 * np.sqrt(1.0",
"and abs(yn) < 1.0: x = xn y = yn n_accepted += 1",
"y2=mean+std, label='mean $\\pm$ std') plt.axhline(y=np.pi, color='k', linestyle='--', label='$\\pi$') plt.ylim([np.pi-0.5, np.pi+0.5]) plt.xlim([0, 10000]) plt.xlabel('step')",
"e = 0.0 for i in range(n_samples): x = np.random.uniform(0.0, 1.0) y =",
"= list() n_inside = 0; n_all = 0 for i in range(n_samples): x",
"np.sqrt(1.0 - np.power(x, 2)) e += (y - e) / (np.float(i) + 1.0)",
"1.0) est.append(e) return np.array(est) def pi_estimator_markov_chain(n_samples, step=0.1): est = list() n_inside = 0;",
"y = np.random.uniform(-1.0, 1.0) for i in range(n_samples): dx = np.random.uniform(-step, step) dy",
"np.mean(runs, axis=0), np.std(runs, axis=0) parser = argparse.ArgumentParser(usage='python %(prog)s [options]', description='Implements pi estimators.') parser.add_argument('--n_samples',",
"0; n_all = 0 for i in range(n_samples): x = np.random.uniform(-1.0, 1.0) y",
"(y - e) / (np.float(i) + 1.0) est.append(e) return np.array(est) def pi_estimator_markov_chain(n_samples, step=0.1):",
"func(n_samples) runs.append(e) return np.mean(runs, axis=0), np.std(runs, axis=0) parser = argparse.ArgumentParser(usage='python %(prog)s [options]', description='Implements",
"= yn n_accepted += 1 dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if",
"np.float(n_inside) / np.float(n_all)) acc_ratio = np.float(n_accepted) / np.float(n_all) return np.array(est) def run(n_runs, n_samples,",
"def run(n_runs, n_samples, func): runs = [] for i in range(n_runs): e =",
"1.0) y = np.random.uniform(-1.0, 1.0) dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if",
"step) dy = np.random.uniform(-step, step) xn = x + dx yn = y",
"/ np.float(n_all)) acc_ratio = np.float(n_accepted) / np.float(n_all) return np.array(est) def run(n_runs, n_samples, func):",
"in range(n_samples): dx = np.random.uniform(-step, step) dy = np.random.uniform(-step, step) xn = x",
"dy = np.random.uniform(-step, step) xn = x + dx yn = y +",
"pi_estimator(n_samples): est = list() n_inside = 0; n_all = 0 for i in",
"def pi_estimator_markov_chain(n_samples, step=0.1): est = list() n_inside = 0; n_all = 0; n_accepted",
"axis=0), np.std(runs, axis=0) parser = argparse.ArgumentParser(usage='python %(prog)s [options]', description='Implements pi estimators.') parser.add_argument('--n_samples', type=int,",
"1.0) for i in range(n_samples): dx = np.random.uniform(-step, step) dy = np.random.uniform(-step, step)",
"axis=0) parser = argparse.ArgumentParser(usage='python %(prog)s [options]', description='Implements pi estimators.') parser.add_argument('--n_samples', type=int, help='number of",
"y = yn n_accepted += 1 dist = np.sqrt(np.power(x, 2) + np.power(y, 2))",
"1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) acc_ratio = np.float(n_accepted) / np.float(n_all) return np.array(est)",
"import matplotlib.pyplot as plt def pi_estimator(n_samples): est = list() n_inside = 0; n_all",
"np import matplotlib.pyplot as plt def pi_estimator(n_samples): est = list() n_inside = 0;",
"+ 1.0) est.append(e) return np.array(est) def pi_estimator_markov_chain(n_samples, step=0.1): est = list() n_inside =",
"+= (y - e) / (np.float(i) + 1.0) est.append(e) return np.array(est) def pi_estimator_markov_chain(n_samples,",
"1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) return np.array(est) def pi_estimator_integral(n_samples): est = list()",
"dy if abs(xn) < 1.0 and abs(yn) < 1.0: x = xn y",
"numpy as np import matplotlib.pyplot as plt def pi_estimator(n_samples): est = list() n_inside",
"n_inside += 1 n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) return np.array(est)",
"2)) e += (y - e) / (np.float(i) + 1.0) est.append(e) return np.array(est)",
"parser = argparse.ArgumentParser(usage='python %(prog)s [options]', description='Implements pi estimators.') parser.add_argument('--n_samples', type=int, help='number of samples',",
"0.0 for i in range(n_samples): x = np.random.uniform(0.0, 1.0) y = 4.0 *",
"func = pi_estimator_markov_chain mean, std = run(n_runs, n_samples, func) plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std, label='mean",
"est.append(e) return np.array(est) def pi_estimator_markov_chain(n_samples, step=0.1): est = list() n_inside = 0; n_all",
"= np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) dist = np.sqrt(np.power(x, 2) + np.power(y,",
"y = np.random.uniform(-1.0, 1.0) dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist",
"1 dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist <= 1.0: n_inside",
"std') plt.axhline(y=np.pi, color='k', linestyle='--', label='$\\pi$') plt.ylim([np.pi-0.5, np.pi+0.5]) plt.xlim([0, 10000]) plt.xlabel('step') plt.ylabel('estimate of $\\pi$')",
"n_samples, func): runs = [] for i in range(n_runs): e = func(n_samples) runs.append(e)",
"- np.power(x, 2)) e += (y - e) / (np.float(i) + 1.0) est.append(e)",
"list() n_inside = 0; n_all = 0 for i in range(n_samples): x =",
"y + dy if abs(xn) < 1.0 and abs(yn) < 1.0: x =",
"def pi_estimator_integral(n_samples): est = list() e = 0.0 for i in range(n_samples): x",
"= np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) for i in range(n_samples): dx =",
"0; n_accepted = 0 x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) for",
"* np.sqrt(1.0 - np.power(x, 2)) e += (y - e) / (np.float(i) +",
"args = parser.parse_args() n_runs = args.n_runs n_samples = args.n_samples func = pi_estimator_markov_chain mean,",
"list() e = 0.0 for i in range(n_samples): x = np.random.uniform(0.0, 1.0) y",
"np.random.uniform(0.0, 1.0) y = 4.0 * np.sqrt(1.0 - np.power(x, 2)) e += (y",
"np.random.uniform(-1.0, 1.0) dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist <= 1.0:",
"step=0.1): est = list() n_inside = 0; n_all = 0; n_accepted = 0",
"color='k', linestyle='--', label='$\\pi$') plt.ylim([np.pi-0.5, np.pi+0.5]) plt.xlim([0, 10000]) plt.xlabel('step') plt.ylabel('estimate of $\\pi$') plt.legend() plt.show()",
"description='Implements pi estimators.') parser.add_argument('--n_samples', type=int, help='number of samples', required=True) parser.add_argument('--n_runs', type=int, help='number of",
"+ np.power(y, 2)) if dist <= 1.0: n_inside += 1 n_all += 1",
"= np.random.uniform(-step, step) xn = x + dx yn = y + dy",
"as plt def pi_estimator(n_samples): est = list() n_inside = 0; n_all = 0",
"= args.n_runs n_samples = args.n_samples func = pi_estimator_markov_chain mean, std = run(n_runs, n_samples,",
"= np.float(n_accepted) / np.float(n_all) return np.array(est) def run(n_runs, n_samples, func): runs = []",
"pi_estimator_markov_chain(n_samples, step=0.1): est = list() n_inside = 0; n_all = 0; n_accepted =",
"= 4.0 * np.sqrt(1.0 - np.power(x, 2)) e += (y - e) /",
"n_all = 0; n_accepted = 0 x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0,",
"return np.array(est) def run(n_runs, n_samples, func): runs = [] for i in range(n_runs):",
"n_samples = args.n_samples func = pi_estimator_markov_chain mean, std = run(n_runs, n_samples, func) plt.fill_between(x=range(n_samples),",
"est = list() e = 0.0 for i in range(n_samples): x = np.random.uniform(0.0,",
"return np.mean(runs, axis=0), np.std(runs, axis=0) parser = argparse.ArgumentParser(usage='python %(prog)s [options]', description='Implements pi estimators.')",
"parser.add_argument('--n_samples', type=int, help='number of samples', required=True) parser.add_argument('--n_runs', type=int, help='number of runs', required=True) args",
"np.float(n_accepted) / np.float(n_all) return np.array(est) def run(n_runs, n_samples, func): runs = [] for",
"required=True) parser.add_argument('--n_runs', type=int, help='number of runs', required=True) args = parser.parse_args() n_runs = args.n_runs",
"+= 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) return np.array(est) def pi_estimator_integral(n_samples): est =",
"/ (np.float(i) + 1.0) est.append(e) return np.array(est) def pi_estimator_markov_chain(n_samples, step=0.1): est = list()",
"np.float(n_inside) / np.float(n_all)) return np.array(est) def pi_estimator_integral(n_samples): est = list() e = 0.0",
"= y + dy if abs(xn) < 1.0 and abs(yn) < 1.0: x",
"np.float(n_all) return np.array(est) def run(n_runs, n_samples, func): runs = [] for i in",
"< 1.0: x = xn y = yn n_accepted += 1 dist =",
"yn n_accepted += 1 dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist",
"= [] for i in range(n_runs): e = func(n_samples) runs.append(e) return np.mean(runs, axis=0),",
"= func(n_samples) runs.append(e) return np.mean(runs, axis=0), np.std(runs, axis=0) parser = argparse.ArgumentParser(usage='python %(prog)s [options]',",
"- e) / (np.float(i) + 1.0) est.append(e) return np.array(est) def pi_estimator_markov_chain(n_samples, step=0.1): est",
"help='number of runs', required=True) args = parser.parse_args() n_runs = args.n_runs n_samples = args.n_samples",
"parser.add_argument('--n_runs', type=int, help='number of runs', required=True) args = parser.parse_args() n_runs = args.n_runs n_samples",
"$\\pm$ std') plt.axhline(y=np.pi, color='k', linestyle='--', label='$\\pi$') plt.ylim([np.pi-0.5, np.pi+0.5]) plt.xlim([0, 10000]) plt.xlabel('step') plt.ylabel('estimate of",
"= 0 for i in range(n_samples): x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0,",
"func) plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std, label='mean $\\pm$ std') plt.axhline(y=np.pi, color='k', linestyle='--', label='$\\pi$') plt.ylim([np.pi-0.5, np.pi+0.5])",
"n_accepted += 1 dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist <=",
"args.n_samples func = pi_estimator_markov_chain mean, std = run(n_runs, n_samples, func) plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std,",
"est = list() n_inside = 0; n_all = 0; n_accepted = 0 x",
"4.0 * np.sqrt(1.0 - np.power(x, 2)) e += (y - e) / (np.float(i)",
"+= 1 n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) acc_ratio = np.float(n_accepted)",
"/ np.float(n_all) return np.array(est) def run(n_runs, n_samples, func): runs = [] for i",
"np.array(est) def pi_estimator_integral(n_samples): est = list() e = 0.0 for i in range(n_samples):",
"argparse.ArgumentParser(usage='python %(prog)s [options]', description='Implements pi estimators.') parser.add_argument('--n_samples', type=int, help='number of samples', required=True) parser.add_argument('--n_runs',",
"runs.append(e) return np.mean(runs, axis=0), np.std(runs, axis=0) parser = argparse.ArgumentParser(usage='python %(prog)s [options]', description='Implements pi",
"i in range(n_samples): x = np.random.uniform(0.0, 1.0) y = 4.0 * np.sqrt(1.0 -",
"= parser.parse_args() n_runs = args.n_runs n_samples = args.n_samples func = pi_estimator_markov_chain mean, std",
"abs(xn) < 1.0 and abs(yn) < 1.0: x = xn y = yn",
"run(n_runs, n_samples, func): runs = [] for i in range(n_runs): e = func(n_samples)",
"= 0; n_accepted = 0 x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0)",
"n_accepted = 0 x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) for i",
"np.random.uniform(-1.0, 1.0) for i in range(n_samples): dx = np.random.uniform(-step, step) dy = np.random.uniform(-step,",
"if abs(xn) < 1.0 and abs(yn) < 1.0: x = xn y =",
"for i in range(n_samples): dx = np.random.uniform(-step, step) dy = np.random.uniform(-step, step) xn",
"1.0) dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist <= 1.0: n_inside",
"plt.axhline(y=np.pi, color='k', linestyle='--', label='$\\pi$') plt.ylim([np.pi-0.5, np.pi+0.5]) plt.xlim([0, 10000]) plt.xlabel('step') plt.ylabel('estimate of $\\pi$') plt.legend()",
"args.n_runs n_samples = args.n_samples func = pi_estimator_markov_chain mean, std = run(n_runs, n_samples, func)",
"0 for i in range(n_samples): x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0)",
"* np.float(n_inside) / np.float(n_all)) return np.array(est) def pi_estimator_integral(n_samples): est = list() e =",
"i in range(n_samples): dx = np.random.uniform(-step, step) dy = np.random.uniform(-step, step) xn =",
"= np.random.uniform(-1.0, 1.0) dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist <=",
"/ np.float(n_all)) return np.array(est) def pi_estimator_integral(n_samples): est = list() e = 0.0 for",
"x = np.random.uniform(0.0, 1.0) y = 4.0 * np.sqrt(1.0 - np.power(x, 2)) e",
"xn = x + dx yn = y + dy if abs(xn) <",
"pi_estimator_integral(n_samples): est = list() e = 0.0 for i in range(n_samples): x =",
"help='number of samples', required=True) parser.add_argument('--n_runs', type=int, help='number of runs', required=True) args = parser.parse_args()",
"label='mean $\\pm$ std') plt.axhline(y=np.pi, color='k', linestyle='--', label='$\\pi$') plt.ylim([np.pi-0.5, np.pi+0.5]) plt.xlim([0, 10000]) plt.xlabel('step') plt.ylabel('estimate",
"pi_estimator_markov_chain mean, std = run(n_runs, n_samples, func) plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std, label='mean $\\pm$ std')",
"dx = np.random.uniform(-step, step) dy = np.random.uniform(-step, step) xn = x + dx",
"n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) return np.array(est) def pi_estimator_integral(n_samples): est",
"import numpy as np import matplotlib.pyplot as plt def pi_estimator(n_samples): est = list()",
"2) + np.power(y, 2)) if dist <= 1.0: n_inside += 1 n_all +=",
"< 1.0 and abs(yn) < 1.0: x = xn y = yn n_accepted",
"np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist <= 1.0: n_inside += 1 n_all",
"samples', required=True) parser.add_argument('--n_runs', type=int, help='number of runs', required=True) args = parser.parse_args() n_runs =",
"np.random.uniform(-step, step) dy = np.random.uniform(-step, step) xn = x + dx yn =",
"mean, std = run(n_runs, n_samples, func) plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std, label='mean $\\pm$ std') plt.axhline(y=np.pi,",
"[options]', description='Implements pi estimators.') parser.add_argument('--n_samples', type=int, help='number of samples', required=True) parser.add_argument('--n_runs', type=int, help='number",
"runs', required=True) args = parser.parse_args() n_runs = args.n_runs n_samples = args.n_samples func =",
"e = func(n_samples) runs.append(e) return np.mean(runs, axis=0), np.std(runs, axis=0) parser = argparse.ArgumentParser(usage='python %(prog)s",
"= pi_estimator_markov_chain mean, std = run(n_runs, n_samples, func) plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std, label='mean $\\pm$",
"= np.random.uniform(0.0, 1.0) y = 4.0 * np.sqrt(1.0 - np.power(x, 2)) e +=",
"<reponame>jakryd/0800-fizobl import argparse import numpy as np import matplotlib.pyplot as plt def pi_estimator(n_samples):",
"abs(yn) < 1.0: x = xn y = yn n_accepted += 1 dist",
"np.float(n_all)) acc_ratio = np.float(n_accepted) / np.float(n_all) return np.array(est) def run(n_runs, n_samples, func): runs",
"= 0; n_all = 0 for i in range(n_samples): x = np.random.uniform(-1.0, 1.0)",
"i in range(n_runs): e = func(n_samples) runs.append(e) return np.mean(runs, axis=0), np.std(runs, axis=0) parser",
"x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) for i in range(n_samples): dx",
"for i in range(n_samples): x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) dist",
"x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) dist = np.sqrt(np.power(x, 2) +",
"if dist <= 1.0: n_inside += 1 n_all += 1 est.append(4.0 * np.float(n_inside)",
"* np.float(n_inside) / np.float(n_all)) acc_ratio = np.float(n_accepted) / np.float(n_all) return np.array(est) def run(n_runs,",
"yn = y + dy if abs(xn) < 1.0 and abs(yn) < 1.0:",
"return np.array(est) def pi_estimator_integral(n_samples): est = list() e = 0.0 for i in",
"type=int, help='number of samples', required=True) parser.add_argument('--n_runs', type=int, help='number of runs', required=True) args =",
"est.append(4.0 * np.float(n_inside) / np.float(n_all)) return np.array(est) def pi_estimator_integral(n_samples): est = list() e",
"for i in range(n_runs): e = func(n_samples) runs.append(e) return np.mean(runs, axis=0), np.std(runs, axis=0)",
"2)) if dist <= 1.0: n_inside += 1 n_all += 1 est.append(4.0 *",
"= 0; n_all = 0; n_accepted = 0 x = np.random.uniform(-1.0, 1.0) y",
"argparse import numpy as np import matplotlib.pyplot as plt def pi_estimator(n_samples): est =",
"np.power(x, 2)) e += (y - e) / (np.float(i) + 1.0) est.append(e) return",
"y1=mean-std, y2=mean+std, label='mean $\\pm$ std') plt.axhline(y=np.pi, color='k', linestyle='--', label='$\\pi$') plt.ylim([np.pi-0.5, np.pi+0.5]) plt.xlim([0, 10000])",
"+ dx yn = y + dy if abs(xn) < 1.0 and abs(yn)",
"np.array(est) def run(n_runs, n_samples, func): runs = [] for i in range(n_runs): e",
"+= 1 dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist <= 1.0:",
"+= 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) acc_ratio = np.float(n_accepted) / np.float(n_all) return",
"x + dx yn = y + dy if abs(xn) < 1.0 and",
"of samples', required=True) parser.add_argument('--n_runs', type=int, help='number of runs', required=True) args = parser.parse_args() n_runs",
"type=int, help='number of runs', required=True) args = parser.parse_args() n_runs = args.n_runs n_samples =",
"= np.random.uniform(-step, step) dy = np.random.uniform(-step, step) xn = x + dx yn",
"= args.n_samples func = pi_estimator_markov_chain mean, std = run(n_runs, n_samples, func) plt.fill_between(x=range(n_samples), y1=mean-std,",
"np.random.uniform(-step, step) xn = x + dx yn = y + dy if",
"def pi_estimator(n_samples): est = list() n_inside = 0; n_all = 0 for i",
"range(n_samples): dx = np.random.uniform(-step, step) dy = np.random.uniform(-step, step) xn = x +",
"1.0: x = xn y = yn n_accepted += 1 dist = np.sqrt(np.power(x,",
"= run(n_runs, n_samples, func) plt.fill_between(x=range(n_samples), y1=mean-std, y2=mean+std, label='mean $\\pm$ std') plt.axhline(y=np.pi, color='k', linestyle='--',",
"n_inside += 1 n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) acc_ratio =",
"plt def pi_estimator(n_samples): est = list() n_inside = 0; n_all = 0 for",
"pi estimators.') parser.add_argument('--n_samples', type=int, help='number of samples', required=True) parser.add_argument('--n_runs', type=int, help='number of runs',",
"1.0: n_inside += 1 n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) acc_ratio",
"as np import matplotlib.pyplot as plt def pi_estimator(n_samples): est = list() n_inside =",
"range(n_samples): x = np.random.uniform(0.0, 1.0) y = 4.0 * np.sqrt(1.0 - np.power(x, 2))",
"matplotlib.pyplot as plt def pi_estimator(n_samples): est = list() n_inside = 0; n_all =",
"dist = np.sqrt(np.power(x, 2) + np.power(y, 2)) if dist <= 1.0: n_inside +=",
"dist <= 1.0: n_inside += 1 n_all += 1 est.append(4.0 * np.float(n_inside) /",
"= np.random.uniform(-1.0, 1.0) for i in range(n_samples): dx = np.random.uniform(-step, step) dy =",
"1.0) y = 4.0 * np.sqrt(1.0 - np.power(x, 2)) e += (y -",
"return np.array(est) def pi_estimator_markov_chain(n_samples, step=0.1): est = list() n_inside = 0; n_all =",
"= 0 x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) for i in",
"0 x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) for i in range(n_samples):",
"(np.float(i) + 1.0) est.append(e) return np.array(est) def pi_estimator_markov_chain(n_samples, step=0.1): est = list() n_inside",
"= xn y = yn n_accepted += 1 dist = np.sqrt(np.power(x, 2) +",
"np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) for i in range(n_samples): dx = np.random.uniform(-step,",
"i in range(n_samples): x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) dist =",
"+= 1 n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) return np.array(est) def",
"= 0.0 for i in range(n_samples): x = np.random.uniform(0.0, 1.0) y = 4.0",
"n_inside = 0; n_all = 0 for i in range(n_samples): x = np.random.uniform(-1.0,",
"x = xn y = yn n_accepted += 1 dist = np.sqrt(np.power(x, 2)",
"np.std(runs, axis=0) parser = argparse.ArgumentParser(usage='python %(prog)s [options]', description='Implements pi estimators.') parser.add_argument('--n_samples', type=int, help='number",
"%(prog)s [options]', description='Implements pi estimators.') parser.add_argument('--n_samples', type=int, help='number of samples', required=True) parser.add_argument('--n_runs', type=int,",
"n_runs = args.n_runs n_samples = args.n_samples func = pi_estimator_markov_chain mean, std = run(n_runs,",
"est.append(4.0 * np.float(n_inside) / np.float(n_all)) acc_ratio = np.float(n_accepted) / np.float(n_all) return np.array(est) def",
"= x + dx yn = y + dy if abs(xn) < 1.0",
"1 n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) acc_ratio = np.float(n_accepted) /",
"1 n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) return np.array(est) def pi_estimator_integral(n_samples):",
"acc_ratio = np.float(n_accepted) / np.float(n_all) return np.array(est) def run(n_runs, n_samples, func): runs =",
"n_all = 0 for i in range(n_samples): x = np.random.uniform(-1.0, 1.0) y =",
"in range(n_samples): x = np.random.uniform(-1.0, 1.0) y = np.random.uniform(-1.0, 1.0) dist = np.sqrt(np.power(x,",
"runs = [] for i in range(n_runs): e = func(n_samples) runs.append(e) return np.mean(runs,",
"step) xn = x + dx yn = y + dy if abs(xn)",
"n_inside = 0; n_all = 0; n_accepted = 0 x = np.random.uniform(-1.0, 1.0)",
"estimators.') parser.add_argument('--n_samples', type=int, help='number of samples', required=True) parser.add_argument('--n_runs', type=int, help='number of runs', required=True)",
"n_all += 1 est.append(4.0 * np.float(n_inside) / np.float(n_all)) acc_ratio = np.float(n_accepted) / np.float(n_all)",
"y = 4.0 * np.sqrt(1.0 - np.power(x, 2)) e += (y - e)"
] |
[
"field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name':",
"editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory',",
"models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL),",
"name='name', field=models.CharField(default='nothing', max_length=512, unique=True), preserve_default=False, ), migrations.AddField( model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list",
"related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='description', field=models.TextField(blank=True, default=''),",
"), migrations.AddField( model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label':",
"Django 2.2.8 on 2020-03-26 11:23 from django.conf import settings from django.db import migrations,",
"'0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'), ] operations = [ migrations.AddField( model_name='deployhistory', name='created', field=models.DateTimeField(default=None, editable=False),",
"model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'), ), ]",
"preserve_default=False, ), migrations.AddField( model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag',",
"<filename>awx/main/migrations/0118_auto_20200326_1123.py # Generated by Django 2.2.8 on 2020-03-26 11:23 from django.conf import settings",
"[ migrations.AddField( model_name='deployhistory', name='created', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None, editable=False, null=True,",
"'deployhistory', 'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='description', field=models.TextField(blank=True, default=''), ), migrations.AddField( model_name='deployhistory',",
"on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='description', field=models.TextField(blank=True,",
"migrations.AddField( model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'), ),",
"name='modified_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ),",
"model_name='deployhistory', name='created', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class':",
"= [ ('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'), ] operations = [ migrations.AddField( model_name='deployhistory',",
"model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL),",
"('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'), ] operations = [ migrations.AddField( model_name='deployhistory', name='created', field=models.DateTimeField(default=None,",
"import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration):",
"model_name='deployhistory', name='name', field=models.CharField(default='nothing', max_length=512, unique=True), preserve_default=False, ), migrations.AddField( model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated",
"import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main',",
"import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'), ]",
"2.2.8 on 2020-03-26 11:23 from django.conf import settings from django.db import migrations, models",
"editable=False), ), migrations.AddField( model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory',",
"name='created_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ),",
"field=models.CharField(default='nothing', max_length=512, unique=True), preserve_default=False, ), migrations.AddField( model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of",
"migrations.AddField( model_name='deployhistory', name='description', field=models.TextField(blank=True, default=''), ), migrations.AddField( model_name='deployhistory', name='modified', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField(",
"name='description', field=models.TextField(blank=True, default=''), ), migrations.AddField( model_name='deployhistory', name='modified', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='modified_by',",
"), migrations.AddField( model_name='deployhistory', name='modified', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None, editable=False, null=True,",
"field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name':",
"by Django 2.2.8 on 2020-03-26 11:23 from django.conf import settings from django.db import",
"class Migration(migrations.Migration): dependencies = [ ('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'), ] operations =",
"model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL),",
"'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='name', field=models.CharField(default='nothing', max_length=512, unique=True),",
"'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='description', field=models.TextField(blank=True, default=''), ), migrations.AddField( model_name='deployhistory', name='modified',",
"name='created', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory',",
"'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='description', field=models.TextField(blank=True, default=''), ),",
"django.conf import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class",
"null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='name',",
"on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='name', field=models.CharField(default='nothing',",
"model_name='deployhistory', name='modified', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class':",
"editable=False), ), migrations.AddField( model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory',",
"'deployhistory', 'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='name', field=models.CharField(default='nothing', max_length=512, unique=True), preserve_default=False, ),",
"max_length=512, unique=True), preserve_default=False, ), migrations.AddField( model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.',",
"migrations.AddField( model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_modified+\",",
"'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='name', field=models.CharField(default='nothing', max_length=512, unique=True), preserve_default=False, ), migrations.AddField( model_name='deployhistory',",
"'0117_auto_20200326_1043'), ] operations = [ migrations.AddField( model_name='deployhistory', name='created', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory',",
"# Generated by Django 2.2.8 on 2020-03-26 11:23 from django.conf import settings from",
"field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField(",
"2020-03-26 11:23 from django.conf import settings from django.db import migrations, models import django.db.models.deletion",
"name='modified', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory',",
"migrations.AddField( model_name='deployhistory', name='name', field=models.CharField(default='nothing', max_length=512, unique=True), preserve_default=False, ), migrations.AddField( model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True, help_text='A",
"null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='description',",
"field=models.TextField(blank=True, default=''), ), migrations.AddField( model_name='deployhistory', name='modified', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None,",
"to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='name', field=models.CharField(default='nothing', max_length=512, unique=True), preserve_default=False, ), migrations.AddField( model_name='deployhistory', name='tags',",
"Generated by Django 2.2.8 on 2020-03-26 11:23 from django.conf import settings from django.db",
"model_name='deployhistory', name='description', field=models.TextField(blank=True, default=''), ), migrations.AddField( model_name='deployhistory', name='modified', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory',",
"default=''), ), migrations.AddField( model_name='deployhistory', name='modified', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None, editable=False,",
"from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies =",
"] operations = [ migrations.AddField( model_name='deployhistory', name='created', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='created_by',",
"('main', '0117_auto_20200326_1043'), ] operations = [ migrations.AddField( model_name='deployhistory', name='created', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField(",
"to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='description', field=models.TextField(blank=True, default=''), ), migrations.AddField( model_name='deployhistory', name='modified', field=models.DateTimeField(default=None, editable=False),",
"), migrations.AddField( model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),",
"11:23 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import",
"), migrations.AddField( model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label':",
"migrations.AddField( model_name='deployhistory', name='created', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL,",
"editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory',",
"migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'), ] operations = [ migrations.AddField( model_name='deployhistory', name='created', field=models.DateTimeField(default=None, editable=False), ),",
"on 2020-03-26 11:23 from django.conf import settings from django.db import migrations, models import",
"), migrations.AddField( model_name='deployhistory', name='description', field=models.TextField(blank=True, default=''), ), migrations.AddField( model_name='deployhistory', name='modified', field=models.DateTimeField(default=None, editable=False), ),",
"[ ('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'), ] operations = [ migrations.AddField( model_name='deployhistory', name='created',",
"import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit',",
"taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'), ] operations",
"migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0003_taggeditem_add_unique_index'),",
"Migration(migrations.Migration): dependencies = [ ('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'), ] operations = [",
"field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField(",
"migrations.AddField( model_name='deployhistory', name='modified', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='modified_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL,",
"django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [",
"'model_name': 'deployhistory', 'app_label': 'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='description', field=models.TextField(blank=True, default=''), ), migrations.AddField(",
"settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies",
"dependencies = [ ('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'), ] operations = [ migrations.AddField(",
"related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='name', field=models.CharField(default='nothing', max_length=512,",
"), migrations.AddField( model_name='deployhistory', name='name', field=models.CharField(default='nothing', max_length=512, unique=True), preserve_default=False, ), migrations.AddField( model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True,",
"migrations.AddField( model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name=\"{'class': 'deployhistory', 'model_name': 'deployhistory', 'app_label': 'main'}(class)s_created+\",",
"operations = [ migrations.AddField( model_name='deployhistory', name='created', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None,",
"'model_name': 'deployhistory', 'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='name', field=models.CharField(default='nothing', max_length=512, unique=True), preserve_default=False,",
"unique=True), preserve_default=False, ), migrations.AddField( model_name='deployhistory', name='tags', field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem',",
"'main'}(class)s_created+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='description', field=models.TextField(blank=True, default=''), ), migrations.AddField( model_name='deployhistory', name='modified', field=models.DateTimeField(default=None,",
"= [ migrations.AddField( model_name='deployhistory', name='created', field=models.DateTimeField(default=None, editable=False), ), migrations.AddField( model_name='deployhistory', name='created_by', field=models.ForeignKey(default=None, editable=False,",
"from django.conf import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers",
"'app_label': 'main'}(class)s_modified+\", to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='deployhistory', name='name', field=models.CharField(default='nothing', max_length=512, unique=True), preserve_default=False, ), migrations.AddField(",
"django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0003_taggeditem_add_unique_index'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0117_auto_20200326_1043'),"
] |
[
"urlpatterns = [ re_path(r\"^$\", mainapp.products, name=\"index\"), re_path(r\"^category/(?P<pk>\\d+)/$\", mainapp.products, name=\"category\"), re_path(r\"^category/(?P<pk>\\d+)/page/(?P<page>\\d+)/$\", mainapp.products, name=\"page\"), re_path(r\"^product/(?P<pk>\\d+)/$\",",
".apps import MainappConfig app_name = MainappConfig.name urlpatterns = [ re_path(r\"^$\", mainapp.products, name=\"index\"), re_path(r\"^category/(?P<pk>\\d+)/$\",",
"import MainappConfig app_name = MainappConfig.name urlpatterns = [ re_path(r\"^$\", mainapp.products, name=\"index\"), re_path(r\"^category/(?P<pk>\\d+)/$\", mainapp.products,",
"mainapp.views as mainapp from .apps import MainappConfig app_name = MainappConfig.name urlpatterns = [",
"= MainappConfig.name urlpatterns = [ re_path(r\"^$\", mainapp.products, name=\"index\"), re_path(r\"^category/(?P<pk>\\d+)/$\", mainapp.products, name=\"category\"), re_path(r\"^category/(?P<pk>\\d+)/page/(?P<page>\\d+)/$\", mainapp.products,",
"app_name = MainappConfig.name urlpatterns = [ re_path(r\"^$\", mainapp.products, name=\"index\"), re_path(r\"^category/(?P<pk>\\d+)/$\", mainapp.products, name=\"category\"), re_path(r\"^category/(?P<pk>\\d+)/page/(?P<page>\\d+)/$\",",
"re_path(r\"^$\", mainapp.products, name=\"index\"), re_path(r\"^category/(?P<pk>\\d+)/$\", mainapp.products, name=\"category\"), re_path(r\"^category/(?P<pk>\\d+)/page/(?P<page>\\d+)/$\", mainapp.products, name=\"page\"), re_path(r\"^product/(?P<pk>\\d+)/$\", mainapp.product, name=\"product\"), ]",
"= [ re_path(r\"^$\", mainapp.products, name=\"index\"), re_path(r\"^category/(?P<pk>\\d+)/$\", mainapp.products, name=\"category\"), re_path(r\"^category/(?P<pk>\\d+)/page/(?P<page>\\d+)/$\", mainapp.products, name=\"page\"), re_path(r\"^product/(?P<pk>\\d+)/$\", mainapp.product,",
"MainappConfig.name urlpatterns = [ re_path(r\"^$\", mainapp.products, name=\"index\"), re_path(r\"^category/(?P<pk>\\d+)/$\", mainapp.products, name=\"category\"), re_path(r\"^category/(?P<pk>\\d+)/page/(?P<page>\\d+)/$\", mainapp.products, name=\"page\"),",
"from django.urls import re_path import mainapp.views as mainapp from .apps import MainappConfig app_name",
"mainapp from .apps import MainappConfig app_name = MainappConfig.name urlpatterns = [ re_path(r\"^$\", mainapp.products,",
"import re_path import mainapp.views as mainapp from .apps import MainappConfig app_name = MainappConfig.name",
"[ re_path(r\"^$\", mainapp.products, name=\"index\"), re_path(r\"^category/(?P<pk>\\d+)/$\", mainapp.products, name=\"category\"), re_path(r\"^category/(?P<pk>\\d+)/page/(?P<page>\\d+)/$\", mainapp.products, name=\"page\"), re_path(r\"^product/(?P<pk>\\d+)/$\", mainapp.product, name=\"product\"),",
"django.urls import re_path import mainapp.views as mainapp from .apps import MainappConfig app_name =",
"MainappConfig app_name = MainappConfig.name urlpatterns = [ re_path(r\"^$\", mainapp.products, name=\"index\"), re_path(r\"^category/(?P<pk>\\d+)/$\", mainapp.products, name=\"category\"),",
"import mainapp.views as mainapp from .apps import MainappConfig app_name = MainappConfig.name urlpatterns =",
"as mainapp from .apps import MainappConfig app_name = MainappConfig.name urlpatterns = [ re_path(r\"^$\",",
"re_path import mainapp.views as mainapp from .apps import MainappConfig app_name = MainappConfig.name urlpatterns",
"from .apps import MainappConfig app_name = MainappConfig.name urlpatterns = [ re_path(r\"^$\", mainapp.products, name=\"index\"),"
] |
[
"only run locally.\") args = \"<zenossbaseurl> <zenossselector>\" # option_list = ApiCommand.option_list + (",
"then remove whitespace, then get rid of the start quote ' and end",
"if not p in pools: logger.info(\"Ensuring pool %s\", unicode(p)) try: pool, created =",
"KIND, either express or implied. # See the License for the specific language",
"p) pools[p] = pool except: pass pool_success = False else: pool = pools[p]",
"Unless required by applicable law or agreed to in writing, software # distributed",
"\"You must provide at least zenossbaseurl and zenossselector\") zenossbaseurl = args[0] if not",
"must provide at least zenossbaseurl and zenossselector\") zenossbaseurl = args[0] if not zenossbaseurl.endswith(\"/\"):",
"zenoss_client = makeHttps(zenossbaseurl, **options) # issue_tracker = self.ensure_issue_tracker(jiraname, jirabaseurl) # project = self.ensure_project(issue_tracker,",
"devlist = [(p.replace(\"/\", \"_\"), n) for (p, n) in devlist] # so now",
"= True # lets be positive :) if not p in pools: logger.info(\"Ensuring",
"role.undelete() return role def _format_pool_name(self, name): return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower() @transaction.commit_manually def ensure_pool(self,",
"= [x.replace(\"/zport/dmd/\",\"\", 1) for x in devlist] # get rid of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist",
"transaction.commit() return pool, created # @transaction.commit_manually # def ensure_ip_address(self, node, ip_address): # try:",
"rid of /zport/dmd/ devlist = [x.replace(\"/zport/dmd/\",\"\", 1) for x in devlist] # get",
"Management # Copyright 2012 British Broadcasting Corporation # # Licensed under the Apache",
"return env pools = {} environments = {} c = 0 for p,",
"try: # ip_address, created = IpAddress.objects.get_or_create(address=ip_address) # if not node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address) #",
"from optparse import make_option from django.core.management.base import CommandError from django.db import transaction from",
"# the pool creation we do here seems a bit hacky / our-zenoss-setup-specific",
"% str(e)) transaction.rollback() raise else: transaction.commit() return pool, created # @transaction.commit_manually # def",
"= Pool.objects.get_or_create(environment=environment, name=name, defaults={ \"role\": role, }) if pool.role != role: pool.role =",
"logger = logging.getLogger(__name__) class Command(ApiCommand): help = (\"Crawl a zenoss device collection and",
"not worthy of migration into the PoolManager class imho pool = None created",
"*args, **options): if len(args) < 2: raise CommandError( \"You must provide at least",
"# try: # ip_address, created = IpAddress.objects.get_or_create(address=ip_address) # if not node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address)",
"this file except in compliance with the License. # You may obtain a",
"raise # else: # transaction.commit() def handle(self, *args, **options): if len(args) < 2:",
"then get rid of the start quote ' and end quote ', devlist",
"now we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split on \"/devices/\" devlist = [x.split(\"/devices/\") for x",
"https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key \\ # --ca-file=/Users/$USER/.bbc/ca.pem import re",
"--ca-file=/Users/$USER/.bbc/ca.pem import re from optparse import make_option from django.core.management.base import CommandError from django.db",
"# so it is not worthy of migration into the PoolManager class imho",
"crichtonweb.system.models import Environment, Pool, Node, PoolMembership, Role, crichtonCronJobStatus import logging logger = logging.getLogger(__name__)",
"and # limitations under the License. # # # example that you can",
"split on \"/devices/\" devlist = [x.split(\"/devices/\") for x in devlist] devlist = [(p.replace(\"/\",",
"quote ', devlist = [x.strip()[1:][:-1] for x in content.split(\",\")] # split on \"",
"@transaction.commit_manually # def ensure_ip_address(self, node, ip_address): # try: # ip_address, created = IpAddress.objects.get_or_create(address=ip_address)",
"back\" % str(e)) transaction.rollback() raise else: transaction.commit() return pool, created # @transaction.commit_manually #",
"= role pool.save() pool.undelete() except Exception, e: logger.error(\"ensure_pool failed with %s, roolling this",
"devlist] # so now we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split on \"/devices/\" devlist =",
"Environment.objects.ensure(e) if created: logger.info(\"Created environment %s\", unicode(environment)) environments[e] = environment else: environment =",
"on mac: # ./crichton.py indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key",
"throw away the first part devlist = [x.split(\" at \")[1].strip() for x in",
"British Broadcasting Corporation # # Licensed under the Apache License, Version 2.0 (the",
"away the first part devlist = [x.split(\" at \")[1].strip() for x in devlist]",
"ANY KIND, either express or implied. # See the License for the specific",
"node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address) # node.save() # except: # transaction.rollback() # raise # else:",
"from crichtonweb.system.models import Environment, Pool, Node, PoolMembership, Role, crichtonCronJobStatus import logging logger =",
"'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get rid of [' and of '] content =",
"= environment else: environment = environments[e] pool_success = True # lets be positive",
"django.utils.encoding import iri_to_uri from crichtoncli.apihelpers import * from crichtoncli.commands import ApiCommand from crichtonweb.core.httpshelpers",
"start quote ' and end quote ', devlist = [x.strip()[1:][:-1] for x in",
"created = Role.objects.get_or_create(name=role_name) role.undelete() return role def _format_pool_name(self, name): return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower()",
"have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def get_env(n): # ipmq001.back.int.cwwtf.local env = n[n.find(\".\")+1:] # back.int.cwwtf.local env",
"self.ensure_issue_tracker(jiraname, jirabaseurl) # project = self.ensure_project(issue_tracker, projectname) logger.info(\"Getting list of nodes for %s\",",
"logger.error(\"ensure_pool failed with %s, roolling this transaction back\" % str(e)) transaction.rollback() raise else:",
"{} environments = {} c = 0 for p, n in devlist: e",
"# transaction.rollback() # raise # else: # transaction.commit() def handle(self, *args, **options): if",
"role pool.save() pool.undelete() except Exception, e: logger.error(\"ensure_pool failed with %s, roolling this transaction",
"add all\" \"devices it contains to the crichton db as nodes.\" \" Can",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"(zenossbaseurl, zenossselector) resp, content = zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp, content) # expect_xml(resp, content) #",
"we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split on \"/devices/\" devlist = [x.split(\"/devices/\") for x in",
"if pool.role != role: pool.role = role pool.save() pool.undelete() except Exception, e: logger.error(\"ensure_pool",
"e = get_env(n) # an exmaple # n -> db118.back.stage.telhc.local # p ->",
"jirabaseurl) # project = self.ensure_project(issue_tracker, projectname) logger.info(\"Getting list of nodes for %s\", zenossselector)",
"1) for x in devlist] # get rid of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist = [x.replace(zenossselector",
"/zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # .... # 'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get rid of [' and",
"at \")[1].strip() for x in devlist] # get rid of /zport/dmd/ devlist =",
"can run on mac: # ./crichton.py indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\",
"handle(self, *args, **options): if len(args) < 2: raise CommandError( \"You must provide at",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"# e -> stage if not e in environments: environment, created = Environment.objects.ensure(e)",
"positive :) if not p in pools: logger.info(\"Ensuring pool %s\", unicode(p)) try: pool,",
"\"<zenossbaseurl> <zenossselector>\" # option_list = ApiCommand.option_list + ( # ) # uses database!",
"resp, content = zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp, content) # expect_xml(resp, content) # ['BBCApplicationHostDevice at",
"_format_pool_name(self, name): return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower() @transaction.commit_manually def ensure_pool(self, environment, name): # the",
".... # 'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get rid of [' and of ']",
"now we have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def get_env(n): # ipmq001.back.int.cwwtf.local env = n[n.find(\".\")+1:] #",
"2012 British Broadcasting Corporation # # Licensed under the Apache License, Version 2.0",
"logging logger = logging.getLogger(__name__) class Command(ApiCommand): help = (\"Crawl a zenoss device collection",
"OF ANY KIND, either express or implied. # See the License for the",
"x in content.split(\",\")] # split on \" at \" and throw away the",
"Node, PoolMembership, Role, crichtonCronJobStatus import logging logger = logging.getLogger(__name__) class Command(ApiCommand): help =",
"= n[n.find(\".\")+1:] # back.int.cwwtf.local env = env.replace(\"back.\", \"\") # int.cwwtf.local env = env.replace(\".local\",",
"environments: environment, created = Environment.objects.ensure(e) if created: logger.info(\"Created environment %s\", unicode(environment)) environments[e] =",
"environments[e] pool_success = True # lets be positive :) if not p in",
"# issue_tracker = self.ensure_issue_tracker(jiraname, jirabaseurl) # project = self.ensure_project(issue_tracker, projectname) logger.info(\"Getting list of",
"import ApiCommand from crichtonweb.core.httpshelpers import * from crichtonweb.system.models import Environment, Pool, Node, PoolMembership,",
"you can run on mac: # ./crichton.py indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem",
"= self._format_pool_name(name) role = self._ensure_role_for_pool(name) pool, created = Pool.objects.get_or_create(environment=environment, name=name, defaults={ \"role\": role,",
"transaction.commit() def handle(self, *args, **options): if len(args) < 2: raise CommandError( \"You must",
"that you can run on mac: # ./crichton.py indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\ #",
"**options): if len(args) < 2: raise CommandError( \"You must provide at least zenossbaseurl",
"Crichton, Admirable Source Configuration Management # Copyright 2012 British Broadcasting Corporation # #",
"and end quote ', devlist = [x.strip()[1:][:-1] for x in content.split(\",\")] # split",
"/ our-zenoss-setup-specific # so it is not worthy of migration into the PoolManager",
"issue_tracker = self.ensure_issue_tracker(jiraname, jirabaseurl) # project = self.ensure_project(issue_tracker, projectname) logger.info(\"Getting list of nodes",
"in pools: logger.info(\"Ensuring pool %s\", unicode(p)) try: pool, created = self.ensure_pool(environment, p) pools[p]",
"True # lets be positive :) if not p in pools: logger.info(\"Ensuring pool",
"e -> stage if not e in environments: environment, created = Environment.objects.ensure(e) if",
"= self.ensure_project(issue_tracker, projectname) logger.info(\"Getting list of nodes for %s\", zenossselector) device_list_url = \"%szport/dmd/%s/getSubDevices\"",
"pools: logger.info(\"Ensuring pool %s\", unicode(p)) try: pool, created = self.ensure_pool(environment, p) pools[p] =",
"role = self._ensure_role_for_pool(name) pool, created = Pool.objects.get_or_create(environment=environment, name=name, defaults={ \"role\": role, }) if",
"contains to the crichton db as nodes.\" \" Can only run locally.\") args",
"# lets be positive :) if not p in pools: logger.info(\"Ensuring pool %s\",",
"import iri_to_uri from crichtoncli.apihelpers import * from crichtoncli.commands import ApiCommand from crichtonweb.core.httpshelpers import",
"= args[0] if not zenossbaseurl.endswith(\"/\"): zenossbaseurl += \"/\" zenossselector = args[1] zenoss_client =",
"self.ensure_project(issue_tracker, projectname) logger.info(\"Getting list of nodes for %s\", zenossselector) device_list_url = \"%szport/dmd/%s/getSubDevices\" %",
"n[n.find(\".\")+1:] # back.int.cwwtf.local env = env.replace(\"back.\", \"\") # int.cwwtf.local env = env.replace(\".local\", \"\")",
"in content.split(\",\")] # split on \" at \" and throw away the first",
"ApiCommand.option_list + ( # ) # uses database! requires_model_validation = True def print_help(self,",
"[x.replace(zenossselector + \"/\",\"\", 1) for x in devlist] # so now we have",
"<zenossselector>\" # option_list = ApiCommand.option_list + ( # ) # uses database! requires_model_validation",
"for x in devlist] # get rid of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist = [x.replace(zenossselector +",
"for x in devlist] # so now we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split on",
"= get_env(n) # an exmaple # n -> db118.back.stage.telhc.local # p -> Database_Postgres",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"zenossbaseurl = args[0] if not zenossbaseurl.endswith(\"/\"): zenossbaseurl += \"/\" zenossselector = args[1] zenoss_client",
"a zenoss device collection and add all\" \"devices it contains to the crichton",
"pool.undelete() except Exception, e: logger.error(\"ensure_pool failed with %s, roolling this transaction back\" %",
"/zport/dmd/ devlist = [x.replace(\"/zport/dmd/\",\"\", 1) for x in devlist] # get rid of",
"= Environment.objects.ensure(e) if created: logger.info(\"Created environment %s\", unicode(environment)) environments[e] = environment else: environment",
"\\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key \\ # --ca-file=/Users/$USER/.bbc/ca.pem import re from optparse import make_option from",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"# so now we have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def get_env(n): # ipmq001.back.int.cwwtf.local env =",
"[x.replace(\"/zport/dmd/\",\"\", 1) for x in devlist] # get rid of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist =",
"Pool.objects.get_or_create(environment=environment, name=name, defaults={ \"role\": role, }) if pool.role != role: pool.role = role",
"def handle(self, *args, **options): if len(args) < 2: raise CommandError( \"You must provide",
"env.replace(\"back.\", \"\") # int.cwwtf.local env = env.replace(\".local\", \"\") # int.cwwtf env = env.split(\".\")[0]",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"[x.split(\"/devices/\") for x in devlist] devlist = [(p.replace(\"/\", \"_\"), n) for (p, n)",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"self._ensure_role_for_pool(name) pool, created = Pool.objects.get_or_create(environment=environment, name=name, defaults={ \"role\": role, }) if pool.role !=",
"crichtoncli.apihelpers import * from crichtoncli.commands import ApiCommand from crichtonweb.core.httpshelpers import * from crichtonweb.system.models",
"(p, n) in devlist] # so now we have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def get_env(n):",
"ApiCommand from crichtonweb.core.httpshelpers import * from crichtonweb.system.models import Environment, Pool, Node, PoolMembership, Role,",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"= pool except: pass pool_success = False else: pool = pools[p] c +=",
"# example that you can run on mac: # ./crichton.py indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery",
") # uses database! requires_model_validation = True def print_help(self, zenossbaseurl, zenossselector): super(ApiCommand, self).print_help(zenossbaseurl,",
"# an exmaple # n -> db118.back.stage.telhc.local # p -> Database_Postgres # e",
"c += 1 node, created = Node.objects.ensure(environment, n) if pool_success: pool_membership, created =",
"\"/devices/\" devlist = [x.split(\"/devices/\") for x in devlist] devlist = [(p.replace(\"/\", \"_\"), n)",
"# option_list = ApiCommand.option_list + ( # ) # uses database! requires_model_validation =",
"if len(args) < 2: raise CommandError( \"You must provide at least zenossbaseurl and",
"so it is not worthy of migration into the PoolManager class imho pool",
"so now we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split on \"/devices/\" devlist = [x.split(\"/devices/\") for",
"iri_to_uri from crichtoncli.apihelpers import * from crichtoncli.commands import ApiCommand from crichtonweb.core.httpshelpers import *",
"required by applicable law or agreed to in writing, software # distributed under",
"\" and throw away the first part devlist = [x.split(\" at \")[1].strip() for",
"# split on , then remove whitespace, then get rid of the start",
"applicable law or agreed to in writing, software # distributed under the License",
"ensure_ip_address(self, node, ip_address): # try: # ip_address, created = IpAddress.objects.get_or_create(address=ip_address) # if not",
"str(e)) transaction.rollback() raise else: transaction.commit() return pool, created # @transaction.commit_manually # def ensure_ip_address(self,",
"# split on \" at \" and throw away the first part devlist",
"', devlist = [x.strip()[1:][:-1] for x in content.split(\",\")] # split on \" at",
"or agreed to in writing, software # distributed under the License is distributed",
"# int return env pools = {} environments = {} c = 0",
"zenossbaseurl, zenossselector): super(ApiCommand, self).print_help(zenossbaseurl, zenossselector) def _ensure_role_for_pool(self, pool_name): role_name = pool_name.split(\"_\")[0] role, created",
"the crichton db as nodes.\" \" Can only run locally.\") args = \"<zenossbaseurl>",
"created = Environment.objects.ensure(e) if created: logger.info(\"Created environment %s\", unicode(environment)) environments[e] = environment else:",
"at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get rid of [' and of '] content = content[2:][:-1]",
"of nodes for %s\", zenossselector) device_list_url = \"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl, zenossselector) resp, content",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"Copyright 2012 British Broadcasting Corporation # # Licensed under the Apache License, Version",
"created = Pool.objects.get_or_create(environment=environment, name=name, defaults={ \"role\": role, }) if pool.role != role: pool.role",
"try: pool, created = self.ensure_pool(environment, p) pools[p] = pool except: pass pool_success =",
"created = False try: name = self._format_pool_name(name) role = self._ensure_role_for_pool(name) pool, created =",
"return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower() @transaction.commit_manually def ensure_pool(self, environment, name): # the pool creation",
"= content[2:][:-1] # split on , then remove whitespace, then get rid of",
"\\ # --ca-file=/Users/$USER/.bbc/ca.pem import re from optparse import make_option from django.core.management.base import CommandError",
"= zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp, content) # expect_xml(resp, content) # ['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', #",
"= (\"Crawl a zenoss device collection and add all\" \"devices it contains to",
"on , then remove whitespace, then get rid of the start quote '",
"# limitations under the License. # # # example that you can run",
"the PoolManager class imho pool = None created = False try: name =",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"crichton db as nodes.\" \" Can only run locally.\") args = \"<zenossbaseurl> <zenossselector>\"",
"Devices/BBC/ApplicationHost/Platform/Delivery/ devlist = [x.replace(zenossselector + \"/\",\"\", 1) for x in devlist] # so",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"return pool, created # @transaction.commit_manually # def ensure_ip_address(self, node, ip_address): # try: #",
"\"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl, zenossselector) resp, content = zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp, content) # expect_xml(resp,",
"= env.replace(\".local\", \"\") # int.cwwtf env = env.split(\".\")[0] # int return env pools",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"exmaple # n -> db118.back.stage.telhc.local # p -> Database_Postgres # e -> stage",
"License. # You may obtain a copy of the License at # #",
"= 0 for p, n in devlist: e = get_env(n) # an exmaple",
"= pool_name.split(\"_\")[0] role, created = Role.objects.get_or_create(name=role_name) role.undelete() return role def _format_pool_name(self, name): return",
"with %s, roolling this transaction back\" % str(e)) transaction.rollback() raise else: transaction.commit() return",
"split on \" at \" and throw away the first part devlist =",
"Configuration Management # Copyright 2012 British Broadcasting Corporation # # Licensed under the",
"devlist = [x.replace(zenossselector + \"/\",\"\", 1) for x in devlist] # so now",
"# uses database! requires_model_validation = True def print_help(self, zenossbaseurl, zenossselector): super(ApiCommand, self).print_help(zenossbaseurl, zenossselector)",
"# raise # else: # transaction.commit() def handle(self, *args, **options): if len(args) <",
"# p -> Database_Postgres # e -> stage if not e in environments:",
"Devices/BBC/ApplicationHost/Platform/Delivery \\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key \\ # --ca-file=/Users/$USER/.bbc/ca.pem import re from",
"compliance with the License. # You may obtain a copy of the License",
"= True def print_help(self, zenossbaseurl, zenossselector): super(ApiCommand, self).print_help(zenossbaseurl, zenossselector) def _ensure_role_for_pool(self, pool_name): role_name",
"_ensure_role_for_pool(self, pool_name): role_name = pool_name.split(\"_\")[0] role, created = Role.objects.get_or_create(name=role_name) role.undelete() return role def",
"not p in pools: logger.info(\"Ensuring pool %s\", unicode(p)) try: pool, created = self.ensure_pool(environment,",
"in devlist] # get rid of /zport/dmd/ devlist = [x.replace(\"/zport/dmd/\",\"\", 1) for x",
"db as nodes.\" \" Can only run locally.\") args = \"<zenossbaseurl> <zenossselector>\" #",
"Role, crichtonCronJobStatus import logging logger = logging.getLogger(__name__) class Command(ApiCommand): help = (\"Crawl a",
"environment %s\", unicode(environment)) environments[e] = environment else: environment = environments[e] pool_success = True",
"name): return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower() @transaction.commit_manually def ensure_pool(self, environment, name): # the pool",
"defaults={ \"role\": role, }) if pool.role != role: pool.role = role pool.save() pool.undelete()",
"env.split(\".\")[0] # int return env pools = {} environments = {} c =",
"ip_address): # try: # ip_address, created = IpAddress.objects.get_or_create(address=ip_address) # if not node.ip_addresses.filter(address=ip_address): #",
"have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split on \"/devices/\" devlist = [x.split(\"/devices/\") for x in devlist]",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"p -> Database_Postgres # e -> stage if not e in environments: environment,",
"for (p, n) in devlist] # so now we have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def",
"p in pools: logger.info(\"Ensuring pool %s\", unicode(p)) try: pool, created = self.ensure_pool(environment, p)",
"rid of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist = [x.replace(zenossselector + \"/\",\"\", 1) for x in devlist]",
"optparse import make_option from django.core.management.base import CommandError from django.db import transaction from django.utils.encoding",
"}) if pool.role != role: pool.role = role pool.save() pool.undelete() except Exception, e:",
"remove whitespace, then get rid of the start quote ' and end quote",
"the start quote ' and end quote ', devlist = [x.strip()[1:][:-1] for x",
"it is not worthy of migration into the PoolManager class imho pool =",
"not zenossbaseurl.endswith(\"/\"): zenossbaseurl += \"/\" zenossselector = args[1] zenoss_client = makeHttps(zenossbaseurl, **options) #",
"django.db import transaction from django.utils.encoding import iri_to_uri from crichtoncli.apihelpers import * from crichtoncli.commands",
"help = (\"Crawl a zenoss device collection and add all\" \"devices it contains",
"name=name, defaults={ \"role\": role, }) if pool.role != role: pool.role = role pool.save()",
"this transaction back\" % str(e)) transaction.rollback() raise else: transaction.commit() return pool, created #",
"def print_help(self, zenossbaseurl, zenossselector): super(ApiCommand, self).print_help(zenossbaseurl, zenossselector) def _ensure_role_for_pool(self, pool_name): role_name = pool_name.split(\"_\")[0]",
"Command(ApiCommand): help = (\"Crawl a zenoss device collection and add all\" \"devices it",
"e in environments: environment, created = Environment.objects.ensure(e) if created: logger.info(\"Created environment %s\", unicode(environment))",
"rid of the start quote ' and end quote ', devlist = [x.strip()[1:][:-1]",
"%s\", unicode(environment)) environments[e] = environment else: environment = environments[e] pool_success = True #",
"not use this file except in compliance with the License. # You may",
"pass pool_success = False else: pool = pools[p] c += 1 node, created",
"env = n[n.find(\".\")+1:] # back.int.cwwtf.local env = env.replace(\"back.\", \"\") # int.cwwtf.local env =",
"\" Can only run locally.\") args = \"<zenossbaseurl> <zenossselector>\" # option_list = ApiCommand.option_list",
"we have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def get_env(n): # ipmq001.back.int.cwwtf.local env = n[n.find(\".\")+1:] # back.int.cwwtf.local",
"pool, created # @transaction.commit_manually # def ensure_ip_address(self, node, ip_address): # try: # ip_address,",
"name): # the pool creation we do here seems a bit hacky /",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"env pools = {} environments = {} c = 0 for p, n",
"[x.strip()[1:][:-1] for x in content.split(\",\")] # split on \" at \" and throw",
"Corporation # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"devlist] # get rid of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist = [x.replace(zenossselector + \"/\",\"\", 1) for",
"device collection and add all\" \"devices it contains to the crichton db as",
"class Command(ApiCommand): help = (\"Crawl a zenoss device collection and add all\" \"devices",
"./crichton.py indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key \\ # --ca-file=/Users/$USER/.bbc/ca.pem",
"= pools[p] c += 1 node, created = Node.objects.ensure(environment, n) if pool_success: pool_membership,",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"\"/\",\"\", 1) for x in devlist] # so now we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" #",
"# back.int.cwwtf.local env = env.replace(\"back.\", \"\") # int.cwwtf.local env = env.replace(\".local\", \"\") #",
"= env.split(\".\")[0] # int return env pools = {} environments = {} c",
"args[1] zenoss_client = makeHttps(zenossbaseurl, **options) # issue_tracker = self.ensure_issue_tracker(jiraname, jirabaseurl) # project =",
"example that you can run on mac: # ./crichton.py indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\",
"and add all\" \"devices it contains to the crichton db as nodes.\" \"",
"# int.cwwtf.local env = env.replace(\".local\", \"\") # int.cwwtf env = env.split(\".\")[0] # int",
"1) for x in devlist] # so now we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split",
"# you may not use this file except in compliance with the License.",
"to the crichton db as nodes.\" \" Can only run locally.\") args =",
"devlist = [x.strip()[1:][:-1] for x in content.split(\",\")] # split on \" at \"",
"content = content[2:][:-1] # split on , then remove whitespace, then get rid",
"e: logger.error(\"ensure_pool failed with %s, roolling this transaction back\" % str(e)) transaction.rollback() raise",
"n in devlist: e = get_env(n) # an exmaple # n -> db118.back.stage.telhc.local",
"node.ip_addresses.add(ip_address) # node.save() # except: # transaction.rollback() # raise # else: # transaction.commit()",
"agreed to in writing, software # distributed under the License is distributed on",
"['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # .... # 'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get rid of",
"False try: name = self._format_pool_name(name) role = self._ensure_role_for_pool(name) pool, created = Pool.objects.get_or_create(environment=environment, name=name,",
"imho pool = None created = False try: name = self._format_pool_name(name) role =",
"# Copyright 2012 British Broadcasting Corporation # # Licensed under the Apache License,",
"(the \"License\"); # you may not use this file except in compliance with",
"so now we have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def get_env(n): # ipmq001.back.int.cwwtf.local env = n[n.find(\".\")+1:]",
"# --ca-file=/Users/$USER/.bbc/ca.pem import re from optparse import make_option from django.core.management.base import CommandError from",
"pool = pools[p] c += 1 node, created = Node.objects.ensure(environment, n) if pool_success:",
"# else: # transaction.commit() def handle(self, *args, **options): if len(args) < 2: raise",
"# ) # uses database! requires_model_validation = True def print_help(self, zenossbaseurl, zenossselector): super(ApiCommand,",
"# project = self.ensure_project(issue_tracker, projectname) logger.info(\"Getting list of nodes for %s\", zenossselector) device_list_url",
"created: logger.info(\"Created environment %s\", unicode(environment)) environments[e] = environment else: environment = environments[e] pool_success",
"# Unless required by applicable law or agreed to in writing, software #",
", then remove whitespace, then get rid of the start quote ' and",
"by applicable law or agreed to in writing, software # distributed under the",
"role, }) if pool.role != role: pool.role = role pool.save() pool.undelete() except Exception,",
"= [x.replace(zenossselector + \"/\",\"\", 1) for x in devlist] # so now we",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"'] content = content[2:][:-1] # split on , then remove whitespace, then get",
"-> Database_Postgres # e -> stage if not e in environments: environment, created",
"pools[p] c += 1 node, created = Node.objects.ensure(environment, n) if pool_success: pool_membership, created",
"\"ipmq001.back.int.cwwtf.local\") def get_env(n): # ipmq001.back.int.cwwtf.local env = n[n.find(\".\")+1:] # back.int.cwwtf.local env = env.replace(\"back.\",",
"# --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key \\ # --ca-file=/Users/$USER/.bbc/ca.pem import re from optparse import",
"= Role.objects.get_or_create(name=role_name) role.undelete() return role def _format_pool_name(self, name): return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower() @transaction.commit_manually",
"# if not node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address) # node.save() # except: # transaction.rollback() #",
"else: environment = environments[e] pool_success = True # lets be positive :) if",
"mac: # ./crichton.py indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key \\",
"0 for p, n in devlist: e = get_env(n) # an exmaple #",
"file except in compliance with the License. # You may obtain a copy",
"on \"/devices/\" devlist = [x.split(\"/devices/\") for x in devlist] devlist = [(p.replace(\"/\", \"_\"),",
"re from optparse import make_option from django.core.management.base import CommandError from django.db import transaction",
"def ensure_pool(self, environment, name): # the pool creation we do here seems a",
"ensure_pool(self, environment, name): # the pool creation we do here seems a bit",
"import * from crichtonweb.system.models import Environment, Pool, Node, PoolMembership, Role, crichtonCronJobStatus import logging",
"= environments[e] pool_success = True # lets be positive :) if not p",
"indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key \\ # --ca-file=/Users/$USER/.bbc/ca.pem import",
"= self._ensure_role_for_pool(name) pool, created = Pool.objects.get_or_create(environment=environment, name=name, defaults={ \"role\": role, }) if pool.role",
"Exception, e: logger.error(\"ensure_pool failed with %s, roolling this transaction back\" % str(e)) transaction.rollback()",
"License for the specific language governing permissions and # limitations under the License.",
"def ensure_ip_address(self, node, ip_address): # try: # ip_address, created = IpAddress.objects.get_or_create(address=ip_address) # if",
"logging.getLogger(__name__) class Command(ApiCommand): help = (\"Crawl a zenoss device collection and add all\"",
"= {} environments = {} c = 0 for p, n in devlist:",
"= False else: pool = pools[p] c += 1 node, created = Node.objects.ensure(environment,",
"= env.replace(\"back.\", \"\") # int.cwwtf.local env = env.replace(\".local\", \"\") # int.cwwtf env =",
"x in devlist] devlist = [(p.replace(\"/\", \"_\"), n) for (p, n) in devlist]",
"locally.\") args = \"<zenossbaseurl> <zenossselector>\" # option_list = ApiCommand.option_list + ( # )",
"except: pass pool_success = False else: pool = pools[p] c += 1 node,",
"to in writing, software # distributed under the License is distributed on an",
"x in devlist] # get rid of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist = [x.replace(zenossselector + \"/\",\"\",",
"!= role: pool.role = role pool.save() pool.undelete() except Exception, e: logger.error(\"ensure_pool failed with",
"implied. # See the License for the specific language governing permissions and #",
"role_name = pool_name.split(\"_\")[0] role, created = Role.objects.get_or_create(name=role_name) role.undelete() return role def _format_pool_name(self, name):",
"\"License\"); # you may not use this file except in compliance with the",
"# ip_address, created = IpAddress.objects.get_or_create(address=ip_address) # if not node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address) # node.save()",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"pool_name.split(\"_\")[0] role, created = Role.objects.get_or_create(name=role_name) role.undelete() return role def _format_pool_name(self, name): return re.sub(r'[^a-zA-Z0-9_]',",
"least zenossbaseurl and zenossselector\") zenossbaseurl = args[0] if not zenossbaseurl.endswith(\"/\"): zenossbaseurl += \"/\"",
"n) for (p, n) in devlist] # so now we have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\")",
"zenossselector\") zenossbaseurl = args[0] if not zenossbaseurl.endswith(\"/\"): zenossbaseurl += \"/\" zenossselector = args[1]",
"devlist] # get rid of /zport/dmd/ devlist = [x.replace(\"/zport/dmd/\",\"\", 1) for x in",
"created = Node.objects.ensure(environment, n) if pool_success: pool_membership, created = PoolMembership.objects.ensure(pool, node) logger.info(\"Saw %d",
"in environments: environment, created = Environment.objects.ensure(e) if created: logger.info(\"Created environment %s\", unicode(environment)) environments[e]",
"= \"<zenossbaseurl> <zenossselector>\" # option_list = ApiCommand.option_list + ( # ) # uses",
"= [x.split(\"/devices/\") for x in devlist] devlist = [(p.replace(\"/\", \"_\"), n) for (p,",
"logger.info(\"Created environment %s\", unicode(environment)) environments[e] = environment else: environment = environments[e] pool_success =",
"# # # example that you can run on mac: # ./crichton.py indexzenoss",
"devlist] devlist = [(p.replace(\"/\", \"_\"), n) for (p, n) in devlist] # so",
"in devlist: e = get_env(n) # an exmaple # n -> db118.back.stage.telhc.local #",
"Database_Postgres # e -> stage if not e in environments: environment, created =",
"Pool, Node, PoolMembership, Role, crichtonCronJobStatus import logging logger = logging.getLogger(__name__) class Command(ApiCommand): help",
"get rid of [' and of '] content = content[2:][:-1] # split on",
"or implied. # See the License for the specific language governing permissions and",
"CommandError from django.db import transaction from django.utils.encoding import iri_to_uri from crichtoncli.apihelpers import *",
"at \" and throw away the first part devlist = [x.split(\" at \")[1].strip()",
"collection and add all\" \"devices it contains to the crichton db as nodes.\"",
"# .... # 'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get rid of [' and of",
"we do here seems a bit hacky / our-zenoss-setup-specific # so it is",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"provide at least zenossbaseurl and zenossselector\") zenossbaseurl = args[0] if not zenossbaseurl.endswith(\"/\"): zenossbaseurl",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"Can only run locally.\") args = \"<zenossbaseurl> <zenossselector>\" # option_list = ApiCommand.option_list +",
"run on mac: # ./crichton.py indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ #",
"is not worthy of migration into the PoolManager class imho pool = None",
"in devlist] devlist = [(p.replace(\"/\", \"_\"), n) for (p, n) in devlist] #",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"env.replace(\".local\", \"\") # int.cwwtf env = env.split(\".\")[0] # int return env pools =",
"in writing, software # distributed under the License is distributed on an \"AS",
"nodes for %s\", zenossselector) device_list_url = \"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl, zenossselector) resp, content =",
"zenossbaseurl and zenossselector\") zenossbaseurl = args[0] if not zenossbaseurl.endswith(\"/\"): zenossbaseurl += \"/\" zenossselector",
"expect_xml(resp, content) # ['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # .... # 'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] #",
"else: transaction.commit() return pool, created # @transaction.commit_manually # def ensure_ip_address(self, node, ip_address): #",
"role def _format_pool_name(self, name): return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower() @transaction.commit_manually def ensure_pool(self, environment, name):",
"into the PoolManager class imho pool = None created = False try: name",
"import CommandError from django.db import transaction from django.utils.encoding import iri_to_uri from crichtoncli.apihelpers import",
"args = \"<zenossbaseurl> <zenossselector>\" # option_list = ApiCommand.option_list + ( # ) #",
"2: raise CommandError( \"You must provide at least zenossbaseurl and zenossselector\") zenossbaseurl =",
"\"/\" zenossselector = args[1] zenoss_client = makeHttps(zenossbaseurl, **options) # issue_tracker = self.ensure_issue_tracker(jiraname, jirabaseurl)",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"import re from optparse import make_option from django.core.management.base import CommandError from django.db import",
"run locally.\") args = \"<zenossbaseurl> <zenossselector>\" # option_list = ApiCommand.option_list + ( #",
"n) in devlist] # so now we have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def get_env(n): #",
"first part devlist = [x.split(\" at \")[1].strip() for x in devlist] # get",
"--key-file=/Users/$USER/.bbc/dev.domain.com.key \\ # --ca-file=/Users/$USER/.bbc/ca.pem import re from optparse import make_option from django.core.management.base import",
"if created: logger.info(\"Created environment %s\", unicode(environment)) environments[e] = environment else: environment = environments[e]",
"= Node.objects.ensure(environment, n) if pool_success: pool_membership, created = PoolMembership.objects.ensure(pool, node) logger.info(\"Saw %d nodes\",",
"devlist] # so now we have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def get_env(n): # ipmq001.back.int.cwwtf.local env",
"database! requires_model_validation = True def print_help(self, zenossbaseurl, zenossselector): super(ApiCommand, self).print_help(zenossbaseurl, zenossselector) def _ensure_role_for_pool(self,",
"# ['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # .... # 'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get rid",
"device_list_url = \"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl, zenossselector) resp, content = zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp, content)",
"limitations under the License. # # # example that you can run on",
"quote ' and end quote ', devlist = [x.strip()[1:][:-1] for x in content.split(\",\")]",
"= False try: name = self._format_pool_name(name) role = self._ensure_role_for_pool(name) pool, created = Pool.objects.get_or_create(environment=environment,",
"unicode(environment)) environments[e] = environment else: environment = environments[e] pool_success = True # lets",
"not node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address) # node.save() # except: # transaction.rollback() # raise #",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"of /zport/dmd/ devlist = [x.replace(\"/zport/dmd/\",\"\", 1) for x in devlist] # get rid",
"# @transaction.commit_manually # def ensure_ip_address(self, node, ip_address): # try: # ip_address, created =",
"you may not use this file except in compliance with the License. #",
"content = zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp, content) # expect_xml(resp, content) # ['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>',",
"not e in environments: environment, created = Environment.objects.ensure(e) if created: logger.info(\"Created environment %s\",",
"devlist = [x.split(\"/devices/\") for x in devlist] devlist = [(p.replace(\"/\", \"_\"), n) for",
"from crichtoncli.apihelpers import * from crichtoncli.commands import ApiCommand from crichtonweb.core.httpshelpers import * from",
"an exmaple # n -> db118.back.stage.telhc.local # p -> Database_Postgres # e ->",
"pool except: pass pool_success = False else: pool = pools[p] c += 1",
"[x.split(\" at \")[1].strip() for x in devlist] # get rid of /zport/dmd/ devlist",
"seems a bit hacky / our-zenoss-setup-specific # so it is not worthy of",
"projectname) logger.info(\"Getting list of nodes for %s\", zenossselector) device_list_url = \"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl,",
"IpAddress.objects.get_or_create(address=ip_address) # if not node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address) # node.save() # except: # transaction.rollback()",
"pool_success = False else: pool = pools[p] c += 1 node, created =",
"role, created = Role.objects.get_or_create(name=role_name) role.undelete() return role def _format_pool_name(self, name): return re.sub(r'[^a-zA-Z0-9_]', '_',",
"ipmq001.back.int.cwwtf.local env = n[n.find(\".\")+1:] # back.int.cwwtf.local env = env.replace(\"back.\", \"\") # int.cwwtf.local env",
"use this file except in compliance with the License. # You may obtain",
"of [' and of '] content = content[2:][:-1] # split on , then",
"[(p.replace(\"/\", \"_\"), n) for (p, n) in devlist] # so now we have",
"= self.ensure_pool(environment, p) pools[p] = pool except: pass pool_success = False else: pool",
"transaction from django.utils.encoding import iri_to_uri from crichtoncli.apihelpers import * from crichtoncli.commands import ApiCommand",
"uses database! requires_model_validation = True def print_help(self, zenossbaseurl, zenossselector): super(ApiCommand, self).print_help(zenossbaseurl, zenossselector) def",
"+ ( # ) # uses database! requires_model_validation = True def print_help(self, zenossbaseurl,",
"( # ) # uses database! requires_model_validation = True def print_help(self, zenossbaseurl, zenossselector):",
"of migration into the PoolManager class imho pool = None created = False",
"pool.role = role pool.save() pool.undelete() except Exception, e: logger.error(\"ensure_pool failed with %s, roolling",
"zenossbaseurl += \"/\" zenossselector = args[1] zenoss_client = makeHttps(zenossbaseurl, **options) # issue_tracker =",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"Role.objects.get_or_create(name=role_name) role.undelete() return role def _format_pool_name(self, name): return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower() @transaction.commit_manually def",
"# int.cwwtf env = env.split(\".\")[0] # int return env pools = {} environments",
"it contains to the crichton db as nodes.\" \" Can only run locally.\")",
"bit hacky / our-zenoss-setup-specific # so it is not worthy of migration into",
"import logging logger = logging.getLogger(__name__) class Command(ApiCommand): help = (\"Crawl a zenoss device",
"\\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key \\ # --ca-file=/Users/$USER/.bbc/ca.pem import re from optparse",
"* from crichtonweb.system.models import Environment, Pool, Node, PoolMembership, Role, crichtonCronJobStatus import logging logger",
"from django.utils.encoding import iri_to_uri from crichtoncli.apihelpers import * from crichtoncli.commands import ApiCommand from",
"False else: pool = pools[p] c += 1 node, created = Node.objects.ensure(environment, n)",
"try: name = self._format_pool_name(name) role = self._ensure_role_for_pool(name) pool, created = Pool.objects.get_or_create(environment=environment, name=name, defaults={",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"raise CommandError( \"You must provide at least zenossbaseurl and zenossselector\") zenossbaseurl = args[0]",
"CommandError( \"You must provide at least zenossbaseurl and zenossselector\") zenossbaseurl = args[0] if",
"lets be positive :) if not p in pools: logger.info(\"Ensuring pool %s\", unicode(p))",
"\"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split on \"/devices/\" devlist = [x.split(\"/devices/\") for x in devlist] devlist",
"for the specific language governing permissions and # limitations under the License. #",
"# Crichton, Admirable Source Configuration Management # Copyright 2012 British Broadcasting Corporation #",
"name).lower() @transaction.commit_manually def ensure_pool(self, environment, name): # the pool creation we do here",
"+= \"/\" zenossselector = args[1] zenoss_client = makeHttps(zenossbaseurl, **options) # issue_tracker = self.ensure_issue_tracker(jiraname,",
"migration into the PoolManager class imho pool = None created = False try:",
"' and end quote ', devlist = [x.strip()[1:][:-1] for x in content.split(\",\")] #",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"\"\") # int.cwwtf env = env.split(\".\")[0] # int return env pools = {}",
"# so now we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split on \"/devices/\" devlist = [x.split(\"/devices/\")",
"Broadcasting Corporation # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"pool = None created = False try: name = self._format_pool_name(name) role = self._ensure_role_for_pool(name)",
"zenossselector): super(ApiCommand, self).print_help(zenossbaseurl, zenossselector) def _ensure_role_for_pool(self, pool_name): role_name = pool_name.split(\"_\")[0] role, created =",
"License. # # # example that you can run on mac: # ./crichton.py",
"node, created = Node.objects.ensure(environment, n) if pool_success: pool_membership, created = PoolMembership.objects.ensure(pool, node) logger.info(\"Saw",
"\"role\": role, }) if pool.role != role: pool.role = role pool.save() pool.undelete() except",
"the License. # # # example that you can run on mac: #",
"zenossselector = args[1] zenoss_client = makeHttps(zenossbaseurl, **options) # issue_tracker = self.ensure_issue_tracker(jiraname, jirabaseurl) #",
"# split on \"/devices/\" devlist = [x.split(\"/devices/\") for x in devlist] devlist =",
"# # Unless required by applicable law or agreed to in writing, software",
"= None created = False try: name = self._format_pool_name(name) role = self._ensure_role_for_pool(name) pool,",
"# node.ip_addresses.add(ip_address) # node.save() # except: # transaction.rollback() # raise # else: #",
"express or implied. # See the License for the specific language governing permissions",
"pool.role != role: pool.role = role pool.save() pool.undelete() except Exception, e: logger.error(\"ensure_pool failed",
"--cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key \\ # --ca-file=/Users/$USER/.bbc/ca.pem import re from optparse import make_option",
"self._format_pool_name(name) role = self._ensure_role_for_pool(name) pool, created = Pool.objects.get_or_create(environment=environment, name=name, defaults={ \"role\": role, })",
"int.cwwtf env = env.split(\".\")[0] # int return env pools = {} environments =",
"end quote ', devlist = [x.strip()[1:][:-1] for x in content.split(\",\")] # split on",
"either express or implied. # See the License for the specific language governing",
"for %s\", zenossselector) device_list_url = \"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl, zenossselector) resp, content = zenoss_client.request(iri_to_uri(device_list_url),",
"for p, n in devlist: e = get_env(n) # an exmaple # n",
"split on , then remove whitespace, then get rid of the start quote",
"* from crichtoncli.commands import ApiCommand from crichtonweb.core.httpshelpers import * from crichtonweb.system.models import Environment,",
"as nodes.\" \" Can only run locally.\") args = \"<zenossbaseurl> <zenossselector>\" # option_list",
"return role def _format_pool_name(self, name): return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower() @transaction.commit_manually def ensure_pool(self, environment,",
"of '] content = content[2:][:-1] # split on , then remove whitespace, then",
"[' and of '] content = content[2:][:-1] # split on , then remove",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"def _format_pool_name(self, name): return re.sub(r'[^a-zA-Z0-9_]', '_', name).lower() @transaction.commit_manually def ensure_pool(self, environment, name): #",
"\"_\"), n) for (p, n) in devlist] # so now we have (\"InterPlatformMQ_Integration\",",
"import * from crichtoncli.commands import ApiCommand from crichtonweb.core.httpshelpers import * from crichtonweb.system.models import",
"# transaction.commit() def handle(self, *args, **options): if len(args) < 2: raise CommandError( \"You",
"list of nodes for %s\", zenossselector) device_list_url = \"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl, zenossselector) resp,",
"-> db118.back.stage.telhc.local # p -> Database_Postgres # e -> stage if not e",
"the first part devlist = [x.split(\" at \")[1].strip() for x in devlist] #",
"n -> db118.back.stage.telhc.local # p -> Database_Postgres # e -> stage if not",
"@transaction.commit_manually def ensure_pool(self, environment, name): # the pool creation we do here seems",
"under the License. # # # example that you can run on mac:",
"in devlist] # so now we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split on \"/devices/\" devlist",
"environments = {} c = 0 for p, n in devlist: e =",
"on \" at \" and throw away the first part devlist = [x.split(\"",
"the License. # You may obtain a copy of the License at #",
"env = env.replace(\".local\", \"\") # int.cwwtf env = env.split(\".\")[0] # int return env",
"content) # ['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # .... # 'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get",
"of the start quote ' and end quote ', devlist = [x.strip()[1:][:-1] for",
"get rid of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist = [x.replace(zenossselector + \"/\",\"\", 1) for x in",
"None created = False try: name = self._format_pool_name(name) role = self._ensure_role_for_pool(name) pool, created",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"raise else: transaction.commit() return pool, created # @transaction.commit_manually # def ensure_ip_address(self, node, ip_address):",
"pool creation we do here seems a bit hacky / our-zenoss-setup-specific # so",
"makeHttps(zenossbaseurl, **options) # issue_tracker = self.ensure_issue_tracker(jiraname, jirabaseurl) # project = self.ensure_project(issue_tracker, projectname) logger.info(\"Getting",
"here seems a bit hacky / our-zenoss-setup-specific # so it is not worthy",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"% (zenossbaseurl, zenossselector) resp, content = zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp, content) # expect_xml(resp, content)",
"= [x.strip()[1:][:-1] for x in content.split(\",\")] # split on \" at \" and",
"(\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def get_env(n): # ipmq001.back.int.cwwtf.local env = n[n.find(\".\")+1:] # back.int.cwwtf.local env =",
"\"devices it contains to the crichton db as nodes.\" \" Can only run",
"nodes.\" \" Can only run locally.\") args = \"<zenossbaseurl> <zenossselector>\" # option_list =",
"%s\", zenossselector) device_list_url = \"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl, zenossselector) resp, content = zenoss_client.request(iri_to_uri(device_list_url), \"GET\")",
"def get_env(n): # ipmq001.back.int.cwwtf.local env = n[n.find(\".\")+1:] # back.int.cwwtf.local env = env.replace(\"back.\", \"\")",
"\")[1].strip() for x in devlist] # get rid of /zport/dmd/ devlist = [x.replace(\"/zport/dmd/\",\"\",",
"devlist: e = get_env(n) # an exmaple # n -> db118.back.stage.telhc.local # p",
"name = self._format_pool_name(name) role = self._ensure_role_for_pool(name) pool, created = Pool.objects.get_or_create(environment=environment, name=name, defaults={ \"role\":",
"environment, created = Environment.objects.ensure(e) if created: logger.info(\"Created environment %s\", unicode(environment)) environments[e] = environment",
"logger.info(\"Ensuring pool %s\", unicode(p)) try: pool, created = self.ensure_pool(environment, p) pools[p] = pool",
"unicode(p)) try: pool, created = self.ensure_pool(environment, p) pools[p] = pool except: pass pool_success",
"at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # .... # 'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get rid of ['",
"True def print_help(self, zenossbaseurl, zenossselector): super(ApiCommand, self).print_help(zenossbaseurl, zenossselector) def _ensure_role_for_pool(self, pool_name): role_name =",
"language governing permissions and # limitations under the License. # # # example",
"re.sub(r'[^a-zA-Z0-9_]', '_', name).lower() @transaction.commit_manually def ensure_pool(self, environment, name): # the pool creation we",
"<reponame>bpluly/crichton<gh_stars>0 # Crichton, Admirable Source Configuration Management # Copyright 2012 British Broadcasting Corporation",
"db118.back.stage.telhc.local # p -> Database_Postgres # e -> stage if not e in",
"project = self.ensure_project(issue_tracker, projectname) logger.info(\"Getting list of nodes for %s\", zenossselector) device_list_url =",
"except Exception, e: logger.error(\"ensure_pool failed with %s, roolling this transaction back\" % str(e))",
"pool.save() pool.undelete() except Exception, e: logger.error(\"ensure_pool failed with %s, roolling this transaction back\"",
"at least zenossbaseurl and zenossselector\") zenossbaseurl = args[0] if not zenossbaseurl.endswith(\"/\"): zenossbaseurl +=",
"**options) # issue_tracker = self.ensure_issue_tracker(jiraname, jirabaseurl) # project = self.ensure_project(issue_tracker, projectname) logger.info(\"Getting list",
"class imho pool = None created = False try: name = self._format_pool_name(name) role",
"created # @transaction.commit_manually # def ensure_ip_address(self, node, ip_address): # try: # ip_address, created",
"pool_name): role_name = pool_name.split(\"_\")[0] role, created = Role.objects.get_or_create(name=role_name) role.undelete() return role def _format_pool_name(self,",
"of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist = [x.replace(zenossselector + \"/\",\"\", 1) for x in devlist] #",
"\" at \" and throw away the first part devlist = [x.split(\" at",
"devlist = [x.replace(\"/zport/dmd/\",\"\", 1) for x in devlist] # get rid of Devices/BBC/ApplicationHost/Platform/Delivery/",
"with the License. # You may obtain a copy of the License at",
"# ipmq001.back.int.cwwtf.local env = n[n.find(\".\")+1:] # back.int.cwwtf.local env = env.replace(\"back.\", \"\") # int.cwwtf.local",
"crichtoncli.commands import ApiCommand from crichtonweb.core.httpshelpers import * from crichtonweb.system.models import Environment, Pool, Node,",
"{} c = 0 for p, n in devlist: e = get_env(n) #",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"PoolMembership, Role, crichtonCronJobStatus import logging logger = logging.getLogger(__name__) class Command(ApiCommand): help = (\"Crawl",
"= IpAddress.objects.get_or_create(address=ip_address) # if not node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address) # node.save() # except: #",
"permissions and # limitations under the License. # # # example that you",
"get_env(n): # ipmq001.back.int.cwwtf.local env = n[n.find(\".\")+1:] # back.int.cwwtf.local env = env.replace(\"back.\", \"\") #",
"from django.db import transaction from django.utils.encoding import iri_to_uri from crichtoncli.apihelpers import * from",
"logger.info(\"Getting list of nodes for %s\", zenossselector) device_list_url = \"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl, zenossselector)",
"if not zenossbaseurl.endswith(\"/\"): zenossbaseurl += \"/\" zenossselector = args[1] zenoss_client = makeHttps(zenossbaseurl, **options)",
":) if not p in pools: logger.info(\"Ensuring pool %s\", unicode(p)) try: pool, created",
"int.cwwtf.local env = env.replace(\".local\", \"\") # int.cwwtf env = env.split(\".\")[0] # int return",
"# def ensure_ip_address(self, node, ip_address): # try: # ip_address, created = IpAddress.objects.get_or_create(address=ip_address) #",
"+ \"/\",\"\", 1) for x in devlist] # so now we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\"",
"self.ensure_pool(environment, p) pools[p] = pool except: pass pool_success = False else: pool =",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"= logging.getLogger(__name__) class Command(ApiCommand): help = (\"Crawl a zenoss device collection and add",
"rid of [' and of '] content = content[2:][:-1] # split on ,",
"devlist = [x.split(\" at \")[1].strip() for x in devlist] # get rid of",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"env = env.split(\".\")[0] # int return env pools = {} environments = {}",
"be positive :) if not p in pools: logger.info(\"Ensuring pool %s\", unicode(p)) try:",
"ip_address, created = IpAddress.objects.get_or_create(address=ip_address) # if not node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address) # node.save() #",
"creation we do here seems a bit hacky / our-zenoss-setup-specific # so it",
"get rid of the start quote ' and end quote ', devlist =",
"else: pool = pools[p] c += 1 node, created = Node.objects.ensure(environment, n) if",
"= {} c = 0 for p, n in devlist: e = get_env(n)",
"1 node, created = Node.objects.ensure(environment, n) if pool_success: pool_membership, created = PoolMembership.objects.ensure(pool, node)",
"all\" \"devices it contains to the crichton db as nodes.\" \" Can only",
"env = env.replace(\"back.\", \"\") # int.cwwtf.local env = env.replace(\".local\", \"\") # int.cwwtf env",
"roolling this transaction back\" % str(e)) transaction.rollback() raise else: transaction.commit() return pool, created",
"in compliance with the License. # You may obtain a copy of the",
"self).print_help(zenossbaseurl, zenossselector) def _ensure_role_for_pool(self, pool_name): role_name = pool_name.split(\"_\")[0] role, created = Role.objects.get_or_create(name=role_name) role.undelete()",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"n) if pool_success: pool_membership, created = PoolMembership.objects.ensure(pool, node) logger.info(\"Saw %d nodes\", c) crichtonCronJobStatus.objects.update_success('index_zenoss')",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"for x in content.split(\",\")] # split on \" at \" and throw away",
"len(args) < 2: raise CommandError( \"You must provide at least zenossbaseurl and zenossselector\")",
"= self.ensure_issue_tracker(jiraname, jirabaseurl) # project = self.ensure_project(issue_tracker, projectname) logger.info(\"Getting list of nodes for",
"= ApiCommand.option_list + ( # ) # uses database! requires_model_validation = True def",
"See the License for the specific language governing permissions and # limitations under",
"created = self.ensure_pool(environment, p) pools[p] = pool except: pass pool_success = False else:",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"from crichtonweb.core.httpshelpers import * from crichtonweb.system.models import Environment, Pool, Node, PoolMembership, Role, crichtonCronJobStatus",
"governing permissions and # limitations under the License. # # # example that",
"our-zenoss-setup-specific # so it is not worthy of migration into the PoolManager class",
"pool %s\", unicode(p)) try: pool, created = self.ensure_pool(environment, p) pools[p] = pool except:",
"option_list = ApiCommand.option_list + ( # ) # uses database! requires_model_validation = True",
"%s\", unicode(p)) try: pool, created = self.ensure_pool(environment, p) pools[p] = pool except: pass",
"worthy of migration into the PoolManager class imho pool = None created =",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"zenoss device collection and add all\" \"devices it contains to the crichton db",
"# get rid of [' and of '] content = content[2:][:-1] # split",
"content[2:][:-1] # split on , then remove whitespace, then get rid of the",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"transaction.rollback() raise else: transaction.commit() return pool, created # @transaction.commit_manually # def ensure_ip_address(self, node,",
"super(ApiCommand, self).print_help(zenossbaseurl, zenossselector) def _ensure_role_for_pool(self, pool_name): role_name = pool_name.split(\"_\")[0] role, created = Role.objects.get_or_create(name=role_name)",
"transaction back\" % str(e)) transaction.rollback() raise else: transaction.commit() return pool, created # @transaction.commit_manually",
"= [(p.replace(\"/\", \"_\"), n) for (p, n) in devlist] # so now we",
"environment, name): # the pool creation we do here seems a bit hacky",
"x in devlist] # so now we have \"InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local\" # split on \"/devices/\"",
"pool_success = True # lets be positive :) if not p in pools:",
"# # example that you can run on mac: # ./crichton.py indexzenoss https://monitor.forge.domain.local/",
"+= 1 node, created = Node.objects.ensure(environment, n) if pool_success: pool_membership, created = PoolMembership.objects.ensure(pool,",
"Environment, Pool, Node, PoolMembership, Role, crichtonCronJobStatus import logging logger = logging.getLogger(__name__) class Command(ApiCommand):",
"%s, roolling this transaction back\" % str(e)) transaction.rollback() raise else: transaction.commit() return pool,",
"except: # transaction.rollback() # raise # else: # transaction.commit() def handle(self, *args, **options):",
"# --key-file=/Users/$USER/.bbc/dev.domain.com.key \\ # --ca-file=/Users/$USER/.bbc/ca.pem import re from optparse import make_option from django.core.management.base",
"import transaction from django.utils.encoding import iri_to_uri from crichtoncli.apihelpers import * from crichtoncli.commands import",
"node, ip_address): # try: # ip_address, created = IpAddress.objects.get_or_create(address=ip_address) # if not node.ip_addresses.filter(address=ip_address):",
"# 'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get rid of [' and of '] content",
"specific language governing permissions and # limitations under the License. # # #",
"import Environment, Pool, Node, PoolMembership, Role, crichtonCronJobStatus import logging logger = logging.getLogger(__name__) class",
"and zenossselector\") zenossbaseurl = args[0] if not zenossbaseurl.endswith(\"/\"): zenossbaseurl += \"/\" zenossselector =",
"zenossselector) device_list_url = \"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl, zenossselector) resp, content = zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp,",
"-> stage if not e in environments: environment, created = Environment.objects.ensure(e) if created:",
"'_', name).lower() @transaction.commit_manually def ensure_pool(self, environment, name): # the pool creation we do",
"and of '] content = content[2:][:-1] # split on , then remove whitespace,",
"= \"%szport/dmd/%s/getSubDevices\" % (zenossbaseurl, zenossselector) resp, content = zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp, content) #",
"in devlist] # so now we have (\"InterPlatformMQ_Integration\", \"ipmq001.back.int.cwwtf.local\") def get_env(n): # ipmq001.back.int.cwwtf.local",
"zenossbaseurl.endswith(\"/\"): zenossbaseurl += \"/\" zenossselector = args[1] zenoss_client = makeHttps(zenossbaseurl, **options) # issue_tracker",
"args[0] if not zenossbaseurl.endswith(\"/\"): zenossbaseurl += \"/\" zenossselector = args[1] zenoss_client = makeHttps(zenossbaseurl,",
"created = IpAddress.objects.get_or_create(address=ip_address) # if not node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address) # node.save() # except:",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"do here seems a bit hacky / our-zenoss-setup-specific # so it is not",
"except in compliance with the License. # You may obtain a copy of",
"expect_ok(resp, content) # expect_xml(resp, content) # ['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # .... # 'BBCApplicationHostDevice",
"stage if not e in environments: environment, created = Environment.objects.ensure(e) if created: logger.info(\"Created",
"environments[e] = environment else: environment = environments[e] pool_success = True # lets be",
"PoolManager class imho pool = None created = False try: name = self._format_pool_name(name)",
"hacky / our-zenoss-setup-specific # so it is not worthy of migration into the",
"and throw away the first part devlist = [x.split(\" at \")[1].strip() for x",
"zenossselector) resp, content = zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp, content) # expect_xml(resp, content) # ['BBCApplicationHostDevice",
"from crichtoncli.commands import ApiCommand from crichtonweb.core.httpshelpers import * from crichtonweb.system.models import Environment, Pool,",
"Node.objects.ensure(environment, n) if pool_success: pool_membership, created = PoolMembership.objects.ensure(pool, node) logger.info(\"Saw %d nodes\", c)",
"for x in devlist] devlist = [(p.replace(\"/\", \"_\"), n) for (p, n) in",
"Source Configuration Management # Copyright 2012 British Broadcasting Corporation # # Licensed under",
"requires_model_validation = True def print_help(self, zenossbaseurl, zenossselector): super(ApiCommand, self).print_help(zenossbaseurl, zenossselector) def _ensure_role_for_pool(self, pool_name):",
"pool, created = Pool.objects.get_or_create(environment=environment, name=name, defaults={ \"role\": role, }) if pool.role != role:",
"transaction.rollback() # raise # else: # transaction.commit() def handle(self, *args, **options): if len(args)",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"the pool creation we do here seems a bit hacky / our-zenoss-setup-specific #",
"in devlist] # get rid of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist = [x.replace(zenossselector + \"/\",\"\", 1)",
"else: # transaction.commit() def handle(self, *args, **options): if len(args) < 2: raise CommandError(",
"for x in devlist] # get rid of /zport/dmd/ devlist = [x.replace(\"/zport/dmd/\",\"\", 1)",
"get_env(n) # an exmaple # n -> db118.back.stage.telhc.local # p -> Database_Postgres #",
"from django.core.management.base import CommandError from django.db import transaction from django.utils.encoding import iri_to_uri from",
"# get rid of /zport/dmd/ devlist = [x.replace(\"/zport/dmd/\",\"\", 1) for x in devlist]",
"Admirable Source Configuration Management # Copyright 2012 British Broadcasting Corporation # # Licensed",
"zenoss_client.request(iri_to_uri(device_list_url), \"GET\") expect_ok(resp, content) # expect_xml(resp, content) # ['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # ....",
"(\"Crawl a zenoss device collection and add all\" \"devices it contains to the",
"if not node.ip_addresses.filter(address=ip_address): # node.ip_addresses.add(ip_address) # node.save() # except: # transaction.rollback() # raise",
"\"\") # int.cwwtf.local env = env.replace(\".local\", \"\") # int.cwwtf env = env.split(\".\")[0] #",
"int return env pools = {} environments = {} c = 0 for",
"import make_option from django.core.management.base import CommandError from django.db import transaction from django.utils.encoding import",
"crichtonCronJobStatus import logging logger = logging.getLogger(__name__) class Command(ApiCommand): help = (\"Crawl a zenoss",
"= [x.split(\" at \")[1].strip() for x in devlist] # get rid of /zport/dmd/",
"role: pool.role = role pool.save() pool.undelete() except Exception, e: logger.error(\"ensure_pool failed with %s,",
"x in devlist] # get rid of /zport/dmd/ devlist = [x.replace(\"/zport/dmd/\",\"\", 1) for",
"< 2: raise CommandError( \"You must provide at least zenossbaseurl and zenossselector\") zenossbaseurl",
"a bit hacky / our-zenoss-setup-specific # so it is not worthy of migration",
"if not e in environments: environment, created = Environment.objects.ensure(e) if created: logger.info(\"Created environment",
"# node.save() # except: # transaction.rollback() # raise # else: # transaction.commit() def",
"def _ensure_role_for_pool(self, pool_name): role_name = pool_name.split(\"_\")[0] role, created = Role.objects.get_or_create(name=role_name) role.undelete() return role",
"the specific language governing permissions and # limitations under the License. # #",
"= makeHttps(zenossbaseurl, **options) # issue_tracker = self.ensure_issue_tracker(jiraname, jirabaseurl) # project = self.ensure_project(issue_tracker, projectname)",
"part devlist = [x.split(\" at \")[1].strip() for x in devlist] # get rid",
"failed with %s, roolling this transaction back\" % str(e)) transaction.rollback() raise else: transaction.commit()",
"pools = {} environments = {} c = 0 for p, n in",
"zenossselector) def _ensure_role_for_pool(self, pool_name): role_name = pool_name.split(\"_\")[0] role, created = Role.objects.get_or_create(name=role_name) role.undelete() return",
"# expect_xml(resp, content) # ['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # .... # 'BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local']",
"django.core.management.base import CommandError from django.db import transaction from django.utils.encoding import iri_to_uri from crichtoncli.apihelpers",
"= args[1] zenoss_client = makeHttps(zenossbaseurl, **options) # issue_tracker = self.ensure_issue_tracker(jiraname, jirabaseurl) # project",
"crichtonweb.core.httpshelpers import * from crichtonweb.system.models import Environment, Pool, Node, PoolMembership, Role, crichtonCronJobStatus import",
"content) # expect_xml(resp, content) # ['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # .... # 'BBCApplicationHostDevice at",
"/zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/InterPlatformMQ/Integration/devices/ipmq001.back.int.cwwtf.local'] # get rid of [' and of '] content = content[2:][:-1] #",
"content.split(\",\")] # split on \" at \" and throw away the first part",
"# n -> db118.back.stage.telhc.local # p -> Database_Postgres # e -> stage if",
"# except: # transaction.rollback() # raise # else: # transaction.commit() def handle(self, *args,",
"make_option from django.core.management.base import CommandError from django.db import transaction from django.utils.encoding import iri_to_uri",
"c = 0 for p, n in devlist: e = get_env(n) # an",
"whitespace, then get rid of the start quote ' and end quote ',",
"node.save() # except: # transaction.rollback() # raise # else: # transaction.commit() def handle(self,",
"\"GET\") expect_ok(resp, content) # expect_xml(resp, content) # ['BBCApplicationHostDevice at /zport/dmd/Devices/BBC/ApplicationHost/Platform/Delivery/Database/MySQL-Only/devices/db030.back.live.cwwtf.local>', # .... #",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"# ./crichton.py indexzenoss https://monitor.forge.domain.local/ Devices/BBC/ApplicationHost/Platform/Delivery \\ # --cert-file=/Users/$USER/.bbc/dev.domain.com.pem \\ # --key-file=/Users/$USER/.bbc/dev.domain.com.key \\ #",
"back.int.cwwtf.local env = env.replace(\"back.\", \"\") # int.cwwtf.local env = env.replace(\".local\", \"\") # int.cwwtf",
"pool, created = self.ensure_pool(environment, p) pools[p] = pool except: pass pool_success = False",
"pools[p] = pool except: pass pool_success = False else: pool = pools[p] c",
"# get rid of Devices/BBC/ApplicationHost/Platform/Delivery/ devlist = [x.replace(zenossselector + \"/\",\"\", 1) for x",
"environment = environments[e] pool_success = True # lets be positive :) if not",
"get rid of /zport/dmd/ devlist = [x.replace(\"/zport/dmd/\",\"\", 1) for x in devlist] #",
"environment else: environment = environments[e] pool_success = True # lets be positive :)",
"p, n in devlist: e = get_env(n) # an exmaple # n ->",
"print_help(self, zenossbaseurl, zenossselector): super(ApiCommand, self).print_help(zenossbaseurl, zenossselector) def _ensure_role_for_pool(self, pool_name): role_name = pool_name.split(\"_\")[0] role,"
] |
[
"event): locid = screen_to_hex( event.scenePos() ) pos = hex_to_screen(locid) longitude = 2*pi*pos.x()/self.dimensions[0] latitude",
"\"temp.svg\")).scaled(48,48) @classmethod def tool_layer(cls): return ToolLayer.mapuse def primary_mouse_released(self, event): locid = screen_to_hex( event.scenePos()",
"from MultiHex2.actions import NullAction from tools.basic_tool import ToolLayer from PyQt5 import QtGui art_dir",
"= hex_to_screen(locid) longitude = 2*pi*pos.x()/self.dimensions[0] latitude = -(pi*pos.y()/self.dimensions[1]) + 0.5*pi self.parent.config_with(latitude,longitude) self.parent.update_times() #",
"2*pi*pos.x()/self.dimensions[0] latitude = -(pi*pos.y()/self.dimensions[1]) + 0.5*pi self.parent.config_with(latitude,longitude) self.parent.update_times() # check for mobile here,",
"math import pi import os from MultiHex2.tools import Basic_Tool from MultiHex2.core.coordinates import screen_to_hex,",
"QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod def tool_layer(cls): return ToolLayer.mapuse def primary_mouse_released(self, event): locid = screen_to_hex(",
"return ToolLayer.mapuse def primary_mouse_released(self, event): locid = screen_to_hex( event.scenePos() ) pos = hex_to_screen(locid)",
"class MapUse(Basic_Tool): \"\"\" Define the tool that can be used to move mobiles",
"MapUse(Basic_Tool): \"\"\" Define the tool that can be used to move mobiles around,",
"@classmethod def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod def tool_layer(cls): return ToolLayer.mapuse",
"ToolLayer from PyQt5 import QtGui art_dir = os.path.join( os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool): \"\"\" Define",
"@classmethod def tool_layer(cls): return ToolLayer.mapuse def primary_mouse_released(self, event): locid = screen_to_hex( event.scenePos() )",
"locid = screen_to_hex( event.scenePos() ) pos = hex_to_screen(locid) longitude = 2*pi*pos.x()/self.dimensions[0] latitude =",
"them, etc... \"\"\" def __init__(self, parent=None): super().__init__(parent) self.dimensions = self.parent.dimensions @classmethod def buttonIcon(cls):",
"from math import pi import os from MultiHex2.tools import Basic_Tool from MultiHex2.core.coordinates import",
"latitude = -(pi*pos.y()/self.dimensions[1]) + 0.5*pi self.parent.config_with(latitude,longitude) self.parent.update_times() # check for mobile here, return",
"import os from MultiHex2.tools import Basic_Tool from MultiHex2.core.coordinates import screen_to_hex, hex_to_screen from MultiHex2.actions",
"around, look at them, edit them, etc... \"\"\" def __init__(self, parent=None): super().__init__(parent) self.dimensions",
"from MultiHex2.core.coordinates import screen_to_hex, hex_to_screen from MultiHex2.actions import NullAction from tools.basic_tool import ToolLayer",
"\"\"\" def __init__(self, parent=None): super().__init__(parent) self.dimensions = self.parent.dimensions @classmethod def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\")))",
"MultiHex2.tools import Basic_Tool from MultiHex2.core.coordinates import screen_to_hex, hex_to_screen from MultiHex2.actions import NullAction from",
"tool that can be used to move mobiles around, look at them, edit",
"tool_layer(cls): return ToolLayer.mapuse def primary_mouse_released(self, event): locid = screen_to_hex( event.scenePos() ) pos =",
"screen_to_hex, hex_to_screen from MultiHex2.actions import NullAction from tools.basic_tool import ToolLayer from PyQt5 import",
"tools.basic_tool import ToolLayer from PyQt5 import QtGui art_dir = os.path.join( os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool):",
"MultiHex2.actions import NullAction from tools.basic_tool import ToolLayer from PyQt5 import QtGui art_dir =",
"QtGui art_dir = os.path.join( os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool): \"\"\" Define the tool that can",
"\"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod def tool_layer(cls): return ToolLayer.mapuse def primary_mouse_released(self, event): locid",
"that can be used to move mobiles around, look at them, edit them,",
"PyQt5 import QtGui art_dir = os.path.join( os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool): \"\"\" Define the tool",
"self.dimensions = self.parent.dimensions @classmethod def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod def",
"assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod def tool_layer(cls): return ToolLayer.mapuse def primary_mouse_released(self, event):",
"import Basic_Tool from MultiHex2.core.coordinates import screen_to_hex, hex_to_screen from MultiHex2.actions import NullAction from tools.basic_tool",
"return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod def tool_layer(cls): return ToolLayer.mapuse def primary_mouse_released(self, event): locid =",
"mobiles around, look at them, edit them, etc... \"\"\" def __init__(self, parent=None): super().__init__(parent)",
"self.parent.dimensions @classmethod def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod def tool_layer(cls): return",
"= 2*pi*pos.x()/self.dimensions[0] latitude = -(pi*pos.y()/self.dimensions[1]) + 0.5*pi self.parent.config_with(latitude,longitude) self.parent.update_times() # check for mobile",
"NullAction from tools.basic_tool import ToolLayer from PyQt5 import QtGui art_dir = os.path.join( os.path.dirname(__file__),'..','assets','buttons')",
"the tool that can be used to move mobiles around, look at them,",
"def tool_layer(cls): return ToolLayer.mapuse def primary_mouse_released(self, event): locid = screen_to_hex( event.scenePos() ) pos",
"Define the tool that can be used to move mobiles around, look at",
"at them, edit them, etc... \"\"\" def __init__(self, parent=None): super().__init__(parent) self.dimensions = self.parent.dimensions",
"super().__init__(parent) self.dimensions = self.parent.dimensions @classmethod def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod",
"look at them, edit them, etc... \"\"\" def __init__(self, parent=None): super().__init__(parent) self.dimensions =",
"art_dir = os.path.join( os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool): \"\"\" Define the tool that can be",
"screen_to_hex( event.scenePos() ) pos = hex_to_screen(locid) longitude = 2*pi*pos.x()/self.dimensions[0] latitude = -(pi*pos.y()/self.dimensions[1]) +",
"can be used to move mobiles around, look at them, edit them, etc...",
"hex_to_screen from MultiHex2.actions import NullAction from tools.basic_tool import ToolLayer from PyQt5 import QtGui",
"os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool): \"\"\" Define the tool that can be used to move",
"= screen_to_hex( event.scenePos() ) pos = hex_to_screen(locid) longitude = 2*pi*pos.x()/self.dimensions[0] latitude = -(pi*pos.y()/self.dimensions[1])",
"def primary_mouse_released(self, event): locid = screen_to_hex( event.scenePos() ) pos = hex_to_screen(locid) longitude =",
"import NullAction from tools.basic_tool import ToolLayer from PyQt5 import QtGui art_dir = os.path.join(",
"MultiHex2.core.coordinates import screen_to_hex, hex_to_screen from MultiHex2.actions import NullAction from tools.basic_tool import ToolLayer from",
"longitude = 2*pi*pos.x()/self.dimensions[0] latitude = -(pi*pos.y()/self.dimensions[1]) + 0.5*pi self.parent.config_with(latitude,longitude) self.parent.update_times() # check for",
"def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod def tool_layer(cls): return ToolLayer.mapuse def",
"from PyQt5 import QtGui art_dir = os.path.join( os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool): \"\"\" Define the",
"from MultiHex2.tools import Basic_Tool from MultiHex2.core.coordinates import screen_to_hex, hex_to_screen from MultiHex2.actions import NullAction",
"__init__(self, parent=None): super().__init__(parent) self.dimensions = self.parent.dimensions @classmethod def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir,",
"edit them, etc... \"\"\" def __init__(self, parent=None): super().__init__(parent) self.dimensions = self.parent.dimensions @classmethod def",
"hex_to_screen(locid) longitude = 2*pi*pos.x()/self.dimensions[0] latitude = -(pi*pos.y()/self.dimensions[1]) + 0.5*pi self.parent.config_with(latitude,longitude) self.parent.update_times() # check",
"ToolLayer.mapuse def primary_mouse_released(self, event): locid = screen_to_hex( event.scenePos() ) pos = hex_to_screen(locid) longitude",
"buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod def tool_layer(cls): return ToolLayer.mapuse def primary_mouse_released(self,",
"parent=None): super().__init__(parent) self.dimensions = self.parent.dimensions @classmethod def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48)",
"them, edit them, etc... \"\"\" def __init__(self, parent=None): super().__init__(parent) self.dimensions = self.parent.dimensions @classmethod",
"to move mobiles around, look at them, edit them, etc... \"\"\" def __init__(self,",
"Basic_Tool from MultiHex2.core.coordinates import screen_to_hex, hex_to_screen from MultiHex2.actions import NullAction from tools.basic_tool import",
"pos = hex_to_screen(locid) longitude = 2*pi*pos.x()/self.dimensions[0] latitude = -(pi*pos.y()/self.dimensions[1]) + 0.5*pi self.parent.config_with(latitude,longitude) self.parent.update_times()",
"etc... \"\"\" def __init__(self, parent=None): super().__init__(parent) self.dimensions = self.parent.dimensions @classmethod def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir,",
"move mobiles around, look at them, edit them, etc... \"\"\" def __init__(self, parent=None):",
"primary_mouse_released(self, event): locid = screen_to_hex( event.scenePos() ) pos = hex_to_screen(locid) longitude = 2*pi*pos.x()/self.dimensions[0]",
"be used to move mobiles around, look at them, edit them, etc... \"\"\"",
"import pi import os from MultiHex2.tools import Basic_Tool from MultiHex2.core.coordinates import screen_to_hex, hex_to_screen",
"from tools.basic_tool import ToolLayer from PyQt5 import QtGui art_dir = os.path.join( os.path.dirname(__file__),'..','assets','buttons') class",
"= -(pi*pos.y()/self.dimensions[1]) + 0.5*pi self.parent.config_with(latitude,longitude) self.parent.update_times() # check for mobile here, return NullAction()",
"= self.parent.dimensions @classmethod def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return QtGui.QPixmap(os.path.join(art_dir, \"temp.svg\")).scaled(48,48) @classmethod def tool_layer(cls):",
"def __init__(self, parent=None): super().__init__(parent) self.dimensions = self.parent.dimensions @classmethod def buttonIcon(cls): assert(os.path.exists(os.path.join(art_dir, \"temp.svg\"))) return",
"import QtGui art_dir = os.path.join( os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool): \"\"\" Define the tool that",
"os from MultiHex2.tools import Basic_Tool from MultiHex2.core.coordinates import screen_to_hex, hex_to_screen from MultiHex2.actions import",
"\"\"\" Define the tool that can be used to move mobiles around, look",
"os.path.join( os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool): \"\"\" Define the tool that can be used to",
"import ToolLayer from PyQt5 import QtGui art_dir = os.path.join( os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool): \"\"\"",
"= os.path.join( os.path.dirname(__file__),'..','assets','buttons') class MapUse(Basic_Tool): \"\"\" Define the tool that can be used",
"import screen_to_hex, hex_to_screen from MultiHex2.actions import NullAction from tools.basic_tool import ToolLayer from PyQt5",
"event.scenePos() ) pos = hex_to_screen(locid) longitude = 2*pi*pos.x()/self.dimensions[0] latitude = -(pi*pos.y()/self.dimensions[1]) + 0.5*pi",
") pos = hex_to_screen(locid) longitude = 2*pi*pos.x()/self.dimensions[0] latitude = -(pi*pos.y()/self.dimensions[1]) + 0.5*pi self.parent.config_with(latitude,longitude)",
"pi import os from MultiHex2.tools import Basic_Tool from MultiHex2.core.coordinates import screen_to_hex, hex_to_screen from",
"used to move mobiles around, look at them, edit them, etc... \"\"\" def"
] |
[
"hero.alive(): print(\"You have {} health and {} power.\".format(hero.health, hero.power)) print(\"The {} has {}",
"flee\") print(\"> \", end=' ') raw_input = input() if raw_input == \"1\": hero.attack(enemy)",
"game, the hero fights the goblin. He has the options to: # 1.",
"== \"1\": hero.attack(enemy) elif raw_input == \"2\": pass elif raw_input == \"3\": print(\"Goodbye.\")",
"dead.\") class Goblin(Character): def __init__(self): super(Goblin, self).__init__(\"Goblin\", 6, 2) # def attack(self, hero):",
"if self.alive() == True: # goblin.health -= self.power # print(f'You do {self.power} damage",
"self).__init__(\"Goblin\", 6, 2) # def attack(self, hero): # if self.alive() == True: #",
"attack(self, goblin): # if self.alive() == True: # goblin.health -= self.power # print(f'You",
"# def attack(self, hero): # if self.alive() == True: # hero.health -= self.power",
"def attack(self, enemy): if enemy.name != \"Zombie\" and self.alive() == True: enemy.health -=",
"1. fight goblin # 2. do nothing - in which case the goblin",
"!= \"Zombie\" and self.alive() == True: enemy.health -= self.power print(f'{self.name} does {self.power} damage",
"self.power print(f'{self.name} does {self.power} damage to the {enemy.name}') if enemy.alive() != True: print(f'The",
"= Hero() goblin = Goblin() zombie = Zombie() def main(enemy): # hero_health =",
"print(\"What do you want to do?\") print(f'1. fight {enemy.name}') print(\"2. do nothing\") print(\"3.",
"{enemy.name}') print(\"2. do nothing\") print(\"3. flee\") print(\"> \", end=' ') raw_input = input()",
"-= self.power # print(f'The goblin does {self.power} to you') # if hero.alive() !=",
"options to: # 1. fight goblin # 2. do nothing - in which",
"hero.alive() != True: # print(\"You are dead.\") class Zombie(Character): def __init__(self): super(Zombie, self).__init__(\"Zombie\",",
"goblin = Goblin() zombie = Zombie() def main(enemy): # hero_health = 10 #",
"def __init__(self): super(Hero, self).__init__(\"Hero\", 10, 5) # def attack(self, goblin): # if self.alive()",
"# goblin.health -= self.power # print(f'You do {self.power} damage to the goblin') #",
"Hero() goblin = Goblin() zombie = Zombie() def main(enemy): # hero_health = 10",
"alive(self): if self.health > 0: return True def attack(self, enemy): if enemy.name !=",
"the hero fights the goblin. He has the options to: # 1. fight",
"hero = Hero() goblin = Goblin() zombie = Zombie() def main(enemy): # hero_health",
"while enemy.alive() and hero.alive(): print(\"You have {} health and {} power.\".format(hero.health, hero.power)) print(\"The",
"if enemy.alive() != True: print(f'The {enemy.name} is dead') class Hero(Character): def __init__(self): super(Hero,",
"has the options to: # 1. fight goblin # 2. do nothing -",
"def attack(self, goblin): # if self.alive() == True: # goblin.health -= self.power #",
"= Zombie() def main(enemy): # hero_health = 10 # hero_power = 5 #",
"enemy.health -= self.power print(f'{self.name} does {self.power} damage to the {enemy.name}') if enemy.alive() !=",
"10 # hero_power = 5 # goblin_health = 6 # goblin_power = 2",
"enemy.power)) print() print(\"What do you want to do?\") print(f'1. fight {enemy.name}') print(\"2. do",
"do {self.power} damage to the goblin') # if goblin.alive() != True: # print(\"The",
"to the {enemy.name}') if enemy.alive() != True: print(f'The {enemy.name} is dead') class Hero(Character):",
"= input() if raw_input == \"1\": hero.attack(enemy) elif raw_input == \"2\": pass elif",
"6, 2) # def attack(self, hero): # if self.alive() == True: # hero.health",
"= 10 # hero_power = 5 # goblin_health = 6 # goblin_power =",
"nothing - in which case the goblin will attack him anyway # 3.",
"# 1. fight goblin # 2. do nothing - in which case the",
"- in which case the goblin will attack him anyway # 3. flee",
"goblin): # if self.alive() == True: # goblin.health -= self.power # print(f'You do",
"which case the goblin will attack him anyway # 3. flee class Character:",
"class Character: def __init__(self, name, health, power): self.health = health self.power = power",
"hero): # if self.alive() == True: # hero.health -= self.power # print(f'The goblin",
"goblin is dead.\") class Goblin(Character): def __init__(self): super(Goblin, self).__init__(\"Goblin\", 6, 2) # def",
"5 # goblin_health = 6 # goblin_power = 2 while enemy.alive() and hero.alive():",
"goblin # 2. do nothing - in which case the goblin will attack",
"True: # print(\"You are dead.\") class Zombie(Character): def __init__(self): super(Zombie, self).__init__(\"Zombie\", 10, 1)",
"True: # print(\"The goblin is dead.\") class Goblin(Character): def __init__(self): super(Goblin, self).__init__(\"Goblin\", 6,",
"damage to the goblin') # if goblin.alive() != True: # print(\"The goblin is",
"main(enemy): # hero_health = 10 # hero_power = 5 # goblin_health = 6",
"want to do?\") print(f'1. fight {enemy.name}') print(\"2. do nothing\") print(\"3. flee\") print(\"> \",",
"and {} power.\".format( enemy.name, enemy.health, enemy.power)) print() print(\"What do you want to do?\")",
"self.alive() == True: enemy.health -= self.power print(f'{self.name} does {self.power} damage to the {enemy.name}')",
"# goblin_power = 2 while enemy.alive() and hero.alive(): print(\"You have {} health and",
"power.\".format(hero.health, hero.power)) print(\"The {} has {} health and {} power.\".format( enemy.name, enemy.health, enemy.power))",
"super(Goblin, self).__init__(\"Goblin\", 6, 2) # def attack(self, hero): # if self.alive() == True:",
"do you want to do?\") print(f'1. fight {enemy.name}') print(\"2. do nothing\") print(\"3. flee\")",
"RPG game, the hero fights the goblin. He has the options to: #",
"health self.power = power self.name = name def alive(self): if self.health > 0:",
"case the goblin will attack him anyway # 3. flee class Character: def",
"Zombie() def main(enemy): # hero_health = 10 # hero_power = 5 # goblin_health",
"to you') # if hero.alive() != True: # print(\"You are dead.\") class Zombie(Character):",
"{} power.\".format(hero.health, hero.power)) print(\"The {} has {} health and {} power.\".format( enemy.name, enemy.health,",
"# In this simple RPG game, the hero fights the goblin. He has",
"and hero.alive(): print(\"You have {} health and {} power.\".format(hero.health, hero.power)) print(\"The {} has",
"He has the options to: # 1. fight goblin # 2. do nothing",
"{enemy.name}') if enemy.alive() != True: print(f'The {enemy.name} is dead') class Hero(Character): def __init__(self):",
"do nothing\") print(\"3. flee\") print(\"> \", end=' ') raw_input = input() if raw_input",
"the goblin will attack him anyway # 3. flee class Character: def __init__(self,",
"print(\"> \", end=' ') raw_input = input() if raw_input == \"1\": hero.attack(enemy) elif",
"True: # hero.health -= self.power # print(f'The goblin does {self.power} to you') #",
"raw_input == \"1\": hero.attack(enemy) elif raw_input == \"2\": pass elif raw_input == \"3\":",
"elif raw_input == \"2\": pass elif raw_input == \"3\": print(\"Goodbye.\") break else: print(\"Invalid",
"raw_input == \"2\": pass elif raw_input == \"3\": print(\"Goodbye.\") break else: print(\"Invalid input",
"print(\"You have {} health and {} power.\".format(hero.health, hero.power)) print(\"The {} has {} health",
"dead.\") class Zombie(Character): def __init__(self): super(Zombie, self).__init__(\"Zombie\", 10, 1) hero = Hero() goblin",
"does {self.power} damage to the {enemy.name}') if enemy.alive() != True: print(f'The {enemy.name} is",
"goblin') # if goblin.alive() != True: # print(\"The goblin is dead.\") class Goblin(Character):",
"goblin_health = 6 # goblin_power = 2 while enemy.alive() and hero.alive(): print(\"You have",
"# print(\"The goblin is dead.\") class Goblin(Character): def __init__(self): super(Goblin, self).__init__(\"Goblin\", 6, 2)",
"10, 1) hero = Hero() goblin = Goblin() zombie = Zombie() def main(enemy):",
"super(Zombie, self).__init__(\"Zombie\", 10, 1) hero = Hero() goblin = Goblin() zombie = Zombie()",
"def main(enemy): # hero_health = 10 # hero_power = 5 # goblin_health =",
"2 while enemy.alive() and hero.alive(): print(\"You have {} health and {} power.\".format(hero.health, hero.power))",
"you want to do?\") print(f'1. fight {enemy.name}') print(\"2. do nothing\") print(\"3. flee\") print(\">",
"def __init__(self): super(Goblin, self).__init__(\"Goblin\", 6, 2) # def attack(self, hero): # if self.alive()",
"simple RPG game, the hero fights the goblin. He has the options to:",
"# if hero.alive() != True: # print(\"You are dead.\") class Zombie(Character): def __init__(self):",
"is dead') class Hero(Character): def __init__(self): super(Hero, self).__init__(\"Hero\", 10, 5) # def attack(self,",
"health and {} power.\".format(hero.health, hero.power)) print(\"The {} has {} health and {} power.\".format(",
"nothing\") print(\"3. flee\") print(\"> \", end=' ') raw_input = input() if raw_input ==",
"enemy.alive() and hero.alive(): print(\"You have {} health and {} power.\".format(hero.health, hero.power)) print(\"The {}",
"self.health > 0: return True def attack(self, enemy): if enemy.name != \"Zombie\" and",
"= 2 while enemy.alive() and hero.alive(): print(\"You have {} health and {} power.\".format(hero.health,",
"\"Zombie\" and self.alive() == True: enemy.health -= self.power print(f'{self.name} does {self.power} damage to",
"goblin.alive() != True: # print(\"The goblin is dead.\") class Goblin(Character): def __init__(self): super(Goblin,",
"= 6 # goblin_power = 2 while enemy.alive() and hero.alive(): print(\"You have {}",
"enemy.alive() != True: print(f'The {enemy.name} is dead') class Hero(Character): def __init__(self): super(Hero, self).__init__(\"Hero\",",
"pass elif raw_input == \"3\": print(\"Goodbye.\") break else: print(\"Invalid input {}\".format(raw_input)) if enemy.alive():",
"goblin.health -= self.power # print(f'You do {self.power} damage to the goblin') # if",
"is dead.\") class Goblin(Character): def __init__(self): super(Goblin, self).__init__(\"Goblin\", 6, 2) # def attack(self,",
"__init__(self): super(Zombie, self).__init__(\"Zombie\", 10, 1) hero = Hero() goblin = Goblin() zombie =",
"self).__init__(\"Hero\", 10, 5) # def attack(self, goblin): # if self.alive() == True: #",
"__init__(self): super(Goblin, self).__init__(\"Goblin\", 6, 2) # def attack(self, hero): # if self.alive() ==",
"= 5 # goblin_health = 6 # goblin_power = 2 while enemy.alive() and",
"# 3. flee class Character: def __init__(self, name, health, power): self.health = health",
"10, 5) # def attack(self, goblin): # if self.alive() == True: # goblin.health",
"fights the goblin. He has the options to: # 1. fight goblin #",
"__init__(self): super(Hero, self).__init__(\"Hero\", 10, 5) # def attack(self, goblin): # if self.alive() ==",
"self).__init__(\"Zombie\", 10, 1) hero = Hero() goblin = Goblin() zombie = Zombie() def",
"<gh_stars>0 #!/usr/bin/env python # In this simple RPG game, the hero fights the",
"Goblin(Character): def __init__(self): super(Goblin, self).__init__(\"Goblin\", 6, 2) # def attack(self, hero): # if",
"goblin_power = 2 while enemy.alive() and hero.alive(): print(\"You have {} health and {}",
"attack(self, enemy): if enemy.name != \"Zombie\" and self.alive() == True: enemy.health -= self.power",
"have {} health and {} power.\".format(hero.health, hero.power)) print(\"The {} has {} health and",
"hero.power)) print(\"The {} has {} health and {} power.\".format( enemy.name, enemy.health, enemy.power)) print()",
"{} health and {} power.\".format( enemy.name, enemy.health, enemy.power)) print() print(\"What do you want",
"!= True: # print(\"You are dead.\") class Zombie(Character): def __init__(self): super(Zombie, self).__init__(\"Zombie\", 10,",
"# goblin_health = 6 # goblin_power = 2 while enemy.alive() and hero.alive(): print(\"You",
"print(\"You are dead.\") class Zombie(Character): def __init__(self): super(Zombie, self).__init__(\"Zombie\", 10, 1) hero =",
"__init__(self, name, health, power): self.health = health self.power = power self.name = name",
"# hero_health = 10 # hero_power = 5 # goblin_health = 6 #",
"print(\"The {} has {} health and {} power.\".format( enemy.name, enemy.health, enemy.power)) print() print(\"What",
"# print(\"You are dead.\") class Zombie(Character): def __init__(self): super(Zombie, self).__init__(\"Zombie\", 10, 1) hero",
"== \"2\": pass elif raw_input == \"3\": print(\"Goodbye.\") break else: print(\"Invalid input {}\".format(raw_input))",
"goblin. He has the options to: # 1. fight goblin # 2. do",
"self.health = health self.power = power self.name = name def alive(self): if self.health",
"{} has {} health and {} power.\".format( enemy.name, enemy.health, enemy.power)) print() print(\"What do",
"goblin will attack him anyway # 3. flee class Character: def __init__(self, name,",
"6 # goblin_power = 2 while enemy.alive() and hero.alive(): print(\"You have {} health",
"{self.power} damage to the {enemy.name}') if enemy.alive() != True: print(f'The {enemy.name} is dead')",
"# hero.health -= self.power # print(f'The goblin does {self.power} to you') # if",
"the options to: # 1. fight goblin # 2. do nothing - in",
"def alive(self): if self.health > 0: return True def attack(self, enemy): if enemy.name",
"if self.health > 0: return True def attack(self, enemy): if enemy.name != \"Zombie\"",
"python # In this simple RPG game, the hero fights the goblin. He",
"super(Hero, self).__init__(\"Hero\", 10, 5) # def attack(self, goblin): # if self.alive() == True:",
"True: # goblin.health -= self.power # print(f'You do {self.power} damage to the goblin')",
"to do?\") print(f'1. fight {enemy.name}') print(\"2. do nothing\") print(\"3. flee\") print(\"> \", end='",
"print(\"The goblin is dead.\") class Goblin(Character): def __init__(self): super(Goblin, self).__init__(\"Goblin\", 6, 2) #",
"# 2. do nothing - in which case the goblin will attack him",
"power.\".format( enemy.name, enemy.health, enemy.power)) print() print(\"What do you want to do?\") print(f'1. fight",
"# print(f'You do {self.power} damage to the goblin') # if goblin.alive() != True:",
"self.alive() == True: # goblin.health -= self.power # print(f'You do {self.power} damage to",
"attack him anyway # 3. flee class Character: def __init__(self, name, health, power):",
"# if self.alive() == True: # hero.health -= self.power # print(f'The goblin does",
"Goblin() zombie = Zombie() def main(enemy): # hero_health = 10 # hero_power =",
"fight {enemy.name}') print(\"2. do nothing\") print(\"3. flee\") print(\"> \", end=' ') raw_input =",
"raw_input = input() if raw_input == \"1\": hero.attack(enemy) elif raw_input == \"2\": pass",
"self.power # print(f'The goblin does {self.power} to you') # if hero.alive() != True:",
"elif raw_input == \"3\": print(\"Goodbye.\") break else: print(\"Invalid input {}\".format(raw_input)) if enemy.alive(): enemy.attack(hero)",
"to: # 1. fight goblin # 2. do nothing - in which case",
"3. flee class Character: def __init__(self, name, health, power): self.health = health self.power",
"self.name = name def alive(self): if self.health > 0: return True def attack(self,",
"class Goblin(Character): def __init__(self): super(Goblin, self).__init__(\"Goblin\", 6, 2) # def attack(self, hero): #",
"class Zombie(Character): def __init__(self): super(Zombie, self).__init__(\"Zombie\", 10, 1) hero = Hero() goblin =",
"if enemy.name != \"Zombie\" and self.alive() == True: enemy.health -= self.power print(f'{self.name} does",
"Character: def __init__(self, name, health, power): self.health = health self.power = power self.name",
"== True: enemy.health -= self.power print(f'{self.name} does {self.power} damage to the {enemy.name}') if",
"== True: # hero.health -= self.power # print(f'The goblin does {self.power} to you')",
"hero fights the goblin. He has the options to: # 1. fight goblin",
"the {enemy.name}') if enemy.alive() != True: print(f'The {enemy.name} is dead') class Hero(Character): def",
"goblin does {self.power} to you') # if hero.alive() != True: # print(\"You are",
"print(f'The {enemy.name} is dead') class Hero(Character): def __init__(self): super(Hero, self).__init__(\"Hero\", 10, 5) #",
"anyway # 3. flee class Character: def __init__(self, name, health, power): self.health =",
"hero.health -= self.power # print(f'The goblin does {self.power} to you') # if hero.alive()",
"!= True: print(f'The {enemy.name} is dead') class Hero(Character): def __init__(self): super(Hero, self).__init__(\"Hero\", 10,",
"True: enemy.health -= self.power print(f'{self.name} does {self.power} damage to the {enemy.name}') if enemy.alive()",
"health and {} power.\".format( enemy.name, enemy.health, enemy.power)) print() print(\"What do you want to",
"name, health, power): self.health = health self.power = power self.name = name def",
"# if self.alive() == True: # goblin.health -= self.power # print(f'You do {self.power}",
"{self.power} to you') # if hero.alive() != True: # print(\"You are dead.\") class",
"!= True: # print(\"The goblin is dead.\") class Goblin(Character): def __init__(self): super(Goblin, self).__init__(\"Goblin\",",
"In this simple RPG game, the hero fights the goblin. He has the",
"print(f'{self.name} does {self.power} damage to the {enemy.name}') if enemy.alive() != True: print(f'The {enemy.name}",
"end=' ') raw_input = input() if raw_input == \"1\": hero.attack(enemy) elif raw_input ==",
"True: print(f'The {enemy.name} is dead') class Hero(Character): def __init__(self): super(Hero, self).__init__(\"Hero\", 10, 5)",
"def __init__(self): super(Zombie, self).__init__(\"Zombie\", 10, 1) hero = Hero() goblin = Goblin() zombie",
"in which case the goblin will attack him anyway # 3. flee class",
"print(f'The goblin does {self.power} to you') # if hero.alive() != True: # print(\"You",
"health, power): self.health = health self.power = power self.name = name def alive(self):",
"self.power = power self.name = name def alive(self): if self.health > 0: return",
"self.power # print(f'You do {self.power} damage to the goblin') # if goblin.alive() !=",
"Zombie(Character): def __init__(self): super(Zombie, self).__init__(\"Zombie\", 10, 1) hero = Hero() goblin = Goblin()",
"this simple RPG game, the hero fights the goblin. He has the options",
"\"1\": hero.attack(enemy) elif raw_input == \"2\": pass elif raw_input == \"3\": print(\"Goodbye.\") break",
"do nothing - in which case the goblin will attack him anyway #",
"power self.name = name def alive(self): if self.health > 0: return True def",
"enemy): if enemy.name != \"Zombie\" and self.alive() == True: enemy.health -= self.power print(f'{self.name}",
"if raw_input == \"1\": hero.attack(enemy) elif raw_input == \"2\": pass elif raw_input ==",
"True def attack(self, enemy): if enemy.name != \"Zombie\" and self.alive() == True: enemy.health",
"return True def attack(self, enemy): if enemy.name != \"Zombie\" and self.alive() == True:",
"to the goblin') # if goblin.alive() != True: # print(\"The goblin is dead.\")",
"\"2\": pass elif raw_input == \"3\": print(\"Goodbye.\") break else: print(\"Invalid input {}\".format(raw_input)) if",
"fight goblin # 2. do nothing - in which case the goblin will",
"print(f'You do {self.power} damage to the goblin') # if goblin.alive() != True: #",
"if goblin.alive() != True: # print(\"The goblin is dead.\") class Goblin(Character): def __init__(self):",
"= Goblin() zombie = Zombie() def main(enemy): # hero_health = 10 # hero_power",
"do?\") print(f'1. fight {enemy.name}') print(\"2. do nothing\") print(\"3. flee\") print(\"> \", end=' ')",
"and self.alive() == True: enemy.health -= self.power print(f'{self.name} does {self.power} damage to the",
"# print(f'The goblin does {self.power} to you') # if hero.alive() != True: #",
"1) hero = Hero() goblin = Goblin() zombie = Zombie() def main(enemy): #",
"{} power.\".format( enemy.name, enemy.health, enemy.power)) print() print(\"What do you want to do?\") print(f'1.",
"attack(self, hero): # if self.alive() == True: # hero.health -= self.power # print(f'The",
"if hero.alive() != True: # print(\"You are dead.\") class Zombie(Character): def __init__(self): super(Zombie,",
"class Hero(Character): def __init__(self): super(Hero, self).__init__(\"Hero\", 10, 5) # def attack(self, goblin): #",
"= health self.power = power self.name = name def alive(self): if self.health >",
"and {} power.\".format(hero.health, hero.power)) print(\"The {} has {} health and {} power.\".format( enemy.name,",
"#!/usr/bin/env python # In this simple RPG game, the hero fights the goblin.",
"you') # if hero.alive() != True: # print(\"You are dead.\") class Zombie(Character): def",
"-= self.power # print(f'You do {self.power} damage to the goblin') # if goblin.alive()",
"damage to the {enemy.name}') if enemy.alive() != True: print(f'The {enemy.name} is dead') class",
"{self.power} damage to the goblin') # if goblin.alive() != True: # print(\"The goblin",
"print(\"3. flee\") print(\"> \", end=' ') raw_input = input() if raw_input == \"1\":",
"5) # def attack(self, goblin): # if self.alive() == True: # goblin.health -=",
"2. do nothing - in which case the goblin will attack him anyway",
"name def alive(self): if self.health > 0: return True def attack(self, enemy): if",
"does {self.power} to you') # if hero.alive() != True: # print(\"You are dead.\")",
"2) # def attack(self, hero): # if self.alive() == True: # hero.health -=",
"the goblin') # if goblin.alive() != True: # print(\"The goblin is dead.\") class",
"dead') class Hero(Character): def __init__(self): super(Hero, self).__init__(\"Hero\", 10, 5) # def attack(self, goblin):",
"enemy.health, enemy.power)) print() print(\"What do you want to do?\") print(f'1. fight {enemy.name}') print(\"2.",
"zombie = Zombie() def main(enemy): # hero_health = 10 # hero_power = 5",
"will attack him anyway # 3. flee class Character: def __init__(self, name, health,",
"-= self.power print(f'{self.name} does {self.power} damage to the {enemy.name}') if enemy.alive() != True:",
"hero_power = 5 # goblin_health = 6 # goblin_power = 2 while enemy.alive()",
"raw_input == \"3\": print(\"Goodbye.\") break else: print(\"Invalid input {}\".format(raw_input)) if enemy.alive(): enemy.attack(hero) main(zombie)",
"0: return True def attack(self, enemy): if enemy.name != \"Zombie\" and self.alive() ==",
"print(\"2. do nothing\") print(\"3. flee\") print(\"> \", end=' ') raw_input = input() if",
"= name def alive(self): if self.health > 0: return True def attack(self, enemy):",
"enemy.name != \"Zombie\" and self.alive() == True: enemy.health -= self.power print(f'{self.name} does {self.power}",
"') raw_input = input() if raw_input == \"1\": hero.attack(enemy) elif raw_input == \"2\":",
"{enemy.name} is dead') class Hero(Character): def __init__(self): super(Hero, self).__init__(\"Hero\", 10, 5) # def",
"flee class Character: def __init__(self, name, health, power): self.health = health self.power =",
"has {} health and {} power.\".format( enemy.name, enemy.health, enemy.power)) print() print(\"What do you",
"\", end=' ') raw_input = input() if raw_input == \"1\": hero.attack(enemy) elif raw_input",
"if self.alive() == True: # hero.health -= self.power # print(f'The goblin does {self.power}",
"are dead.\") class Zombie(Character): def __init__(self): super(Zombie, self).__init__(\"Zombie\", 10, 1) hero = Hero()",
"{} health and {} power.\".format(hero.health, hero.power)) print(\"The {} has {} health and {}",
"the goblin. He has the options to: # 1. fight goblin # 2.",
"Hero(Character): def __init__(self): super(Hero, self).__init__(\"Hero\", 10, 5) # def attack(self, goblin): # if",
"def attack(self, hero): # if self.alive() == True: # hero.health -= self.power #",
"# def attack(self, goblin): # if self.alive() == True: # goblin.health -= self.power",
"== True: # goblin.health -= self.power # print(f'You do {self.power} damage to the",
"power): self.health = health self.power = power self.name = name def alive(self): if",
"print() print(\"What do you want to do?\") print(f'1. fight {enemy.name}') print(\"2. do nothing\")",
"def __init__(self, name, health, power): self.health = health self.power = power self.name =",
"# hero_power = 5 # goblin_health = 6 # goblin_power = 2 while",
"# if goblin.alive() != True: # print(\"The goblin is dead.\") class Goblin(Character): def",
"print(f'1. fight {enemy.name}') print(\"2. do nothing\") print(\"3. flee\") print(\"> \", end=' ') raw_input",
"> 0: return True def attack(self, enemy): if enemy.name != \"Zombie\" and self.alive()",
"enemy.name, enemy.health, enemy.power)) print() print(\"What do you want to do?\") print(f'1. fight {enemy.name}')",
"hero.attack(enemy) elif raw_input == \"2\": pass elif raw_input == \"3\": print(\"Goodbye.\") break else:",
"self.alive() == True: # hero.health -= self.power # print(f'The goblin does {self.power} to",
"input() if raw_input == \"1\": hero.attack(enemy) elif raw_input == \"2\": pass elif raw_input",
"him anyway # 3. flee class Character: def __init__(self, name, health, power): self.health",
"= power self.name = name def alive(self): if self.health > 0: return True",
"hero_health = 10 # hero_power = 5 # goblin_health = 6 # goblin_power"
] |
[
"soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if lines == []: break for line in lines: contents =",
"from time import sleep seq = [] print(\"Fetching\", end=\"\") for i in range(1,",
"sleep(1.0) url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i) responce = requests.get(url) print(\".\", end=\"\", flush=True) soup",
"str(i) responce = requests.get(url) print(\".\", end=\"\", flush=True) soup = BeautifulSoup(responce.text, \"lxml\") lines =",
"lines == []: break for line in lines: contents = line.find_all(\"td\")[-1].contents seq +=",
"seq = [line.replace(\"○○\", \"P\").replace(\" \", \"\") for line in seq if line !=",
"= requests.get(url) print(\".\", end=\"\", flush=True) soup = BeautifulSoup(responce.text, \"lxml\") lines = soup.find(\"tbody\", class_=\"result\").find_all(\"tr\")",
"seq += contents print(\"\\nGot {} lines.\".format(len(seq))) seq = [line.replace(\"○○\", \"P\").replace(\" \", \"\") for",
"end=\"\") for i in range(1, 1000): sleep(1.0) url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i) responce",
"for line in lines: contents = line.find_all(\"td\")[-1].contents seq += contents print(\"\\nGot {} lines.\".format(len(seq)))",
"i in range(1, 1000): sleep(1.0) url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i) responce = requests.get(url)",
"import sleep seq = [] print(\"Fetching\", end=\"\") for i in range(1, 1000): sleep(1.0)",
"seq = [] print(\"Fetching\", end=\"\") for i in range(1, 1000): sleep(1.0) url =",
"lines.\".format(len(seq))) seq = [line.replace(\"○○\", \"P\").replace(\" \", \"\") for line in seq if line",
"[line.replace(\"○○\", \"P\").replace(\" \", \"\") for line in seq if line != \"なし\"] with",
"== []: break for line in lines: contents = line.find_all(\"td\")[-1].contents seq += contents",
"= \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i) responce = requests.get(url) print(\".\", end=\"\", flush=True) soup = BeautifulSoup(responce.text,",
"+ str(i) responce = requests.get(url) print(\".\", end=\"\", flush=True) soup = BeautifulSoup(responce.text, \"lxml\") lines",
"for line in seq if line != \"なし\"] with open(\"./dataset/charactor/miku.txt\", \"w\") as f:",
"BeautifulSoup from time import sleep seq = [] print(\"Fetching\", end=\"\") for i in",
"end=\"\", flush=True) soup = BeautifulSoup(responce.text, \"lxml\") lines = soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if lines ==",
"= BeautifulSoup(responce.text, \"lxml\") lines = soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if lines == []: break for",
"= soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if lines == []: break for line in lines: contents",
"requests.get(url) print(\".\", end=\"\", flush=True) soup = BeautifulSoup(responce.text, \"lxml\") lines = soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if",
"\"P\").replace(\" \", \"\") for line in seq if line != \"なし\"] with open(\"./dataset/charactor/miku.txt\",",
"1000): sleep(1.0) url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i) responce = requests.get(url) print(\".\", end=\"\", flush=True)",
"\"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i) responce = requests.get(url) print(\".\", end=\"\", flush=True) soup = BeautifulSoup(responce.text, \"lxml\")",
"[]: break for line in lines: contents = line.find_all(\"td\")[-1].contents seq += contents print(\"\\nGot",
"contents = line.find_all(\"td\")[-1].contents seq += contents print(\"\\nGot {} lines.\".format(len(seq))) seq = [line.replace(\"○○\", \"P\").replace(\"",
"\"\") for line in seq if line != \"なし\"] with open(\"./dataset/charactor/miku.txt\", \"w\") as",
"print(\".\", end=\"\", flush=True) soup = BeautifulSoup(responce.text, \"lxml\") lines = soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if lines",
"= [line.replace(\"○○\", \"P\").replace(\" \", \"\") for line in seq if line != \"なし\"]",
"print(\"Fetching\", end=\"\") for i in range(1, 1000): sleep(1.0) url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i)",
"from bs4 import BeautifulSoup from time import sleep seq = [] print(\"Fetching\", end=\"\")",
"bs4 import BeautifulSoup from time import sleep seq = [] print(\"Fetching\", end=\"\") for",
"line.find_all(\"td\")[-1].contents seq += contents print(\"\\nGot {} lines.\".format(len(seq))) seq = [line.replace(\"○○\", \"P\").replace(\" \", \"\")",
"flush=True) soup = BeautifulSoup(responce.text, \"lxml\") lines = soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if lines == []:",
"line in seq if line != \"なし\"] with open(\"./dataset/charactor/miku.txt\", \"w\") as f: f.write(\"\\n\".join(seq))",
"contents print(\"\\nGot {} lines.\".format(len(seq))) seq = [line.replace(\"○○\", \"P\").replace(\" \", \"\") for line in",
"BeautifulSoup(responce.text, \"lxml\") lines = soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if lines == []: break for line",
"{} lines.\".format(len(seq))) seq = [line.replace(\"○○\", \"P\").replace(\" \", \"\") for line in seq if",
"[] print(\"Fetching\", end=\"\") for i in range(1, 1000): sleep(1.0) url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" +",
"in range(1, 1000): sleep(1.0) url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i) responce = requests.get(url) print(\".\",",
"time import sleep seq = [] print(\"Fetching\", end=\"\") for i in range(1, 1000):",
"<filename>src/dataset_miku.py import requests from bs4 import BeautifulSoup from time import sleep seq =",
"in lines: contents = line.find_all(\"td\")[-1].contents seq += contents print(\"\\nGot {} lines.\".format(len(seq))) seq =",
"if lines == []: break for line in lines: contents = line.find_all(\"td\")[-1].contents seq",
"break for line in lines: contents = line.find_all(\"td\")[-1].contents seq += contents print(\"\\nGot {}",
"import requests from bs4 import BeautifulSoup from time import sleep seq = []",
"+= contents print(\"\\nGot {} lines.\".format(len(seq))) seq = [line.replace(\"○○\", \"P\").replace(\" \", \"\") for line",
"responce = requests.get(url) print(\".\", end=\"\", flush=True) soup = BeautifulSoup(responce.text, \"lxml\") lines = soup.find(\"tbody\",",
"line in lines: contents = line.find_all(\"td\")[-1].contents seq += contents print(\"\\nGot {} lines.\".format(len(seq))) seq",
"\", \"\") for line in seq if line != \"なし\"] with open(\"./dataset/charactor/miku.txt\", \"w\")",
"soup = BeautifulSoup(responce.text, \"lxml\") lines = soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if lines == []: break",
"lines: contents = line.find_all(\"td\")[-1].contents seq += contents print(\"\\nGot {} lines.\".format(len(seq))) seq = [line.replace(\"○○\",",
"range(1, 1000): sleep(1.0) url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i) responce = requests.get(url) print(\".\", end=\"\",",
"= [] print(\"Fetching\", end=\"\") for i in range(1, 1000): sleep(1.0) url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\"",
"requests from bs4 import BeautifulSoup from time import sleep seq = [] print(\"Fetching\",",
"url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i) responce = requests.get(url) print(\".\", end=\"\", flush=True) soup =",
"class_=\"result\").find_all(\"tr\") if lines == []: break for line in lines: contents = line.find_all(\"td\")[-1].contents",
"sleep seq = [] print(\"Fetching\", end=\"\") for i in range(1, 1000): sleep(1.0) url",
"import BeautifulSoup from time import sleep seq = [] print(\"Fetching\", end=\"\") for i",
"print(\"\\nGot {} lines.\".format(len(seq))) seq = [line.replace(\"○○\", \"P\").replace(\" \", \"\") for line in seq",
"for i in range(1, 1000): sleep(1.0) url = \"https://icws.indigo-bell.com/search?q=前川みく&st=n&page=\" + str(i) responce =",
"lines = soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if lines == []: break for line in lines:",
"\"lxml\") lines = soup.find(\"tbody\", class_=\"result\").find_all(\"tr\") if lines == []: break for line in",
"= line.find_all(\"td\")[-1].contents seq += contents print(\"\\nGot {} lines.\".format(len(seq))) seq = [line.replace(\"○○\", \"P\").replace(\" \","
] |
[
"from setuptools import setup with open('README.md', 'r') as f: long_description = f.read() setup(",
"CTF challenges', long_description = long_description, long_description_content_type = 'text/markdown', author = '<NAME>', author_email =",
"long_description = long_description, long_description_content_type = 'text/markdown', author = '<NAME>', author_email = '<EMAIL>', packages",
"= 'pystrfry', version = '1.0.3', license = 'BSD-3-Clause', description = 'a tool for",
"those annoying strfry CTF challenges', long_description = long_description, long_description_content_type = 'text/markdown', author =",
"author_email = '<EMAIL>', packages = ['strfry'], scripts = ['scripts/strfry'], python_requires = '>=3.6' )",
"= 'text/markdown', author = '<NAME>', author_email = '<EMAIL>', packages = ['strfry'], scripts =",
"description = 'a tool for solving those annoying strfry CTF challenges', long_description =",
"'a tool for solving those annoying strfry CTF challenges', long_description = long_description, long_description_content_type",
"tool for solving those annoying strfry CTF challenges', long_description = long_description, long_description_content_type =",
"<gh_stars>1-10 #!/usr/bin/env python3 from setuptools import setup with open('README.md', 'r') as f: long_description",
"solving those annoying strfry CTF challenges', long_description = long_description, long_description_content_type = 'text/markdown', author",
"as f: long_description = f.read() setup( name = 'pystrfry', version = '1.0.3', license",
"'BSD-3-Clause', description = 'a tool for solving those annoying strfry CTF challenges', long_description",
"= 'a tool for solving those annoying strfry CTF challenges', long_description = long_description,",
"'1.0.3', license = 'BSD-3-Clause', description = 'a tool for solving those annoying strfry",
"with open('README.md', 'r') as f: long_description = f.read() setup( name = 'pystrfry', version",
"'pystrfry', version = '1.0.3', license = 'BSD-3-Clause', description = 'a tool for solving",
"long_description_content_type = 'text/markdown', author = '<NAME>', author_email = '<EMAIL>', packages = ['strfry'], scripts",
"annoying strfry CTF challenges', long_description = long_description, long_description_content_type = 'text/markdown', author = '<NAME>',",
"'text/markdown', author = '<NAME>', author_email = '<EMAIL>', packages = ['strfry'], scripts = ['scripts/strfry'],",
"'r') as f: long_description = f.read() setup( name = 'pystrfry', version = '1.0.3',",
"= '1.0.3', license = 'BSD-3-Clause', description = 'a tool for solving those annoying",
"#!/usr/bin/env python3 from setuptools import setup with open('README.md', 'r') as f: long_description =",
"f.read() setup( name = 'pystrfry', version = '1.0.3', license = 'BSD-3-Clause', description =",
"version = '1.0.3', license = 'BSD-3-Clause', description = 'a tool for solving those",
"= long_description, long_description_content_type = 'text/markdown', author = '<NAME>', author_email = '<EMAIL>', packages =",
"author = '<NAME>', author_email = '<EMAIL>', packages = ['strfry'], scripts = ['scripts/strfry'], python_requires",
"'<NAME>', author_email = '<EMAIL>', packages = ['strfry'], scripts = ['scripts/strfry'], python_requires = '>=3.6'",
"setuptools import setup with open('README.md', 'r') as f: long_description = f.read() setup( name",
"challenges', long_description = long_description, long_description_content_type = 'text/markdown', author = '<NAME>', author_email = '<EMAIL>',",
"f: long_description = f.read() setup( name = 'pystrfry', version = '1.0.3', license =",
"setup( name = 'pystrfry', version = '1.0.3', license = 'BSD-3-Clause', description = 'a",
"python3 from setuptools import setup with open('README.md', 'r') as f: long_description = f.read()",
"strfry CTF challenges', long_description = long_description, long_description_content_type = 'text/markdown', author = '<NAME>', author_email",
"= f.read() setup( name = 'pystrfry', version = '1.0.3', license = 'BSD-3-Clause', description",
"= 'BSD-3-Clause', description = 'a tool for solving those annoying strfry CTF challenges',",
"name = 'pystrfry', version = '1.0.3', license = 'BSD-3-Clause', description = 'a tool",
"long_description = f.read() setup( name = 'pystrfry', version = '1.0.3', license = 'BSD-3-Clause',",
"for solving those annoying strfry CTF challenges', long_description = long_description, long_description_content_type = 'text/markdown',",
"long_description, long_description_content_type = 'text/markdown', author = '<NAME>', author_email = '<EMAIL>', packages = ['strfry'],",
"license = 'BSD-3-Clause', description = 'a tool for solving those annoying strfry CTF",
"import setup with open('README.md', 'r') as f: long_description = f.read() setup( name =",
"setup with open('README.md', 'r') as f: long_description = f.read() setup( name = 'pystrfry',",
"open('README.md', 'r') as f: long_description = f.read() setup( name = 'pystrfry', version =",
"= '<NAME>', author_email = '<EMAIL>', packages = ['strfry'], scripts = ['scripts/strfry'], python_requires ="
] |
[
":: Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System",
"\"Programming Language :: Python :: 3\", \"License :: OSI Approved :: MIT License\",",
"\"r\", encoding=\"utf-8\") as fh: long_description = fh.read() setuptools.setup( name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A",
"predictive analysis of CITE-seq data\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming Language :: Python",
"version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A package for integrative and predictive analysis of CITE-seq data\",",
"and predictive analysis of CITE-seq data\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming Language ::",
"long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved",
"author_email=\"<EMAIL>\", description=\"A package for integrative and predictive analysis of CITE-seq data\", long_description=long_description, long_description_content_type=\"text/markdown\",",
"classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved :: MIT",
"integrative and predictive analysis of CITE-seq data\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming Language",
"as fh: long_description = fh.read() setuptools.setup( name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A package for",
"setuptools.setup( name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A package for integrative and predictive analysis of",
"Independent\", ], package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"), install_requires=['torch>=1.6.1', 'numba<=0.50.0', 'scanpy>=1.7.1', 'pandas>=1.1.5', 'numpy>=1.20.1', 'scipy>=1.6.1', 'tqdm>=4.59.0', 'anndata>=0.7.5'],",
"], package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"), install_requires=['torch>=1.6.1', 'numba<=0.50.0', 'scanpy>=1.7.1', 'pandas>=1.1.5', 'numpy>=1.20.1', 'scipy>=1.6.1', 'tqdm>=4.59.0', 'anndata>=0.7.5'], python_requires=\">=3.7\",",
"for integrative and predictive analysis of CITE-seq data\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming",
"fh: long_description = fh.read() setuptools.setup( name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A package for integrative",
"open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read() setuptools.setup( name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\",",
"analysis of CITE-seq data\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming Language :: Python ::",
":: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS",
"\"Operating System :: OS Independent\", ], package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"), install_requires=['torch>=1.6.1', 'numba<=0.50.0', 'scanpy>=1.7.1', 'pandas>=1.1.5',",
"CITE-seq data\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming Language :: Python :: 3\", \"License",
"long_description = fh.read() setuptools.setup( name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A package for integrative and",
"3\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\",",
"System :: OS Independent\", ], package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"), install_requires=['torch>=1.6.1', 'numba<=0.50.0', 'scanpy>=1.7.1', 'pandas>=1.1.5', 'numpy>=1.20.1',",
"License\", \"Operating System :: OS Independent\", ], package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"), install_requires=['torch>=1.6.1', 'numba<=0.50.0', 'scanpy>=1.7.1',",
"= fh.read() setuptools.setup( name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A package for integrative and predictive",
"of CITE-seq data\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming Language :: Python :: 3\",",
":: OS Independent\", ], package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"), install_requires=['torch>=1.6.1', 'numba<=0.50.0', 'scanpy>=1.7.1', 'pandas>=1.1.5', 'numpy>=1.20.1', 'scipy>=1.6.1',",
"encoding=\"utf-8\") as fh: long_description = fh.read() setuptools.setup( name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A package",
"with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read() setuptools.setup( name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\",",
"Approved :: MIT License\", \"Operating System :: OS Independent\", ], package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"),",
"package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"), install_requires=['torch>=1.6.1', 'numba<=0.50.0', 'scanpy>=1.7.1', 'pandas>=1.1.5', 'numpy>=1.20.1', 'scipy>=1.6.1', 'tqdm>=4.59.0', 'anndata>=0.7.5'], python_requires=\">=3.7\", )",
"description=\"A package for integrative and predictive analysis of CITE-seq data\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\",",
"\"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ],",
":: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ], package_dir={\"\":",
":: MIT License\", \"Operating System :: OS Independent\", ], package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"), install_requires=['torch>=1.6.1',",
"setuptools with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read() setuptools.setup( name=\"sciPENN\", version=\"0.9.6\",",
"author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A package for integrative and predictive analysis of CITE-seq data\", long_description=long_description,",
"data\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming Language :: Python :: 3\", \"License ::",
"package for integrative and predictive analysis of CITE-seq data\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[",
"MIT License\", \"Operating System :: OS Independent\", ], package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"), install_requires=['torch>=1.6.1', 'numba<=0.50.0',",
"import setuptools with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read() setuptools.setup( name=\"sciPENN\",",
"OS Independent\", ], package_dir={\"\": \"src\"}, packages=setuptools.find_packages(where=\"src\"), install_requires=['torch>=1.6.1', 'numba<=0.50.0', 'scanpy>=1.7.1', 'pandas>=1.1.5', 'numpy>=1.20.1', 'scipy>=1.6.1', 'tqdm>=4.59.0',",
"name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A package for integrative and predictive analysis of CITE-seq",
"OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ], package_dir={\"\": \"src\"},",
"Language :: Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating",
"long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI",
"url=\"https://github.com/jlakkis/sciPENN\", classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved ::",
"fh.read() setuptools.setup( name=\"sciPENN\", version=\"0.9.6\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A package for integrative and predictive analysis",
"Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System ::"
] |
[
"keyPath accessible in all of MainWindow class def getVaultFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self,",
"!= (None or \"\"): self.searchedAccounts = self.accounts.copy() # copy sets values to new",
"AES.new(key, AES.MODE_CBC) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(desktopPath + \"\\\\vault.bin\", \"wb\") #",
"viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # else disables table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False)",
"from Crypto.Random import get_random_bytes from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad",
"you want to delete the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_() def",
"= data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.csv\" if data != \"\": row",
"of accounts were added and then someone attempts to delete an account #",
"== VIEWEDITEM: VIEWEDITEM[2] = self.ui.passwordEdit.text() # updates the item being viewed accounts[i] =",
"\"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name or Username has been left empty\") else: #",
"and (row['password'] != \"\") and (row['name'] != \"\"): values = [row['name'], row['username'], row['password']]",
"key = get_random_bytes(32) # 32 bytes is 256 bits data = ''.encode('utf-8') #",
"= QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210,",
"Key File or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either one or",
"\"\": # stores accounts as nested lists seperated by value accounts.append(value.split(',')) for account",
"iv out - this is 16 bytes long ciphered_data = readVaultFile.read() # Read",
"self.accounts[i] = value.split(',') i += 1 self.ui.accountsTable.setRowCount(0) # removes all data in table",
"file[0] # makes path accessible in importWin def importData(self): if self.ui.fileLbl.text() == \"Select",
"= cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(desktopPath + \"\\\\vault.bin\", \"wb\") # creates vault file",
"= Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword)",
"# Setup cipher # Decrypt and then up-pad the result data = unpad(cipher.decrypt(ciphered_data),",
"if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file has no data to import\")",
"MainWindow(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_startPage() self.ui.setupUi(self) # initializes",
"path += \"\\Accounts.csv\" if data != \"\": row = data.split('\\n') accounts = []",
"global variables to store paths to the vault and key file global KEYPATH,",
"format json.dump(accounts, file, indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"# show new window self.hide() # close old window except (ValueError, FileNotFoundError) as",
"VIEWEDITEM = self.accounts[row] else: for n, key in enumerate(sorted(self.searchedAccounts.keys())): if row == n:",
"VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.json\" if data !=",
"account or username\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.generatedPassLabel.text()",
"class addAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack)",
"all of MainWindow class def getVaultFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\",",
"**kwargs) self.ui = Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self): passwordOptions = \"\"",
"self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from name of account or username\") else:",
"to edit self.count -= 1 # decreases count for table to reset when",
"\"__main__\": # displays when starting application app = QtWidgets.QApplication(sys.argv) startPage = MainWindow() startPage.show()",
"this code was a for loop in range len(accounts) sometimes it would give",
"beginning or end of Account name\") elif \" \" in self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"QtGui from Crypto.Random import get_random_bytes from Crypto.Cipher import AES from Crypto.Util.Padding import pad,",
"elif self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path) as jsonFile: data = json.load(jsonFile) if 'items' in data:",
"if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")): Alert(\"Error\",",
"= AES.new(key, AES.MODE_CBC) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(desktopPath + \"\\\\vault.bin\", \"wb\")",
"generatePasswordWin() self.newWindow.show() # show new window self.hide() # close old window except (ValueError,",
"\"Either one or no files were selected. Please select files to open the",
"self.newWindow = classToAccess self.newWindow.show() self.hide() def copyUsername(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\",",
"QtWidgets.QMessageBox.Information, \"JSON file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack()",
"= terms[0], terms[1], terms[2] accounts.append(temp) with open(path, 'w') as file: # writes to",
"vault is open def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_passwordGen() self.ui.setupUi(self)",
"for file name in gui self.keyPath = file[0] # makes keyPath accessible in",
"viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210))",
"self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self): passwordOptions = \"\" if self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked()",
"= {} uris = [{\"match\": None, \"uri\": \"http://\"}] loginValues['uris'], loginValues['username'], loginValues['password'], loginValues['totp'] =",
"self.ui.numbersCheck.isChecked(): passwordOptions += digits if self.ui.specialCharsCheck.isChecked(): passwordOptions += punctuation.replace(',', '') lengths = [i",
"if data != \"\": row = data.split('\\n') accounts = [] for value in",
"calls updateAccounts self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui =",
"data to import was found\") else: for item in accounts: writeData(item[0], item[1], item[2])",
"= getPathToDesktop() path += \"\\Accounts.csv\" if data != \"\": row = data.split('\\n') accounts",
"message = QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon) message.setText(text) message.exec_() def getData(pathToKey, pathToVault): # allows me",
"for value in row: if value != \"\": # stores accounts as nested",
"lastpass format if (row['username'] != \"\") and (row['password'] != \"\") and (row['name'] !=",
"+= ascii_uppercase if self.ui.numbersCheck.isChecked(): passwordOptions += digits if self.ui.specialCharsCheck.isChecked(): passwordOptions += punctuation.replace(',', '')",
"+= 1 self.ui.accountsTable.setRowCount(0) # removes all data in table before making table for",
"for n, key in enumerate(sorted(self.accounts.keys())): # displays code in table in window if",
"Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No file was selected. Please select",
"\"\") and (row['password'] != \"\") and (row['name'] != \"\"): values = [row['name'], row['username'],",
"adjusts file name in gui self.ui.vaultFileLabel.adjustSize() # adjusts size of text wrapper for",
"MainWindow class def openVaultFiles(self): keyFile = self.ui.keyFileLabel.text() vaultFile = self.ui.vaultFileLabel.text() if (keyFile ==",
"the item in the accounts nested list updateAccounts(accounts) # calls updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information,",
"**kwargs) self.ui = Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self): self.newWindow = allAccountsWin()",
"Files (*)\") # lets user choose files from explorer url = QtCore.QUrl.fromLocalFile(file[0]) #",
"import Ui_startPage from genPassPage import Ui_passwordGen from allAccountsPage import Ui_allAccounts from AddAccountPage import",
"QMessageBox based on arguements in function message = QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon) message.setText(text) message.exec_()",
"to generate password window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin()))",
"keyFile.close cipher = AES.new(key, AES.MODE_CBC) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(desktopPath +",
"iv, data = getData(self.keyPath, self.vaultPath) # display new window for generating password or",
"open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() if __name__ == \"__main__\":",
"== (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One or Both of the password fields",
"# makes vaultPath accessible in all of MainWindow class def openVaultFiles(self): keyFile =",
"an object self.ui.keyFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.keyFileLabel.adjustSize() # adjusts size",
"object self.ui.fileLbl.setText(url.fileName()) # adjusts file name in gui self.ui.fileLbl.adjustSize() # adjusts size of",
"in window self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem)",
"read bytes iv = readVaultFile.read(16) # Read the iv out - this is",
"iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop() path +=",
"**kwargs): super().__init__(*args, **kwargs) self.ui = Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self): self.newWindow =",
"in row) and ('password' in row): # lastpass format if (row['username'] != \"\")",
"that a Key File or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either",
"key in enumerate(sorted(self.accounts.keys())): # displays code in table in window if not(term.lower() in",
"accounts nested list updateAccounts(accounts) # calls updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password Changed\") self.goBack() #",
"row = data.split('\\n') self.accounts = {} i = 0 for value in row:",
"self.newWindow.show() self.hide() def changePassword(self): if (self.ui.passwordEdit.text() == (None or \"\")) or (self.ui.confirmPassEdit.text() ==",
"= getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') self.count = 1 # count for resetting",
"for i in range(0, passLength): password += random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else:",
"Ui_addAccount from viewAccountPage import Ui_viewAccount from changePassPage import Ui_changePass from importAccountsPage import Ui_importAccounts",
"row: if value != \"\": terms = value.split(',') temp = {} temp[\"name\"], temp[\"username\"],",
"key in enumerate(sorted(self.accounts.keys())): # displays code in table in window self.ui.accountsTable.insertRow(n) newitem =",
"format if (row['name'] != \"\") and (row['login_username'] != \"\") and (row['login_password'] != \"\"):",
"open the vault\") # Alert function to display error QMessageBox else: # exception",
"or (\" \" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username or",
"writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") self.goBack() class viewAccountWin(QtWidgets.QWidget): def __init__(self,",
"to display error QMessageBox else: # exception handling try: key, iv, data =",
"(item['login']['password'] is not None): values = [item['name'], item['login'] ['username'], item['login']['password']] accounts.append(values) else: Alert(\"Error\",",
"for file to encrypt desktopPath = getPathToDesktop() # gets path to desktop keyFile",
"def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage)",
"nested lists seperated by value accounts.append(value.split(',')) for account in accounts: if account ==",
"data.decode('utf-8') row = data.split('\\n') accounts = [] for value in row: if value",
"in loadAccounts but with search terms for n, key in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem",
"\" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username or Password\") elif",
"self.ui.passwordEdit.text() # updates the item being viewed accounts[i] = VIEWEDITEM # updates the",
"getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') self.count = 1 # count for resetting all",
"opens window to view all accounts self.newWindow = allAccountsWin() self.newWindow.show() # show new",
"else: key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row = data.split('\\n')",
"Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad # global variables to store",
"!= self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords dont match\") elif (\" \" in self.ui.passwordEdit.text()) or",
"and (row['login_password'] != \"\"): values = [row['name'], row['login_username'], row['login_password']] accounts.append(values) if len(accounts) <",
"= self.ui.accountsTable.currentRow() if not(self.searchedAccounts): # checks if searchedAccounts is empty VIEWEDITEM = self.accounts[row]",
"= getData(self.keyPath, self.vaultPath) # display new window for generating password or viewing accounts",
"self.hide() def saveAccount(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() == (None",
"for driveLetter in ascii_uppercase: # find drive desktop folder is on if os.path.exists(\"{0}:{1}\".format(driveLetter,",
"of the data readVaultFile.close() readKeyFile = open(KEYPATH, 'rb') key = readKeyFile.read() readKeyFile.close() cipher",
"QtWidgets.QMessageBox.Critical, \"Passwords dont match\") elif (\" \" in self.ui.passwordEdit.text()) or (\" \" in",
"value in data: row = ','.join(value) accounts.append(row) newData = b'' for line in",
"Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\")",
"cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close()",
"def getFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\") #",
"sure you only run loadAccounts after a search self.searchedAccounts = {} self.loadAccounts() class",
"pathToVault): # allows me to access Paths throughout document global KEYPATH, VAULTPATH KEYPATH,",
"Please select a file to import from\") # Alert function to display error",
"username, password): # writes name of account, username and password to vaultFile global",
"{} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') self.count =",
"displays any error message if the user input fields are empty or incorrectly",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def getPathToDesktop(): # path to desktop",
"item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .CSV\") self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path)",
"deletes tables contents for n, key in enumerate(sorted(self.accounts.keys())): # displays code in table",
"self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self, classToAccess): self.newWindow =",
"bytes long ciphered_data = readVaultFile.read() # Read the rest of the data readVaultFile.close()",
"in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username or Password\") elif (\",\"",
"to file and stores it as an object self.ui.vaultFileLabel.setText(url.fileName()) # adjusts file name",
"for n, key in enumerate(sorted(self.accounts.keys())): # displays code in table in window self.ui.accountsTable.insertRow(n)",
"values not in search # code below works just like in loadAccounts but",
"beginning or end of Account name\") elif (\" \" in self.ui.usernameEdit.text()) or (\"",
"os.environ[\"HOMEPATH\"] + \"\\Desktop\" # finds path to desktop for driveLetter in ascii_uppercase: #",
"''.encode('utf-8') # basic data for file to encrypt desktopPath = getPathToDesktop() # gets",
"when writing to a json if value != \"\": terms = value.split(',') loginValues",
"data in table before making table for n, key in enumerate(sorted(self.accounts.keys())): # displays",
"saved\") # reset check boxes after saving accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) #",
"or Both of the password fields are empty\") else: if self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text():",
"== (None or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")) or (self.ui.passwordEdit.text() ==",
"\"http://\"}] loginValues['uris'], loginValues['username'], loginValues['password'], loginValues['totp'] = uris, terms[1], terms[2], None temp = {}",
"remove spaces from the beginning or end of Account name\") elif \" \"",
"self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self, classToAccess): self.newWindow",
"window self.hide() # close old window def loadAccounts(self): # added feature to read",
"# stores accounts as nested lists seperated by value accounts.append(value.split(',')) for i in",
"AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault",
"self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def saveAccount(self): if (self.ui.nameOfAccountEdit.text()",
"in row: if value != \"\": terms = value.split(',') temp = {} temp[\"name\"],",
"\"Password copied to clipboard\") def deleteAccount(self): message = QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you",
"= {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') self.count",
"the vault\") # Alert function to display error QMessageBox else: # exception handling",
"# 32 bytes is 256 bits data = ''.encode('utf-8') # basic data for",
"self.ui.searchBox.text() if term != (None or \"\"): self.searchedAccounts = self.accounts.copy() # copy sets",
"QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\") # lets user choose files",
"AES.MODE_CBC, iv=iv) # Setup cipher # Decrypt and then up-pad the result data",
"class importWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack)",
"in gui self.ui.vaultFileLabel.adjustSize() # adjusts size of text wrapper for file name in",
"self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def saveAccount(self): if (self.ui.nameOfAccountEdit.text() ==",
"key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop() path",
"uses None for null and False for false when writing to a json",
"window self.hide() # close old window class allAccountsWin(QtWidgets.QWidget): # view all accounts window",
"QtWidgets.QMessageBox.Critical, \"Please remove spaces from the beginning or end of Account name\") elif",
"self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked(): passwordOptions += ascii_lowercase if self.ui.upperCaseCheck.isChecked(): passwordOptions",
"\"File type not supported\") class exportWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui",
"password = self.ui.passwordEdit.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") self.goBack() class",
"selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either one or no files were selected. Please select files",
"changed successfully class importWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_importAccounts()",
"# gets path to desktop keyFile = open(desktopPath + \"\\\\key.bin\", \"wb\") keyFile.write(key) #",
"*args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self):",
"vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() def updateAccounts(data): global KEYPATH, VAULTPATH key, iv, oldData = getData(KEYPATH,",
"genPassPage import Ui_passwordGen from allAccountsPage import Ui_allAccounts from AddAccountPage import Ui_addAccount from viewAccountPage",
"global KEYPATH, VAULTPATH KEYPATH, VAULTPATH = pathToKey, pathToVault readVaultFile = open(VAULTPATH, 'rb') #",
"exportAccountsPage import Ui_exportPage from PyQt5 import QtWidgets, QtCore, QtGui from Crypto.Random import get_random_bytes",
"but with search terms for n, key in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0])",
"# reset check boxes after saving accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) # the",
"or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name, Username or the Password field has been",
"i in range(0, passLength): password += random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\",",
"else: desktopPath = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return desktopPath def Alert(title, icon, text): # creates",
"= getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.json\" if",
"(self.ui.nameOfAccountEdit.text()[-1] == \" \"): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from the beginning or",
"or no data to import was found\") else: for item in accounts: writeData(item[0],",
"class def openVaultFiles(self): keyFile = self.ui.keyFileLabel.text() vaultFile = self.ui.vaultFileLabel.text() if (keyFile == \"Key",
"button variables which execute a specific function def createVaultFiles(self): key = get_random_bytes(32) #",
"n, key in enumerate(sorted(self.accounts.keys())): # displays code in table in window if not(term.lower()",
"code to generate a QMessageBox def getKeyFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file',",
"self.goBack() else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File type not supported\") class exportWin(QtWidgets.QWidget): def __init__(self, *args,",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect files selected\") # Alert function to show error message class",
"to clipboard\") def deleteAccount(self): message = QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you sure you",
"name in gui self.Path = file[0] # makes path accessible in importWin def",
"# writes to csv in lastpass format json.dump(accounts, file, indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON",
"== \"View\") and (self.ui.accountsTable.currentColumn() == 1): row = self.ui.accountsTable.currentRow() if not(self.searchedAccounts): # checks",
"not in search # code below works just like in loadAccounts but with",
"copied to clipboard\") def deleteAccount(self): message = QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you sure",
"\"\"): values = [row['name'], row['login_username'], row['login_password']] accounts.append(values) if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"= QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password copied to clipboard\") def deleteAccount(self): message",
"= [item['name'], item['login'] ['username'], item['login']['password']] accounts.append(values) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file format not",
"text wrapper for file name in gui self.keyPath = file[0] # makes keyPath",
"# lets user choose files from explorer url = QtCore.QUrl.fromLocalFile(file[0]) # gets path",
"= open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() def updateAccounts(data): global",
"== (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name, Username or the Password field",
"error message class generatePasswordWin(QtWidgets.QWidget): # displays generate password window when vault is open",
"QtWidgets.QMessageBox.Information, \"Created vault.bin and key.bin\") # Alert function to reuse the code to",
"and (row['name'] != \"\"): values = [row['name'], row['username'], row['password']] accounts.append(values) elif ('name' in",
"checks for bitwarden format if 'login' in item: if ('username' in item['login']) and",
"{} uris = [{\"match\": None, \"uri\": \"http://\"}] loginValues['uris'], loginValues['username'], loginValues['password'], loginValues['totp'] = uris,",
"temp[\"username\"], temp[\"password\"] = terms[0], terms[1], terms[2] accounts.append(temp) with open(path, 'w') as file: #",
"'login' in item: if ('username' in item['login']) and ('password' in item['login']): if (item['login']['username']",
"accounts self.newWindow = generatePasswordWin() self.newWindow.show() # show new window self.hide() # close old",
"close old window def loadAccounts(self): # added feature to read accounts from file",
"False for false when writing to a json if value != \"\": terms",
"to import from\") # Alert function to display error QMessageBox else: accounts =",
"window if not(term.lower() in self.accounts[key][0].lower()): self.searchedAccounts.pop(key) # removes values not in search #",
"seperated by value accounts.append(value.split(',')) for i in range(len(accounts)): if accounts[i] == VIEWEDITEM: VIEWEDITEM[2]",
"file[0] # makes keyPath accessible in all of MainWindow class def getVaultFile(self): file",
"data += (\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(data,",
"error message if the user input fields are empty or incorrectly entered if",
"accounts.append(value.split(',')) for account in accounts: if account == VIEWEDITEM: index = accounts.index(account) accounts.pop(index)",
"viewAccountWin() self.newWindow.show() self.hide() def changePassword(self): if (self.ui.passwordEdit.text() == (None or \"\")) or (self.ui.confirmPassEdit.text()",
"an account # although the code is now longer, this fixes the index",
"# although the code is now longer, this fixes the index error issue",
"json.dump(accounts, file, indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No",
"lengths = [i for i in range(8, 17)] passLength = random.choice(lengths) password =",
"check boxes after saving accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) # the code below",
"+ \"\\\\vault.bin\", \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process Completed\", QtWidgets.QMessageBox.Information,",
"code below resets that generatedPassLabel, nameOfAccount input and username input after saving self.ui.generatedPassLabel.setText(\"\")",
"= data.decode('utf-8') self.count = 1 # count for resetting all accounts view if",
"\"&Yes\": key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row = data.split('\\n')",
"vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Created vault.bin and key.bin\") # Alert function",
"to new variable to edit self.count -= 1 # decreases count for table",
"= allAccountsWin() self.newWindow.show() self.hide() def saveAccount(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or",
"confirmDelete(self, clickedBtn): if clickedBtn.text() == \"&Yes\": key, iv, data = getData(KEYPATH, VAULTPATH) data",
"+= (\"{}\\n\".format(line)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(newData, AES.block_size)) vaultFile =",
"loadAccounts but with search terms for n, key in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem =",
"import from\": # checks that a Key File or Vault file have been",
"= self.accounts[key] self.changeWindow(viewAccountWin()) def searchAccounts(self): term = self.ui.searchBox.text() if term != (None or",
"indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to",
"(None or \"\")) or (self.ui.confirmPassEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One or",
"# takes new window argument self.newWindow = classToAccess self.newWindow.show() # show new window",
"newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # else",
"self.ui = Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide()",
"(row['login_password'] != \"\"): values = [row['name'], row['login_username'], row['login_password']] accounts.append(values) if len(accounts) < 1:",
"gets path to file and stores it as an object self.ui.vaultFileLabel.setText(url.fileName()) # adjusts",
"nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.passwordEdit.text() writeData(nameOfAccount, username, password) Alert(\"Process",
"although the code is now longer, this fixes the index error issue updateAccounts(accounts)",
"in gui self.ui.fileLbl.adjustSize() # adjusts size of text wrapper for file name in",
"if (row['name'] != \"\") and (row['login_username'] != \"\") and (row['login_password'] != \"\"): values",
"table in window self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0,",
"resets that generatedPassLabel, nameOfAccount input and username input after saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\")",
"message.setIcon(icon) message.setText(text) message.exec_() def getData(pathToKey, pathToVault): # allows me to access Paths throughout",
"window except (ValueError, FileNotFoundError) as e: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect files selected\") # Alert",
"page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) # button variables which execute a specific function",
"QtWidgets.QMessageBox.Critical, \"Account name, Username or the Password field has been left empty\") else:",
"viewAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin()))",
"desktopPath = getPathToDesktop() # gets path to desktop keyFile = open(desktopPath + \"\\\\key.bin\",",
"account with open(path, 'w') as file: # writes to csv in lastpass format",
"json if value != \"\": terms = value.split(',') loginValues = {} uris =",
"!= \"\": row = data.split('\\n') self.accounts = {} i = 0 for value",
"from .CSV\") self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path) as jsonFile: data = json.load(jsonFile) if",
"self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords dont match\") elif (\" \" in self.ui.passwordEdit.text())",
"super().__init__(*args, **kwargs) self.ui = Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self): self.newWindow = allAccountsWin()",
"data to import\") else: for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information,",
"[] if self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path, 'r') as csvFile: reader = csv.DictReader(csvFile, delimiter=',') for",
"added and then someone attempts to delete an account # although the code",
"self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) # the code below resets that generatedPassLabel, nameOfAccount input",
"= [] for value in row: if value != \"\": terms = value.split(',')",
"random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No options to generate password",
"wrapper for file name in gui self.keyPath = file[0] # makes keyPath accessible",
"# writes encryption key to file keyFile.close cipher = AES.new(key, AES.MODE_CBC) ciphered_data =",
"as an object self.ui.vaultFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.vaultFileLabel.adjustSize() # adjusts",
"import random import csv import json from platform import system from string import",
"else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No options to generate password from\") def savePassword(self): if (self.ui.nameOfAccountEdit.text()",
"or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name or",
"or incorrectly entered if (self.ui.nameOfAccountEdit.text()[0] == \" \") or (self.ui.nameOfAccountEdit.text()[-1] == \" \"):",
"not(self.searchedAccounts): # checks if searchedAccounts is empty VIEWEDITEM = self.accounts[row] else: for n,",
"# removes values not in search # code below works just like in",
"createVaultFiles(self): key = get_random_bytes(32) # 32 bytes is 256 bits data = ''.encode('utf-8')",
"pathToVault readVaultFile = open(VAULTPATH, 'rb') # Open the file to read bytes iv",
"old window def loadAccounts(self): # added feature to read accounts from file global",
"readKeyFile = open(KEYPATH, 'rb') key = readKeyFile.read() readKeyFile.close() cipher = AES.new(key, AES.MODE_CBC, iv=iv)",
"KEYPATH, VAULTPATH key, iv, data = getData(KEYPATH, VAULTPATH) data += (\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8')",
"row = self.ui.accountsTable.currentRow() if not(self.searchedAccounts): # checks if searchedAccounts is empty VIEWEDITEM =",
"self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No options to generate password from\") def savePassword(self): if",
"if self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords dont match\") elif (\" \" in",
"__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def",
"# writes to csv file in lastpass format as lastpass' format is widely",
"= open(KEYPATH, 'rb') key = readKeyFile.read() readKeyFile.close() cipher = AES.new(key, AES.MODE_CBC, iv=iv) #",
"# checks for bitwarden format if 'login' in item: if ('username' in item['login'])",
"QtCore.QUrl.fromLocalFile(file[0]) # gets path to file and stores it as an object self.ui.fileLbl.setText(url.fileName())",
"seperated by value accounts.append(value.split(',')) for account in accounts: if account == VIEWEDITEM: index",
"= value.split(',') loginValues = {} uris = [{\"match\": None, \"uri\": \"http://\"}] loginValues['uris'], loginValues['username'],",
"to generate a QMessageBox def getKeyFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\",",
"self.goBack() def getPathToDesktop(): # path to desktop is different on windows and unix",
"username and password to vaultFile global KEYPATH, VAULTPATH key, iv, data = getData(KEYPATH,",
"me to access Paths throughout document global KEYPATH, VAULTPATH KEYPATH, VAULTPATH = pathToKey,",
"= getPathToDesktop() path += \"\\Accounts.json\" if data != \"\": row = data.split('\\n') accounts",
"Decrypt and then up-pad the result data = unpad(cipher.decrypt(ciphered_data), AES.block_size) return key, iv,",
"range(8, 17)] passLength = random.choice(lengths) password = \"\" for i in range(0, passLength):",
"format not supported or no data to import was found\") else: for item",
"vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() if __name__ == \"__main__\": # displays when starting application app",
"from exportAccountsPage import Ui_exportPage from PyQt5 import QtWidgets, QtCore, QtGui from Crypto.Random import",
"window def loadAccounts(self): # added feature to read accounts from file global KEYPATH,",
"in data: for item in data['items']: # checks for bitwarden format if 'login'",
"with open(path, 'w') as file: # writes to csv file in lastpass format",
"get_random_bytes(32) # 32 bytes is 256 bits data = ''.encode('utf-8') # basic data",
"viewing accounts self.newWindow = generatePasswordWin() self.newWindow.show() # show new window self.hide() # close",
"readKeyFile.close() cipher = AES.new(key, AES.MODE_CBC, iv=iv) # Setup cipher # Decrypt and then",
"checks that a Key File or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"or end of Account name\") elif (\" \" in self.ui.usernameEdit.text()) or (\" \"",
"open def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword)",
"keyFile.write(key) # writes encryption key to file keyFile.close cipher = AES.new(key, AES.MODE_CBC) ciphered_data",
"AES.block_size) return key, iv, data def writeData(nameOfAccount, username, password): # writes name of",
"mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password copied to clipboard\") def deleteAccount(self): message = QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\")",
"\"Please remove spaces from the beginning or end of Account name\") elif \"",
"def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_allAccounts() self.ui.setupUi(self) # button which",
"def changeWindow(self, classToAccess): self.newWindow = classToAccess self.newWindow.show() self.hide() def copyUsername(self): cb = QtGui.QGuiApplication.clipboard()",
"Changed\") self.goBack() # go to view account page after password is changed successfully",
"= readVaultFile.read(16) # Read the iv out - this is 16 bytes long",
"importWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile)",
"from Crypto.Util.Padding import pad, unpad # global variables to store paths to the",
"loadAccounts after a search self.searchedAccounts = {} self.loadAccounts() class addAccountWin(QtWidgets.QWidget): def __init__(self, *args,",
"'username', 'password', 'extra', 'name', 'grouping', 'fav'] writer = csv.DictWriter(file, fieldnames=columns, lineterminator='\\n') writer.writeheader() writer.writerows(accounts)",
"Ui_allAccounts from AddAccountPage import Ui_addAccount from viewAccountPage import Ui_viewAccount from changePassPage import Ui_changePass",
"count for table to reset when nothing in searchBox self.ui.accountsTable.setRowCount(0) # deletes tables",
"class MainWindow(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_startPage() self.ui.setupUi(self) #",
"to view all accounts self.newWindow = allAccountsWin() self.newWindow.show() # show new window self.hide()",
"(row['username'] != \"\") and (row['password'] != \"\") and (row['name'] != \"\"): values =",
"self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked(): passwordOptions += ascii_lowercase if self.ui.upperCaseCheck.isChecked(): passwordOptions += ascii_uppercase if self.ui.numbersCheck.isChecked():",
"copyUsername(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username copied to clipboard\") def",
"system() == 'Windows': desktopPath = os.environ[\"HOMEPATH\"] + \"\\Desktop\" # finds path to desktop",
"else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def exportJSON(self): key, iv, data",
"else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File type not supported\") class exportWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs):",
"username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") self.goBack() class viewAccountWin(QtWidgets.QWidget): def __init__(self, *args,",
"('username' in item['login']) and ('password' in item['login']): if (item['login']['username'] is not None) and",
"self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) # the code below resets that generatedPassLabel, nameOfAccount input and",
"\"One or Both of the password fields are empty\") else: if self.ui.passwordEdit.text() !=",
"= random.choice(lengths) password = \"\" for i in range(0, passLength): password += random.choice(passwordOptions)",
"vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() if __name__ == \"__main__\": # displays when starting",
"32 bytes is 256 bits data = ''.encode('utf-8') # basic data for file",
"as e: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect files selected\") # Alert function to show error",
"to import\") else: for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported",
"super().__init__(*args, **kwargs) self.ui = Ui_startPage() self.ui.setupUi(self) # initializes start page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile)",
"new window self.hide() def getFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All",
"message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you sure you want to delete the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes |",
"key to file keyFile.close cipher = AES.new(key, AES.MODE_CBC) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile",
"(row['login_username'] != \"\") and (row['login_password'] != \"\"): values = [row['name'], row['login_username'], row['login_password']] accounts.append(values)",
"*args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_allAccounts() self.ui.setupUi(self) # button which links to",
"from\") # Alert function to display error QMessageBox else: accounts = [] if",
"data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row = data.split('\\n') accounts = []",
"and ('login_username' in row) and ('login_password' in row): # bitwarden format if (row['name']",
"1 # count for resetting all accounts view if data != \"\": row",
"if (self.ui.passwordEdit.text() == (None or \"\")) or (self.ui.confirmPassEdit.text() == (None or \"\")): Alert(\"Error\",",
"now longer, this fixes the index error issue updateAccounts(accounts) # calls updateAccounts self.changeWindow(allAccountsWin())",
"self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.passwordEdit.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information,",
"or \"\")) or (self.ui.passwordEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name, Username",
"lets user choose files from explorer url = QtCore.QUrl.fromLocalFile(file[0]) # gets path to",
"self, 'Open file', \"\", \"All Files (*)\") # lets user choose files from",
"import csv import json from platform import system from string import ascii_uppercase, ascii_lowercase,",
"for table to reset when nothing in searchBox self.ui.accountsTable.setRowCount(0) # deletes tables contents",
"= self.ui.usernameEdit.text() password = self.ui.passwordEdit.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\")",
"adjusts size of text wrapper for file name in gui self.Path = file[0]",
"# comparison to make sure you only run loadAccounts after a search self.searchedAccounts",
"item: if ('username' in item['login']) and ('password' in item['login']): if (item['login']['username'] is not",
"\"\\Accounts.csv\" if data != \"\": row = data.split('\\n') accounts = [] for value",
"generate a QMessageBox def getKeyFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All",
"\"Username copied to clipboard\") def copyPassword(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information,",
"# writes name of account, username and password to vaultFile global KEYPATH, VAULTPATH",
"def copyUsername(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username copied to clipboard\")",
"\"): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from the beginning or end of Account",
"self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def viewItem(self): global VIEWEDITEM if (self.ui.accountsTable.currentItem().text() == \"View\") and (self.ui.accountsTable.currentColumn() ==",
"username\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.generatedPassLabel.text() writeData(nameOfAccount, username,",
"dont match\") elif (\" \" in self.ui.passwordEdit.text()) or (\" \" in self.ui.confirmPassEdit.text()): Alert(\"Error\",",
"gui self.ui.vaultFileLabel.adjustSize() # adjusts size of text wrapper for file name in gui",
"remove spaces from Username or Password\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in",
"('login_password' in row): # bitwarden format if (row['name'] != \"\") and (row['login_username'] !=",
"self.hide() # close old window except (ValueError, FileNotFoundError) as e: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect",
"\"\")) or (self.ui.confirmPassEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One or Both of",
"self.ui.usernameEdit.text() password = self.ui.generatedPassLabel.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") #",
"(\",\" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove commas from password fields\") else: key, iv,",
"string import ascii_uppercase, ascii_lowercase, digits, punctuation from startPage import Ui_startPage from genPassPage import",
"comparison to make sure you only run loadAccounts after a search self.searchedAccounts =",
"creates QMessageBox based on arguements in function message = QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon) message.setText(text)",
"def getData(pathToKey, pathToVault): # allows me to access Paths throughout document global KEYPATH,",
"(None or \"\")) or (self.ui.passwordEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name,",
"= Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def",
"== (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name or Username has been left",
"\"Please remove commas from Name of account, Username or Password\") else: nameOfAccount =",
"self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def exportCSV(self): key, iv,",
"\"Please remove spaces from the beginning or end of Account name\") elif (\"",
"values to new variable to edit self.count -= 1 # decreases count for",
"to vaultFile global KEYPATH, VAULTPATH key, iv, data = getData(KEYPATH, VAULTPATH) data +=",
"\"\\\\vault.bin\", \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Created",
"= QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username copied to clipboard\") def copyPassword(self): cb",
"QtWidgets.QMessageBox.Information, \"Password copied to clipboard\") def deleteAccount(self): message = QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are",
"a random error when lots of accounts were added and then someone attempts",
"key, iv, oldData = getData(KEYPATH, VAULTPATH) accounts = [] for value in data:",
"value.split(',') loginValues = {} uris = [{\"match\": None, \"uri\": \"http://\"}] loginValues['uris'], loginValues['username'], loginValues['password'],",
"this fixes the index error issue updateAccounts(accounts) # calls updateAccounts self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget):",
"self.ui.usernameEdit.text()) or (\" \" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username",
"newData += (\"{}\\n\".format(line)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(newData, AES.block_size)) vaultFile",
"\"\") and (row['login_password'] != \"\"): values = [row['name'], row['login_username'], row['login_password']] accounts.append(values) if len(accounts)",
"in item['login']) and ('password' in item['login']): if (item['login']['username'] is not None) and (item['login']['password']",
"viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # else disables table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def viewItem(self): global",
"self.ui.fileLbl.adjustSize() # adjusts size of text wrapper for file name in gui self.Path",
"= json.load(jsonFile) if 'items' in data: for item in data['items']: # checks for",
"= pathToKey, pathToVault readVaultFile = open(VAULTPATH, 'rb') # Open the file to read",
"in row: if value != \"\": self.accounts[i] = value.split(',') i += 1 self.ui.accountsTable.setRowCount(0)",
"key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') self.count = 1 #",
"__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize()",
"\"Password Changed\") self.goBack() # go to view account page after password is changed",
"of account, username and password to vaultFile global KEYPATH, VAULTPATH key, iv, data",
"self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self, classToAccess): self.newWindow = classToAccess self.newWindow.show() self.hide() def",
"accounts = [] for value in data: row = ','.join(value) accounts.append(row) newData =",
"the vault and key file global KEYPATH, VAULTPATH, VIEWEDITEM class MainWindow(QtWidgets.QWidget): def __init__(self,",
"being viewed accounts[i] = VIEWEDITEM # updates the item in the accounts nested",
"desktopPath = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return desktopPath def Alert(title, icon, text): # creates QMessageBox",
"window class allAccountsWin(QtWidgets.QWidget): # view all accounts window def __init__(self, *args, **kwargs): super().__init__(*args,",
"fields are empty\") else: if self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords dont match\")",
"# Read the rest of the data readVaultFile.close() readKeyFile = open(KEYPATH, 'rb') key",
"in self.ui.passwordEdit.text()) or (\",\" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove commas from password fields\")",
"password is changed successfully class importWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui",
"false when writing to a json if value != \"\": terms = value.split(',')",
"self.changeWindow(exportWin())) def changeWindow(self, classToAccess): # takes new window argument self.newWindow = classToAccess self.newWindow.show()",
"QtWidgets.QMessageBox.Critical, \"One or Both of the password fields are empty\") else: if self.ui.passwordEdit.text()",
"\"\"): self.searchedAccounts = self.accounts.copy() # copy sets values to new variable to edit",
"data.split('\\n') accounts = [] for value in row: if value != \"\": terms",
"or username\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.generatedPassLabel.text() writeData(nameOfAccount,",
"(\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()) or (\",\" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"and key file global KEYPATH, VAULTPATH, VIEWEDITEM class MainWindow(QtWidgets.QWidget): def __init__(self, *args, **kwargs):",
"windows the drive the desktop is on can be changed if system() ==",
"+= (\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(data, AES.block_size))",
"def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def saveAccount(self): if (self.ui.nameOfAccountEdit.text() == (None",
"row in reader: if ('name' in row) and ('username' in row) and ('password'",
"view if data != \"\": row = data.split('\\n') self.accounts = {} i =",
"# makes path accessible in importWin def importData(self): if self.ui.fileLbl.text() == \"Select file",
"elif (\" \" in self.ui.passwordEdit.text()) or (\" \" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove",
"0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: #",
"just like in loadAccounts but with search terms for n, key in enumerate(sorted(self.searchedAccounts.keys())):",
"= [] for value in data: row = ','.join(value) accounts.append(row) newData = b''",
"self.ui.lowerCaseCheck.isChecked(): passwordOptions += ascii_lowercase if self.ui.upperCaseCheck.isChecked(): passwordOptions += ascii_uppercase if self.ui.numbersCheck.isChecked(): passwordOptions +=",
"after password is changed successfully class importWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)",
"Alert function to display error QMessageBox else: accounts = [] if self.ui.fileLbl.text().lower().endswith(\".csv\"): with",
"in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .JSON\") self.goBack() else:",
"folder is on if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath = \"{0}:{1}\".format(driveLetter, desktopPath) else: desktopPath =",
"if clickedBtn.text() == \"&Yes\": key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8')",
"size of text wrapper for file name in gui self.vaultPath = file[0] #",
"empty if self.count <= 0: # comparison to make sure you only run",
"self.count = 1 # count for resetting all accounts view if data !=",
"self.hide() def copyUsername(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username copied to",
"in data: row = ','.join(value) accounts.append(row) newData = b'' for line in accounts:",
"getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.csv\" if data",
"spaces from the beginning or end of Account name\") elif \" \" in",
"range(len(accounts)): if accounts[i] == VIEWEDITEM: VIEWEDITEM[2] = self.ui.passwordEdit.text() # updates the item being",
"were selected. Please select files to open the vault\") # Alert function to",
"self.ui = Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show()",
"you sure you want to delete the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete)",
"# initializes start page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) # button variables which execute",
"goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() # show new window self.hide() def getFile(self): file",
"256 bits data = ''.encode('utf-8') # basic data for file to encrypt desktopPath",
"changePassword(self): if (self.ui.passwordEdit.text() == (None or \"\")) or (self.ui.confirmPassEdit.text() == (None or \"\")):",
"def getVaultFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\") #",
"data = unpad(cipher.decrypt(ciphered_data), AES.block_size) return key, iv, data def writeData(nameOfAccount, username, password): #",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords dont match\") elif (\" \" in self.ui.passwordEdit.text()) or (\" \"",
"in table in window self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n,",
"(row['name'] != \"\"): values = [row['name'], row['username'], row['password']] accounts.append(values) elif ('name' in row)",
"goBack(self): self.newWindow = viewAccountWin() self.newWindow.show() self.hide() def changePassword(self): if (self.ui.passwordEdit.text() == (None or",
"random.choice(lengths) password = \"\" for i in range(0, passLength): password += random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password)",
"VIEWEDITEM if (self.ui.accountsTable.currentItem().text() == \"View\") and (self.ui.accountsTable.currentColumn() == 1): row = self.ui.accountsTable.currentRow() if",
"variable to edit self.count -= 1 # decreases count for table to reset",
"csv in lastpass format json.dump(accounts, file, indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON file successfully created\")",
"(\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from",
"desktop folder is on if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath = \"{0}:{1}\".format(driveLetter, desktopPath) else: desktopPath",
"= unpad(cipher.decrypt(ciphered_data), AES.block_size) return key, iv, data def writeData(nameOfAccount, username, password): # writes",
"type not supported\") class exportWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui =",
"to display error QMessageBox else: accounts = [] if self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path, 'r')",
"# Open the file to read bytes iv = readVaultFile.read(16) # Read the",
"row['password']] accounts.append(values) elif ('name' in row) and ('login_username' in row) and ('login_password' in",
"getVaultFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\") # lets",
"sometimes it would give # a random error when lots of accounts were",
"self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def changeWindow(self, classToAccess): # takes new window argument self.newWindow =",
"in lastpass format as lastpass' format is widely supported columns = ['url', 'username',",
"self.newWindow = allAccountsWin() self.newWindow.show() # show new window self.hide() # close old window",
"like in loadAccounts but with search terms for n, key in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n)",
"to delete an account # although the code is now longer, this fixes",
"if search box is empty if self.count <= 0: # comparison to make",
"desktopPath = \"{0}:{1}\".format(driveLetter, desktopPath) else: desktopPath = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return desktopPath def Alert(title,",
"self.ui.vaultFileLabel.text() if (keyFile == \"Key File\") or (vaultFile == \"Vault File\"): # checks",
"drive the desktop is on can be changed if system() == 'Windows': desktopPath",
"in row) and ('login_password' in row): # bitwarden format if (row['name'] != \"\")",
"uris = [{\"match\": None, \"uri\": \"http://\"}] loginValues['uris'], loginValues['username'], loginValues['password'], loginValues['totp'] = uris, terms[1],",
"loginValues['password'], loginValues['totp'] = uris, terms[1], terms[2], None temp = {} temp['id'], temp['organizationId'], temp['folderId'],",
"to file and stores it as an object self.ui.keyFileLabel.setText(url.fileName()) # adjusts file name",
"= data.split('\\n') self.accounts = {} i = 0 for value in row: if",
"enumerate(sorted(self.searchedAccounts.keys())): if row == n: VIEWEDITEM = self.accounts[key] self.changeWindow(viewAccountWin()) def searchAccounts(self): term =",
"None, 1, terms[0], None, False, loginValues, False account.append(temp) accounts['items'] = account with open(path,",
"Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Created vault.bin and key.bin\") # Alert function to reuse the",
"from\": # checks that a Key File or Vault file have been selected",
"the beginning or end of Account name\") elif (\" \" in self.ui.usernameEdit.text()) or",
"encrypt desktopPath = getPathToDesktop() # gets path to desktop keyFile = open(desktopPath +",
"QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210,",
"writes to csv file in lastpass format as lastpass' format is widely supported",
"punctuation.replace(',', '') lengths = [i for i in range(8, 17)] passLength = random.choice(lengths)",
"if self.ui.fileLbl.text() == \"Select file to import from\": # checks that a Key",
"read accounts from file global KEYPATH, VAULTPATH self.searchedAccounts = {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv,",
"writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to",
"making table for n, key in enumerate(sorted(self.accounts.keys())): # displays code in table in",
"accounts from .JSON\") self.goBack() else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File type not supported\") class exportWin(QtWidgets.QWidget):",
"in window if not(term.lower() in self.accounts[key][0].lower()): self.searchedAccounts.pop(key) # removes values not in search",
"if not(term.lower() in self.accounts[key][0].lower()): self.searchedAccounts.pop(key) # removes values not in search # code",
"= csv.DictReader(csvFile, delimiter=',') for row in reader: if ('name' in row) and ('username'",
"in item['login']): if (item['login']['username'] is not None) and (item['login']['password'] is not None): values",
"nested list updateAccounts(accounts) # calls updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password Changed\") self.goBack() # go",
"commas from name of account or username\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username =",
"# find drive desktop folder is on if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath = \"{0}:{1}\".format(driveLetter,",
"AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates",
"data = data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.json\" if data != \"\":",
"QtCore.Qt.ItemIsEditable) else: # if search box is empty if self.count <= 0: #",
"paths to the vault and key file global KEYPATH, VAULTPATH, VIEWEDITEM class MainWindow(QtWidgets.QWidget):",
"('login_username' in row) and ('login_password' in row): # bitwarden format if (row['name'] !=",
"box is empty if self.count <= 0: # comparison to make sure you",
"the beginning or end of Account name\") elif \" \" in self.ui.usernameEdit.text(): Alert(\"Error\",",
"punctuation from startPage import Ui_startPage from genPassPage import Ui_passwordGen from allAccountsPage import Ui_allAccounts",
"= self.ui.vaultFileLabel.text() if (keyFile == \"Key File\") or (vaultFile == \"Vault File\"): #",
"# Alert function to reuse the code to generate a QMessageBox def getKeyFile(self):",
"for n, key in enumerate(sorted(self.searchedAccounts.keys())): if row == n: VIEWEDITEM = self.accounts[key] self.changeWindow(viewAccountWin())",
"self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username or Password\") elif (\",\" in",
"window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def",
"password or viewing accounts self.newWindow = generatePasswordWin() self.newWindow.show() # show new window self.hide()",
"supported\") if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file has no data to",
"desktop for driveLetter in ascii_uppercase: # find drive desktop folder is on if",
"self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1,",
"self.ui = Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self): self.newWindow = viewAccountWin()",
"# global variables to store paths to the vault and key file global",
"(self.ui.accountsTable.currentColumn() == 1): row = self.ui.accountsTable.currentRow() if not(self.searchedAccounts): # checks if searchedAccounts is",
"# displays generate password window when vault is open def __init__(self, *args, **kwargs):",
"if (self.ui.nameOfAccountEdit.text()[0] == \" \") or (self.ui.nameOfAccountEdit.text()[-1] == \" \"): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please",
"in self.ui.usernameEdit.text()) or (\" \" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from",
"is different on windows and unix systems as on windows the drive the",
"item['login']['password']] accounts.append(values) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file format not supported\") if len(accounts) <",
"wrapper for file name in gui self.Path = file[0] # makes path accessible",
"!= \"\": row = data.split('\\n') accounts = [] for value in row: if",
"= {} temp[\"name\"], temp[\"username\"], temp[\"password\"] = terms[0], terms[1], terms[2] accounts.append(temp) with open(path, 'w')",
"self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No options to generate password from\") def",
"file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Created vault.bin and key.bin\") # Alert",
"- this is 16 bytes long ciphered_data = readVaultFile.read() # Read the rest",
"changeWindow(self, classToAccess): # takes new window argument self.newWindow = classToAccess self.newWindow.show() # show",
"updateAccounts(accounts) # calls updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password Changed\") self.goBack() # go to view",
"window to view all accounts self.newWindow = allAccountsWin() self.newWindow.show() # show new window",
"Ui_startPage() self.ui.setupUi(self) # initializes start page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) # button variables",
"when lots of accounts were added and then someone attempts to delete an",
"Key File or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No file was",
"file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No file was selected. Please select a",
"= getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row = data.split('\\n') accounts = [] for",
"False account.append(temp) accounts['items'] = account with open(path, 'w') as file: # writes to",
"for value in data: row = ','.join(value) accounts.append(row) newData = b'' for line",
"key file global KEYPATH, VAULTPATH, VIEWEDITEM class MainWindow(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args,",
"self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def changeWindow(self, classToAccess):",
"vault and key file global KEYPATH, VAULTPATH, VIEWEDITEM class MainWindow(QtWidgets.QWidget): def __init__(self, *args,",
"# close old window class allAccountsWin(QtWidgets.QWidget): # view all accounts window def __init__(self,",
"terms[2] accounts.append(temp) with open(path, 'w') as file: # writes to csv file in",
"text): # creates QMessageBox based on arguements in function message = QtWidgets.QMessageBox() message.setWindowTitle(title)",
"{} account = [] for value in row: # json uses None for",
"sys import os import random import csv import json from platform import system",
"message.setWindowTitle(title) message.setIcon(icon) message.setText(text) message.exec_() def getData(pathToKey, pathToVault): # allows me to access Paths",
"newData = b'' for line in accounts: newData += (\"{}\\n\".format(line)).encode('utf-8') cipher = AES.new(key,",
"self.newWindow = classToAccess self.newWindow.show() # show new window self.hide() # close old window",
"and (self.ui.accountsTable.currentColumn() == 1): row = self.ui.accountsTable.currentRow() if not(self.searchedAccounts): # checks if searchedAccounts",
"is empty VIEWEDITEM = self.accounts[row] else: for n, key in enumerate(sorted(self.searchedAccounts.keys())): if row",
"1, terms[0], None, False, loginValues, False account.append(temp) accounts['items'] = account with open(path, 'w')",
"self.ui.keyFileLabel.adjustSize() # adjusts size of text wrapper for file name in gui self.keyPath",
"temp['folderId'], temp['type'], temp['name'], temp['notes'], temp[ 'favorite'], temp['login'], temp['collectionIds'] = \"\", None, None, 1,",
"(None or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")) or (self.ui.passwordEdit.text() == (None",
"in gui self.Path = file[0] # makes path accessible in importWin def importData(self):",
"(self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"**kwargs): super().__init__(*args, **kwargs) self.ui = Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self): self.newWindow",
"\"View\") and (self.ui.accountsTable.currentColumn() == 1): row = self.ui.accountsTable.currentRow() if not(self.searchedAccounts): # checks if",
"(self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")) or (self.ui.passwordEdit.text()",
"# adjusts file name in gui self.ui.fileLbl.adjustSize() # adjusts size of text wrapper",
"file keyFile.close cipher = AES.new(key, AES.MODE_CBC) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(desktopPath",
"\"\" for i in range(0, passLength): password += random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True)",
"AES from Crypto.Util.Padding import pad, unpad # global variables to store paths to",
"Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") # reset check boxes after saving accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False)",
"self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin()))",
"gets path to file and stores it as an object self.ui.fileLbl.setText(url.fileName()) # adjusts",
"function def createVaultFiles(self): key = get_random_bytes(32) # 32 bytes is 256 bits data",
"'rb') # Open the file to read bytes iv = readVaultFile.read(16) # Read",
"password fields are empty\") else: if self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords dont",
"Username has been left empty\") else: # displays any error message if the",
"== 'Windows': desktopPath = os.environ[\"HOMEPATH\"] + \"\\Desktop\" # finds path to desktop for",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\"",
"= allAccountsWin() self.newWindow.show() # show new window self.hide() # close old window class",
"QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username or Password\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or",
"getPathToDesktop() path += \"\\Accounts.csv\" if data != \"\": row = data.split('\\n') accounts =",
"== (None or \"\")) or (self.ui.passwordEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account",
"'items' in data: for item in data['items']: # checks for bitwarden format if",
"self.ui.keyFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.keyFileLabel.adjustSize() # adjusts size of text",
"open(VAULTPATH, 'rb') # Open the file to read bytes iv = readVaultFile.read(16) #",
"\"No options to generate password from\") def savePassword(self): if (self.ui.nameOfAccountEdit.text() == (None or",
"File\"): # checks that a Key File or Vault file have been selected",
"QtWidgets.QMessageBox.Information, \"CSV file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack()",
"password)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(VAULTPATH,",
"self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() # show new window",
"table to reset when nothing in searchBox self.ui.accountsTable.setRowCount(0) # deletes tables contents for",
"import Ui_viewAccount from changePassPage import Ui_changePass from importAccountsPage import Ui_importAccounts from exportAccountsPage import",
"format as lastpass' format is widely supported columns = ['url', 'username', 'password', 'extra',",
"in accounts: if account == VIEWEDITEM: index = accounts.index(account) accounts.pop(index) # when this",
"QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def exportJSON(self): key, iv, data = getData(KEYPATH,",
"enumerate(sorted(self.accounts.keys())): # displays code in table in window if not(term.lower() in self.accounts[key][0].lower()): self.searchedAccounts.pop(key)",
"in range(8, 17)] passLength = random.choice(lengths) password = \"\" for i in range(0,",
"\") or (self.ui.nameOfAccountEdit.text()[-1] == \" \"): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from the",
"with open(self.Path, 'r') as csvFile: reader = csv.DictReader(csvFile, delimiter=',') for row in reader:",
"key in enumerate(sorted(self.searchedAccounts.keys())): if row == n: VIEWEDITEM = self.accounts[key] self.changeWindow(viewAccountWin()) def searchAccounts(self):",
"accounts.pop(index) # when this code was a for loop in range len(accounts) sometimes",
"Open the file to read bytes iv = readVaultFile.read(16) # Read the iv",
"accounts window def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_allAccounts() self.ui.setupUi(self) #",
"nothing in searchBox self.ui.accountsTable.setRowCount(0) # deletes tables contents for n, key in enumerate(sorted(self.accounts.keys())):",
"n: VIEWEDITEM = self.accounts[key] self.changeWindow(viewAccountWin()) def searchAccounts(self): term = self.ui.searchBox.text() if term !=",
"from allAccountsPage import Ui_allAccounts from AddAccountPage import Ui_addAccount from viewAccountPage import Ui_viewAccount from",
"getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.json\" if data",
"gui self.Path = file[0] # makes path accessible in importWin def importData(self): if",
"digits, punctuation from startPage import Ui_startPage from genPassPage import Ui_passwordGen from allAccountsPage import",
"*args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_startPage() self.ui.setupUi(self) # initializes start page self.ui.startButton.clicked.connect(self.createVaultFiles)",
"or no files were selected. Please select files to open the vault\") #",
"view account page after password is changed successfully class importWin(QtWidgets.QWidget): def __init__(self, *args,",
"File or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either one or no",
"selected. Please select files to open the vault\") # Alert function to display",
".JSON\") self.goBack() else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File type not supported\") class exportWin(QtWidgets.QWidget): def __init__(self,",
"= viewAccountWin() self.newWindow.show() self.hide() def changePassword(self): if (self.ui.passwordEdit.text() == (None or \"\")) or",
"data.split('\\n') accounts = {} account = [] for value in row: # json",
"data = data.decode('utf-8') self.count = 1 # count for resetting all accounts view",
"from importAccountsPage import Ui_importAccounts from exportAccountsPage import Ui_exportPage from PyQt5 import QtWidgets, QtCore,",
"clickedBtn.text() == \"&Yes\": key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row",
"# view all accounts window def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui =",
"**kwargs): super().__init__(*args, **kwargs) self.ui = Ui_startPage() self.ui.setupUi(self) # initializes start page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile)",
"self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') self.count = 1",
"# Alert function to show error message class generatePasswordWin(QtWidgets.QWidget): # displays generate password",
"adjusts size of text wrapper for file name in gui self.keyPath = file[0]",
"list updateAccounts(accounts) # calls updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password Changed\") self.goBack() # go to",
"= accounts.index(account) accounts.pop(index) # when this code was a for loop in range",
"import Ui_addAccount from viewAccountPage import Ui_viewAccount from changePassPage import Ui_changePass from importAccountsPage import",
"if self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path, 'r') as csvFile: reader = csv.DictReader(csvFile, delimiter=',') for row",
"close old window except (ValueError, FileNotFoundError) as e: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect files selected\")",
"index error issue updateAccounts(accounts) # calls updateAccounts self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget): def __init__(self, *args,",
"self.newWindow.show() # show new window self.hide() def getFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open",
"None): values = [item['name'], item['login'] ['username'], item['login']['password']] accounts.append(values) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file",
"format not supported\") if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file has no",
"of text wrapper for file name in gui self.keyPath = file[0] # makes",
"= AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") #",
"= AES.new(key, AES.MODE_CBC, iv=iv) # Setup cipher # Decrypt and then up-pad the",
"input fields are empty or incorrectly entered if (self.ui.nameOfAccountEdit.text()[0] == \" \") or",
"to access Paths throughout document global KEYPATH, VAULTPATH KEYPATH, VAULTPATH = pathToKey, pathToVault",
"in search # code below works just like in loadAccounts but with search",
"open(desktopPath + \"\\\\key.bin\", \"wb\") keyFile.write(key) # writes encryption key to file keyFile.close cipher",
"key, iv, data = getData(KEYPATH, VAULTPATH) data += (\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8') cipher =",
"supported\") class exportWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_exportPage() self.ui.setupUi(self)",
"= allAccountsWin() self.newWindow.show() # show new window self.hide() def getFile(self): file = QtWidgets.QFileDialog.getOpenFileName(",
"the Password field has been left empty\") else: # displays any error message",
"lastpass format json.dump(accounts, file, indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON file successfully created\") else: Alert(\"Error\",",
"a QMessageBox def getKeyFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files",
"'w') as file: # writes to csv in lastpass format json.dump(accounts, file, indent=4)",
"password += random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No options to",
"up-pad the result data = unpad(cipher.decrypt(ciphered_data), AES.block_size) return key, iv, data def writeData(nameOfAccount,",
"data.decode('utf-8') self.count = 1 # count for resetting all accounts view if data",
"searchBox self.ui.accountsTable.setRowCount(0) # deletes tables contents for n, key in enumerate(sorted(self.accounts.keys())): # displays",
"loop in range len(accounts) sometimes it would give # a random error when",
"# adjusts size of text wrapper for file name in gui self.Path =",
"QMessageBox else: # exception handling try: key, iv, data = getData(self.keyPath, self.vaultPath) #",
"make sure you only run loadAccounts after a search self.searchedAccounts = {} self.loadAccounts()",
"name, Username or the Password field has been left empty\") else: # displays",
"QtWidgets.QMessageBox.Critical, \"No options to generate password from\") def savePassword(self): if (self.ui.nameOfAccountEdit.text() == (None",
"QtWidgets.QMessageBox.Critical, \"Incorrect files selected\") # Alert function to show error message class generatePasswordWin(QtWidgets.QWidget):",
"is changed successfully class importWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui =",
"in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .CSV\") self.goBack() elif",
"generating password or viewing accounts self.newWindow = generatePasswordWin() self.newWindow.show() # show new window",
"for n, key in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter)",
"__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_startPage() self.ui.setupUi(self) # initializes start page",
"is on can be changed if system() == 'Windows': desktopPath = os.environ[\"HOMEPATH\"] +",
"self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No options to generate password from\") def savePassword(self):",
"for i in range(len(accounts)): if accounts[i] == VIEWEDITEM: VIEWEDITEM[2] = self.ui.passwordEdit.text() # updates",
"*args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self): self.newWindow",
"file was selected. Please select a file to import from\") # Alert function",
"value.split(',') temp = {} temp[\"name\"], temp[\"username\"], temp[\"password\"] = terms[0], terms[1], terms[2] accounts.append(temp) with",
"for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .JSON\")",
"Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def",
"= self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.passwordEdit.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\",",
"empty or incorrectly entered if (self.ui.nameOfAccountEdit.text()[0] == \" \") or (self.ui.nameOfAccountEdit.text()[-1] == \"",
"== 1): row = self.ui.accountsTable.currentRow() if not(self.searchedAccounts): # checks if searchedAccounts is empty",
"readVaultFile = open(VAULTPATH, 'rb') # Open the file to read bytes iv =",
"vaultFile.write(ciphered_data) vaultFile.close() def updateAccounts(data): global KEYPATH, VAULTPATH key, iv, oldData = getData(KEYPATH, VAULTPATH)",
"writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") # reset check boxes after",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No file was selected. Please select a file to import from\")",
"allows me to access Paths throughout document global KEYPATH, VAULTPATH KEYPATH, VAULTPATH =",
"= ''.encode('utf-8') # basic data for file to encrypt desktopPath = getPathToDesktop() #",
"\"CSV file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def",
"table for n, key in enumerate(sorted(self.accounts.keys())): # displays code in table in window",
"passwordOptions += digits if self.ui.specialCharsCheck.isChecked(): passwordOptions += punctuation.replace(',', '') lengths = [i for",
"importAccountsPage import Ui_importAccounts from exportAccountsPage import Ui_exportPage from PyQt5 import QtWidgets, QtCore, QtGui",
"QtWidgets.QMessageBox.Information, \"Username copied to clipboard\") def copyPassword(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\",",
"# button which links to generate password window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda:",
"viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable)",
"account, username and password to vaultFile global KEYPATH, VAULTPATH key, iv, data =",
"def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData)",
"= [row['name'], row['username'], row['password']] accounts.append(values) elif ('name' in row) and ('login_username' in row)",
"item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .CSV\") self.goBack()",
"QtWidgets.QMessageBox.Information, \"Account saved\") self.goBack() class viewAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui",
"self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def",
"message = QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you sure you want to delete the",
"import Ui_allAccounts from AddAccountPage import Ui_addAccount from viewAccountPage import Ui_viewAccount from changePassPage import",
"e: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect files selected\") # Alert function to show error message",
"to export\") self.goBack() def exportJSON(self): key, iv, data = getData(KEYPATH, VAULTPATH) data =",
"new window self.hide() # close old window except (ValueError, FileNotFoundError) as e: Alert(\"Error\",",
"# displays code in table in window self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel =",
"an object self.ui.vaultFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.vaultFileLabel.adjustSize() # adjusts size",
"code was a for loop in range len(accounts) sometimes it would give #",
"= [{\"match\": None, \"uri\": \"http://\"}] loginValues['uris'], loginValues['username'], loginValues['password'], loginValues['totp'] = uris, terms[1], terms[2],",
"in searchBox self.ui.accountsTable.setRowCount(0) # deletes tables contents for n, key in enumerate(sorted(self.accounts.keys())): #",
"Both of the password fields are empty\") else: if self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text(): Alert(\"Error\",",
"if value != \"\": terms = value.split(',') temp = {} temp[\"name\"], temp[\"username\"], temp[\"password\"]",
"self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def saveAccount(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\"))",
"Username or Password\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()) or (\",\"",
"getData(KEYPATH, VAULTPATH) data += (\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data",
"elif \" \" in self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username\") elif",
"= data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.json\" if data != \"\": row",
"KEYPATH, VAULTPATH self.searchedAccounts = {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv, data = getData(KEYPATH, VAULTPATH) data",
"if self.ui.numbersCheck.isChecked(): passwordOptions += digits if self.ui.specialCharsCheck.isChecked(): passwordOptions += punctuation.replace(',', '') lengths =",
"(ValueError, FileNotFoundError) as e: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect files selected\") # Alert function to",
"all data in table before making table for n, key in enumerate(sorted(self.accounts.keys())): #",
"# calls updateAccounts self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui",
"Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() # show",
"import ascii_uppercase, ascii_lowercase, digits, punctuation from startPage import Ui_startPage from genPassPage import Ui_passwordGen",
"initializes start page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) # button variables which execute a",
"accounts from file global KEYPATH, VAULTPATH self.searchedAccounts = {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv, data",
"'w') as file: # writes to csv file in lastpass format as lastpass'",
"the rest of the data readVaultFile.close() readKeyFile = open(KEYPATH, 'rb') key = readKeyFile.read()",
"self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self): self.newWindow = viewAccountWin() self.newWindow.show() self.hide() def",
"17)] passLength = random.choice(lengths) password = \"\" for i in range(0, passLength): password",
"added feature to read accounts from file global KEYPATH, VAULTPATH self.searchedAccounts = {}",
"self.ui.passwordEdit.text()) or (\" \" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove spaces from password fields\")",
"of account, Username or Password\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password",
"accounts.append(temp) with open(path, 'w') as file: # writes to csv file in lastpass",
"table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def viewItem(self): global VIEWEDITEM if (self.ui.accountsTable.currentItem().text() == \"View\") and (self.ui.accountsTable.currentColumn()",
"\" \" in self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username\") elif (\",\"",
"from startPage import Ui_startPage from genPassPage import Ui_passwordGen from allAccountsPage import Ui_allAccounts from",
"remove commas from name of account or username\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username",
"size of text wrapper for file name in gui self.Path = file[0] #",
"import pad, unpad # global variables to store paths to the vault and",
"gui self.keyPath = file[0] # makes keyPath accessible in all of MainWindow class",
"new variable to edit self.count -= 1 # decreases count for table to",
"'fav'] writer = csv.DictWriter(file, fieldnames=columns, lineterminator='\\n') writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV file successfully",
"import system from string import ascii_uppercase, ascii_lowercase, digits, punctuation from startPage import Ui_startPage",
"gui self.ui.keyFileLabel.adjustSize() # adjusts size of text wrapper for file name in gui",
"csv file in lastpass format as lastpass' format is widely supported columns =",
"self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords dont match\") elif (\" \" in self.ui.passwordEdit.text()) or (\"",
"table in window if not(term.lower() in self.accounts[key][0].lower()): self.searchedAccounts.pop(key) # removes values not in",
"self.newWindow.show() self.hide() def copyUsername(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username copied",
"updates the item being viewed accounts[i] = VIEWEDITEM # updates the item in",
"Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") # reset check boxes after saving accounts self.ui.lowerCaseCheck.setChecked(False)",
"uris, terms[1], terms[2], None temp = {} temp['id'], temp['organizationId'], temp['folderId'], temp['type'], temp['name'], temp['notes'],",
"self.newWindow.show() self.hide() def saveAccount(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() ==",
"when this code was a for loop in range len(accounts) sometimes it would",
"def updateAccounts(data): global KEYPATH, VAULTPATH key, iv, oldData = getData(KEYPATH, VAULTPATH) accounts =",
"self.ui.setupUi(self) # initializes start page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) # button variables which",
"**kwargs): super().__init__(*args, **kwargs) self.ui = Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def goBack(self): self.newWindow",
"self.ui.accountsTable.setRowCount(0) # deletes tables contents for n, key in enumerate(sorted(self.accounts.keys())): # displays code",
"(None or \"\"): self.searchedAccounts = self.accounts.copy() # copy sets values to new variable",
"loginValues['uris'], loginValues['username'], loginValues['password'], loginValues['totp'] = uris, terms[1], terms[2], None temp = {} temp['id'],",
"File\") or (vaultFile == \"Vault File\"): # checks that a Key File or",
"Setup cipher # Decrypt and then up-pad the result data = unpad(cipher.decrypt(ciphered_data), AES.block_size)",
"# show new window self.hide() # close old window def loadAccounts(self): # added",
"displays generate password window when vault is open def __init__(self, *args, **kwargs): super().__init__(*args,",
"with search terms for n, key in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel",
"file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() if __name__ == \"__main__\": # displays when starting application",
"def Alert(title, icon, text): # creates QMessageBox based on arguements in function message",
"= getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.csv\" if",
"to read bytes iv = readVaultFile.read(16) # Read the iv out - this",
"**kwargs): super().__init__(*args, **kwargs) self.ui = Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self):",
"import AES from Crypto.Util.Padding import pad, unpad # global variables to store paths",
"to store paths to the vault and key file global KEYPATH, VAULTPATH, VIEWEDITEM",
"temp['type'], temp['name'], temp['notes'], temp[ 'favorite'], temp['login'], temp['collectionIds'] = \"\", None, None, 1, terms[0],",
"the file to read bytes iv = readVaultFile.read(16) # Read the iv out",
"VAULTPATH) accounts = [] for value in data: row = ','.join(value) accounts.append(row) newData",
"= 0 for value in row: if value != \"\": self.accounts[i] = value.split(',')",
"selected\") # Alert function to show error message class generatePasswordWin(QtWidgets.QWidget): # displays generate",
"in range(0, passLength): password += random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"= get_random_bytes(32) # 32 bytes is 256 bits data = ''.encode('utf-8') # basic",
"out - this is 16 bytes long ciphered_data = readVaultFile.read() # Read the",
"1 self.ui.accountsTable.setRowCount(0) # removes all data in table before making table for n,",
"import was found\") else: for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information,",
"is not None) and (item['login']['password'] is not None): values = [item['name'], item['login'] ['username'],",
"sure you want to delete the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_()",
"self.newWindow = generatePasswordWin() self.newWindow.show() # show new window self.hide() # close old window",
"(self.ui.usernameEdit.text() == (None or \"\")) or (self.ui.passwordEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # if search box is empty",
"updates the item in the accounts nested list updateAccounts(accounts) # calls updateAccounts Alert(\"Confirmed\",",
"accounts[i] == VIEWEDITEM: VIEWEDITEM[2] = self.ui.passwordEdit.text() # updates the item being viewed accounts[i]",
"password fields\") elif (\",\" in self.ui.passwordEdit.text()) or (\",\" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove",
"a search self.searchedAccounts = {} self.loadAccounts() class addAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args,",
"File or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No file was selected.",
"Crypto.Util.Padding import pad, unpad # global variables to store paths to the vault",
"VIEWEDITEM: index = accounts.index(account) accounts.pop(index) # when this code was a for loop",
"saving accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) # the code below resets that generatedPassLabel,",
"updateAccounts(accounts) # calls updateAccounts self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)",
"the index error issue updateAccounts(accounts) # calls updateAccounts self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget): def __init__(self,",
"KEYPATH, VAULTPATH = pathToKey, pathToVault readVaultFile = open(VAULTPATH, 'rb') # Open the file",
"name in gui self.ui.vaultFileLabel.adjustSize() # adjusts size of text wrapper for file name",
"elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()) or (\",\" in self.ui.passwordEdit.text()): Alert(\"Error\",",
"Name of account, Username or Password\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text()",
"remove commas from Name of account, Username or Password\") else: nameOfAccount = self.ui.nameOfAccountEdit.text()",
"supported or no data to import was found\") else: for item in accounts:",
"is on if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath = \"{0}:{1}\".format(driveLetter, desktopPath) else: desktopPath = os.path.join(os.path.join(os.path.expanduser('~')),",
"accounts from .CSV\") self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path) as jsonFile: data = json.load(jsonFile)",
"to desktop is different on windows and unix systems as on windows the",
"file to import from\") # Alert function to display error QMessageBox else: accounts",
"class viewAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda:",
"n, key in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n,",
"self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self): # opens window to view all accounts self.newWindow = allAccountsWin()",
"message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_() def confirmDelete(self, clickedBtn): if clickedBtn.text() == \"&Yes\":",
"\"\"): values = [row['name'], row['username'], row['password']] accounts.append(values) elif ('name' in row) and ('login_username'",
"self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.generatedPassLabel.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information,",
"**kwargs) self.ui = Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize()",
"ascii_uppercase: # find drive desktop folder is on if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath =",
"0 for value in row: if value != \"\": self.accounts[i] = value.split(',') i",
"= \"\" if self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked(): passwordOptions",
"by value accounts.append(value.split(',')) for account in accounts: if account == VIEWEDITEM: index =",
"adjusts file name in gui self.ui.keyFileLabel.adjustSize() # adjusts size of text wrapper for",
"values = [row['name'], row['username'], row['password']] accounts.append(values) elif ('name' in row) and ('login_username' in",
"self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self): # opens window to view all accounts self.newWindow =",
"path = getPathToDesktop() path += \"\\Accounts.json\" if data != \"\": row = data.split('\\n')",
"path to file and stores it as an object self.ui.vaultFileLabel.setText(url.fileName()) # adjusts file",
"in all of MainWindow class def getVaultFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file',",
"('password' in row): # lastpass format if (row['username'] != \"\") and (row['password'] !=",
"in row) and ('login_username' in row) and ('login_password' in row): # bitwarden format",
"iv, data = getData(KEYPATH, VAULTPATH) data += (\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8') cipher = AES.new(key,",
"display error QMessageBox else: # exception handling try: key, iv, data = getData(self.keyPath,",
"bitwarden format if (row['name'] != \"\") and (row['login_username'] != \"\") and (row['login_password'] !=",
"item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .CSV\") self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path) as",
"not supported\") if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file has no data",
"self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) # the code below resets that generatedPassLabel, nameOfAccount input and username",
"from password fields\") elif (\",\" in self.ui.passwordEdit.text()) or (\",\" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username copied to clipboard\") def copyPassword(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard)",
"function to show error message class generatePasswordWin(QtWidgets.QWidget): # displays generate password window when",
"getData(pathToKey, pathToVault): # allows me to access Paths throughout document global KEYPATH, VAULTPATH",
"object self.ui.keyFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.keyFileLabel.adjustSize() # adjusts size of",
"exception handling try: key, iv, data = getData(self.keyPath, self.vaultPath) # display new window",
"if system() == 'Windows': desktopPath = os.environ[\"HOMEPATH\"] + \"\\Desktop\" # finds path to",
"want to delete the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_() def confirmDelete(self,",
"= {} i = 0 for value in row: if value != \"\":",
"self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self): self.newWindow = viewAccountWin() self.newWindow.show() self.hide() def changePassword(self): if",
"# stores accounts as nested lists seperated by value accounts.append(value.split(',')) for account in",
"row) and ('login_password' in row): # bitwarden format if (row['name'] != \"\") and",
"= VIEWEDITEM # updates the item in the accounts nested list updateAccounts(accounts) #",
"\"Key File\") or (vaultFile == \"Vault File\"): # checks that a Key File",
"in all of MainWindow class def openVaultFiles(self): keyFile = self.ui.keyFileLabel.text() vaultFile = self.ui.vaultFileLabel.text()",
"select a file to import from\") # Alert function to display error QMessageBox",
"unpad # global variables to store paths to the vault and key file",
"result data = unpad(cipher.decrypt(ciphered_data), AES.block_size) return key, iv, data def writeData(nameOfAccount, username, password):",
"\"Created vault.bin and key.bin\") # Alert function to reuse the code to generate",
"newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # if",
"or \"\"): self.searchedAccounts = self.accounts.copy() # copy sets values to new variable to",
"Account name\") elif \" \" in self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from",
"below works just like in loadAccounts but with search terms for n, key",
"classToAccess): # takes new window argument self.newWindow = classToAccess self.newWindow.show() # show new",
"global KEYPATH, VAULTPATH, VIEWEDITEM class MainWindow(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui",
"\"uri\": \"http://\"}] loginValues['uris'], loginValues['username'], loginValues['password'], loginValues['totp'] = uris, terms[1], terms[2], None temp =",
"if self.ui.specialCharsCheck.isChecked(): passwordOptions += punctuation.replace(',', '') lengths = [i for i in range(8,",
"deleteAccount(self): message = QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you sure you want to delete",
"digits if self.ui.specialCharsCheck.isChecked(): passwordOptions += punctuation.replace(',', '') lengths = [i for i in",
"= file[0] # makes keyPath accessible in all of MainWindow class def getVaultFile(self):",
"fields are empty or incorrectly entered if (self.ui.nameOfAccountEdit.text()[0] == \" \") or (self.ui.nameOfAccountEdit.text()[-1]",
"','.join(value) accounts.append(row) newData = b'' for line in accounts: newData += (\"{}\\n\".format(line)).encode('utf-8') cipher",
"accounts: if account == VIEWEDITEM: index = accounts.index(account) accounts.pop(index) # when this code",
"\"\", \"All Files (*)\") # lets user choose files from explorer url =",
"# updates the item being viewed accounts[i] = VIEWEDITEM # updates the item",
"before making table for n, key in enumerate(sorted(self.accounts.keys())): # displays code in table",
"path to desktop is different on windows and unix systems as on windows",
"Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self): passwordOptions = \"\" if self.ui.lowerCaseCheck.isChecked() or",
"stores accounts as nested lists seperated by value accounts.append(value.split(',')) for i in range(len(accounts)):",
"\"Account name, Username or the Password field has been left empty\") else: #",
"data = getData(KEYPATH, VAULTPATH) data += (\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC,",
"stores accounts as nested lists seperated by value accounts.append(value.split(',')) for account in accounts:",
"selected. Please select a file to import from\") # Alert function to display",
"lastpass format as lastpass' format is widely supported columns = ['url', 'username', 'password',",
"Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\")",
"name of account or username\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password",
"or (\",\" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove commas from password fields\") else: key,",
"message.buttonClicked.connect(self.confirmDelete) message.exec_() def confirmDelete(self, clickedBtn): if clickedBtn.text() == \"&Yes\": key, iv, data =",
"(keyFile == \"Key File\") or (vaultFile == \"Vault File\"): # checks that a",
"row: # json uses None for null and False for false when writing",
"VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.csv\" if data !=",
"unix systems as on windows the drive the desktop is on can be",
"open(self.Path) as jsonFile: data = json.load(jsonFile) if 'items' in data: for item in",
"Alert function to show error message class generatePasswordWin(QtWidgets.QWidget): # displays generate password window",
"Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password copied to clipboard\") def deleteAccount(self): message = QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning)",
"accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .JSON\") self.goBack() else: Alert(\"Error\",",
"arguements in function message = QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon) message.setText(text) message.exec_() def getData(pathToKey, pathToVault):",
"# allows me to access Paths throughout document global KEYPATH, VAULTPATH KEYPATH, VAULTPATH",
"updateAccounts self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_changePass()",
"error QMessageBox else: # exception handling try: key, iv, data = getData(self.keyPath, self.vaultPath)",
"oldData = getData(KEYPATH, VAULTPATH) accounts = [] for value in data: row =",
"from Username or Password\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()) or",
"global KEYPATH, VAULTPATH key, iv, data = getData(KEYPATH, VAULTPATH) data += (\"{},{},{}\\n\".format(nameOfAccount, username,",
"feature to read accounts from file global KEYPATH, VAULTPATH self.searchedAccounts = {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)",
"# gets path to file and stores it as an object self.ui.vaultFileLabel.setText(url.fileName()) #",
"passwordOptions += punctuation.replace(',', '') lengths = [i for i in range(8, 17)] passLength",
"that generatedPassLabel, nameOfAccount input and username input after saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False)",
"the iv out - this is 16 bytes long ciphered_data = readVaultFile.read() #",
"(*)\") # lets user choose files from explorer url = QtCore.QUrl.fromLocalFile(file[0]) # gets",
"+= \"\\Accounts.json\" if data != \"\": row = data.split('\\n') accounts = {} account",
"searchAccounts(self): term = self.ui.searchBox.text() if term != (None or \"\"): self.searchedAccounts = self.accounts.copy()",
"ciphered_data = readVaultFile.read() # Read the rest of the data readVaultFile.close() readKeyFile =",
"__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_allAccounts() self.ui.setupUi(self) # button which links",
"# gets path to file and stores it as an object self.ui.keyFileLabel.setText(url.fileName()) #",
"Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either one or no files were",
"'favorite'], temp['login'], temp['collectionIds'] = \"\", None, None, 1, terms[0], None, False, loginValues, False",
"are empty\") else: if self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords dont match\") elif",
"file and stores it as an object self.ui.keyFileLabel.setText(url.fileName()) # adjusts file name in",
"if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")) or",
"if 'items' in data: for item in data['items']: # checks for bitwarden format",
"VAULTPATH KEYPATH, VAULTPATH = pathToKey, pathToVault readVaultFile = open(VAULTPATH, 'rb') # Open the",
"csvFile: reader = csv.DictReader(csvFile, delimiter=',') for row in reader: if ('name' in row)",
"QtWidgets.QMessageBox.Critical, \"Either one or no files were selected. Please select files to open",
"self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self): self.newWindow = viewAccountWin() self.newWindow.show() self.hide() def changePassword(self):",
"\"\\Accounts.json\" if data != \"\": row = data.split('\\n') accounts = {} account =",
"temp[\"name\"], temp[\"username\"], temp[\"password\"] = terms[0], terms[1], terms[2] accounts.append(temp) with open(path, 'w') as file:",
"display error QMessageBox else: accounts = [] if self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path, 'r') as",
"not supported or no data to import was found\") else: for item in",
"QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210,",
"== \"&Yes\": key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row =",
"else: if self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords dont match\") elif (\" \"",
"import QtWidgets, QtCore, QtGui from Crypto.Random import get_random_bytes from Crypto.Cipher import AES from",
"contents for n, key in enumerate(sorted(self.accounts.keys())): # displays code in table in window",
"for row in reader: if ('name' in row) and ('username' in row) and",
"value in row: # json uses None for null and False for false",
"and (row['login_username'] != \"\") and (row['login_password'] != \"\"): values = [row['name'], row['login_username'], row['login_password']]",
"ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(desktopPath + \"\\\\vault.bin\", \"wb\") # creates vault",
"(vaultFile == \"Vault File\"): # checks that a Key File or Vault file",
"accounts.append(value.split(',')) for i in range(len(accounts)): if accounts[i] == VIEWEDITEM: VIEWEDITEM[2] = self.ui.passwordEdit.text() #",
"as an object self.ui.keyFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.keyFileLabel.adjustSize() # adjusts",
"access Paths throughout document global KEYPATH, VAULTPATH KEYPATH, VAULTPATH = pathToKey, pathToVault readVaultFile",
"this is 16 bytes long ciphered_data = readVaultFile.read() # Read the rest of",
"self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or",
"elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas",
"VAULTPATH) data = data.decode('utf-8') row = data.split('\\n') accounts = [] for value in",
"def deleteAccount(self): message = QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you sure you want to",
"# updates the item in the accounts nested list updateAccounts(accounts) # calls updateAccounts",
"from\") def savePassword(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() == (None",
"else disables table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def viewItem(self): global VIEWEDITEM if (self.ui.accountsTable.currentItem().text() == \"View\")",
"getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row = data.split('\\n') accounts = [] for value",
"lineterminator='\\n') writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No",
"None, \"uri\": \"http://\"}] loginValues['uris'], loginValues['username'], loginValues['password'], loginValues['totp'] = uris, terms[1], terms[2], None temp",
"self.ui.keyFileLabel.text() vaultFile = self.ui.vaultFileLabel.text() if (keyFile == \"Key File\") or (vaultFile == \"Vault",
"QtCore.Qt.ItemIsEditable) else: # else disables table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def viewItem(self): global VIEWEDITEM if",
"Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") self.goBack() class viewAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)",
"goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def exportCSV(self): key, iv, data = getData(KEYPATH,",
"json uses None for null and False for false when writing to a",
"from name of account or username\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text()",
"if account == VIEWEDITEM: index = accounts.index(account) accounts.pop(index) # when this code was",
"{} temp['id'], temp['organizationId'], temp['folderId'], temp['type'], temp['name'], temp['notes'], temp[ 'favorite'], temp['login'], temp['collectionIds'] = \"\",",
"file: # writes to csv in lastpass format json.dump(accounts, file, indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information,",
"classToAccess self.newWindow.show() self.hide() def copyUsername(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username",
"self.newWindow.show() # show new window self.hide() # close old window except (ValueError, FileNotFoundError)",
"QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password copied to clipboard\") def deleteAccount(self): message =",
"would give # a random error when lots of accounts were added and",
"\"\") and (row['login_username'] != \"\") and (row['login_password'] != \"\"): values = [row['name'], row['login_username'],",
"cipher = AES.new(key, AES.MODE_CBC, iv=iv) # Setup cipher # Decrypt and then up-pad",
"on arguements in function message = QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon) message.setText(text) message.exec_() def getData(pathToKey,",
"supported columns = ['url', 'username', 'password', 'extra', 'name', 'grouping', 'fav'] writer = csv.DictWriter(file,",
"csv.DictWriter(file, fieldnames=columns, lineterminator='\\n') writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV file successfully created\") else: Alert(\"Error\",",
"as on windows the drive the desktop is on can be changed if",
"= QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags()",
"Username or the Password field has been left empty\") else: # displays any",
"the password fields are empty\") else: if self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords",
"after a search self.searchedAccounts = {} self.loadAccounts() class addAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs):",
"cipher = AES.new(key, AES.MODE_CBC) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(desktopPath + \"\\\\vault.bin\",",
"self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self): self.newWindow = viewAccountWin() self.newWindow.show() self.hide() def changePassword(self): if (self.ui.passwordEdit.text() ==",
"generate password window when vault is open def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)",
"row == n: VIEWEDITEM = self.accounts[key] self.changeWindow(viewAccountWin()) def searchAccounts(self): term = self.ui.searchBox.text() if",
"then someone attempts to delete an account # although the code is now",
"and ('password' in item['login']): if (item['login']['username'] is not None) and (item['login']['password'] is not",
"AddAccountPage import Ui_addAccount from viewAccountPage import Ui_viewAccount from changePassPage import Ui_changePass from importAccountsPage",
"\"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Created vault.bin",
"\"\") and (row['name'] != \"\"): values = [row['name'], row['username'], row['password']] accounts.append(values) elif ('name'",
"show new window self.hide() # close old window except (ValueError, FileNotFoundError) as e:",
"vault.bin and key.bin\") # Alert function to reuse the code to generate a",
"+= digits if self.ui.specialCharsCheck.isChecked(): passwordOptions += punctuation.replace(',', '') lengths = [i for i",
"16 bytes long ciphered_data = readVaultFile.read() # Read the rest of the data",
"= [] if self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path, 'r') as csvFile: reader = csv.DictReader(csvFile, delimiter=',')",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from name of account or username\") else: nameOfAccount",
"def writeData(nameOfAccount, username, password): # writes name of account, username and password to",
"= self.accounts[row] else: for n, key in enumerate(sorted(self.searchedAccounts.keys())): if row == n: VIEWEDITEM",
"Username or Password\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.passwordEdit.text()",
"getData(self.keyPath, self.vaultPath) # display new window for generating password or viewing accounts self.newWindow",
"!= \"\": row = data.split('\\n') accounts = {} account = [] for value",
"show error message class generatePasswordWin(QtWidgets.QWidget): # displays generate password window when vault is",
"!= \"\"): values = [row['name'], row['login_username'], row['login_password']] accounts.append(values) if len(accounts) < 1: Alert(\"Error\",",
"try: key, iv, data = getData(self.keyPath, self.vaultPath) # display new window for generating",
"1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # else disables table",
"not None) and (item['login']['password'] is not None): values = [item['name'], item['login'] ['username'], item['login']['password']]",
"VAULTPATH self.searchedAccounts = {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv, data = getData(KEYPATH, VAULTPATH) data =",
"QtCore.QUrl.fromLocalFile(file[0]) # gets path to file and stores it as an object self.ui.keyFileLabel.setText(url.fileName())",
"specific function def createVaultFiles(self): key = get_random_bytes(32) # 32 bytes is 256 bits",
"in range len(accounts) sometimes it would give # a random error when lots",
"class def getVaultFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\")",
"display new window for generating password or viewing accounts self.newWindow = generatePasswordWin() self.newWindow.show()",
"\" in self.ui.usernameEdit.text()) or (\" \" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces",
"data != \"\": row = data.split('\\n') accounts = [] for value in row:",
"import os import random import csv import json from platform import system from",
"= open(desktopPath + \"\\\\key.bin\", \"wb\") keyFile.write(key) # writes encryption key to file keyFile.close",
"argument self.newWindow = classToAccess self.newWindow.show() # show new window self.hide() # close old",
"cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password copied to clipboard\") def deleteAccount(self):",
"self.ui.accountsTable.setRowCount(0) # removes all data in table before making table for n, key",
"name\") elif (\" \" in self.ui.usernameEdit.text()) or (\" \" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"{} temp[\"name\"], temp[\"username\"], temp[\"password\"] = terms[0], terms[1], terms[2] accounts.append(temp) with open(path, 'w') as",
"def goBack(self): self.newWindow = viewAccountWin() self.newWindow.show() self.hide() def changePassword(self): if (self.ui.passwordEdit.text() == (None",
"button which links to generate password window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin()))",
"== n: VIEWEDITEM = self.accounts[key] self.changeWindow(viewAccountWin()) def searchAccounts(self): term = self.ui.searchBox.text() if term",
"of account or username\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password =",
"ascii_uppercase if self.ui.numbersCheck.isChecked(): passwordOptions += digits if self.ui.specialCharsCheck.isChecked(): passwordOptions += punctuation.replace(',', '') lengths",
"allAccountsWin() self.newWindow.show() self.hide() def saveAccount(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text()",
"accounts.append(values) if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV file format not supported or",
"__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword)",
"in gui self.keyPath = file[0] # makes keyPath accessible in all of MainWindow",
"range len(accounts) sometimes it would give # a random error when lots of",
"reader = csv.DictReader(csvFile, delimiter=',') for row in reader: if ('name' in row) and",
"# when this code was a for loop in range len(accounts) sometimes it",
"data = ''.encode('utf-8') # basic data for file to encrypt desktopPath = getPathToDesktop()",
"fields\") elif (\",\" in self.ui.passwordEdit.text()) or (\",\" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove commas",
"path to desktop for driveLetter in ascii_uppercase: # find drive desktop folder is",
"for file name in gui self.vaultPath = file[0] # makes vaultPath accessible in",
"window self.hide() # close old window except (ValueError, FileNotFoundError) as e: Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"path to file and stores it as an object self.ui.keyFileLabel.setText(url.fileName()) # adjusts file",
"search self.searchedAccounts = {} self.loadAccounts() class addAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)",
"= QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\") # lets user choose",
"in ascii_uppercase: # find drive desktop folder is on if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath",
"def changeWindow(self, classToAccess): # takes new window argument self.newWindow = classToAccess self.newWindow.show() #",
"def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def exportCSV(self): key, iv, data =",
"# added feature to read accounts from file global KEYPATH, VAULTPATH self.searchedAccounts =",
"or end of Account name\") elif \" \" in self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please",
"# deletes tables contents for n, key in enumerate(sorted(self.accounts.keys())): # displays code in",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def exportJSON(self): key, iv, data =",
"from Username\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please",
"Account name\") elif (\" \" in self.ui.usernameEdit.text()) or (\" \" in self.ui.passwordEdit.text()): Alert(\"Error\",",
"\" \") or (self.ui.nameOfAccountEdit.text()[-1] == \" \"): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from",
"window when vault is open def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui =",
"from the beginning or end of Account name\") elif \" \" in self.ui.usernameEdit.text():",
"if not(self.searchedAccounts): # checks if searchedAccounts is empty VIEWEDITEM = self.accounts[row] else: for",
"210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # else disables table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def",
"if self.ui.upperCaseCheck.isChecked(): passwordOptions += ascii_uppercase if self.ui.numbersCheck.isChecked(): passwordOptions += digits if self.ui.specialCharsCheck.isChecked(): passwordOptions",
"accounts self.newWindow = allAccountsWin() self.newWindow.show() # show new window self.hide() # close old",
"from Name of account, Username or Password\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username =",
"self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self): passwordOptions = \"\" if self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked()",
"= Ui_startPage() self.ui.setupUi(self) # initializes start page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) # button",
"self.searchedAccounts = {} self.loadAccounts() class addAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui",
".CSV\") self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path) as jsonFile: data = json.load(jsonFile) if 'items'",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file format not supported\") if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"VAULTPATH) data += (\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data =",
"if term != (None or \"\"): self.searchedAccounts = self.accounts.copy() # copy sets values",
"import Ui_changePass from importAccountsPage import Ui_importAccounts from exportAccountsPage import Ui_exportPage from PyQt5 import",
"is now longer, this fixes the index error issue updateAccounts(accounts) # calls updateAccounts",
"page after password is changed successfully class importWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args,",
"self.searchedAccounts.pop(key) # removes values not in search # code below works just like",
"loginValues, False account.append(temp) accounts['items'] = account with open(path, 'w') as file: # writes",
"basic data for file to encrypt desktopPath = getPathToDesktop() # gets path to",
"based on arguements in function message = QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon) message.setText(text) message.exec_() def",
"in table in window if not(term.lower() in self.accounts[key][0].lower()): self.searchedAccounts.pop(key) # removes values not",
"getPathToDesktop() # gets path to desktop keyFile = open(desktopPath + \"\\\\key.bin\", \"wb\") keyFile.write(key)",
"range(0, passLength): password += random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No",
"goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def saveAccount(self): if (self.ui.nameOfAccountEdit.text() == (None or",
"or self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked(): passwordOptions += ascii_lowercase if self.ui.upperCaseCheck.isChecked():",
"accounts.append(values) elif ('name' in row) and ('login_username' in row) and ('login_password' in row):",
"self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self, classToAccess): self.newWindow = classToAccess self.newWindow.show()",
"getKeyFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\") # lets",
"\"JSON file format not supported\") if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file",
"= b'' for line in accounts: newData += (\"{}\\n\".format(line)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC,",
"def genPassword(self): passwordOptions = \"\" if self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked():",
"username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") # reset check boxes after saving",
"import Ui_importAccounts from exportAccountsPage import Ui_exportPage from PyQt5 import QtWidgets, QtCore, QtGui from",
"== \"Vault File\"): # checks that a Key File or Vault file have",
"writes name of account, username and password to vaultFile global KEYPATH, VAULTPATH key,",
"successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def getPathToDesktop(): #",
"self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else:",
"cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password copied to clipboard\") def deleteAccount(self): message = QtWidgets.QMessageBox()",
"import sys import os import random import csv import json from platform import",
"Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self): self.newWindow = viewAccountWin() self.newWindow.show() self.hide()",
"not None): values = [item['name'], item['login'] ['username'], item['login']['password']] accounts.append(values) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON",
"to export\") self.goBack() def getPathToDesktop(): # path to desktop is different on windows",
"self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path) as jsonFile: data = json.load(jsonFile) if 'items' in data: for",
"i = 0 for value in row: if value != \"\": self.accounts[i] =",
"= readVaultFile.read() # Read the rest of the data readVaultFile.close() readKeyFile = open(KEYPATH,",
"all accounts self.newWindow = allAccountsWin() self.newWindow.show() # show new window self.hide() # close",
"were added and then someone attempts to delete an account # although the",
"self.ui.searchBox.setEnabled(False) def viewItem(self): global VIEWEDITEM if (self.ui.accountsTable.currentItem().text() == \"View\") and (self.ui.accountsTable.currentColumn() == 1):",
"\"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() if __name__ == \"__main__\": #",
"password from\") def savePassword(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() ==",
"adjusts size of text wrapper for file name in gui self.vaultPath = file[0]",
"self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) # button variables which execute a specific function def createVaultFiles(self): key",
"savePassword(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")):",
"!= \"\") and (row['password'] != \"\") and (row['name'] != \"\"): values = [row['name'],",
"self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path, 'r') as csvFile: reader = csv.DictReader(csvFile, delimiter=',') for row in",
"iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row = data.split('\\n') accounts =",
"self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() # show new window self.hide()",
"or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")) or (self.ui.passwordEdit.text() == (None or",
"# gets path to file and stores it as an object self.ui.fileLbl.setText(url.fileName()) #",
"vault\") # Alert function to display error QMessageBox else: # exception handling try:",
"copied to clipboard\") def copyPassword(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password",
"self.hide() def changePassword(self): if (self.ui.passwordEdit.text() == (None or \"\")) or (self.ui.confirmPassEdit.text() == (None",
"clickedBtn): if clickedBtn.text() == \"&Yes\": key, iv, data = getData(KEYPATH, VAULTPATH) data =",
"to a json if value != \"\": terms = value.split(',') loginValues = {}",
"= csv.DictWriter(file, fieldnames=columns, lineterminator='\\n') writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV file successfully created\") else:",
"QtWidgets.QMessageBox.Critical, \"JSON file has no data to import\") else: for item in accounts:",
"self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() # show new",
"in accounts: newData += (\"{}\\n\".format(line)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(newData,",
"terms for n, key in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\")",
"(\" \" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove spaces from password fields\") elif (\",\"",
"input after saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self): # opens window",
"generate password window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda:",
"from .JSON\") self.goBack() else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File type not supported\") class exportWin(QtWidgets.QWidget): def",
"works just like in loadAccounts but with search terms for n, key in",
"else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.passwordEdit.text() writeData(nameOfAccount, username, password)",
"accounts view if data != \"\": row = data.split('\\n') self.accounts = {} i",
"self.ui.passwordEdit.text()) or (\",\" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove commas from password fields\") else:",
"no data to import was found\") else: for item in accounts: writeData(item[0], item[1],",
"password = \"\" for i in range(0, passLength): password += random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True)",
"(None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One or Both of the password fields are",
"a specific function def createVaultFiles(self): key = get_random_bytes(32) # 32 bytes is 256",
"210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # else disables table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def viewItem(self):",
"# a random error when lots of accounts were added and then someone",
"= os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return desktopPath def Alert(title, icon, text): # creates QMessageBox based",
"file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either one or no files were selected.",
"temp[\"password\"] = terms[0], terms[1], terms[2] accounts.append(temp) with open(path, 'w') as file: # writes",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from the beginning or end of Account name\")",
"def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON)",
"= Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() #",
"ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv)",
"remove spaces from the beginning or end of Account name\") elif (\" \"",
"format if (row['username'] != \"\") and (row['password'] != \"\") and (row['name'] != \"\"):",
"has been left empty\") else: # displays any error message if the user",
"or (self.ui.usernameEdit.text() == (None or \"\")) or (self.ui.passwordEdit.text() == (None or \"\")): Alert(\"Error\",",
"= {} account = [] for value in row: # json uses None",
"# basic data for file to encrypt desktopPath = getPathToDesktop() # gets path",
"= self.ui.generatedPassLabel.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") # reset check",
"in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem)",
"account == VIEWEDITEM: index = accounts.index(account) accounts.pop(index) # when this code was a",
"been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No file was selected. Please select a file to",
"temp['organizationId'], temp['folderId'], temp['type'], temp['name'], temp['notes'], temp[ 'favorite'], temp['login'], temp['collectionIds'] = \"\", None, None,",
"vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() def updateAccounts(data): global KEYPATH, VAULTPATH key, iv, oldData",
"self.ui = Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername)",
"from genPassPage import Ui_passwordGen from allAccountsPage import Ui_allAccounts from AddAccountPage import Ui_addAccount from",
"self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self): # opens window to view all accounts self.newWindow",
"len(accounts) sometimes it would give # a random error when lots of accounts",
"'Open file', \"\", \"All Files (*)\") # lets user choose files from explorer",
"data for file to encrypt desktopPath = getPathToDesktop() # gets path to desktop",
"or Username has been left empty\") else: # displays any error message if",
"# count for resetting all accounts view if data != \"\": row =",
"(self.ui.passwordEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name, Username or the Password",
"self.accounts[row] else: for n, key in enumerate(sorted(self.searchedAccounts.keys())): if row == n: VIEWEDITEM =",
"QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_() def confirmDelete(self, clickedBtn): if clickedBtn.text() == \"&Yes\": key, iv,",
"self.ui.usernameEdit.text() password = self.ui.passwordEdit.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") self.goBack()",
"accounts = [] if self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path, 'r') as csvFile: reader = csv.DictReader(csvFile,",
"message.exec_() def getData(pathToKey, pathToVault): # allows me to access Paths throughout document global",
"readVaultFile.read(16) # Read the iv out - this is 16 bytes long ciphered_data",
"= self.ui.passwordEdit.text() # updates the item being viewed accounts[i] = VIEWEDITEM # updates",
"fields\") else: key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row =",
"it as an object self.ui.keyFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.keyFileLabel.adjustSize() #",
"and (item['login']['password'] is not None): values = [item['name'], item['login'] ['username'], item['login']['password']] accounts.append(values) else:",
"data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.csv\" if data != \"\": row =",
"or Password\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()) or (\",\" in",
"or the Password field has been left empty\") else: # displays any error",
"Password field has been left empty\") else: # displays any error message if",
"AES.new(key, AES.MODE_CBC, iv=iv) # Setup cipher # Decrypt and then up-pad the result",
"password = self.ui.generatedPassLabel.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") # reset",
"platform import system from string import ascii_uppercase, ascii_lowercase, digits, punctuation from startPage import",
"MainWindow class def getVaultFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files",
"in self.ui.passwordEdit.text()) or (\" \" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove spaces from password",
"to encrypt desktopPath = getPathToDesktop() # gets path to desktop keyFile = open(desktopPath",
"for item in data['items']: # checks for bitwarden format if 'login' in item:",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove spaces from password fields\") elif (\",\" in self.ui.passwordEdit.text()) or (\",\"",
"# displays when starting application app = QtWidgets.QApplication(sys.argv) startPage = MainWindow() startPage.show() sys.exit(app.exec_())",
"is widely supported columns = ['url', 'username', 'password', 'extra', 'name', 'grouping', 'fav'] writer",
"class changePassWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0])",
"and username input after saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self): #",
"data def writeData(nameOfAccount, username, password): # writes name of account, username and password",
"addAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount)",
"or viewing accounts self.newWindow = generatePasswordWin() self.newWindow.show() # show new window self.hide() #",
"= [i for i in range(8, 17)] passLength = random.choice(lengths) password = \"\"",
"copy sets values to new variable to edit self.count -= 1 # decreases",
"terms = value.split(',') loginValues = {} uris = [{\"match\": None, \"uri\": \"http://\"}] loginValues['uris'],",
"empty\") else: if self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Passwords dont match\") elif (\"",
"vaultPath accessible in all of MainWindow class def openVaultFiles(self): keyFile = self.ui.keyFileLabel.text() vaultFile",
"files were selected. Please select files to open the vault\") # Alert function",
"def loadAccounts(self): # added feature to read accounts from file global KEYPATH, VAULTPATH",
"\"CSV file format not supported or no data to import was found\") else:",
"in table before making table for n, key in enumerate(sorted(self.accounts.keys())): # displays code",
"calls updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password Changed\") self.goBack() # go to view account page",
"item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .JSON\") self.goBack() else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File",
"Ui_exportPage from PyQt5 import QtWidgets, QtCore, QtGui from Crypto.Random import get_random_bytes from Crypto.Cipher",
"file[0] # makes vaultPath accessible in all of MainWindow class def openVaultFiles(self): keyFile",
"(\",\" in self.ui.passwordEdit.text()) or (\",\" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove commas from password",
"self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def saveAccount(self): if",
"systems as on windows the drive the desktop is on can be changed",
"# else disables table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def viewItem(self): global VIEWEDITEM if (self.ui.accountsTable.currentItem().text() ==",
"desktop is different on windows and unix systems as on windows the drive",
"self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def changeWindow(self, classToAccess): # takes new",
"# opens window to view all accounts self.newWindow = allAccountsWin() self.newWindow.show() # show",
"\"Account saved\") # reset check boxes after saving accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False)",
"self.ui.specialCharsCheck.setChecked(False) # the code below resets that generatedPassLabel, nameOfAccount input and username input",
"\" \"): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from the beginning or end of",
"nested lists seperated by value accounts.append(value.split(',')) for i in range(len(accounts)): if accounts[i] ==",
"window self.hide() def getFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files",
"importData(self): if self.ui.fileLbl.text() == \"Select file to import from\": # checks that a",
"== \"Key File\") or (vaultFile == \"Vault File\"): # checks that a Key",
"or (self.ui.usernameEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name or Username has",
"cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(newData, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\")",
"self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def changeWindow(self, classToAccess): #",
"to csv in lastpass format json.dump(accounts, file, indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON file successfully",
"VIEWEDITEM class MainWindow(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_startPage() self.ui.setupUi(self)",
"allAccountsWin() self.newWindow.show() self.hide() def exportCSV(self): key, iv, data = getData(KEYPATH, VAULTPATH) data =",
"been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either one or no files were selected. Please select",
"\"\", None, None, 1, terms[0], None, False, loginValues, False account.append(temp) accounts['items'] = account",
"<= 0: # comparison to make sure you only run loadAccounts after a",
"= {} self.loadAccounts() class addAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui =",
"*args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def goBack(self):",
"'r') as csvFile: reader = csv.DictReader(csvFile, delimiter=',') for row in reader: if ('name'",
"None, False, loginValues, False account.append(temp) accounts['items'] = account with open(path, 'w') as file:",
"and ('login_password' in row): # bitwarden format if (row['name'] != \"\") and (row['login_username']",
"displays code in table in window self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\")",
"as file: # writes to csv in lastpass format json.dump(accounts, file, indent=4) Alert(\"Confirmed\",",
"writes to csv in lastpass format json.dump(accounts, file, indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON file",
"below resets that generatedPassLabel, nameOfAccount input and username input after saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\")",
"+= punctuation.replace(',', '') lengths = [i for i in range(8, 17)] passLength =",
"and ('username' in row) and ('password' in row): # lastpass format if (row['username']",
"value != \"\": terms = value.split(',') loginValues = {} uris = [{\"match\": None,",
"drive desktop folder is on if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath = \"{0}:{1}\".format(driveLetter, desktopPath) else:",
"__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def",
"on windows and unix systems as on windows the drive the desktop is",
"was found\") else: for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported",
"columns = ['url', 'username', 'password', 'extra', 'name', 'grouping', 'fav'] writer = csv.DictWriter(file, fieldnames=columns,",
"= open(VAULTPATH, 'rb') # Open the file to read bytes iv = readVaultFile.read(16)",
"^ QtCore.Qt.ItemIsEditable) else: # if search box is empty if self.count <= 0:",
"null and False for false when writing to a json if value !=",
"data['items']: # checks for bitwarden format if 'login' in item: if ('username' in",
"table before making table for n, key in enumerate(sorted(self.accounts.keys())): # displays code in",
"temp['collectionIds'] = \"\", None, None, 1, terms[0], None, False, loginValues, False account.append(temp) accounts['items']",
"vaultFile = open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() def updateAccounts(data):",
"if searchedAccounts is empty VIEWEDITEM = self.accounts[row] else: for n, key in enumerate(sorted(self.searchedAccounts.keys())):",
"terms[1], terms[2], None temp = {} temp['id'], temp['organizationId'], temp['folderId'], temp['type'], temp['name'], temp['notes'], temp[",
"# Alert function to display error QMessageBox else: # exception handling try: key,",
"removes values not in search # code below works just like in loadAccounts",
"adjusts file name in gui self.ui.fileLbl.adjustSize() # adjusts size of text wrapper for",
"found\") else: for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts",
"= \"{0}:{1}\".format(driveLetter, desktopPath) else: desktopPath = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return desktopPath def Alert(title, icon,",
"long ciphered_data = readVaultFile.read() # Read the rest of the data readVaultFile.close() readKeyFile",
"self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # if search",
"'Windows': desktopPath = os.environ[\"HOMEPATH\"] + \"\\Desktop\" # finds path to desktop for driveLetter",
"AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(newData, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault",
"in lastpass format json.dump(accounts, file, indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON file successfully created\") else:",
"if (row['username'] != \"\") and (row['password'] != \"\") and (row['name'] != \"\"): values",
"accounts = [] for value in row: if value != \"\": # stores",
"file', \"\", \"All Files (*)\") # lets user choose files from explorer url",
"# Decrypt and then up-pad the result data = unpad(cipher.decrypt(ciphered_data), AES.block_size) return key,",
"generatePasswordWin(QtWidgets.QWidget): # displays generate password window when vault is open def __init__(self, *args,",
"accounts[i] = VIEWEDITEM # updates the item in the accounts nested list updateAccounts(accounts)",
"from the beginning or end of Account name\") elif (\" \" in self.ui.usernameEdit.text())",
"vaultFile = open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() if __name__",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file has no data to import\") else: for item in",
"lists seperated by value accounts.append(value.split(',')) for i in range(len(accounts)): if accounts[i] == VIEWEDITEM:",
"path = getPathToDesktop() path += \"\\Accounts.csv\" if data != \"\": row = data.split('\\n')",
"= self.ui.passwordEdit.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") self.goBack() class viewAccountWin(QtWidgets.QWidget):",
"for value in row: # json uses None for null and False for",
"= Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self): self.newWindow = viewAccountWin() self.newWindow.show()",
"__name__ == \"__main__\": # displays when starting application app = QtWidgets.QApplication(sys.argv) startPage =",
"= [] for value in row: # json uses None for null and",
"return key, iv, data def writeData(nameOfAccount, username, password): # writes name of account,",
"accounts as nested lists seperated by value accounts.append(value.split(',')) for account in accounts: if",
"Password\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()) or (\",\" in self.ui.passwordEdit.text()):",
"PyQt5 import QtWidgets, QtCore, QtGui from Crypto.Random import get_random_bytes from Crypto.Cipher import AES",
"on if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath = \"{0}:{1}\".format(driveLetter, desktopPath) else: desktopPath = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')",
"name in gui self.ui.keyFileLabel.adjustSize() # adjusts size of text wrapper for file name",
"def viewItem(self): global VIEWEDITEM if (self.ui.accountsTable.currentItem().text() == \"View\") and (self.ui.accountsTable.currentColumn() == 1): row",
"AES.block_size)) vaultFile = open(desktopPath + \"\\\\vault.bin\", \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data)",
"Crypto.Random import get_random_bytes from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad #",
"makes path accessible in importWin def importData(self): if self.ui.fileLbl.text() == \"Select file to",
"# checks that a Key File or Vault file have been selected Alert(\"Error\",",
"left empty\") else: # displays any error message if the user input fields",
"reader: if ('name' in row) and ('username' in row) and ('password' in row):",
"def confirmDelete(self, clickedBtn): if clickedBtn.text() == \"&Yes\": key, iv, data = getData(KEYPATH, VAULTPATH)",
"pathToKey, pathToVault readVaultFile = open(VAULTPATH, 'rb') # Open the file to read bytes",
"to import was found\") else: for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\",",
"the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_() def confirmDelete(self, clickedBtn): if clickedBtn.text()",
"Ui_changePass from importAccountsPage import Ui_importAccounts from exportAccountsPage import Ui_exportPage from PyQt5 import QtWidgets,",
"writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .CSV\") self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"): with",
"account # although the code is now longer, this fixes the index error",
"= getPathToDesktop() # gets path to desktop keyFile = open(desktopPath + \"\\\\key.bin\", \"wb\")",
"key in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0,",
"for line in accounts: newData += (\"{}\\n\".format(line)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data",
"value in row: if value != \"\": # stores accounts as nested lists",
"term = self.ui.searchBox.text() if term != (None or \"\"): self.searchedAccounts = self.accounts.copy() #",
"1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV file format not supported or no data to import",
"password fields\") else: key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row",
"name in gui self.vaultPath = file[0] # makes vaultPath accessible in all of",
"give # a random error when lots of accounts were added and then",
"getFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\") # lets",
"viewAccountPage import Ui_viewAccount from changePassPage import Ui_changePass from importAccountsPage import Ui_importAccounts from exportAccountsPage",
"('username' in row) and ('password' in row): # lastpass format if (row['username'] !=",
"with open(self.Path) as jsonFile: data = json.load(jsonFile) if 'items' in data: for item",
"enumerate(sorted(self.accounts.keys())): # displays code in table in window self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel",
"[] for value in row: if value != \"\": # stores accounts as",
"updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password Changed\") self.goBack() # go to view account page after",
"def openAccountsPage(self): # opens window to view all accounts self.newWindow = allAccountsWin() self.newWindow.show()",
"== VIEWEDITEM: index = accounts.index(account) accounts.pop(index) # when this code was a for",
"name in gui self.keyPath = file[0] # makes keyPath accessible in all of",
"accounts['items'] = account with open(path, 'w') as file: # writes to csv in",
"password): # writes name of account, username and password to vaultFile global KEYPATH,",
"creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() def updateAccounts(data): global KEYPATH, VAULTPATH key, iv,",
"code below works just like in loadAccounts but with search terms for n,",
"accounts to export\") self.goBack() def getPathToDesktop(): # path to desktop is different on",
"created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def getPathToDesktop(): # path",
"bytes iv = readVaultFile.read(16) # Read the iv out - this is 16",
"in self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username\") elif (\",\" in self.ui.nameOfAccountEdit.text())",
"[] for value in row: if value != \"\": terms = value.split(',') temp",
"as nested lists seperated by value accounts.append(value.split(',')) for account in accounts: if account",
"changePassWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1])",
"vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Created vault.bin and key.bin\") #",
"b'' for line in accounts: newData += (\"{}\\n\".format(line)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv)",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from Name of account, Username or Password\") else:",
"(item['login']['username'] is not None) and (item['login']['password'] is not None): values = [item['name'], item['login']",
"('name' in row) and ('username' in row) and ('password' in row): # lastpass",
"exportWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV)",
"else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.generatedPassLabel.text() writeData(nameOfAccount, username, password)",
"global VIEWEDITEM if (self.ui.accountsTable.currentItem().text() == \"View\") and (self.ui.accountsTable.currentColumn() == 1): row = self.ui.accountsTable.currentRow()",
"loginValues['totp'] = uris, terms[1], terms[2], None temp = {} temp['id'], temp['organizationId'], temp['folderId'], temp['type'],",
"unpad(cipher.decrypt(ciphered_data), AES.block_size) return key, iv, data def writeData(nameOfAccount, username, password): # writes name",
"global KEYPATH, VAULTPATH key, iv, oldData = getData(KEYPATH, VAULTPATH) accounts = [] for",
"(\",\" in self.ui.usernameEdit.text()) or (\",\" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from",
"**kwargs): super().__init__(*args, **kwargs) self.ui = Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize()",
"Paths throughout document global KEYPATH, VAULTPATH KEYPATH, VAULTPATH = pathToKey, pathToVault readVaultFile =",
"= self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.generatedPassLabel.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\",",
"self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self,",
"terms[2], None temp = {} temp['id'], temp['organizationId'], temp['folderId'], temp['type'], temp['name'], temp['notes'], temp[ 'favorite'],",
"in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove spaces from password fields\") elif (\",\" in self.ui.passwordEdit.text())",
"\"{0}:{1}\".format(driveLetter, desktopPath) else: desktopPath = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return desktopPath def Alert(title, icon, text):",
"= account with open(path, 'w') as file: # writes to csv in lastpass",
"execute a specific function def createVaultFiles(self): key = get_random_bytes(32) # 32 bytes is",
"no files were selected. Please select files to open the vault\") # Alert",
"self.goBack() # go to view account page after password is changed successfully class",
"desktopPath) else: desktopPath = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return desktopPath def Alert(title, icon, text): #",
"iv=iv) ciphered_data = cipher.encrypt(pad(newData, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault file",
"temp[ 'favorite'], temp['login'], temp['collectionIds'] = \"\", None, None, 1, terms[0], None, False, loginValues,",
"cipher.encrypt(pad(newData, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close()",
"fixes the index error issue updateAccounts(accounts) # calls updateAccounts self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget): def",
"# adjusts file name in gui self.ui.keyFileLabel.adjustSize() # adjusts size of text wrapper",
"__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self):",
"start page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) # button variables which execute a specific",
"# Alert function to display error QMessageBox else: accounts = [] if self.ui.fileLbl.text().lower().endswith(\".csv\"):",
"self.ui.importBtn.clicked.connect(self.importData) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() # show new window self.hide() def",
"super().__init__(*args, **kwargs) self.ui = Ui_allAccounts() self.ui.setupUi(self) # button which links to generate password",
"self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from Name of account, Username or Password\")",
"random import csv import json from platform import system from string import ascii_uppercase,",
"= \"\", None, None, 1, terms[0], None, False, loginValues, False account.append(temp) accounts['items'] =",
"enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n,",
"= [row['name'], row['login_username'], row['login_password']] accounts.append(values) if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV file",
"+= random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No options to generate",
"open(self.Path, 'r') as csvFile: reader = csv.DictReader(csvFile, delimiter=',') for row in reader: if",
"entered if (self.ui.nameOfAccountEdit.text()[0] == \" \") or (self.ui.nameOfAccountEdit.text()[-1] == \" \"): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"if data != \"\": row = data.split('\\n') self.accounts = {} i = 0",
"= os.environ[\"HOMEPATH\"] + \"\\Desktop\" # finds path to desktop for driveLetter in ascii_uppercase:",
"QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def getPathToDesktop(): # path to desktop is",
"desktop is on can be changed if system() == 'Windows': desktopPath = os.environ[\"HOMEPATH\"]",
"updateAccounts(data): global KEYPATH, VAULTPATH key, iv, oldData = getData(KEYPATH, VAULTPATH) accounts = []",
"variables which execute a specific function def createVaultFiles(self): key = get_random_bytes(32) # 32",
"accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .CSV\") self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"):",
"file name in gui self.ui.vaultFileLabel.adjustSize() # adjusts size of text wrapper for file",
"to read accounts from file global KEYPATH, VAULTPATH self.searchedAccounts = {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key,",
"nameOfAccount input and username input after saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def",
"for loop in range len(accounts) sometimes it would give # a random error",
"password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") self.goBack() class viewAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs):",
"makes vaultPath accessible in all of MainWindow class def openVaultFiles(self): keyFile = self.ui.keyFileLabel.text()",
"self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path) as jsonFile: data = json.load(jsonFile) if 'items' in",
"match\") elif (\" \" in self.ui.passwordEdit.text()) or (\" \" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"# creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() def updateAccounts(data): global KEYPATH, VAULTPATH key,",
"code is now longer, this fixes the index error issue updateAccounts(accounts) # calls",
"data.split('\\n') accounts = [] for value in row: if value != \"\": #",
"generatedPassLabel, nameOfAccount input and username input after saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False)",
"Ui_allAccounts() self.ui.setupUi(self) # button which links to generate password window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts()",
"password window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin()))",
"in self.accounts[key][0].lower()): self.searchedAccounts.pop(key) # removes values not in search # code below works",
"new window for generating password or viewing accounts self.newWindow = generatePasswordWin() self.newWindow.show() #",
"in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()) or (\",\" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please",
"self.newWindow = viewAccountWin() self.newWindow.show() self.hide() def changePassword(self): if (self.ui.passwordEdit.text() == (None or \"\"))",
"accounts = [] for value in row: if value != \"\": terms =",
"gets path to file and stores it as an object self.ui.keyFileLabel.setText(url.fileName()) # adjusts",
"Alert(title, icon, text): # creates QMessageBox based on arguements in function message =",
"# button variables which execute a specific function def createVaultFiles(self): key = get_random_bytes(32)",
"data.split('\\n') self.accounts = {} i = 0 for value in row: if value",
"None temp = {} temp['id'], temp['organizationId'], temp['folderId'], temp['type'], temp['name'], temp['notes'], temp[ 'favorite'], temp['login'],",
"passLength = random.choice(lengths) password = \"\" for i in range(0, passLength): password +=",
"['username'], item['login']['password']] accounts.append(values) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file format not supported\") if len(accounts)",
"longer, this fixes the index error issue updateAccounts(accounts) # calls updateAccounts self.changeWindow(allAccountsWin()) class",
"= \"\" for i in range(0, passLength): password += random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True)",
"window def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_allAccounts() self.ui.setupUi(self) # button",
"account = [] for value in row: # json uses None for null",
"(\",\" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from Name of account, Username",
"elif ('name' in row) and ('login_username' in row) and ('login_password' in row): #",
"was selected. Please select a file to import from\") # Alert function to",
"(\"{}\\n\".format(line)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(newData, AES.block_size)) vaultFile = open(VAULTPATH,",
"temp['login'], temp['collectionIds'] = \"\", None, None, 1, terms[0], None, False, loginValues, False account.append(temp)",
"file format not supported\") if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file has",
"to show error message class generatePasswordWin(QtWidgets.QWidget): # displays generate password window when vault",
"different on windows and unix systems as on windows the drive the desktop",
"row['login_username'], row['login_password']] accounts.append(values) if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV file format not",
"is 16 bytes long ciphered_data = readVaultFile.read() # Read the rest of the",
"as jsonFile: data = json.load(jsonFile) if 'items' in data: for item in data['items']:",
"else: # exception handling try: key, iv, data = getData(self.keyPath, self.vaultPath) # display",
"!= \"\": terms = value.split(',') loginValues = {} uris = [{\"match\": None, \"uri\":",
"username input after saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self): # opens",
"AES.MODE_CBC) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(desktopPath + \"\\\\vault.bin\", \"wb\") # creates",
"openVaultFiles(self): keyFile = self.ui.keyFileLabel.text() vaultFile = self.ui.vaultFileLabel.text() if (keyFile == \"Key File\") or",
"QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in",
"someone attempts to delete an account # although the code is now longer,",
"if __name__ == \"__main__\": # displays when starting application app = QtWidgets.QApplication(sys.argv) startPage",
"ascii_uppercase, ascii_lowercase, digits, punctuation from startPage import Ui_startPage from genPassPage import Ui_passwordGen from",
"generate password from\") def savePassword(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text()",
"user choose files from explorer url = QtCore.QUrl.fromLocalFile(file[0]) # gets path to file",
"values = [item['name'], item['login'] ['username'], item['login']['password']] accounts.append(values) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file format",
"by value accounts.append(value.split(',')) for i in range(len(accounts)): if accounts[i] == VIEWEDITEM: VIEWEDITEM[2] =",
"= Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide()",
"item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .JSON\") self.goBack()",
"from explorer url = QtCore.QUrl.fromLocalFile(file[0]) # gets path to file and stores it",
"reset when nothing in searchBox self.ui.accountsTable.setRowCount(0) # deletes tables contents for n, key",
"iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') self.count = 1 # count",
"(row['password'] != \"\") and (row['name'] != \"\"): values = [row['name'], row['username'], row['password']] accounts.append(values)",
"!= \"\": terms = value.split(',') temp = {} temp[\"name\"], temp[\"username\"], temp[\"password\"] = terms[0],",
"function to display error QMessageBox else: # exception handling try: key, iv, data",
"\"\": terms = value.split(',') loginValues = {} uris = [{\"match\": None, \"uri\": \"http://\"}]",
"\" in self.ui.passwordEdit.text()) or (\" \" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove spaces from",
"data != \"\": row = data.split('\\n') accounts = {} account = [] for",
"= cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data)",
"# creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Created vault.bin and",
"from string import ascii_uppercase, ascii_lowercase, digits, punctuation from startPage import Ui_startPage from genPassPage",
"\"Please remove spaces from Username or Password\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\"",
"when nothing in searchBox self.ui.accountsTable.setRowCount(0) # deletes tables contents for n, key in",
"file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() def updateAccounts(data): global KEYPATH, VAULTPATH key, iv, oldData =",
"function message = QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon) message.setText(text) message.exec_() def getData(pathToKey, pathToVault): # allows",
"text wrapper for file name in gui self.vaultPath = file[0] # makes vaultPath",
"getPathToDesktop(): # path to desktop is different on windows and unix systems as",
"stores it as an object self.ui.vaultFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.vaultFileLabel.adjustSize()",
"exportJSON(self): key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop()",
"export\") self.goBack() def getPathToDesktop(): # path to desktop is different on windows and",
"QtWidgets.QMessageBox.Critical, \"Remove commas from password fields\") else: key, iv, data = getData(KEYPATH, VAULTPATH)",
"data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.json\" if data != \"\": row =",
"i += 1 self.ui.accountsTable.setRowCount(0) # removes all data in table before making table",
"row['username'], row['password']] accounts.append(values) elif ('name' in row) and ('login_username' in row) and ('login_password'",
"for file name in gui self.Path = file[0] # makes path accessible in",
"# calls updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password Changed\") self.goBack() # go to view account",
"creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() if __name__ == \"__main__\": # displays when",
"cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username copied to clipboard\") def copyPassword(self): cb = QtGui.QGuiApplication.clipboard()",
"if value != \"\": # stores accounts as nested lists seperated by value",
"classToAccess self.newWindow.show() # show new window self.hide() # close old window def loadAccounts(self):",
"the accounts nested list updateAccounts(accounts) # calls updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password Changed\") self.goBack()",
"searchedAccounts is empty VIEWEDITEM = self.accounts[row] else: for n, key in enumerate(sorted(self.searchedAccounts.keys())): if",
"= QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210,",
"that a Key File or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No",
"importWin def importData(self): if self.ui.fileLbl.text() == \"Select file to import from\": # checks",
"def searchAccounts(self): term = self.ui.searchBox.text() if term != (None or \"\"): self.searchedAccounts =",
"to make sure you only run loadAccounts after a search self.searchedAccounts = {}",
"QtCore.QUrl.fromLocalFile(file[0]) # gets path to file and stores it as an object self.ui.vaultFileLabel.setText(url.fileName())",
"self.count -= 1 # decreases count for table to reset when nothing in",
"name in gui self.ui.fileLbl.adjustSize() # adjusts size of text wrapper for file name",
"(\",\" in self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from name of account or",
"key, iv, data = getData(self.keyPath, self.vaultPath) # display new window for generating password",
"os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath = \"{0}:{1}\".format(driveLetter, desktopPath) else: desktopPath = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return desktopPath",
"terms = value.split(',') temp = {} temp[\"name\"], temp[\"username\"], temp[\"password\"] = terms[0], terms[1], terms[2]",
"value != \"\": terms = value.split(',') temp = {} temp[\"name\"], temp[\"username\"], temp[\"password\"] =",
"or (self.ui.confirmPassEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One or Both of the",
"\"\\\\key.bin\", \"wb\") keyFile.write(key) # writes encryption key to file keyFile.close cipher = AES.new(key,",
"['url', 'username', 'password', 'extra', 'name', 'grouping', 'fav'] writer = csv.DictWriter(file, fieldnames=columns, lineterminator='\\n') writer.writeheader()",
"# close old window def loadAccounts(self): # added feature to read accounts from",
"== \" \"): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from the beginning or end",
"selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No file was selected. Please select a file to import",
"value.split(',') i += 1 self.ui.accountsTable.setRowCount(0) # removes all data in table before making",
"in self.ui.usernameEdit.text()) or (\",\" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from Name",
"data != \"\": row = data.split('\\n') self.accounts = {} i = 0 for",
"iv = readVaultFile.read(16) # Read the iv out - this is 16 bytes",
"# checks if searchedAccounts is empty VIEWEDITEM = self.accounts[row] else: for n, key",
"== \"__main__\": # displays when starting application app = QtWidgets.QApplication(sys.argv) startPage = MainWindow()",
"the user input fields are empty or incorrectly entered if (self.ui.nameOfAccountEdit.text()[0] == \"",
"as csvFile: reader = csv.DictReader(csvFile, delimiter=',') for row in reader: if ('name' in",
"self.keyPath = file[0] # makes keyPath accessible in all of MainWindow class def",
"else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file format not supported\") if len(accounts) < 1: Alert(\"Error\",",
"select files to open the vault\") # Alert function to display error QMessageBox",
"a file to import from\") # Alert function to display error QMessageBox else:",
"from platform import system from string import ascii_uppercase, ascii_lowercase, digits, punctuation from startPage",
"or (\",\" in self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from name of account",
"if data != \"\": row = data.split('\\n') accounts = {} account = []",
"with open(path, 'w') as file: # writes to csv in lastpass format json.dump(accounts,",
"self.ui = Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self): passwordOptions = \"\" if",
"username = self.ui.usernameEdit.text() password = self.ui.passwordEdit.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account",
"to file keyFile.close cipher = AES.new(key, AES.MODE_CBC) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile =",
"(self.ui.passwordEdit.text() == (None or \"\")) or (self.ui.confirmPassEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"of the password fields are empty\") else: if self.ui.passwordEdit.text() != self.ui.confirmPassEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"key, iv, data def writeData(nameOfAccount, username, password): # writes name of account, username",
"in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from name",
"message if the user input fields are empty or incorrectly entered if (self.ui.nameOfAccountEdit.text()[0]",
"self.hide() # close old window def loadAccounts(self): # added feature to read accounts",
"in row) and ('username' in row) and ('password' in row): # lastpass format",
"changed if system() == 'Windows': desktopPath = os.environ[\"HOMEPATH\"] + \"\\Desktop\" # finds path",
"QMessageBox else: accounts = [] if self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path, 'r') as csvFile: reader",
"accounts as nested lists seperated by value accounts.append(value.split(',')) for i in range(len(accounts)): if",
"self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1,",
"makes keyPath accessible in all of MainWindow class def getVaultFile(self): file = QtWidgets.QFileDialog.getOpenFileName(",
"QtWidgets.QMessageBox.Critical, \"No file was selected. Please select a file to import from\") #",
"accounts to export\") self.goBack() def exportJSON(self): key, iv, data = getData(KEYPATH, VAULTPATH) data",
"file to encrypt desktopPath = getPathToDesktop() # gets path to desktop keyFile =",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One or Both of the password fields are empty\") else: if",
"reuse the code to generate a QMessageBox def getKeyFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self,",
"row = data.split('\\n') accounts = [] for value in row: if value !=",
"KEYPATH, VAULTPATH KEYPATH, VAULTPATH = pathToKey, pathToVault readVaultFile = open(VAULTPATH, 'rb') # Open",
"Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .JSON\") self.goBack() else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File type not",
"data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') self.count = 1 # count for",
"account page after password is changed successfully class importWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs):",
"= ','.join(value) accounts.append(row) newData = b'' for line in accounts: newData += (\"{}\\n\".format(line)).encode('utf-8')",
"+ \"\\\\key.bin\", \"wb\") keyFile.write(key) # writes encryption key to file keyFile.close cipher =",
"self.count <= 0: # comparison to make sure you only run loadAccounts after",
"super().__init__(*args, **kwargs) self.ui = Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2])",
"AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() def",
"\"\": self.accounts[i] = value.split(',') i += 1 self.ui.accountsTable.setRowCount(0) # removes all data in",
"import Ui_passwordGen from allAccountsPage import Ui_allAccounts from AddAccountPage import Ui_addAccount from viewAccountPage import",
"def importData(self): if self.ui.fileLbl.text() == \"Select file to import from\": # checks that",
"VAULTPATH key, iv, oldData = getData(KEYPATH, VAULTPATH) accounts = [] for value in",
"**kwargs) self.ui = Ui_startPage() self.ui.setupUi(self) # initializes start page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles)",
"show new window self.hide() def getFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\",",
"pad, unpad # global variables to store paths to the vault and key",
"or (\" \" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove spaces from password fields\") elif",
"to generate password from\") def savePassword(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or",
"or \"\")) or (self.ui.confirmPassEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One or Both",
"import from\") # Alert function to display error QMessageBox else: accounts = []",
"file name in gui self.keyPath = file[0] # makes keyPath accessible in all",
"\" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove spaces from password fields\") elif (\",\" in",
"after saving accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) # the code below resets that",
"value != \"\": self.accounts[i] = value.split(',') i += 1 self.ui.accountsTable.setRowCount(0) # removes all",
"210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # if search box is empty if",
"reset check boxes after saving accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) # the code",
"if ('name' in row) and ('username' in row) and ('password' in row): #",
"line in accounts: newData += (\"{}\\n\".format(line)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data =",
"been left empty\") else: # displays any error message if the user input",
"import json from platform import system from string import ascii_uppercase, ascii_lowercase, digits, punctuation",
"Alert function to display error QMessageBox else: # exception handling try: key, iv,",
"disables table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def viewItem(self): global VIEWEDITEM if (self.ui.accountsTable.currentItem().text() == \"View\") and",
"account.append(temp) accounts['items'] = account with open(path, 'w') as file: # writes to csv",
"from changePassPage import Ui_changePass from importAccountsPage import Ui_importAccounts from exportAccountsPage import Ui_exportPage from",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name, Username or the Password field has been left empty\")",
"in row: # json uses None for null and False for false when",
"empty VIEWEDITEM = self.accounts[row] else: for n, key in enumerate(sorted(self.searchedAccounts.keys())): if row ==",
"in row: if value != \"\": # stores accounts as nested lists seperated",
"def createVaultFiles(self): key = get_random_bytes(32) # 32 bytes is 256 bits data =",
"then up-pad the result data = unpad(cipher.decrypt(ciphered_data), AES.block_size) return key, iv, data def",
"tables contents for n, key in enumerate(sorted(self.accounts.keys())): # displays code in table in",
"message.setText(\"Are you sure you want to delete the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel)",
"self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self, classToAccess): self.newWindow = classToAccess self.newWindow.show() self.hide() def copyUsername(self):",
"self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self, classToAccess):",
"empty\") else: # displays any error message if the user input fields are",
"\"\": row = data.split('\\n') self.accounts = {} i = 0 for value in",
"QtWidgets.QMessageBox.Information, \"Password Changed\") self.goBack() # go to view account page after password is",
"to the vault and key file global KEYPATH, VAULTPATH, VIEWEDITEM class MainWindow(QtWidgets.QWidget): def",
"**kwargs) self.ui = Ui_allAccounts() self.ui.setupUi(self) # button which links to generate password window",
"if self.count <= 0: # comparison to make sure you only run loadAccounts",
"accounts.index(account) accounts.pop(index) # when this code was a for loop in range len(accounts)",
"= getData(KEYPATH, VAULTPATH) accounts = [] for value in data: row = ','.join(value)",
"window for generating password or viewing accounts self.newWindow = generatePasswordWin() self.newWindow.show() # show",
"self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked(): passwordOptions += ascii_lowercase if",
"error when lots of accounts were added and then someone attempts to delete",
"Ui_startPage from genPassPage import Ui_passwordGen from allAccountsPage import Ui_allAccounts from AddAccountPage import Ui_addAccount",
"self.hide() def getFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\")",
"if 'login' in item: if ('username' in item['login']) and ('password' in item['login']): if",
"= uris, terms[1], terms[2], None temp = {} temp['id'], temp['organizationId'], temp['folderId'], temp['type'], temp['name'],",
"# finds path to desktop for driveLetter in ascii_uppercase: # find drive desktop",
"nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.generatedPassLabel.text() writeData(nameOfAccount, username, password) Alert(\"Process",
"FileNotFoundError) as e: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect files selected\") # Alert function to show",
"system from string import ascii_uppercase, ascii_lowercase, digits, punctuation from startPage import Ui_startPage from",
"KEYPATH, VAULTPATH, VIEWEDITEM class MainWindow(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui =",
"to reset when nothing in searchBox self.ui.accountsTable.setRowCount(0) # deletes tables contents for n,",
"import get_random_bytes from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad # global",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File type not supported\") class exportWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args,",
"== (None or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account",
"# path to desktop is different on windows and unix systems as on",
"= AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(newData, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") #",
"as file: # writes to csv file in lastpass format as lastpass' format",
"'name', 'grouping', 'fav'] writer = csv.DictWriter(file, fieldnames=columns, lineterminator='\\n') writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV",
"row['login_password']] accounts.append(values) if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV file format not supported",
"allAccountsWin() self.newWindow.show() # show new window self.hide() # close old window class allAccountsWin(QtWidgets.QWidget):",
"^ QtCore.Qt.ItemIsEditable) else: # else disables table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def viewItem(self): global VIEWEDITEM",
"self.ui.upperCaseCheck.isChecked(): passwordOptions += ascii_uppercase if self.ui.numbersCheck.isChecked(): passwordOptions += digits if self.ui.specialCharsCheck.isChecked(): passwordOptions +=",
"in gui self.vaultPath = file[0] # makes vaultPath accessible in all of MainWindow",
"self.vaultPath = file[0] # makes vaultPath accessible in all of MainWindow class def",
"in data['items']: # checks for bitwarden format if 'login' in item: if ('username'",
"len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file has no data to import\") else:",
"end of Account name\") elif (\" \" in self.ui.usernameEdit.text()) or (\" \" in",
"= readKeyFile.read() readKeyFile.close() cipher = AES.new(key, AES.MODE_CBC, iv=iv) # Setup cipher # Decrypt",
"< 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV file format not supported or no data to",
"and unix systems as on windows the drive the desktop is on can",
"desktop keyFile = open(desktopPath + \"\\\\key.bin\", \"wb\") keyFile.write(key) # writes encryption key to",
"self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # else disables",
"writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .JSON\") self.goBack() else: Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"QtWidgets.QMessageBox.Critical, \"CSV file format not supported or no data to import was found\")",
"# displays code in table in window if not(term.lower() in self.accounts[key][0].lower()): self.searchedAccounts.pop(key) #",
"= file[0] # makes vaultPath accessible in all of MainWindow class def openVaultFiles(self):",
"self.ui.usernameEdit.text()) or (\",\" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from Name of",
"passwordOptions = \"\" if self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked():",
"value in row: if value != \"\": self.accounts[i] = value.split(',') i += 1",
"'password', 'extra', 'name', 'grouping', 'fav'] writer = csv.DictWriter(file, fieldnames=columns, lineterminator='\\n') writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\",",
"a Key File or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either one",
"class generatePasswordWin(QtWidgets.QWidget): # displays generate password window when vault is open def __init__(self,",
"else: for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from",
"from viewAccountPage import Ui_viewAccount from changePassPage import Ui_changePass from importAccountsPage import Ui_importAccounts from",
"self.ui.fileLbl.setText(url.fileName()) # adjusts file name in gui self.ui.fileLbl.adjustSize() # adjusts size of text",
"password to vaultFile global KEYPATH, VAULTPATH key, iv, data = getData(KEYPATH, VAULTPATH) data",
"= data.decode('utf-8') row = data.split('\\n') accounts = [] for value in row: if",
"end of Account name\") elif \" \" in self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove",
"os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return desktopPath def Alert(title, icon, text): # creates QMessageBox based on",
"QtWidgets, QtCore, QtGui from Crypto.Random import get_random_bytes from Crypto.Cipher import AES from Crypto.Util.Padding",
"desktopPath)): desktopPath = \"{0}:{1}\".format(driveLetter, desktopPath) else: desktopPath = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return desktopPath def",
"1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # if search box",
"def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack)",
"False, loginValues, False account.append(temp) accounts['items'] = account with open(path, 'w') as file: #",
"i in range(8, 17)] passLength = random.choice(lengths) password = \"\" for i in",
"accounts were added and then someone attempts to delete an account # although",
"value accounts.append(value.split(',')) for account in accounts: if account == VIEWEDITEM: index = accounts.index(account)",
"file and stores it as an object self.ui.vaultFileLabel.setText(url.fileName()) # adjusts file name in",
"classToAccess): self.newWindow = classToAccess self.newWindow.show() self.hide() def copyUsername(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard)",
"an object self.ui.fileLbl.setText(url.fileName()) # adjusts file name in gui self.ui.fileLbl.adjustSize() # adjusts size",
"self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def exportCSV(self): key, iv, data = getData(KEYPATH, VAULTPATH)",
"1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file has no data to import\") else: for item",
"if value != \"\": self.accounts[i] = value.split(',') i += 1 self.ui.accountsTable.setRowCount(0) # removes",
"is 256 bits data = ''.encode('utf-8') # basic data for file to encrypt",
"and ('password' in row): # lastpass format if (row['username'] != \"\") and (row['password']",
"successfully class importWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_importAccounts() self.ui.setupUi(self)",
"self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) # button variables which execute a specific function def",
"it as an object self.ui.fileLbl.setText(url.fileName()) # adjusts file name in gui self.ui.fileLbl.adjustSize() #",
"saveAccount(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() == (None or \"\"))",
"= allAccountsWin() self.newWindow.show() self.hide() def exportCSV(self): key, iv, data = getData(KEYPATH, VAULTPATH) data",
"+ \"\\Desktop\" # finds path to desktop for driveLetter in ascii_uppercase: # find",
"have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No file was selected. Please select a file",
"return desktopPath def Alert(title, icon, text): # creates QMessageBox based on arguements in",
"self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def exportCSV(self):",
"allAccountsPage import Ui_allAccounts from AddAccountPage import Ui_addAccount from viewAccountPage import Ui_viewAccount from changePassPage",
"def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0])",
"if (item['login']['username'] is not None) and (item['login']['password'] is not None): values = [item['name'],",
"super().__init__(*args, **kwargs) self.ui = Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self): self.newWindow",
"saved\") self.goBack() class viewAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_viewAccount()",
"for i in range(8, 17)] passLength = random.choice(lengths) password = \"\" for i",
"Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .CSV\") self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path) as jsonFile:",
"self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def exportCSV(self): key, iv, data",
"= QtCore.QUrl.fromLocalFile(file[0]) # gets path to file and stores it as an object",
"\"\")) or (self.ui.passwordEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name, Username or",
"[item['name'], item['login'] ['username'], item['login']['password']] accounts.append(values) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file format not supported\")",
"QtWidgets.QMessageBox.Critical, \"JSON file format not supported\") if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON",
"self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def exportCSV(self): key,",
"row = data.split('\\n') accounts = {} account = [] for value in row:",
"# Read the iv out - this is 16 bytes long ciphered_data =",
"handling try: key, iv, data = getData(self.keyPath, self.vaultPath) # display new window for",
"self.loadAccounts() class addAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_addAccount() self.ui.setupUi(self)",
"account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_() def confirmDelete(self, clickedBtn): if clickedBtn.text() ==",
"accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) # the code below resets that generatedPassLabel, nameOfAccount",
"('password' in item['login']): if (item['login']['username'] is not None) and (item['login']['password'] is not None):",
"in range(len(accounts)): if accounts[i] == VIEWEDITEM: VIEWEDITEM[2] = self.ui.passwordEdit.text() # updates the item",
"self.changeWindow(viewAccountWin()) def searchAccounts(self): term = self.ui.searchBox.text() if term != (None or \"\"): self.searchedAccounts",
"window self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n,",
"changeWindow(self, classToAccess): self.newWindow = classToAccess self.newWindow.show() self.hide() def copyUsername(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(),",
"if accounts[i] == VIEWEDITEM: VIEWEDITEM[2] = self.ui.passwordEdit.text() # updates the item being viewed",
"\"\" if self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked(): passwordOptions +=",
"\"Please remove commas from name of account or username\") else: nameOfAccount = self.ui.nameOfAccountEdit.text()",
"terms[0], None, False, loginValues, False account.append(temp) accounts['items'] = account with open(path, 'w') as",
"in item: if ('username' in item['login']) and ('password' in item['login']): if (item['login']['username'] is",
"close old window class allAccountsWin(QtWidgets.QWidget): # view all accounts window def __init__(self, *args,",
"in function message = QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon) message.setText(text) message.exec_() def getData(pathToKey, pathToVault): #",
"(None or \"\")) or (self.ui.usernameEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name",
"if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath = \"{0}:{1}\".format(driveLetter, desktopPath) else: desktopPath = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') return",
"newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel)",
"clipboard\") def copyPassword(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password copied to",
"except (ValueError, FileNotFoundError) as e: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect files selected\") # Alert function",
"path += \"\\Accounts.json\" if data != \"\": row = data.split('\\n') accounts = {}",
"gets path to desktop keyFile = open(desktopPath + \"\\\\key.bin\", \"wb\") keyFile.write(key) # writes",
"iv, oldData = getData(KEYPATH, VAULTPATH) accounts = [] for value in data: row",
"row) and ('username' in row) and ('password' in row): # lastpass format if",
"(self.ui.confirmPassEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One or Both of the password",
"the code below resets that generatedPassLabel, nameOfAccount input and username input after saving",
"(\" \" in self.ui.usernameEdit.text()) or (\" \" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove",
"VAULTPATH) data = data.decode('utf-8') self.count = 1 # count for resetting all accounts",
"to import from\": # checks that a Key File or Vault file have",
"item in data['items']: # checks for bitwarden format if 'login' in item: if",
"QtWidgets.QMessageBox.Critical, \"File type not supported\") class exportWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)",
"from file global KEYPATH, VAULTPATH self.searchedAccounts = {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv, data =",
"elif (\",\" in self.ui.passwordEdit.text()) or (\",\" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove commas from",
"or (self.ui.nameOfAccountEdit.text()[-1] == \" \"): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from the beginning",
"throughout document global KEYPATH, VAULTPATH KEYPATH, VAULTPATH = pathToKey, pathToVault readVaultFile = open(VAULTPATH,",
"file global KEYPATH, VAULTPATH self.searchedAccounts = {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv, data = getData(KEYPATH,",
"in gui self.ui.keyFileLabel.adjustSize() # adjusts size of text wrapper for file name in",
"self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self): # opens window to view all",
"cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\")",
"decreases count for table to reset when nothing in searchBox self.ui.accountsTable.setRowCount(0) # deletes",
"in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove commas from password fields\") else: key, iv, data",
"else: # else disables table self.ui.accountsTable.setEnabled(False) self.ui.searchBox.setEnabled(False) def viewItem(self): global VIEWEDITEM if (self.ui.accountsTable.currentItem().text()",
"self.searchedAccounts = {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8')",
"| QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_() def confirmDelete(self, clickedBtn): if clickedBtn.text() == \"&Yes\": key,",
"*args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self):",
"checks if searchedAccounts is empty VIEWEDITEM = self.accounts[row] else: for n, key in",
"spaces from Username\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No file was selected. Please",
"json.load(jsonFile) if 'items' in data: for item in data['items']: # checks for bitwarden",
"allAccountsWin() self.newWindow.show() # show new window self.hide() def getFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self,",
"def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def",
"or (vaultFile == \"Vault File\"): # checks that a Key File or Vault",
"mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username copied to clipboard\") def copyPassword(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(),",
"file, indent=4) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"JSON file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts",
"self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove commas from password fields\") else: key, iv, data =",
"else: # displays any error message if the user input fields are empty",
"n, key in enumerate(sorted(self.searchedAccounts.keys())): if row == n: VIEWEDITEM = self.accounts[key] self.changeWindow(viewAccountWin()) def",
"a Key File or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No file",
"input and username input after saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self):",
"__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def",
"term != (None or \"\"): self.searchedAccounts = self.accounts.copy() # copy sets values to",
"None, None, 1, terms[0], None, False, loginValues, False account.append(temp) accounts['items'] = account with",
"export\") self.goBack() def exportJSON(self): key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8')",
"\"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One or Both of the password fields are empty\") else:",
"key = readKeyFile.read() readKeyFile.close() cipher = AES.new(key, AES.MODE_CBC, iv=iv) # Setup cipher #",
"# close old window except (ValueError, FileNotFoundError) as e: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect files",
"+= \"\\Accounts.csv\" if data != \"\": row = data.split('\\n') accounts = [] for",
"message.exec_() def confirmDelete(self, clickedBtn): if clickedBtn.text() == \"&Yes\": key, iv, data = getData(KEYPATH,",
"stores it as an object self.ui.fileLbl.setText(url.fileName()) # adjusts file name in gui self.ui.fileLbl.adjustSize()",
"open(path, 'w') as file: # writes to csv file in lastpass format as",
"run loadAccounts after a search self.searchedAccounts = {} self.loadAccounts() class addAccountWin(QtWidgets.QWidget): def __init__(self,",
"gui self.ui.fileLbl.adjustSize() # adjusts size of text wrapper for file name in gui",
"search terms for n, key in enumerate(sorted(self.searchedAccounts.keys())): self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel =",
"options to generate password from\") def savePassword(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\"))",
"window argument self.newWindow = classToAccess self.newWindow.show() # show new window self.hide() # close",
"creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Created vault.bin and key.bin\")",
"temp['id'], temp['organizationId'], temp['folderId'], temp['type'], temp['name'], temp['notes'], temp[ 'favorite'], temp['login'], temp['collectionIds'] = \"\", None,",
"getData(KEYPATH, VAULTPATH) accounts = [] for value in data: row = ','.join(value) accounts.append(row)",
"210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # if search box is empty if self.count",
"self.newWindow.show() # show new window self.hide() # close old window class allAccountsWin(QtWidgets.QWidget): #",
"bitwarden format if 'login' in item: if ('username' in item['login']) and ('password' in",
"Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password Changed\") self.goBack() # go to view account page after password",
"accounts.append(row) newData = b'' for line in accounts: newData += (\"{}\\n\".format(line)).encode('utf-8') cipher =",
"is empty if self.count <= 0: # comparison to make sure you only",
"key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') row = data.split('\\n') accounts",
"new window self.hide() # close old window def loadAccounts(self): # added feature to",
"row): # lastpass format if (row['username'] != \"\") and (row['password'] != \"\") and",
"!= \"\"): values = [row['name'], row['username'], row['password']] accounts.append(values) elif ('name' in row) and",
"in importWin def importData(self): if self.ui.fileLbl.text() == \"Select file to import from\": #",
"self.goBack() class viewAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_viewAccount() self.ui.setupUi(self)",
"QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you sure you want to delete the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes",
"from AddAccountPage import Ui_addAccount from viewAccountPage import Ui_viewAccount from changePassPage import Ui_changePass from",
"Read the iv out - this is 16 bytes long ciphered_data = readVaultFile.read()",
"= classToAccess self.newWindow.show() # show new window self.hide() # close old window def",
"is not None): values = [item['name'], item['login'] ['username'], item['login']['password']] accounts.append(values) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"# go to view account page after password is changed successfully class importWin(QtWidgets.QWidget):",
"allAccountsWin(QtWidgets.QWidget): # view all accounts window def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui",
"files to open the vault\") # Alert function to display error QMessageBox else:",
"copyPassword(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password copied to clipboard\") def",
"\"Remove commas from password fields\") else: key, iv, data = getData(KEYPATH, VAULTPATH) data",
"delete the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_() def confirmDelete(self, clickedBtn): if",
"\"\": # stores accounts as nested lists seperated by value accounts.append(value.split(',')) for i",
"'grouping', 'fav'] writer = csv.DictWriter(file, fieldnames=columns, lineterminator='\\n') writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV file",
"from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad # global variables to",
"= [] for value in row: if value != \"\": # stores accounts",
"for value in row: if value != \"\": terms = value.split(',') temp =",
"{} i = 0 for value in row: if value != \"\": self.accounts[i]",
"writeData(nameOfAccount, username, password): # writes name of account, username and password to vaultFile",
"self.ui.accountsTable.currentRow() if not(self.searchedAccounts): # checks if searchedAccounts is empty VIEWEDITEM = self.accounts[row] else:",
"**kwargs) self.ui = Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show()",
"of text wrapper for file name in gui self.vaultPath = file[0] # makes",
"rest of the data readVaultFile.close() readKeyFile = open(KEYPATH, 'rb') key = readKeyFile.read() readKeyFile.close()",
"boxes after saving accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False) self.ui.specialCharsCheck.setChecked(False) # the code below resets",
"it would give # a random error when lots of accounts were added",
"*args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def",
"if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV file format not supported or no",
"file format not supported or no data to import was found\") else: for",
"QtWidgets.QMessageBox.Critical, \"Please remove commas from name of account or username\") else: nameOfAccount =",
"# removes all data in table before making table for n, key in",
"data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.json\"",
"self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def changeWindow(self, classToAccess): # takes new window argument self.newWindow",
"\"\": terms = value.split(',') temp = {} temp[\"name\"], temp[\"username\"], temp[\"password\"] = terms[0], terms[1],",
"def getPathToDesktop(): # path to desktop is different on windows and unix systems",
"VIEWEDITEM: VIEWEDITEM[2] = self.ui.passwordEdit.text() # updates the item being viewed accounts[i] = VIEWEDITEM",
"[row['name'], row['username'], row['password']] accounts.append(values) elif ('name' in row) and ('login_username' in row) and",
"file in lastpass format as lastpass' format is widely supported columns = ['url',",
"displays code in table in window if not(term.lower() in self.accounts[key][0].lower()): self.searchedAccounts.pop(key) # removes",
"(self.ui.accountsTable.currentItem().text() == \"View\") and (self.ui.accountsTable.currentColumn() == 1): row = self.ui.accountsTable.currentRow() if not(self.searchedAccounts): #",
"removes all data in table before making table for n, key in enumerate(sorted(self.accounts.keys())):",
"username, password)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile =",
"self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def changeWindow(self, classToAccess): # takes",
"= self.ui.usernameEdit.text() password = self.ui.generatedPassLabel.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\")",
"or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name or Username has been left empty\") else:",
"1): row = self.ui.accountsTable.currentRow() if not(self.searchedAccounts): # checks if searchedAccounts is empty VIEWEDITEM",
"spaces from the beginning or end of Account name\") elif (\" \" in",
"created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def exportJSON(self): key, iv,",
"Ui_addAccount() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.saveBtn.clicked.connect(self.saveAccount) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() self.hide() def saveAccount(self):",
"value in row: if value != \"\": terms = value.split(',') temp = {}",
"!= \"\") and (row['name'] != \"\"): values = [row['name'], row['username'], row['password']] accounts.append(values) elif",
"url = QtCore.QUrl.fromLocalFile(file[0]) # gets path to file and stores it as an",
"keyFile = self.ui.keyFileLabel.text() vaultFile = self.ui.vaultFileLabel.text() if (keyFile == \"Key File\") or (vaultFile",
"viewItem(self): global VIEWEDITEM if (self.ui.accountsTable.currentItem().text() == \"View\") and (self.ui.accountsTable.currentColumn() == 1): row =",
"== (None or \"\")) or (self.ui.confirmPassEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One",
"def getKeyFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\") #",
"ascii_lowercase if self.ui.upperCaseCheck.isChecked(): passwordOptions += ascii_uppercase if self.ui.numbersCheck.isChecked(): passwordOptions += digits if self.ui.specialCharsCheck.isChecked():",
"\"Imported accounts from .JSON\") self.goBack() else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File type not supported\") class",
"len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV file format not supported or no data",
"path accessible in importWin def importData(self): if self.ui.fileLbl.text() == \"Select file to import",
"and key.bin\") # Alert function to reuse the code to generate a QMessageBox",
"(row['name'] != \"\") and (row['login_username'] != \"\") and (row['login_password'] != \"\"): values =",
"sets values to new variable to edit self.count -= 1 # decreases count",
"QtCore, QtGui from Crypto.Random import get_random_bytes from Crypto.Cipher import AES from Crypto.Util.Padding import",
"text wrapper for file name in gui self.Path = file[0] # makes path",
"value != \"\": # stores accounts as nested lists seperated by value accounts.append(value.split(','))",
"resetting all accounts view if data != \"\": row = data.split('\\n') self.accounts =",
"all accounts view if data != \"\": row = data.split('\\n') self.accounts = {}",
"open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() def updateAccounts(data): global KEYPATH,",
"to desktop keyFile = open(desktopPath + \"\\\\key.bin\", \"wb\") keyFile.write(key) # writes encryption key",
"self.ui.passwordEdit.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") self.goBack() class viewAccountWin(QtWidgets.QWidget): def",
"when vault is open def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_passwordGen()",
"self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_changePass() self.ui.setupUi(self)",
"item being viewed accounts[i] = VIEWEDITEM # updates the item in the accounts",
"self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def changeWindow(self,",
"= QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon) message.setText(text) message.exec_() def getData(pathToKey, pathToVault): # allows me to",
"self.ui.specialCharsCheck.isChecked(): passwordOptions += punctuation.replace(',', '') lengths = [i for i in range(8, 17)]",
"(self.ui.usernameEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name or Username has been",
"# adjusts file name in gui self.ui.vaultFileLabel.adjustSize() # adjusts size of text wrapper",
"and stores it as an object self.ui.keyFileLabel.setText(url.fileName()) # adjusts file name in gui",
"def openVaultFiles(self): keyFile = self.ui.keyFileLabel.text() vaultFile = self.ui.vaultFileLabel.text() if (keyFile == \"Key File\")",
"def copyPassword(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password copied to clipboard\")",
"[] for value in row: # json uses None for null and False",
"newitem = QtWidgets.QTableWidgetItem(self.searchedAccounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel)",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No options to generate password from\") def savePassword(self): if (self.ui.nameOfAccountEdit.text() ==",
"\"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name, Username or the Password field has been left",
"new window self.hide() # close old window class allAccountsWin(QtWidgets.QWidget): # view all accounts",
"to file and stores it as an object self.ui.fileLbl.setText(url.fileName()) # adjusts file name",
"class exportWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack)",
"to desktop for driveLetter in ascii_uppercase: # find drive desktop folder is on",
"has no data to import\") else: for item in accounts: writeData(item[0], item[1], item[2])",
"self.ui.openButton.clicked.connect(self.openVaultFiles) # button variables which execute a specific function def createVaultFiles(self): key =",
"def savePassword(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() == (None or",
"for generating password or viewing accounts self.newWindow = generatePasswordWin() self.newWindow.show() # show new",
"for null and False for false when writing to a json if value",
"(\" \" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username or Password\")",
"else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def getPathToDesktop(): # path to",
"data = data.decode('utf-8') row = data.split('\\n') accounts = [] for value in row:",
"[{\"match\": None, \"uri\": \"http://\"}] loginValues['uris'], loginValues['username'], loginValues['password'], loginValues['totp'] = uris, terms[1], terms[2], None",
"self.ui = Ui_startPage() self.ui.setupUi(self) # initializes start page self.ui.startButton.clicked.connect(self.createVaultFiles) self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) #",
"+= ascii_lowercase if self.ui.upperCaseCheck.isChecked(): passwordOptions += ascii_uppercase if self.ui.numbersCheck.isChecked(): passwordOptions += digits if",
"commas from Name of account, Username or Password\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username",
"None for null and False for false when writing to a json if",
"[i for i in range(8, 17)] passLength = random.choice(lengths) password = \"\" for",
"data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.csv\"",
"file to import from\": # checks that a Key File or Vault file",
"or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"One or Both of the password fields are empty\")",
"cipher # Decrypt and then up-pad the result data = unpad(cipher.decrypt(ciphered_data), AES.block_size) return",
"\"Select file to import from\": # checks that a Key File or Vault",
"desktopPath def Alert(title, icon, text): # creates QMessageBox based on arguements in function",
"value accounts.append(value.split(',')) for i in range(len(accounts)): if accounts[i] == VIEWEDITEM: VIEWEDITEM[2] = self.ui.passwordEdit.text()",
"document global KEYPATH, VAULTPATH KEYPATH, VAULTPATH = pathToKey, pathToVault readVaultFile = open(VAULTPATH, 'rb')",
"all accounts window def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_allAccounts() self.ui.setupUi(self)",
"file has no data to import\") else: for item in accounts: writeData(item[0], item[1],",
"\"No accounts to export\") self.goBack() def getPathToDesktop(): # path to desktop is different",
"\"Please remove spaces from Username\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()):",
"a for loop in range len(accounts) sometimes it would give # a random",
"message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_() def confirmDelete(self, clickedBtn): if clickedBtn.text() == \"&Yes\": key, iv, data",
"go to view account page after password is changed successfully class importWin(QtWidgets.QWidget): def",
"and then someone attempts to delete an account # although the code is",
"QtWidgets.QMessageBox.Information, \"Imported accounts from .JSON\") self.goBack() else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File type not supported\")",
"accounts.append(values) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file format not supported\") if len(accounts) < 1:",
"# exception handling try: key, iv, data = getData(self.keyPath, self.vaultPath) # display new",
"after saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self): # opens window to",
"icon, text): # creates QMessageBox based on arguements in function message = QtWidgets.QMessageBox()",
"# the code below resets that generatedPassLabel, nameOfAccount input and username input after",
"if value != \"\": terms = value.split(',') loginValues = {} uris = [{\"match\":",
"= QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you sure you want to delete the account?\")",
"= self.accounts.copy() # copy sets values to new variable to edit self.count -=",
"self.newWindow = allAccountsWin() self.newWindow.show() # show new window self.hide() def getFile(self): file =",
"'rb') key = readKeyFile.read() readKeyFile.close() cipher = AES.new(key, AES.MODE_CBC, iv=iv) # Setup cipher",
"Password\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.passwordEdit.text() writeData(nameOfAccount, username,",
"= open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() if __name__ ==",
"'extra', 'name', 'grouping', 'fav'] writer = csv.DictWriter(file, fieldnames=columns, lineterminator='\\n') writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information,",
"else: # if search box is empty if self.count <= 0: # comparison",
"if the user input fields are empty or incorrectly entered if (self.ui.nameOfAccountEdit.text()[0] ==",
"self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self): self.newWindow = viewAccountWin() self.newWindow.show() self.hide() def changePassword(self): if (self.ui.passwordEdit.text()",
"of Account name\") elif \" \" in self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces",
"# code below works just like in loadAccounts but with search terms for",
"'Desktop') return desktopPath def Alert(title, icon, text): # creates QMessageBox based on arguements",
"find drive desktop folder is on if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)): desktopPath = \"{0}:{1}\".format(driveLetter, desktopPath)",
"the result data = unpad(cipher.decrypt(ciphered_data), AES.block_size) return key, iv, data def writeData(nameOfAccount, username,",
"to open the vault\") # Alert function to display error QMessageBox else: #",
"csv.DictReader(csvFile, delimiter=',') for row in reader: if ('name' in row) and ('username' in",
"# lastpass format if (row['username'] != \"\") and (row['password'] != \"\") and (row['name']",
"# makes keyPath accessible in all of MainWindow class def getVaultFile(self): file =",
"\"All Files (*)\") # lets user choose files from explorer url = QtCore.QUrl.fromLocalFile(file[0])",
"if (self.ui.accountsTable.currentItem().text() == \"View\") and (self.ui.accountsTable.currentColumn() == 1): row = self.ui.accountsTable.currentRow() if not(self.searchedAccounts):",
"from password fields\") else: key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8')",
"in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from Name of account, Username or",
"message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you sure you want to delete the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel)",
"super().__init__(*args, **kwargs) self.ui = Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def goBack(self): self.newWindow =",
"data: for item in data['items']: # checks for bitwarden format if 'login' in",
"Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") self.goBack() class viewAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args,",
"json from platform import system from string import ascii_uppercase, ascii_lowercase, digits, punctuation from",
"ascii_lowercase, digits, punctuation from startPage import Ui_startPage from genPassPage import Ui_passwordGen from allAccountsPage",
"Username\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove",
"wrapper for file name in gui self.vaultPath = file[0] # makes vaultPath accessible",
"old window except (ValueError, FileNotFoundError) as e: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Incorrect files selected\") #",
"# creates QMessageBox based on arguements in function message = QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon)",
"self.accounts[key][0].lower()): self.searchedAccounts.pop(key) # removes values not in search # code below works just",
"item['login']) and ('password' in item['login']): if (item['login']['username'] is not None) and (item['login']['password'] is",
"code in table in window if not(term.lower() in self.accounts[key][0].lower()): self.searchedAccounts.pop(key) # removes values",
"one or no files were selected. Please select files to open the vault\")",
"the item being viewed accounts[i] = VIEWEDITEM # updates the item in the",
"file name in gui self.ui.keyFileLabel.adjustSize() # adjusts size of text wrapper for file",
"\"No file was selected. Please select a file to import from\") # Alert",
"windows and unix systems as on windows the drive the desktop is on",
"for resetting all accounts view if data != \"\": row = data.split('\\n') self.accounts",
"vaultFile global KEYPATH, VAULTPATH key, iv, data = getData(KEYPATH, VAULTPATH) data += (\"{},{},{}\\n\".format(nameOfAccount,",
"is open def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword)",
"self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self): passwordOptions = \"\" if self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked() or",
"delimiter=',') for row in reader: if ('name' in row) and ('username' in row)",
"error issue updateAccounts(accounts) # calls updateAccounts self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs):",
"search # code below works just like in loadAccounts but with search terms",
"# adjusts size of text wrapper for file name in gui self.keyPath =",
"data = json.load(jsonFile) if 'items' in data: for item in data['items']: # checks",
"successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def exportJSON(self): key,",
"terms[0], terms[1], terms[2] accounts.append(temp) with open(path, 'w') as file: # writes to csv",
"format is widely supported columns = ['url', 'username', 'password', 'extra', 'name', 'grouping', 'fav']",
"item['login'] ['username'], item['login']['password']] accounts.append(values) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file format not supported\") if",
"file name in gui self.vaultPath = file[0] # makes vaultPath accessible in all",
"QtWidgets.QMessageBox.Information, \"Imported accounts from .CSV\") self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path) as jsonFile: data",
"message.setText(text) message.exec_() def getData(pathToKey, pathToVault): # allows me to access Paths throughout document",
"not supported\") class exportWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_exportPage()",
"and password to vaultFile global KEYPATH, VAULTPATH key, iv, data = getData(KEYPATH, VAULTPATH)",
"< 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"JSON file has no data to import\") else: for",
"for account in accounts: if account == VIEWEDITEM: index = accounts.index(account) accounts.pop(index) #",
"for bitwarden format if 'login' in item: if ('username' in item['login']) and ('password'",
"if row == n: VIEWEDITEM = self.accounts[key] self.changeWindow(viewAccountWin()) def searchAccounts(self): term = self.ui.searchBox.text()",
"QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username copied to clipboard\") def copyPassword(self): cb =",
"temp['name'], temp['notes'], temp[ 'favorite'], temp['login'], temp['collectionIds'] = \"\", None, None, 1, terms[0], None,",
"QtWidgets.QMessageBox.Information, \"Account saved\") # reset check boxes after saving accounts self.ui.lowerCaseCheck.setChecked(False) self.ui.upperCaseCheck.setChecked(False) self.ui.numbersCheck.setChecked(False)",
"writing to a json if value != \"\": terms = value.split(',') loginValues =",
"keyFile = open(desktopPath + \"\\\\key.bin\", \"wb\") keyFile.write(key) # writes encryption key to file",
"self.ui = Ui_allAccounts() self.ui.setupUi(self) # button which links to generate password window self.ui.genPassTab.clicked.connect(lambda:",
"1 # decreases count for table to reset when nothing in searchBox self.ui.accountsTable.setRowCount(0)",
"show new window self.hide() # close old window class allAccountsWin(QtWidgets.QWidget): # view all",
"saving self.ui.generatedPassLabel.setText(\"\") self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self): # opens window to view",
"name\") elif \" \" in self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username\")",
"\"Vault File\"): # checks that a Key File or Vault file have been",
"changePassPage import Ui_changePass from importAccountsPage import Ui_importAccounts from exportAccountsPage import Ui_exportPage from PyQt5",
"= self.ui.keyFileLabel.text() vaultFile = self.ui.vaultFileLabel.text() if (keyFile == \"Key File\") or (vaultFile ==",
"# creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() if __name__ == \"__main__\": # displays",
"'') lengths = [i for i in range(8, 17)] passLength = random.choice(lengths) password",
"super().__init__(*args, **kwargs) self.ui = Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self): self.newWindow =",
"# bitwarden format if (row['name'] != \"\") and (row['login_username'] != \"\") and (row['login_password']",
"readVaultFile.read() # Read the rest of the data readVaultFile.close() readKeyFile = open(KEYPATH, 'rb')",
"open(desktopPath + \"\\\\vault.bin\", \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process Completed\",",
"QtWidgets.QMessageBox.Critical, \"Please remove commas from Name of account, Username or Password\") else: nameOfAccount",
"\"Account name or Username has been left empty\") else: # displays any error",
"you only run loadAccounts after a search self.searchedAccounts = {} self.loadAccounts() class addAccountWin(QtWidgets.QWidget):",
"row): # bitwarden format if (row['name'] != \"\") and (row['login_username'] != \"\") and",
"import\") else: for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts",
"QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter) self.ui.accountsTable.setItem(n, 0, newitem) self.ui.accountsTable.setItem(n, 1, viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^",
"file and stores it as an object self.ui.fileLbl.setText(url.fileName()) # adjusts file name in",
"# if search box is empty if self.count <= 0: # comparison to",
"function to reuse the code to generate a QMessageBox def getKeyFile(self): file =",
"self.ui.selectKeyFile.clicked.connect(self.getKeyFile) self.ui.selectVaultFile.clicked.connect(self.getVaultFile) self.ui.openButton.clicked.connect(self.openVaultFiles) # button variables which execute a specific function def createVaultFiles(self):",
"self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No options to generate password from\")",
"of Account name\") elif (\" \" in self.ui.usernameEdit.text()) or (\" \" in self.ui.passwordEdit.text()):",
"as nested lists seperated by value accounts.append(value.split(',')) for i in range(len(accounts)): if accounts[i]",
"def exportJSON(self): key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path =",
"to view account page after password is changed successfully class importWin(QtWidgets.QWidget): def __init__(self,",
"startPage import Ui_startPage from genPassPage import Ui_passwordGen from allAccountsPage import Ui_allAccounts from AddAccountPage",
"!= \"\") and (row['login_username'] != \"\") and (row['login_password'] != \"\"): values = [row['name'],",
"\"No accounts to export\") self.goBack() def exportJSON(self): key, iv, data = getData(KEYPATH, VAULTPATH)",
"ciphered_data = cipher.encrypt(pad(newData, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv)",
"QtWidgets.QMessageBox.Critical, \"Remove spaces from password fields\") elif (\",\" in self.ui.passwordEdit.text()) or (\",\" in",
"# copy sets values to new variable to edit self.count -= 1 #",
"issue updateAccounts(accounts) # calls updateAccounts self.changeWindow(allAccountsWin()) class changePassWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args,",
"= ['url', 'username', 'password', 'extra', 'name', 'grouping', 'fav'] writer = csv.DictWriter(file, fieldnames=columns, lineterminator='\\n')",
"def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show() # show new window self.hide() def getFile(self):",
"= open(desktopPath + \"\\\\vault.bin\", \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process",
"cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(desktopPath + \"\\\\vault.bin\", \"wb\") # creates vault file vaultFile.write(cipher.iv)",
"are empty or incorrectly entered if (self.ui.nameOfAccountEdit.text()[0] == \" \") or (self.ui.nameOfAccountEdit.text()[-1] ==",
"temp = {} temp['id'], temp['organizationId'], temp['folderId'], temp['type'], temp['name'], temp['notes'], temp[ 'favorite'], temp['login'], temp['collectionIds']",
"Please select files to open the vault\") # Alert function to display error",
"temp = {} temp[\"name\"], temp[\"username\"], temp[\"password\"] = terms[0], terms[1], terms[2] accounts.append(temp) with open(path,",
"\"\": row = data.split('\\n') accounts = [] for value in row: if value",
"passwordOptions += ascii_uppercase if self.ui.numbersCheck.isChecked(): passwordOptions += digits if self.ui.specialCharsCheck.isChecked(): passwordOptions += punctuation.replace(',',",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name or Username has been left empty\") else: # displays",
"encryption key to file keyFile.close cipher = AES.new(key, AES.MODE_CBC) ciphered_data = cipher.encrypt(pad(data, AES.block_size))",
"def changePassword(self): if (self.ui.passwordEdit.text() == (None or \"\")) or (self.ui.confirmPassEdit.text() == (None or",
"self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self, classToAccess): self.newWindow = classToAccess self.newWindow.show() self.hide()",
"key.bin\") # Alert function to reuse the code to generate a QMessageBox def",
"# displays any error message if the user input fields are empty or",
"self.ui.fileLbl.text() == \"Select file to import from\": # checks that a Key File",
"(\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile",
"viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # else disables table self.ui.accountsTable.setEnabled(False)",
"viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # if search box is empty if self.count <=",
"or (\",\" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from Name of account,",
"('name' in row) and ('login_username' in row) and ('login_password' in row): # bitwarden",
"self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked(): passwordOptions += ascii_lowercase if self.ui.upperCaseCheck.isChecked(): passwordOptions += ascii_uppercase",
"get_random_bytes from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad # global variables",
"else: accounts = [] if self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path, 'r') as csvFile: reader =",
"Ui_passwordGen from allAccountsPage import Ui_allAccounts from AddAccountPage import Ui_addAccount from viewAccountPage import Ui_viewAccount",
"self.searchedAccounts = self.accounts.copy() # copy sets values to new variable to edit self.count",
"iv, data def writeData(nameOfAccount, username, password): # writes name of account, username and",
"# decreases count for table to reset when nothing in searchBox self.ui.accountsTable.setRowCount(0) #",
"self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove spaces from password fields\") elif (\",\" in self.ui.passwordEdit.text()) or",
"self.hide() # close old window class allAccountsWin(QtWidgets.QWidget): # view all accounts window def",
"== \"Select file to import from\": # checks that a Key File or",
"row) and ('login_username' in row) and ('login_password' in row): # bitwarden format if",
"account in accounts: if account == VIEWEDITEM: index = accounts.index(account) accounts.pop(index) # when",
"viewed accounts[i] = VIEWEDITEM # updates the item in the accounts nested list",
"Ui_importAccounts from exportAccountsPage import Ui_exportPage from PyQt5 import QtWidgets, QtCore, QtGui from Crypto.Random",
"size of text wrapper for file name in gui self.keyPath = file[0] #",
"\" in self.ui.usernameEdit.text(): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username\") elif (\",\" in",
"(\" \" in self.ui.passwordEdit.text()) or (\" \" in self.ui.confirmPassEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove spaces",
"VAULTPATH = pathToKey, pathToVault readVaultFile = open(VAULTPATH, 'rb') # Open the file to",
"= file[0] # makes path accessible in importWin def importData(self): if self.ui.fileLbl.text() ==",
"= cipher.encrypt(pad(newData, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data)",
"self.Path = file[0] # makes path accessible in importWin def importData(self): if self.ui.fileLbl.text()",
"self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def changeWindow(self, classToAccess): # takes new window",
"writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts",
"of MainWindow class def getVaultFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All",
"def exportCSV(self): key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path =",
"data = data.decode('utf-8') path = getPathToDesktop() path += \"\\Accounts.csv\" if data != \"\":",
"edit self.count -= 1 # decreases count for table to reset when nothing",
"vaultFile.close() Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Created vault.bin and key.bin\") # Alert function to reuse",
"spaces from password fields\") elif (\",\" in self.ui.passwordEdit.text()) or (\",\" in self.ui.confirmPassEdit.text()): Alert(\"Error\",",
"row: if value != \"\": # stores accounts as nested lists seperated by",
"# show new window self.hide() def getFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file',",
"(None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name, Username or the Password field has",
"account, Username or Password\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password =",
"row: if value != \"\": self.accounts[i] = value.split(',') i += 1 self.ui.accountsTable.setRowCount(0) #",
"widely supported columns = ['url', 'username', 'password', 'extra', 'name', 'grouping', 'fav'] writer =",
"if self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked(): passwordOptions += ascii_lowercase",
"attempts to delete an account # although the code is now longer, this",
"or self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked(): passwordOptions += ascii_lowercase if self.ui.upperCaseCheck.isChecked(): passwordOptions +=",
"!= \"\": self.accounts[i] = value.split(',') i += 1 self.ui.accountsTable.setRowCount(0) # removes all data",
"== \" \") or (self.ui.nameOfAccountEdit.text()[-1] == \" \"): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces",
"accounts = {} account = [] for value in row: # json uses",
"show new window self.hide() # close old window def loadAccounts(self): # added feature",
"# json uses None for null and False for false when writing to",
"\"JSON file has no data to import\") else: for item in accounts: writeData(item[0],",
"accounts: newData += (\"{}\\n\".format(line)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(newData, AES.block_size))",
"= data.split('\\n') accounts = [] for value in row: if value != \"\":",
"= getData(KEYPATH, VAULTPATH) data += (\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv)",
"file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\") # lets user",
"to reuse the code to generate a QMessageBox def getKeyFile(self): file = QtWidgets.QFileDialog.getOpenFileName(",
"loadAccounts(self): # added feature to read accounts from file global KEYPATH, VAULTPATH self.searchedAccounts",
"Ui_viewAccount from changePassPage import Ui_changePass from importAccountsPage import Ui_importAccounts from exportAccountsPage import Ui_exportPage",
"choose files from explorer url = QtCore.QUrl.fromLocalFile(file[0]) # gets path to file and",
"or self.ui.specialCharsCheck.isChecked(): if self.ui.lowerCaseCheck.isChecked(): passwordOptions += ascii_lowercase if self.ui.upperCaseCheck.isChecked(): passwordOptions += ascii_uppercase if",
"self.vaultPath) # display new window for generating password or viewing accounts self.newWindow =",
"writer = csv.DictWriter(file, fieldnames=columns, lineterminator='\\n') writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV file successfully created\")",
"= value.split(',') i += 1 self.ui.accountsTable.setRowCount(0) # removes all data in table before",
"spaces from Username or Password\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text())",
"VAULTPATH key, iv, data = getData(KEYPATH, VAULTPATH) data += (\"{},{},{}\\n\".format(nameOfAccount, username, password)).encode('utf-8') cipher",
"if ('username' in item['login']) and ('password' in item['login']): if (item['login']['username'] is not None)",
"as lastpass' format is widely supported columns = ['url', 'username', 'password', 'extra', 'name',",
"file to read bytes iv = readVaultFile.read(16) # Read the iv out -",
"any error message if the user input fields are empty or incorrectly entered",
"row = ','.join(value) accounts.append(row) newData = b'' for line in accounts: newData +=",
"\"\")) or (self.ui.usernameEdit.text() == (None or \"\")) or (self.ui.passwordEdit.text() == (None or \"\")):",
"have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either one or no files were selected. Please",
"self.accounts = {} i = 0 for value in row: if value !=",
"on windows the drive the desktop is on can be changed if system()",
"of text wrapper for file name in gui self.Path = file[0] # makes",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV file format not supported or no data to import was",
"the code is now longer, this fixes the index error issue updateAccounts(accounts) #",
"all of MainWindow class def openVaultFiles(self): keyFile = self.ui.keyFileLabel.text() vaultFile = self.ui.vaultFileLabel.text() if",
"item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .JSON\") self.goBack() else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"File type",
"accessible in all of MainWindow class def getVaultFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open",
"file name in gui self.Path = file[0] # makes path accessible in importWin",
"or Vault file have been selected Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either one or no files",
"and then up-pad the result data = unpad(cipher.decrypt(ciphered_data), AES.block_size) return key, iv, data",
"file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def exportJSON(self):",
"\"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() def updateAccounts(data): global KEYPATH, VAULTPATH",
"lots of accounts were added and then someone attempts to delete an account",
"self.ui.setupUi(self) # button which links to generate password window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem)",
"for false when writing to a json if value != \"\": terms =",
"jsonFile: data = json.load(jsonFile) if 'items' in data: for item in data['items']: #",
"Read the rest of the data readVaultFile.close() readKeyFile = open(KEYPATH, 'rb') key =",
"**kwargs): super().__init__(*args, **kwargs) self.ui = Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self): passwordOptions",
"which links to generate password window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts)",
"search box is empty if self.count <= 0: # comparison to make sure",
"can be changed if system() == 'Windows': desktopPath = os.environ[\"HOMEPATH\"] + \"\\Desktop\" #",
"0: # comparison to make sure you only run loadAccounts after a search",
"self.newWindow.show() self.hide() def exportCSV(self): key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8')",
"[row['name'], row['login_username'], row['login_password']] accounts.append(values) if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV file format",
"in enumerate(sorted(self.accounts.keys())): # displays code in table in window self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0])",
"# adjusts size of text wrapper for file name in gui self.vaultPath =",
"vaultFile.close() if __name__ == \"__main__\": # displays when starting application app = QtWidgets.QApplication(sys.argv)",
"user input fields are empty or incorrectly entered if (self.ui.nameOfAccountEdit.text()[0] == \" \")",
"a json if value != \"\": terms = value.split(',') loginValues = {} uris",
"\"\": row = data.split('\\n') accounts = {} account = [] for value in",
"readKeyFile.read() readKeyFile.close() cipher = AES.new(key, AES.MODE_CBC, iv=iv) # Setup cipher # Decrypt and",
"\"JSON file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def",
"QMessageBox def getKeyFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', \"\", \"All Files (*)\")",
"**kwargs) self.ui = Ui_importAccounts() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.selectFileBtn.clicked.connect(self.getFile) self.ui.importBtn.clicked.connect(self.importData) def goBack(self): self.newWindow = allAccountsWin()",
"of MainWindow class def openVaultFiles(self): keyFile = self.ui.keyFileLabel.text() vaultFile = self.ui.vaultFileLabel.text() if (keyFile",
"openAccountsPage(self): # opens window to view all accounts self.newWindow = allAccountsWin() self.newWindow.show() #",
"self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()) or (\",\" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove",
"self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from name of",
"in self.ui.usernameEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas from name of account or username\")",
"**kwargs): super().__init__(*args, **kwargs) self.ui = Ui_allAccounts() self.ui.setupUi(self) # button which links to generate",
"finds path to desktop for driveLetter in ascii_uppercase: # find drive desktop folder",
"variables to store paths to the vault and key file global KEYPATH, VAULTPATH,",
"file: # writes to csv file in lastpass format as lastpass' format is",
"be changed if system() == 'Windows': desktopPath = os.environ[\"HOMEPATH\"] + \"\\Desktop\" # finds",
"no data to import\") else: for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\",",
"new window argument self.newWindow = classToAccess self.newWindow.show() # show new window self.hide() #",
"self.ui = Ui_exportPage() self.ui.setupUi(self) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.csvBtn.clicked.connect(self.exportCSV) self.ui.jsonBtn.clicked.connect(self.exportJSON) def goBack(self): self.newWindow = allAccountsWin() self.newWindow.show()",
"accessible in all of MainWindow class def openVaultFiles(self): keyFile = self.ui.keyFileLabel.text() vaultFile =",
"name of account, username and password to vaultFile global KEYPATH, VAULTPATH key, iv,",
"[] for value in data: row = ','.join(value) accounts.append(row) newData = b'' for",
"files from explorer url = QtCore.QUrl.fromLocalFile(file[0]) # gets path to file and stores",
"in the accounts nested list updateAccounts(accounts) # calls updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password Changed\")",
"fieldnames=columns, lineterminator='\\n') writer.writeheader() writer.writerows(accounts) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"CSV file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical,",
"{} self.loadAccounts() class addAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_addAccount()",
"error QMessageBox else: accounts = [] if self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path, 'r') as csvFile:",
"in enumerate(sorted(self.accounts.keys())): # displays code in table in window if not(term.lower() in self.accounts[key][0].lower()):",
"function to display error QMessageBox else: accounts = [] if self.ui.fileLbl.text().lower().endswith(\".csv\"): with open(self.Path,",
"index = accounts.index(account) accounts.pop(index) # when this code was a for loop in",
"lastpass' format is widely supported columns = ['url', 'username', 'password', 'extra', 'name', 'grouping',",
"genPassword(self): passwordOptions = \"\" if self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked() or self.ui.numbersCheck.isChecked() or self.ui.specialCharsCheck.isChecked(): if",
"name or Username has been left empty\") else: # displays any error message",
"= Ui_allAccounts() self.ui.setupUi(self) # button which links to generate password window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin()))",
"cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Username copied to clipboard\") def copyPassword(self):",
"not(term.lower() in self.accounts[key][0].lower()): self.searchedAccounts.pop(key) # removes values not in search # code below",
"self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount)",
"or (\",\" in self.ui.usernameEdit.text()) or (\",\" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove commas",
"open(path, 'w') as file: # writes to csv in lastpass format json.dump(accounts, file,",
"# show new window self.hide() # close old window class allAccountsWin(QtWidgets.QWidget): # view",
"files selected\") # Alert function to show error message class generatePasswordWin(QtWidgets.QWidget): # displays",
"VIEWEDITEM # updates the item in the accounts nested list updateAccounts(accounts) # calls",
"iv=iv) ciphered_data = cipher.encrypt(pad(data, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault file",
"elif (\" \" in self.ui.usernameEdit.text()) or (\" \" in self.ui.passwordEdit.text()): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please",
"in row): # lastpass format if (row['username'] != \"\") and (row['password'] != \"\")",
"field has been left empty\") else: # displays any error message if the",
"item['login']): if (item['login']['username'] is not None) and (item['login']['password'] is not None): values =",
"links to generate password window self.ui.genPassTab.clicked.connect(lambda: self.changeWindow(generatePasswordWin())) self.loadAccounts() self.ui.accountsTable.itemClicked.connect(self.viewItem) self.ui.addAccountBtn.clicked.connect(lambda: self.changeWindow(addAccountWin())) self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda:",
"\"Remove spaces from password fields\") elif (\",\" in self.ui.passwordEdit.text()) or (\",\" in self.ui.confirmPassEdit.text()):",
"takes new window argument self.newWindow = classToAccess self.newWindow.show() # show new window self.hide()",
"i in range(len(accounts)): if accounts[i] == VIEWEDITEM: VIEWEDITEM[2] = self.ui.passwordEdit.text() # updates the",
"AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close() if",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Either one or no files were selected. Please select files to",
"lists seperated by value accounts.append(value.split(',')) for account in accounts: if account == VIEWEDITEM:",
"\"wb\") keyFile.write(key) # writes encryption key to file keyFile.close cipher = AES.new(key, AES.MODE_CBC)",
"\"Passwords dont match\") elif (\" \" in self.ui.passwordEdit.text()) or (\" \" in self.ui.confirmPassEdit.text()):",
"file global KEYPATH, VAULTPATH, VIEWEDITEM class MainWindow(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)",
"writes encryption key to file keyFile.close cipher = AES.new(key, AES.MODE_CBC) ciphered_data = cipher.encrypt(pad(data,",
"or (self.ui.passwordEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name, Username or the",
"values = [row['name'], row['login_username'], row['login_password']] accounts.append(values) if len(accounts) < 1: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"CSV",
"temp['notes'], temp[ 'favorite'], temp['login'], temp['collectionIds'] = \"\", None, None, 1, terms[0], None, False,",
"= 1 # count for resetting all accounts view if data != \"\":",
"self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self, classToAccess): self.newWindow = classToAccess self.newWindow.show() self.hide() def copyUsername(self): cb =",
"vaultFile.write(ciphered_data) vaultFile.close() if __name__ == \"__main__\": # displays when starting application app =",
"clipboard\") def deleteAccount(self): message = QtWidgets.QMessageBox() message.setWindowTitle(\"Warning\") message.setIcon(QtWidgets.QMessageBox.Warning) message.setText(\"Are you sure you want",
"os import random import csv import json from platform import system from string",
"= data.split('\\n') accounts = {} account = [] for value in row: #",
"random error when lots of accounts were added and then someone attempts to",
"count for resetting all accounts view if data != \"\": row = data.split('\\n')",
"VIEWEDITEM[2] = self.ui.passwordEdit.text() # updates the item being viewed accounts[i] = VIEWEDITEM #",
"in reader: if ('name' in row) and ('username' in row) and ('password' in",
"code in table in window self.ui.accountsTable.insertRow(n) newitem = QtWidgets.QTableWidgetItem(self.accounts[key][0]) viewLabel = QtWidgets.QTableWidgetItem(\"View\") viewLabel.setTextAlignment(QtCore.Qt.AlignCenter)",
"vaultFile.close() def updateAccounts(data): global KEYPATH, VAULTPATH key, iv, oldData = getData(KEYPATH, VAULTPATH) accounts",
"file successfully created\") else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No accounts to export\") self.goBack() def getPathToDesktop():",
"self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda: self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self, classToAccess): self.newWindow = classToAccess",
"data = getData(self.keyPath, self.vaultPath) # display new window for generating password or viewing",
"passwordOptions += ascii_lowercase if self.ui.upperCaseCheck.isChecked(): passwordOptions += ascii_uppercase if self.ui.numbersCheck.isChecked(): passwordOptions += digits",
"self.ui.vaultFileLabel.adjustSize() # adjusts size of text wrapper for file name in gui self.vaultPath",
"old window class allAccountsWin(QtWidgets.QWidget): # view all accounts window def __init__(self, *args, **kwargs):",
"the data readVaultFile.close() readKeyFile = open(KEYPATH, 'rb') key = readKeyFile.read() readKeyFile.close() cipher =",
"KEYPATH, VAULTPATH key, iv, oldData = getData(KEYPATH, VAULTPATH) accounts = [] for value",
"(None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name or Username has been left empty\")",
"self.newWindow.show() # show new window self.hide() # close old window def loadAccounts(self): #",
"view all accounts self.newWindow = allAccountsWin() self.newWindow.show() # show new window self.hide() #",
"self.ui.searchBox.returnPressed.connect(self.searchAccounts) self.ui.importBtn.clicked.connect(lambda: self.changeWindow(importWin())) self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def changeWindow(self, classToAccess): # takes new window argument",
"commas from password fields\") else: key, iv, data = getData(KEYPATH, VAULTPATH) data =",
"def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_startPage() self.ui.setupUi(self) # initializes start",
"only run loadAccounts after a search self.searchedAccounts = {} self.loadAccounts() class addAccountWin(QtWidgets.QWidget): def",
"format if 'login' in item: if ('username' in item['login']) and ('password' in item['login']):",
"desktopPath = os.environ[\"HOMEPATH\"] + \"\\Desktop\" # finds path to desktop for driveLetter in",
"self.ui.vaultFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.vaultFileLabel.adjustSize() # adjusts size of text",
"= classToAccess self.newWindow.show() self.hide() def copyUsername(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.usernameLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information,",
"delete an account # although the code is now longer, this fixes the",
"path to desktop keyFile = open(desktopPath + \"\\\\key.bin\", \"wb\") keyFile.write(key) # writes encryption",
"row) and ('password' in row): # lastpass format if (row['username'] != \"\") and",
"the code to generate a QMessageBox def getKeyFile(self): file = QtWidgets.QFileDialog.getOpenFileName( self, 'Open",
"bits data = ''.encode('utf-8') # basic data for file to encrypt desktopPath =",
"QtWidgets.QMessageBox() message.setWindowTitle(title) message.setIcon(icon) message.setText(text) message.exec_() def getData(pathToKey, pathToVault): # allows me to access",
"self.goBack() def exportJSON(self): key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path",
"it as an object self.ui.vaultFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.vaultFileLabel.adjustSize() #",
"bytes is 256 bits data = ''.encode('utf-8') # basic data for file to",
"passLength): password += random.choice(passwordOptions) self.ui.generatedPassLabel.setText(password) self.ui.nameOfAccountEdit.setEnabled(True) self.ui.usernameEdit.setEnabled(True) self.ui.saveBtn.setEnabled(True) else: Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"No options",
"stores it as an object self.ui.keyFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.keyFileLabel.adjustSize()",
"class allAccountsWin(QtWidgets.QWidget): # view all accounts window def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)",
"to delete the account?\") message.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel) message.setDefaultButton(QtWidgets.QMessageBox.Cancel) message.buttonClicked.connect(self.confirmDelete) message.exec_() def confirmDelete(self, clickedBtn):",
"file name in gui self.ui.fileLbl.adjustSize() # adjusts size of text wrapper for file",
"explorer url = QtCore.QUrl.fromLocalFile(file[0]) # gets path to file and stores it as",
"QtWidgets.QMessageBox.Critical, \"Account name or Username has been left empty\") else: # displays any",
"import Ui_exportPage from PyQt5 import QtWidgets, QtCore, QtGui from Crypto.Random import get_random_bytes from",
"or Password\") else: nameOfAccount = self.ui.nameOfAccountEdit.text() username = self.ui.usernameEdit.text() password = self.ui.passwordEdit.text() writeData(nameOfAccount,",
"None) and (item['login']['password'] is not None): values = [item['name'], item['login'] ['username'], item['login']['password']] accounts.append(values)",
"VAULTPATH, VIEWEDITEM class MainWindow(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_startPage()",
"terms[1], terms[2] accounts.append(temp) with open(path, 'w') as file: # writes to csv file",
"exportCSV(self): key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path = getPathToDesktop()",
"the drive the desktop is on can be changed if system() == 'Windows':",
"open(KEYPATH, 'rb') key = readKeyFile.read() readKeyFile.close() cipher = AES.new(key, AES.MODE_CBC, iv=iv) # Setup",
"viewLabel) viewLabel.setBackground(QtGui.QColor(210, 210, 210)) viewLabel.setFlags(viewLabel.flags() ^ QtCore.Qt.ItemIsEditable) else: # if search box is",
"self.ui.exportBtn.clicked.connect(lambda: self.changeWindow(exportWin())) def changeWindow(self, classToAccess): # takes new window argument self.newWindow = classToAccess",
"def saveAccount(self): if (self.ui.nameOfAccountEdit.text() == (None or \"\")) or (self.ui.usernameEdit.text() == (None or",
"= value.split(',') temp = {} temp[\"name\"], temp[\"username\"], temp[\"password\"] = terms[0], terms[1], terms[2] accounts.append(temp)",
"\"Incorrect files selected\") # Alert function to show error message class generatePasswordWin(QtWidgets.QWidget): #",
"self.ui.generatedPassLabel.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") # reset check boxes",
"\"\")) or (self.ui.usernameEdit.text() == (None or \"\")): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Account name or Username",
"getPathToDesktop() path += \"\\Accounts.json\" if data != \"\": row = data.split('\\n') accounts =",
"to csv file in lastpass format as lastpass' format is widely supported columns",
"store paths to the vault and key file global KEYPATH, VAULTPATH, VIEWEDITEM class",
"iv=iv) # Setup cipher # Decrypt and then up-pad the result data =",
"\"Imported accounts from .CSV\") self.goBack() elif self.ui.fileLbl.text().lower().endswith(\".json\"): with open(self.Path) as jsonFile: data =",
"view all accounts window def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_allAccounts()",
"loginValues['username'], loginValues['password'], loginValues['totp'] = uris, terms[1], terms[2], None temp = {} temp['id'], temp['organizationId'],",
"else: for n, key in enumerate(sorted(self.searchedAccounts.keys())): if row == n: VIEWEDITEM = self.accounts[key]",
"remove spaces from Username\") elif (\",\" in self.ui.nameOfAccountEdit.text()) or (\",\" in self.ui.usernameEdit.text()): Alert(\"Error\",",
"= Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self): passwordOptions = \"\" if self.ui.lowerCaseCheck.isChecked()",
"as an object self.ui.fileLbl.setText(url.fileName()) # adjusts file name in gui self.ui.fileLbl.adjustSize() # adjusts",
"for item in accounts: writeData(item[0], item[1], item[2]) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Imported accounts from .CSV\")",
"driveLetter in ascii_uppercase: # find drive desktop folder is on if os.path.exists(\"{0}:{1}\".format(driveLetter, desktopPath)):",
"to clipboard\") def copyPassword(self): cb = QtGui.QGuiApplication.clipboard() cb.setText(self.ui.passwordLbl.text(), mode=cb.Clipboard) Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password copied",
"AES.new(key, AES.MODE_CBC, iv=iv) ciphered_data = cipher.encrypt(pad(newData, AES.block_size)) vaultFile = open(VAULTPATH, \"wb\") # creates",
"self.ui.nameOfAccountEdit.setText(\"\") self.ui.usernameEdit.setText(\"\") self.ui.nameOfAccountEdit.setEnabled(False) self.ui.usernameEdit.setEnabled(False) def openAccountsPage(self): # opens window to view all accounts",
"<filename>main.py import sys import os import random import csv import json from platform",
"and stores it as an object self.ui.vaultFileLabel.setText(url.fileName()) # adjusts file name in gui",
"**kwargs) self.ui = Ui_changePass() self.ui.setupUi(self) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.cancelBtn.clicked.connect(self.goBack) self.ui.changePassBtn.clicked.connect(self.changePassword) def goBack(self): self.newWindow =",
"self.accounts.copy() # copy sets values to new variable to edit self.count -= 1",
"= {} temp['id'], temp['organizationId'], temp['folderId'], temp['type'], temp['name'], temp['notes'], temp[ 'favorite'], temp['login'], temp['collectionIds'] =",
"if self.ui.lowerCaseCheck.isChecked(): passwordOptions += ascii_lowercase if self.ui.upperCaseCheck.isChecked(): passwordOptions += ascii_uppercase if self.ui.numbersCheck.isChecked(): passwordOptions",
"password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account saved\") # reset check boxes after saving accounts",
"which execute a specific function def createVaultFiles(self): key = get_random_bytes(32) # 32 bytes",
"(self.ui.nameOfAccountEdit.text()[0] == \" \") or (self.ui.nameOfAccountEdit.text()[-1] == \" \"): Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove",
"Completed\", QtWidgets.QMessageBox.Information, \"Created vault.bin and key.bin\") # Alert function to reuse the code",
"VIEWEDITEM = self.accounts[key] self.changeWindow(viewAccountWin()) def searchAccounts(self): term = self.ui.searchBox.text() if term != (None",
"Alert function to reuse the code to generate a QMessageBox def getKeyFile(self): file",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Please remove spaces from Username or Password\") elif (\",\" in self.ui.nameOfAccountEdit.text())",
"for value in row: if value != \"\": self.accounts[i] = value.split(',') i +=",
"super().__init__(*args, **kwargs) self.ui = Ui_passwordGen() self.ui.setupUi(self) self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self): passwordOptions =",
"on can be changed if system() == 'Windows': desktopPath = os.environ[\"HOMEPATH\"] + \"\\Desktop\"",
"!= \"\") and (row['login_password'] != \"\"): values = [row['name'], row['login_username'], row['login_password']] accounts.append(values) if",
"= self.ui.searchBox.text() if term != (None or \"\"): self.searchedAccounts = self.accounts.copy() # copy",
"in enumerate(sorted(self.searchedAccounts.keys())): if row == n: VIEWEDITEM = self.accounts[key] self.changeWindow(viewAccountWin()) def searchAccounts(self): term",
"if (keyFile == \"Key File\") or (vaultFile == \"Vault File\"): # checks that",
"path to file and stores it as an object self.ui.fileLbl.setText(url.fileName()) # adjusts file",
"self.accounts[key] self.changeWindow(viewAccountWin()) def searchAccounts(self): term = self.ui.searchBox.text() if term != (None or \"\"):",
"was a for loop in range len(accounts) sometimes it would give # a",
"= generatePasswordWin() self.newWindow.show() # show new window self.hide() # close old window except",
"vaultFile.write(ciphered_data) vaultFile.close() Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Created vault.bin and key.bin\") # Alert function to",
"self.hide() def exportCSV(self): key, iv, data = getData(KEYPATH, VAULTPATH) data = data.decode('utf-8') path",
"password window when vault is open def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui",
"username = self.ui.usernameEdit.text() password = self.ui.generatedPassLabel.text() writeData(nameOfAccount, username, password) Alert(\"Process Completed\", QtWidgets.QMessageBox.Information, \"Account",
"global KEYPATH, VAULTPATH self.searchedAccounts = {} self.ui.accountsTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) key, iv, data = getData(KEYPATH, VAULTPATH)",
"-= 1 # decreases count for table to reset when nothing in searchBox",
"the desktop is on can be changed if system() == 'Windows': desktopPath =",
"vaultFile = open(desktopPath + \"\\\\vault.bin\", \"wb\") # creates vault file vaultFile.write(cipher.iv) vaultFile.write(ciphered_data) vaultFile.close()",
"\"\\Desktop\" # finds path to desktop for driveLetter in ascii_uppercase: # find drive",
"incorrectly entered if (self.ui.nameOfAccountEdit.text()[0] == \" \") or (self.ui.nameOfAccountEdit.text()[-1] == \" \"): Alert(\"Error\",",
"in row): # bitwarden format if (row['name'] != \"\") and (row['login_username'] != \"\")",
"# display new window for generating password or viewing accounts self.newWindow = generatePasswordWin()",
"data readVaultFile.close() readKeyFile = open(KEYPATH, 'rb') key = readKeyFile.read() readKeyFile.close() cipher = AES.new(key,",
"readVaultFile.close() readKeyFile = open(KEYPATH, 'rb') key = readKeyFile.read() readKeyFile.close() cipher = AES.new(key, AES.MODE_CBC,",
"accessible in importWin def importData(self): if self.ui.fileLbl.text() == \"Select file to import from\":",
"*args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1])",
"gui self.vaultPath = file[0] # makes vaultPath accessible in all of MainWindow class",
"self.ui.genBtn.clicked.connect(self.genPassword) self.ui.saveBtn.clicked.connect(self.savePassword) self.ui.viewAccountsTab.clicked.connect(self.openAccountsPage) def genPassword(self): passwordOptions = \"\" if self.ui.lowerCaseCheck.isChecked() or self.ui.upperCaseCheck.isChecked() or",
"Ui_viewAccount() self.ui.setupUi(self) self.ui.backBtn.clicked.connect(lambda: self.changeWindow(allAccountsWin())) self.ui.nameOfAccountLbl.setText(VIEWEDITEM[0]) self.ui.nameOfAccountLbl.adjustSize() self.ui.usernameLbl.setText(VIEWEDITEM[1]) self.ui.usernameLbl.adjustSize() self.ui.passwordLbl.setText(VIEWEDITEM[2]) self.ui.passwordLbl.adjustSize() self.ui.copyUserBtn.clicked.connect(self.copyUsername) self.ui.copyPassBtn.clicked.connect(self.copyPassword) self.ui.changePassBtn.clicked.connect(lambda:",
"data: row = ','.join(value) accounts.append(row) newData = b'' for line in accounts: newData",
"csv import json from platform import system from string import ascii_uppercase, ascii_lowercase, digits,",
"!= \"\": # stores accounts as nested lists seperated by value accounts.append(value.split(',')) for",
"and False for false when writing to a json if value != \"\":",
"n, key in enumerate(sorted(self.accounts.keys())): # displays code in table in window self.ui.accountsTable.insertRow(n) newitem",
"loginValues = {} uris = [{\"match\": None, \"uri\": \"http://\"}] loginValues['uris'], loginValues['username'], loginValues['password'], loginValues['totp']",
"\"Account saved\") self.goBack() class viewAccountWin(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui =",
"vaultFile = self.ui.vaultFileLabel.text() if (keyFile == \"Key File\") or (vaultFile == \"Vault File\"):",
"self.changeWindow(changePassWin())) self.ui.deleteBtn.clicked.connect(self.deleteAccount) def changeWindow(self, classToAccess): self.newWindow = classToAccess self.newWindow.show() self.hide() def copyUsername(self): cb",
"message class generatePasswordWin(QtWidgets.QWidget): # displays generate password window when vault is open def",
"object self.ui.vaultFileLabel.setText(url.fileName()) # adjusts file name in gui self.ui.vaultFileLabel.adjustSize() # adjusts size of",
"from PyQt5 import QtWidgets, QtCore, QtGui from Crypto.Random import get_random_bytes from Crypto.Cipher import",
"item in the accounts nested list updateAccounts(accounts) # calls updateAccounts Alert(\"Confirmed\", QtWidgets.QMessageBox.Information, \"Password",
"and stores it as an object self.ui.fileLbl.setText(url.fileName()) # adjusts file name in gui",
"Alert(\"Error\", QtWidgets.QMessageBox.Critical, \"Remove commas from password fields\") else: key, iv, data = getData(KEYPATH,"
] |
[
"# -*- coding:utf-8 -*- \"\"\" @__Create Time__ = 2017/12/11 10:34 @__Description__ = \"",
"-*- coding:utf-8 -*- \"\"\" @__Create Time__ = 2017/12/11 10:34 @__Description__ = \" \"",
"coding:utf-8 -*- \"\"\" @__Create Time__ = 2017/12/11 10:34 @__Description__ = \" \" \"\"\"",
"python3 # -*- coding:utf-8 -*- \"\"\" @__Create Time__ = 2017/12/11 10:34 @__Description__ =",
"#!/usr/bin/env python3 # -*- coding:utf-8 -*- \"\"\" @__Create Time__ = 2017/12/11 10:34 @__Description__"
] |
[
"inc # (c) 2010-2020 california institute of technology # all rights reserved #",
"docstring __doc__ = COV.__doc__ # and return it return COV @altar.foundry( implements=solver, tip=\"a",
"-*- # -*- coding: utf-8 -*- # # <NAME> <<EMAIL>> # # (c)",
"Bayesian sampler based on the Metropolis algorithm\") def metropolis(): # grab the factory",
".Solver import Solver as solver # implementations @altar.foundry( implements=controller, tip=\"a Bayesian controller that",
"solver for δβ based on a Brent minimizer from gsl\") def brent(): #",
"solver for δβ based on a naive grid search\") def grid(): # grab",
"as solver # implementations @altar.foundry( implements=controller, tip=\"a Bayesian controller that implements simulated annealing\")",
"it return COV @altar.foundry( implements=solver, tip=\"a solver for δβ based on a Brent",
"tip=\"a solver for δβ based on a Brent minimizer from gsl\") def brent():",
"docstring __doc__ = Brent.__doc__ # and return it return Brent @altar.foundry( implements=solver, tip=\"a",
"Grid @altar.foundry( implements=sampler, tip=\"a Bayesian sampler based on the Metropolis algorithm\") def metropolis():",
"(c) 2010-2020 california institute of technology # all rights reserved # # the",
"@altar.foundry( implements=controller, tip=\"a Bayesian controller that implements simulated annealing\") def annealer(): # grab",
"# grab the factory from .COV import COV # attach its docstring __doc__",
"cov(): # grab the factory from .COV import COV # attach its docstring",
"factory from .Grid import Grid # attach its docstring __doc__ = Grid.__doc__ #",
"tip=\"a Bayesian sampler based on the Metropolis algorithm\") def metropolis(): # grab the",
"grab the factory from .Brent import Brent # attach its docstring __doc__ =",
"on the Metropolis algorithm\") def metropolis(): # grab the factory from .Metropolis import",
"various simulation phases\") def profiler(): # grab the factory from .Profiler import Profiler",
"# attach its docstring __doc__ = COV.__doc__ # and return it return COV",
"attach its docstring __doc__ = Profiler.__doc__ # and return it return Profiler #",
"import Metropolis # attach its docstring __doc__ = Metropolis.__doc__ # and return it",
"= Metropolis.__doc__ # and return it return Metropolis @altar.foundry( implements=altar.simulations.monitor, tip=\"a monitor that",
"# -*- python -*- # -*- coding: utf-8 -*- # # <NAME> <<EMAIL>>",
"= Grid.__doc__ # and return it return Grid @altar.foundry( implements=sampler, tip=\"a Bayesian sampler",
"attach its docstring __doc__ = Metropolis.__doc__ # and return it return Metropolis @altar.foundry(",
"factory from .Metropolis import Metropolis # attach its docstring __doc__ = Metropolis.__doc__ #",
"from .Profiler import Profiler # attach its docstring __doc__ = Profiler.__doc__ # and",
".Profiler import Profiler # attach its docstring __doc__ = Profiler.__doc__ # and return",
"@altar.foundry( implements=sampler, tip=\"a Bayesian sampler based on the Metropolis algorithm\") def metropolis(): #",
"it return Annealer @altar.foundry( implements=scheduler, tip=\"a Bayesian scheduler based on the COV algorithm\")",
"scheduler based on the COV algorithm\") def cov(): # grab the factory from",
"Annealer # attach its docstring __doc__ = Annealer.__doc__ # and return it return",
"controller from .Sampler import Sampler as sampler from .Scheduler import Scheduler as scheduler",
"δβ based on a naive grid search\") def grid(): # grab the factory",
"Metropolis algorithm\") def metropolis(): # grab the factory from .Metropolis import Metropolis #",
"its docstring __doc__ = Metropolis.__doc__ # and return it return Metropolis @altar.foundry( implements=altar.simulations.monitor,",
"based on the Metropolis algorithm\") def metropolis(): # grab the factory from .Metropolis",
"from .COV import COV # attach its docstring __doc__ = COV.__doc__ # and",
"Profiler # attach its docstring __doc__ = Profiler.__doc__ # and return it return",
"# and return it return Annealer @altar.foundry( implements=scheduler, tip=\"a Bayesian scheduler based on",
"controller that implements simulated annealing\") def annealer(): # grab the factory from .Annealer",
"implements=scheduler, tip=\"a Bayesian scheduler based on the COV algorithm\") def cov(): # grab",
"reserved # # the package import altar # and the protocols from .Controller",
"search\") def grid(): # grab the factory from .Grid import Grid # attach",
"__doc__ = Metropolis.__doc__ # and return it return Metropolis @altar.foundry( implements=altar.simulations.monitor, tip=\"a monitor",
"2013-2020 parasim inc # (c) 2010-2020 california institute of technology # all rights",
"# the package import altar # and the protocols from .Controller import Controller",
"<<EMAIL>> # # (c) 2013-2020 parasim inc # (c) 2010-2020 california institute of",
"the factory from .COV import COV # attach its docstring __doc__ = COV.__doc__",
"COV @altar.foundry( implements=solver, tip=\"a solver for δβ based on a Brent minimizer from",
"based on a Brent minimizer from gsl\") def brent(): # grab the factory",
"__doc__ = COV.__doc__ # and return it return COV @altar.foundry( implements=solver, tip=\"a solver",
"# attach its docstring __doc__ = Profiler.__doc__ # and return it return Profiler",
"of technology # all rights reserved # # the package import altar #",
"# <NAME> <<EMAIL>> # # (c) 2013-2020 parasim inc # (c) 2010-2020 california",
"annealing\") def annealer(): # grab the factory from .Annealer import Annealer # attach",
"import Controller as controller from .Sampler import Sampler as sampler from .Scheduler import",
"implements=controller, tip=\"a Bayesian controller that implements simulated annealing\") def annealer(): # grab the",
"california institute of technology # all rights reserved # # the package import",
".Annealer import Annealer # attach its docstring __doc__ = Annealer.__doc__ # and return",
"COV algorithm\") def cov(): # grab the factory from .COV import COV #",
"# # <NAME> <<EMAIL>> # # (c) 2013-2020 parasim inc # (c) 2010-2020",
"= COV.__doc__ # and return it return COV @altar.foundry( implements=solver, tip=\"a solver for",
"for δβ based on a naive grid search\") def grid(): # grab the",
"from .Metropolis import Metropolis # attach its docstring __doc__ = Metropolis.__doc__ # and",
"import Brent # attach its docstring __doc__ = Brent.__doc__ # and return it",
"phases\") def profiler(): # grab the factory from .Profiler import Profiler # attach",
"from .Controller import Controller as controller from .Sampler import Sampler as sampler from",
"Annealer @altar.foundry( implements=scheduler, tip=\"a Bayesian scheduler based on the COV algorithm\") def cov():",
"its docstring __doc__ = COV.__doc__ # and return it return COV @altar.foundry( implements=solver,",
"as controller from .Sampler import Sampler as sampler from .Scheduler import Scheduler as",
"based on a naive grid search\") def grid(): # grab the factory from",
"grab the factory from .Annealer import Annealer # attach its docstring __doc__ =",
"parasim inc # (c) 2010-2020 california institute of technology # all rights reserved",
"annealer(): # grab the factory from .Annealer import Annealer # attach its docstring",
"import COV # attach its docstring __doc__ = COV.__doc__ # and return it",
"factory from .Brent import Brent # attach its docstring __doc__ = Brent.__doc__ #",
"on the COV algorithm\") def cov(): # grab the factory from .COV import",
"import Grid # attach its docstring __doc__ = Grid.__doc__ # and return it",
"Brent.__doc__ # and return it return Brent @altar.foundry( implements=solver, tip=\"a solver for δβ",
"docstring __doc__ = Grid.__doc__ # and return it return Grid @altar.foundry( implements=sampler, tip=\"a",
"utf-8 -*- # # <NAME> <<EMAIL>> # # (c) 2013-2020 parasim inc #",
"for δβ based on a Brent minimizer from gsl\") def brent(): # grab",
"# attach its docstring __doc__ = Metropolis.__doc__ # and return it return Metropolis",
"its docstring __doc__ = Brent.__doc__ # and return it return Brent @altar.foundry( implements=solver,",
"the factory from .Annealer import Annealer # attach its docstring __doc__ = Annealer.__doc__",
"Brent @altar.foundry( implements=solver, tip=\"a solver for δβ based on a naive grid search\")",
"# and return it return Metropolis @altar.foundry( implements=altar.simulations.monitor, tip=\"a monitor that times the",
"it return Grid @altar.foundry( implements=sampler, tip=\"a Bayesian sampler based on the Metropolis algorithm\")",
"# attach its docstring __doc__ = Grid.__doc__ # and return it return Grid",
"def cov(): # grab the factory from .COV import COV # attach its",
"profiler(): # grab the factory from .Profiler import Profiler # attach its docstring",
"algorithm\") def metropolis(): # grab the factory from .Metropolis import Metropolis # attach",
"that times the various simulation phases\") def profiler(): # grab the factory from",
"from .Scheduler import Scheduler as scheduler from .Solver import Solver as solver #",
"Brent minimizer from gsl\") def brent(): # grab the factory from .Brent import",
".Controller import Controller as controller from .Sampler import Sampler as sampler from .Scheduler",
"# grab the factory from .Metropolis import Metropolis # attach its docstring __doc__",
"import Profiler # attach its docstring __doc__ = Profiler.__doc__ # and return it",
"factory from .Profiler import Profiler # attach its docstring __doc__ = Profiler.__doc__ #",
"# implementations @altar.foundry( implements=controller, tip=\"a Bayesian controller that implements simulated annealing\") def annealer():",
"from .Annealer import Annealer # attach its docstring __doc__ = Annealer.__doc__ # and",
"factory from .COV import COV # attach its docstring __doc__ = COV.__doc__ #",
"metropolis(): # grab the factory from .Metropolis import Metropolis # attach its docstring",
"and return it return COV @altar.foundry( implements=solver, tip=\"a solver for δβ based on",
"brent(): # grab the factory from .Brent import Brent # attach its docstring",
"and return it return Grid @altar.foundry( implements=sampler, tip=\"a Bayesian sampler based on the",
"it return Metropolis @altar.foundry( implements=altar.simulations.monitor, tip=\"a monitor that times the various simulation phases\")",
"implementations @altar.foundry( implements=controller, tip=\"a Bayesian controller that implements simulated annealing\") def annealer(): #",
"Controller as controller from .Sampler import Sampler as sampler from .Scheduler import Scheduler",
"import altar # and the protocols from .Controller import Controller as controller from",
"attach its docstring __doc__ = Grid.__doc__ # and return it return Grid @altar.foundry(",
"minimizer from gsl\") def brent(): # grab the factory from .Brent import Brent",
"def annealer(): # grab the factory from .Annealer import Annealer # attach its",
".Scheduler import Scheduler as scheduler from .Solver import Solver as solver # implementations",
"and return it return Brent @altar.foundry( implements=solver, tip=\"a solver for δβ based on",
"@altar.foundry( implements=solver, tip=\"a solver for δβ based on a naive grid search\") def",
"altar # and the protocols from .Controller import Controller as controller from .Sampler",
"import Scheduler as scheduler from .Solver import Solver as solver # implementations @altar.foundry(",
"that implements simulated annealing\") def annealer(): # grab the factory from .Annealer import",
"tip=\"a Bayesian scheduler based on the COV algorithm\") def cov(): # grab the",
"return Grid @altar.foundry( implements=sampler, tip=\"a Bayesian sampler based on the Metropolis algorithm\") def",
"# attach its docstring __doc__ = Annealer.__doc__ # and return it return Annealer",
"attach its docstring __doc__ = Annealer.__doc__ # and return it return Annealer @altar.foundry(",
".Brent import Brent # attach its docstring __doc__ = Brent.__doc__ # and return",
"# and return it return Brent @altar.foundry( implements=solver, tip=\"a solver for δβ based",
"Bayesian scheduler based on the COV algorithm\") def cov(): # grab the factory",
"from .Grid import Grid # attach its docstring __doc__ = Grid.__doc__ # and",
".Metropolis import Metropolis # attach its docstring __doc__ = Metropolis.__doc__ # and return",
"# (c) 2013-2020 parasim inc # (c) 2010-2020 california institute of technology #",
"return Metropolis @altar.foundry( implements=altar.simulations.monitor, tip=\"a monitor that times the various simulation phases\") def",
"coding: utf-8 -*- # # <NAME> <<EMAIL>> # # (c) 2013-2020 parasim inc",
"<NAME> <<EMAIL>> # # (c) 2013-2020 parasim inc # (c) 2010-2020 california institute",
"# grab the factory from .Annealer import Annealer # attach its docstring __doc__",
"return it return COV @altar.foundry( implements=solver, tip=\"a solver for δβ based on a",
"docstring __doc__ = Profiler.__doc__ # and return it return Profiler # end of",
"# and the protocols from .Controller import Controller as controller from .Sampler import",
"sampler from .Scheduler import Scheduler as scheduler from .Solver import Solver as solver",
".Grid import Grid # attach its docstring __doc__ = Grid.__doc__ # and return",
"return COV @altar.foundry( implements=solver, tip=\"a solver for δβ based on a Brent minimizer",
"COV.__doc__ # and return it return COV @altar.foundry( implements=solver, tip=\"a solver for δβ",
"COV # attach its docstring __doc__ = COV.__doc__ # and return it return",
"# grab the factory from .Profiler import Profiler # attach its docstring __doc__",
"all rights reserved # # the package import altar # and the protocols",
"# and return it return COV @altar.foundry( implements=solver, tip=\"a solver for δβ based",
"__doc__ = Profiler.__doc__ # and return it return Profiler # end of file",
"# # the package import altar # and the protocols from .Controller import",
"its docstring __doc__ = Annealer.__doc__ # and return it return Annealer @altar.foundry( implements=scheduler,",
"Brent # attach its docstring __doc__ = Brent.__doc__ # and return it return",
"a Brent minimizer from gsl\") def brent(): # grab the factory from .Brent",
"# # (c) 2013-2020 parasim inc # (c) 2010-2020 california institute of technology",
"attach its docstring __doc__ = COV.__doc__ # and return it return COV @altar.foundry(",
"implements=altar.simulations.monitor, tip=\"a monitor that times the various simulation phases\") def profiler(): # grab",
"from gsl\") def brent(): # grab the factory from .Brent import Brent #",
"# (c) 2010-2020 california institute of technology # all rights reserved # #",
"simulation phases\") def profiler(): # grab the factory from .Profiler import Profiler #",
"return Annealer @altar.foundry( implements=scheduler, tip=\"a Bayesian scheduler based on the COV algorithm\") def",
"-*- python -*- # -*- coding: utf-8 -*- # # <NAME> <<EMAIL>> #",
"institute of technology # all rights reserved # # the package import altar",
"based on the COV algorithm\") def cov(): # grab the factory from .COV",
"# grab the factory from .Brent import Brent # attach its docstring __doc__",
"as sampler from .Scheduler import Scheduler as scheduler from .Solver import Solver as",
"its docstring __doc__ = Grid.__doc__ # and return it return Grid @altar.foundry( implements=sampler,",
"python -*- # -*- coding: utf-8 -*- # # <NAME> <<EMAIL>> # #",
"from .Solver import Solver as solver # implementations @altar.foundry( implements=controller, tip=\"a Bayesian controller",
"a naive grid search\") def grid(): # grab the factory from .Grid import",
"algorithm\") def cov(): # grab the factory from .COV import COV # attach",
"tip=\"a Bayesian controller that implements simulated annealing\") def annealer(): # grab the factory",
"grab the factory from .Metropolis import Metropolis # attach its docstring __doc__ =",
"return Brent @altar.foundry( implements=solver, tip=\"a solver for δβ based on a naive grid",
"scheduler from .Solver import Solver as solver # implementations @altar.foundry( implements=controller, tip=\"a Bayesian",
"__doc__ = Annealer.__doc__ # and return it return Annealer @altar.foundry( implements=scheduler, tip=\"a Bayesian",
"@altar.foundry( implements=altar.simulations.monitor, tip=\"a monitor that times the various simulation phases\") def profiler(): #",
"grab the factory from .Profiler import Profiler # attach its docstring __doc__ =",
"as scheduler from .Solver import Solver as solver # implementations @altar.foundry( implements=controller, tip=\"a",
"def grid(): # grab the factory from .Grid import Grid # attach its",
"docstring __doc__ = Annealer.__doc__ # and return it return Annealer @altar.foundry( implements=scheduler, tip=\"a",
"return it return Grid @altar.foundry( implements=sampler, tip=\"a Bayesian sampler based on the Metropolis",
"from .Sampler import Sampler as sampler from .Scheduler import Scheduler as scheduler from",
"return it return Annealer @altar.foundry( implements=scheduler, tip=\"a Bayesian scheduler based on the COV",
"the factory from .Grid import Grid # attach its docstring __doc__ = Grid.__doc__",
"import Solver as solver # implementations @altar.foundry( implements=controller, tip=\"a Bayesian controller that implements",
"Metropolis.__doc__ # and return it return Metropolis @altar.foundry( implements=altar.simulations.monitor, tip=\"a monitor that times",
"Scheduler as scheduler from .Solver import Solver as solver # implementations @altar.foundry( implements=controller,",
"docstring __doc__ = Metropolis.__doc__ # and return it return Metropolis @altar.foundry( implements=altar.simulations.monitor, tip=\"a",
"Bayesian controller that implements simulated annealing\") def annealer(): # grab the factory from",
"factory from .Annealer import Annealer # attach its docstring __doc__ = Annealer.__doc__ #",
"-*- # # <NAME> <<EMAIL>> # # (c) 2013-2020 parasim inc # (c)",
"grab the factory from .Grid import Grid # attach its docstring __doc__ =",
"grab the factory from .COV import COV # attach its docstring __doc__ =",
"Metropolis # attach its docstring __doc__ = Metropolis.__doc__ # and return it return",
"2010-2020 california institute of technology # all rights reserved # # the package",
"attach its docstring __doc__ = Brent.__doc__ # and return it return Brent @altar.foundry(",
"# attach its docstring __doc__ = Brent.__doc__ # and return it return Brent",
"# and return it return Grid @altar.foundry( implements=sampler, tip=\"a Bayesian sampler based on",
"grid(): # grab the factory from .Grid import Grid # attach its docstring",
"__doc__ = Grid.__doc__ # and return it return Grid @altar.foundry( implements=sampler, tip=\"a Bayesian",
"@altar.foundry( implements=solver, tip=\"a solver for δβ based on a Brent minimizer from gsl\")",
"δβ based on a Brent minimizer from gsl\") def brent(): # grab the",
"the Metropolis algorithm\") def metropolis(): # grab the factory from .Metropolis import Metropolis",
"the protocols from .Controller import Controller as controller from .Sampler import Sampler as",
"the factory from .Profiler import Profiler # attach its docstring __doc__ = Profiler.__doc__",
"Solver as solver # implementations @altar.foundry( implements=controller, tip=\"a Bayesian controller that implements simulated",
"# all rights reserved # # the package import altar # and the",
"the factory from .Metropolis import Metropolis # attach its docstring __doc__ = Metropolis.__doc__",
"def metropolis(): # grab the factory from .Metropolis import Metropolis # attach its",
"simulated annealing\") def annealer(): # grab the factory from .Annealer import Annealer #",
"the factory from .Brent import Brent # attach its docstring __doc__ = Brent.__doc__",
"monitor that times the various simulation phases\") def profiler(): # grab the factory",
"# grab the factory from .Grid import Grid # attach its docstring __doc__",
"implements=sampler, tip=\"a Bayesian sampler based on the Metropolis algorithm\") def metropolis(): # grab",
"and return it return Metropolis @altar.foundry( implements=altar.simulations.monitor, tip=\"a monitor that times the various",
"return it return Brent @altar.foundry( implements=solver, tip=\"a solver for δβ based on a",
"the various simulation phases\") def profiler(): # grab the factory from .Profiler import",
"Sampler as sampler from .Scheduler import Scheduler as scheduler from .Solver import Solver",
"= Annealer.__doc__ # and return it return Annealer @altar.foundry( implements=scheduler, tip=\"a Bayesian scheduler",
"Metropolis @altar.foundry( implements=altar.simulations.monitor, tip=\"a monitor that times the various simulation phases\") def profiler():",
"times the various simulation phases\") def profiler(): # grab the factory from .Profiler",
"package import altar # and the protocols from .Controller import Controller as controller",
"technology # all rights reserved # # the package import altar # and",
"and return it return Annealer @altar.foundry( implements=scheduler, tip=\"a Bayesian scheduler based on the",
"import Sampler as sampler from .Scheduler import Scheduler as scheduler from .Solver import",
"-*- coding: utf-8 -*- # # <NAME> <<EMAIL>> # # (c) 2013-2020 parasim",
"gsl\") def brent(): # grab the factory from .Brent import Brent # attach",
"the COV algorithm\") def cov(): # grab the factory from .COV import COV",
"Annealer.__doc__ # and return it return Annealer @altar.foundry( implements=scheduler, tip=\"a Bayesian scheduler based",
"grid search\") def grid(): # grab the factory from .Grid import Grid #",
".COV import COV # attach its docstring __doc__ = COV.__doc__ # and return",
"it return Brent @altar.foundry( implements=solver, tip=\"a solver for δβ based on a naive",
"its docstring __doc__ = Profiler.__doc__ # and return it return Profiler # end",
"= Brent.__doc__ # and return it return Brent @altar.foundry( implements=solver, tip=\"a solver for",
"return it return Metropolis @altar.foundry( implements=altar.simulations.monitor, tip=\"a monitor that times the various simulation",
"solver # implementations @altar.foundry( implements=controller, tip=\"a Bayesian controller that implements simulated annealing\") def",
"on a naive grid search\") def grid(): # grab the factory from .Grid",
"protocols from .Controller import Controller as controller from .Sampler import Sampler as sampler",
"rights reserved # # the package import altar # and the protocols from",
"the package import altar # and the protocols from .Controller import Controller as",
"import Annealer # attach its docstring __doc__ = Annealer.__doc__ # and return it",
"implements=solver, tip=\"a solver for δβ based on a Brent minimizer from gsl\") def",
"Grid.__doc__ # and return it return Grid @altar.foundry( implements=sampler, tip=\"a Bayesian sampler based",
"sampler based on the Metropolis algorithm\") def metropolis(): # grab the factory from",
".Sampler import Sampler as sampler from .Scheduler import Scheduler as scheduler from .Solver",
"def brent(): # grab the factory from .Brent import Brent # attach its",
"implements simulated annealing\") def annealer(): # grab the factory from .Annealer import Annealer",
"tip=\"a monitor that times the various simulation phases\") def profiler(): # grab the",
"on a Brent minimizer from gsl\") def brent(): # grab the factory from",
"from .Brent import Brent # attach its docstring __doc__ = Brent.__doc__ # and",
"# -*- coding: utf-8 -*- # # <NAME> <<EMAIL>> # # (c) 2013-2020",
"__doc__ = Brent.__doc__ # and return it return Brent @altar.foundry( implements=solver, tip=\"a solver",
"(c) 2013-2020 parasim inc # (c) 2010-2020 california institute of technology # all",
"Grid # attach its docstring __doc__ = Grid.__doc__ # and return it return",
"tip=\"a solver for δβ based on a naive grid search\") def grid(): #",
"and the protocols from .Controller import Controller as controller from .Sampler import Sampler",
"implements=solver, tip=\"a solver for δβ based on a naive grid search\") def grid():",
"def profiler(): # grab the factory from .Profiler import Profiler # attach its",
"@altar.foundry( implements=scheduler, tip=\"a Bayesian scheduler based on the COV algorithm\") def cov(): #",
"naive grid search\") def grid(): # grab the factory from .Grid import Grid"
] |
[
"Raises: NotEnoughInputData: Not enough data for calculating the indicator. \"\"\" # Not enough",
"Calculates and returns the trading signal for the calculated technical indicator. Returns: {('hold',",
"for calculating the indicator. TypeError: Type error occurred when validating the ``input_data``. ValueError:",
"indicator. \"\"\" import pandas as pd from ._technical_indicator import TechnicalIndicator from ..utils.constants import",
"``pandas.DatetimeIndex``. It contains one column, the ``vosc``. _properties (dict): Indicator properties. _calling_instance (str):",
"Not enough data for calculating the indicator. TypeError: Type error occurred when validating",
"technical indicator. \"\"\" import pandas as pd from ._technical_indicator import TechnicalIndicator from ..utils.constants",
"validating the ``input_data``. ValueError: Value error occurred when validating the ``input_data``. \"\"\" def",
"'long_period', '>0') else: raise WrongTypeForInputParameter( type(long_period), 'long_period', 'int') if isinstance(short_period, int): if short_period",
"WrongValueForInputParameter( short_period, 'short_period', '>0') else: raise WrongTypeForInputParameter( type(short_period), 'short_period', 'int') if self._long_period <=",
"TRADE_SIGNALS from ..utils.exceptions import NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator): \"\"\" Volume Oscillator Technical",
"calculating the indicator. \"\"\" # Not enough data for the requested period if",
"len(self._ti_data.index) < 3: return TRADE_SIGNALS['hold'] if (0 < self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]):",
"import pandas as pd from ._technical_indicator import TechnicalIndicator from ..utils.constants import TRADE_SIGNALS from",
"super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values) def _calculateTi(self): \"\"\" Calculates the technical indicator for the given",
"class. Raises: WrongTypeForInputParameter: Input argument has wrong type. WrongValueForInputParameter: Unsupported value for input",
"len(self._input_data.index) < self._long_period: raise NotEnoughInputData('Volume Oscillator', self._long_period, len(self._input_data.index)) vosc = pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None,",
"'long_period', 'int') if isinstance(short_period, int): if short_period > 0: self._short_period = short_period else:",
"raise WrongValueForInputParameter( long_period, 'long_period ', '> short_period [' + str(self._short_period) + ']') #",
"('sell', 1)}: The calculated trading signal. \"\"\" # Not enough data for calculating",
"(bool, default=True): If set to True, missing values in the input data are",
"Index is of type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``. _properties (dict):",
"indicator. TypeError: Type error occurred when validating the ``input_data``. ValueError: Value error occurred",
"< self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3] > self._ti_data['vosc'].iat[-2] > self._ti_data['vosc'].iat[-1] >",
"error occurred when validating the ``input_data``. \"\"\" def __init__(self, input_data, long_period=5, short_period=2, fill_missing_values=True):",
"on=None, axis=0, closed=None).mean() return vosc.round(4) def getTiSignal(self): \"\"\" Calculates and returns the trading",
"pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None, dtype='float64') vosc['vosc'] = self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period, center=False, win_type=None, on=None, axis=0,",
"TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3] > self._ti_data['vosc'].iat[-2] > self._ti_data['vosc'].iat[-1] > 0): return TRADE_SIGNALS['sell'] return TRADE_SIGNALS['hold']",
"from ..utils.constants import TRADE_SIGNALS from ..utils.exceptions import NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator): \"\"\"",
"\"\"\" Calculates the technical indicator for the given input data. The input data",
"error occurred when validating the ``input_data``. ValueError: Value error occurred when validating the",
"the long moving average. short_period (int, default=2): The past periods to be used",
"input parameters if isinstance(long_period, int): if long_period > 0: self._long_period = long_period else:",
"the parent class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values) def _calculateTi(self): \"\"\" Calculates the technical indicator",
"filled. Attributes: _input_data (pandas.DataFrame): The ``input_data`` after preprocessing. _ti_data (pandas.DataFrame): The calculated indicator.",
"calculated technical indicator. Returns: {('hold', 0), ('buy', -1), ('sell', 1)}: The calculated trading",
"fill_missing_values (bool, default=True): If set to True, missing values in the input data",
"name: _volume_oscillator.py Implements the Volume Oscillator technical indicator. \"\"\" import pandas as pd",
"> 0: self._long_period = long_period else: raise WrongValueForInputParameter( long_period, 'long_period', '>0') else: raise",
"to the parent class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values) def _calculateTi(self): \"\"\" Calculates the technical",
"raise NotEnoughInputData('Volume Oscillator', self._long_period, len(self._input_data.index)) vosc = pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None, dtype='float64') vosc['vosc'] =",
"The index is of type ``pandas.DatetimeIndex``. long_period (int, default=5): The past periods to",
"Returns: pandas.DataFrame: The calculated indicator. Index is of type ``pandas.DatetimeIndex``. It contains one",
"_calculateTi(self): \"\"\" Calculates the technical indicator for the given input data. The input",
"the class. Raises: WrongTypeForInputParameter: Input argument has wrong type. WrongValueForInputParameter: Unsupported value for",
"and returns the trading signal for the calculated technical indicator. Returns: {('hold', 0),",
"(pandas.DataFrame): The calculated indicator. Index is of type ``pandas.DatetimeIndex``. It contains one column,",
"..utils.constants import TRADE_SIGNALS from ..utils.exceptions import NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator): \"\"\" Volume",
"used for the calculation of the long moving average. short_period (int, default=2): The",
"validating the ``input_data``. \"\"\" def __init__(self, input_data, long_period=5, short_period=2, fill_missing_values=True): # Validate and",
"the ``vosc``. Raises: NotEnoughInputData: Not enough data for calculating the indicator. \"\"\" #",
"if (0 < self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3] >",
"0), ('buy', -1), ('sell', 1)}: The calculated trading signal. \"\"\" # Not enough",
"_input_data (pandas.DataFrame): The ``input_data`` after preprocessing. _ti_data (pandas.DataFrame): The calculated indicator. Index is",
"+ str(self._short_period) + ']') # Control is passing to the parent class super().__init__(calling_instance=self.__class__.__name__,",
"Oscillator technical indicator. \"\"\" import pandas as pd from ._technical_indicator import TechnicalIndicator from",
"data for calculating the indicator. TypeError: Type error occurred when validating the ``input_data``.",
"the calculated technical indicator. Returns: {('hold', 0), ('buy', -1), ('sell', 1)}: The calculated",
"win_type=None, on=None, axis=0, closed=None).mean() return vosc.round(4) def getTiSignal(self): \"\"\" Calculates and returns the",
"average. short_period (int, default=2): The past periods to be used for the calculation",
"from an attribute of the parent class. Returns: pandas.DataFrame: The calculated indicator. Index",
"from ..utils.exceptions import NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator): \"\"\" Volume Oscillator Technical Indicator",
"data. The input data are taken from an attribute of the parent class.",
"Control is passing to the parent class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values) def _calculateTi(self): \"\"\"",
"of the parent class. Returns: pandas.DataFrame: The calculated indicator. Index is of type",
"column, the ``vosc``. _properties (dict): Indicator properties. _calling_instance (str): The name of the",
"to True, missing values in the input data are being filled. Attributes: _input_data",
"self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3] > self._ti_data['vosc'].iat[-2] > self._ti_data['vosc'].iat[-1] > 0):",
"parent class. Returns: pandas.DataFrame: The calculated indicator. Index is of type ``pandas.DatetimeIndex``. It",
"type. WrongValueForInputParameter: Unsupported value for input argument. NotEnoughInputData: Not enough data for calculating",
"isinstance(long_period, int): if long_period > 0: self._long_period = long_period else: raise WrongValueForInputParameter( long_period,",
"column, the ``vosc``. Raises: NotEnoughInputData: Not enough data for calculating the indicator. \"\"\"",
"closed=None ).mean() - self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period, center=False, win_type=None, on=None, axis=0, closed=None).mean() return vosc.round(4)",
"Implements the Volume Oscillator technical indicator. \"\"\" import pandas as pd from ._technical_indicator",
"else: raise WrongTypeForInputParameter( type(long_period), 'long_period', 'int') if isinstance(short_period, int): if short_period > 0:",
"the short moving average. fill_missing_values (bool, default=True): If set to True, missing values",
"calculation of the long moving average. short_period (int, default=2): The past periods to",
"the requested period if len(self._input_data.index) < self._long_period: raise NotEnoughInputData('Volume Oscillator', self._long_period, len(self._input_data.index)) vosc",
"python library File name: _volume_oscillator.py Implements the Volume Oscillator technical indicator. \"\"\" import",
"given input data. The input data are taken from an attribute of the",
"short moving average. fill_missing_values (bool, default=True): If set to True, missing values in",
"``input_data``. \"\"\" def __init__(self, input_data, long_period=5, short_period=2, fill_missing_values=True): # Validate and store if",
"WrongTypeForInputParameter( type(short_period), 'short_period', 'int') if self._long_period <= self._short_period: raise WrongValueForInputParameter( long_period, 'long_period ',",
"values in the input data are being filled. Attributes: _input_data (pandas.DataFrame): The ``input_data``",
"def getTiSignal(self): \"\"\" Calculates and returns the trading signal for the calculated technical",
"long moving average. short_period (int, default=2): The past periods to be used for",
"WrongTypeForInputParameter( type(long_period), 'long_period', 'int') if isinstance(short_period, int): if short_period > 0: self._short_period =",
"< self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3] > self._ti_data['vosc'].iat[-2] >",
"axis=0, closed=None ).mean() - self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period, center=False, win_type=None, on=None, axis=0, closed=None).mean() return",
"long_period > 0: self._long_period = long_period else: raise WrongValueForInputParameter( long_period, 'long_period', '>0') else:",
"vosc.round(4) def getTiSignal(self): \"\"\" Calculates and returns the trading signal for the calculated",
"taken from an attribute of the parent class. Returns: pandas.DataFrame: The calculated indicator.",
"input data are being filled. Attributes: _input_data (pandas.DataFrame): The ``input_data`` after preprocessing. _ti_data",
"periods to be used for the calculation of the short moving average. fill_missing_values",
"Raises: WrongTypeForInputParameter: Input argument has wrong type. WrongValueForInputParameter: Unsupported value for input argument.",
"enough data for calculating trading signal if len(self._ti_data.index) < 3: return TRADE_SIGNALS['hold'] if",
"for the requested period if len(self._input_data.index) < self._long_period: raise NotEnoughInputData('Volume Oscillator', self._long_period, len(self._input_data.index))",
"The past periods to be used for the calculation of the long moving",
"are being filled. Attributes: _input_data (pandas.DataFrame): The ``input_data`` after preprocessing. _ti_data (pandas.DataFrame): The",
"\"\"\" def __init__(self, input_data, long_period=5, short_period=2, fill_missing_values=True): # Validate and store if needed,",
"the indicator. \"\"\" # Not enough data for the requested period if len(self._input_data.index)",
"NotEnoughInputData('Volume Oscillator', self._long_period, len(self._input_data.index)) vosc = pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None, dtype='float64') vosc['vosc'] = self._input_data['volume'].rolling(",
"the trading signal for the calculated technical indicator. Returns: {('hold', 0), ('buy', -1),",
"self._short_period = short_period else: raise WrongValueForInputParameter( short_period, 'short_period', '>0') else: raise WrongTypeForInputParameter( type(short_period),",
"indicator. Index is of type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``. _properties",
"input data. The input data are taken from an attribute of the parent",
"calculating trading signal if len(self._ti_data.index) < 3: return TRADE_SIGNALS['hold'] if (0 < self._ti_data['vosc'].iat[-3]",
"{('hold', 0), ('buy', -1), ('sell', 1)}: The calculated trading signal. \"\"\" # Not",
"the calculation of the short moving average. fill_missing_values (bool, default=True): If set to",
"import TRADE_SIGNALS from ..utils.exceptions import NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator): \"\"\" Volume Oscillator",
"average. fill_missing_values (bool, default=True): If set to True, missing values in the input",
"default=2): The past periods to be used for the calculation of the short",
"def __init__(self, input_data, long_period=5, short_period=2, fill_missing_values=True): # Validate and store if needed, the",
"columns=['vosc'], data=None, dtype='float64') vosc['vosc'] = self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period, center=False, win_type=None, on=None, axis=0, closed=None",
"Index is of type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``. Raises: NotEnoughInputData:",
"raise WrongTypeForInputParameter( type(long_period), 'long_period', 'int') if isinstance(short_period, int): if short_period > 0: self._short_period",
"- self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period, center=False, win_type=None, on=None, axis=0, closed=None).mean() return vosc.round(4) def getTiSignal(self):",
"0: self._long_period = long_period else: raise WrongValueForInputParameter( long_period, 'long_period', '>0') else: raise WrongTypeForInputParameter(",
"for the calculated technical indicator. Returns: {('hold', 0), ('buy', -1), ('sell', 1)}: The",
"to be used for the calculation of the short moving average. fill_missing_values (bool,",
"input data are taken from an attribute of the parent class. Returns: pandas.DataFrame:",
"on=None, axis=0, closed=None ).mean() - self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period, center=False, win_type=None, on=None, axis=0, closed=None).mean()",
"signal if len(self._ti_data.index) < 3: return TRADE_SIGNALS['hold'] if (0 < self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2]",
"return TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3] > self._ti_data['vosc'].iat[-2] > self._ti_data['vosc'].iat[-1] > 0): return TRADE_SIGNALS['sell'] return",
"periods to be used for the calculation of the long moving average. short_period",
"# Control is passing to the parent class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values) def _calculateTi(self):",
"Required input column is ``volume``. The index is of type ``pandas.DatetimeIndex``. long_period (int,",
"``vosc``. Raises: NotEnoughInputData: Not enough data for calculating the indicator. \"\"\" # Not",
"and store if needed, the input parameters if isinstance(long_period, int): if long_period >",
"raise WrongTypeForInputParameter( type(short_period), 'short_period', 'int') if self._long_period <= self._short_period: raise WrongValueForInputParameter( long_period, 'long_period",
"of type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``. Raises: NotEnoughInputData: Not enough",
"axis=0, closed=None).mean() return vosc.round(4) def getTiSignal(self): \"\"\" Calculates and returns the trading signal",
"short_period (int, default=2): The past periods to be used for the calculation of",
"indicator. Returns: {('hold', 0), ('buy', -1), ('sell', 1)}: The calculated trading signal. \"\"\"",
"(0 < self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3] > self._ti_data['vosc'].iat[-2]",
"<= self._short_period: raise WrongValueForInputParameter( long_period, 'long_period ', '> short_period [' + str(self._short_period) +",
"NotEnoughInputData: Not enough data for calculating the indicator. \"\"\" # Not enough data",
"Volume Oscillator technical indicator. \"\"\" import pandas as pd from ._technical_indicator import TechnicalIndicator",
"'short_period', '>0') else: raise WrongTypeForInputParameter( type(short_period), 'short_period', 'int') if self._long_period <= self._short_period: raise",
"data are taken from an attribute of the parent class. Returns: pandas.DataFrame: The",
"min_periods=self._short_period, center=False, win_type=None, on=None, axis=0, closed=None ).mean() - self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period, center=False, win_type=None,",
"after preprocessing. _ti_data (pandas.DataFrame): The calculated indicator. Index is of type ``pandas.DatetimeIndex``. It",
"dtype='float64') vosc['vosc'] = self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period, center=False, win_type=None, on=None, axis=0, closed=None ).mean() -",
"when validating the ``input_data``. ValueError: Value error occurred when validating the ``input_data``. \"\"\"",
"def _calculateTi(self): \"\"\" Calculates the technical indicator for the given input data. The",
"past periods to be used for the calculation of the long moving average.",
"trading signal for the calculated technical indicator. Returns: {('hold', 0), ('buy', -1), ('sell',",
"from ._technical_indicator import TechnicalIndicator from ..utils.constants import TRADE_SIGNALS from ..utils.exceptions import NotEnoughInputData, WrongTypeForInputParameter,\\",
"Type error occurred when validating the ``input_data``. ValueError: Value error occurred when validating",
"parent class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values) def _calculateTi(self): \"\"\" Calculates the technical indicator for",
"Not enough data for the requested period if len(self._input_data.index) < self._long_period: raise NotEnoughInputData('Volume",
"raise WrongValueForInputParameter( long_period, 'long_period', '>0') else: raise WrongTypeForInputParameter( type(long_period), 'long_period', 'int') if isinstance(short_period,",
"= long_period else: raise WrongValueForInputParameter( long_period, 'long_period', '>0') else: raise WrongTypeForInputParameter( type(long_period), 'long_period',",
"> 0: self._short_period = short_period else: raise WrongValueForInputParameter( short_period, 'short_period', '>0') else: raise",
"the indicator. TypeError: Type error occurred when validating the ``input_data``. ValueError: Value error",
"self._long_period <= self._short_period: raise WrongValueForInputParameter( long_period, 'long_period ', '> short_period [' + str(self._short_period)",
"self._long_period, len(self._input_data.index)) vosc = pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None, dtype='float64') vosc['vosc'] = self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period,",
"< 3: return TRADE_SIGNALS['hold'] if (0 < self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]): return",
"moving average. fill_missing_values (bool, default=True): If set to True, missing values in the",
"``pandas.DatetimeIndex``. long_period (int, default=5): The past periods to be used for the calculation",
"_properties (dict): Indicator properties. _calling_instance (str): The name of the class. Raises: WrongTypeForInputParameter:",
"name of the class. Raises: WrongTypeForInputParameter: Input argument has wrong type. WrongValueForInputParameter: Unsupported",
"VolumeOscillator(TechnicalIndicator): \"\"\" Volume Oscillator Technical Indicator class implementation. Args: input_data (pandas.DataFrame): The input",
"# Validate and store if needed, the input parameters if isinstance(long_period, int): if",
"_calling_instance (str): The name of the class. Raises: WrongTypeForInputParameter: Input argument has wrong",
"index is of type ``pandas.DatetimeIndex``. long_period (int, default=5): The past periods to be",
"is of type ``pandas.DatetimeIndex``. long_period (int, default=5): The past periods to be used",
"contains one column, the ``vosc``. Raises: NotEnoughInputData: Not enough data for calculating the",
"import TechnicalIndicator from ..utils.constants import TRADE_SIGNALS from ..utils.exceptions import NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter class",
"``input_data`` after preprocessing. _ti_data (pandas.DataFrame): The calculated indicator. Index is of type ``pandas.DatetimeIndex``.",
"'>0') else: raise WrongTypeForInputParameter( type(short_period), 'short_period', 'int') if self._long_period <= self._short_period: raise WrongValueForInputParameter(",
"__init__(self, input_data, long_period=5, short_period=2, fill_missing_values=True): # Validate and store if needed, the input",
"< self._long_period: raise NotEnoughInputData('Volume Oscillator', self._long_period, len(self._input_data.index)) vosc = pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None, dtype='float64')",
"Attributes: _input_data (pandas.DataFrame): The ``input_data`` after preprocessing. _ti_data (pandas.DataFrame): The calculated indicator. Index",
"as pd from ._technical_indicator import TechnicalIndicator from ..utils.constants import TRADE_SIGNALS from ..utils.exceptions import",
"has wrong type. WrongValueForInputParameter: Unsupported value for input argument. NotEnoughInputData: Not enough data",
"enough data for calculating the indicator. \"\"\" # Not enough data for the",
"'int') if isinstance(short_period, int): if short_period > 0: self._short_period = short_period else: raise",
"attribute of the parent class. Returns: pandas.DataFrame: The calculated indicator. Index is of",
"needed, the input parameters if isinstance(long_period, int): if long_period > 0: self._long_period =",
"'short_period', 'int') if self._long_period <= self._short_period: raise WrongValueForInputParameter( long_period, 'long_period ', '> short_period",
"Oscillator Technical Indicator class implementation. Args: input_data (pandas.DataFrame): The input data. Required input",
"If set to True, missing values in the input data are being filled.",
"else: raise WrongValueForInputParameter( short_period, 'short_period', '>0') else: raise WrongTypeForInputParameter( type(short_period), 'short_period', 'int') if",
"value for input argument. NotEnoughInputData: Not enough data for calculating the indicator. TypeError:",
"self._long_period: raise NotEnoughInputData('Volume Oscillator', self._long_period, len(self._input_data.index)) vosc = pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None, dtype='float64') vosc['vosc']",
"The calculated trading signal. \"\"\" # Not enough data for calculating trading signal",
"argument. NotEnoughInputData: Not enough data for calculating the indicator. TypeError: Type error occurred",
"0: self._short_period = short_period else: raise WrongValueForInputParameter( short_period, 'short_period', '>0') else: raise WrongTypeForInputParameter(",
"past periods to be used for the calculation of the short moving average.",
"TypeError: Type error occurred when validating the ``input_data``. ValueError: Value error occurred when",
"in the input data are being filled. Attributes: _input_data (pandas.DataFrame): The ``input_data`` after",
"for calculating trading signal if len(self._ti_data.index) < 3: return TRADE_SIGNALS['hold'] if (0 <",
"The name of the class. Raises: WrongTypeForInputParameter: Input argument has wrong type. WrongValueForInputParameter:",
"# Not enough data for the requested period if len(self._input_data.index) < self._long_period: raise",
"self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period, center=False, win_type=None, on=None, axis=0, closed=None ).mean() - self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period,",
"the given input data. The input data are taken from an attribute of",
"('buy', -1), ('sell', 1)}: The calculated trading signal. \"\"\" # Not enough data",
"input argument. NotEnoughInputData: Not enough data for calculating the indicator. TypeError: Type error",
"Input argument has wrong type. WrongValueForInputParameter: Unsupported value for input argument. NotEnoughInputData: Not",
"window=self._long_period, min_periods=self._long_period, center=False, win_type=None, on=None, axis=0, closed=None).mean() return vosc.round(4) def getTiSignal(self): \"\"\" Calculates",
"(tti) python library File name: _volume_oscillator.py Implements the Volume Oscillator technical indicator. \"\"\"",
"[' + str(self._short_period) + ']') # Control is passing to the parent class",
"_ti_data (pandas.DataFrame): The calculated indicator. Index is of type ``pandas.DatetimeIndex``. It contains one",
"Validate and store if needed, the input parameters if isinstance(long_period, int): if long_period",
"Unsupported value for input argument. NotEnoughInputData: Not enough data for calculating the indicator.",
"one column, the ``vosc``. Raises: NotEnoughInputData: Not enough data for calculating the indicator.",
"._technical_indicator import TechnicalIndicator from ..utils.constants import TRADE_SIGNALS from ..utils.exceptions import NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter",
"is of type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``. _properties (dict): Indicator",
"of the long moving average. short_period (int, default=2): The past periods to be",
"self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3] > self._ti_data['vosc'].iat[-2] > self._ti_data['vosc'].iat[-1] > 0): return TRADE_SIGNALS['sell']",
"short_period else: raise WrongValueForInputParameter( short_period, 'short_period', '>0') else: raise WrongTypeForInputParameter( type(short_period), 'short_period', 'int')",
"one column, the ``vosc``. _properties (dict): Indicator properties. _calling_instance (str): The name of",
"of the class. Raises: WrongTypeForInputParameter: Input argument has wrong type. WrongValueForInputParameter: Unsupported value",
"It contains one column, the ``vosc``. _properties (dict): Indicator properties. _calling_instance (str): The",
"Oscillator', self._long_period, len(self._input_data.index)) vosc = pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None, dtype='float64') vosc['vosc'] = self._input_data['volume'].rolling( window=self._short_period,",
"TechnicalIndicator from ..utils.constants import TRADE_SIGNALS from ..utils.exceptions import NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator):",
"if isinstance(short_period, int): if short_period > 0: self._short_period = short_period else: raise WrongValueForInputParameter(",
"data for calculating the indicator. \"\"\" # Not enough data for the requested",
"occurred when validating the ``input_data``. ValueError: Value error occurred when validating the ``input_data``.",
"to be used for the calculation of the long moving average. short_period (int,",
"raise WrongValueForInputParameter( short_period, 'short_period', '>0') else: raise WrongTypeForInputParameter( type(short_period), 'short_period', 'int') if self._long_period",
"argument has wrong type. WrongValueForInputParameter: Unsupported value for input argument. NotEnoughInputData: Not enough",
"calculation of the short moving average. fill_missing_values (bool, default=True): If set to True,",
"returns the trading signal for the calculated technical indicator. Returns: {('hold', 0), ('buy',",
"\"\"\" Trading-Technical-Indicators (tti) python library File name: _volume_oscillator.py Implements the Volume Oscillator technical",
"implementation. Args: input_data (pandas.DataFrame): The input data. Required input column is ``volume``. The",
"contains one column, the ``vosc``. _properties (dict): Indicator properties. _calling_instance (str): The name",
"an attribute of the parent class. Returns: pandas.DataFrame: The calculated indicator. Index is",
"NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator): \"\"\" Volume Oscillator Technical Indicator class implementation. Args:",
"= pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None, dtype='float64') vosc['vosc'] = self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period, center=False, win_type=None, on=None,",
"type(long_period), 'long_period', 'int') if isinstance(short_period, int): if short_period > 0: self._short_period = short_period",
"moving average. short_period (int, default=2): The past periods to be used for the",
"fill_missing_values=True): # Validate and store if needed, the input parameters if isinstance(long_period, int):",
"library File name: _volume_oscillator.py Implements the Volume Oscillator technical indicator. \"\"\" import pandas",
"The calculated indicator. Index is of type ``pandas.DatetimeIndex``. It contains one column, the",
"Indicator class implementation. Args: input_data (pandas.DataFrame): The input data. Required input column is",
"long_period, 'long_period', '>0') else: raise WrongTypeForInputParameter( type(long_period), 'long_period', 'int') if isinstance(short_period, int): if",
"for input argument. NotEnoughInputData: Not enough data for calculating the indicator. TypeError: Type",
"calculated indicator. Index is of type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``.",
"-1), ('sell', 1)}: The calculated trading signal. \"\"\" # Not enough data for",
"Returns: {('hold', 0), ('buy', -1), ('sell', 1)}: The calculated trading signal. \"\"\" #",
"for the calculation of the short moving average. fill_missing_values (bool, default=True): If set",
"are taken from an attribute of the parent class. Returns: pandas.DataFrame: The calculated",
"(str): The name of the class. Raises: WrongTypeForInputParameter: Input argument has wrong type.",
"(int, default=5): The past periods to be used for the calculation of the",
"File name: _volume_oscillator.py Implements the Volume Oscillator technical indicator. \"\"\" import pandas as",
"the ``input_data``. ValueError: Value error occurred when validating the ``input_data``. \"\"\" def __init__(self,",
"len(self._input_data.index)) vosc = pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None, dtype='float64') vosc['vosc'] = self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period, center=False,",
"\"\"\" Volume Oscillator Technical Indicator class implementation. Args: input_data (pandas.DataFrame): The input data.",
"of type ``pandas.DatetimeIndex``. long_period (int, default=5): The past periods to be used for",
"import NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator): \"\"\" Volume Oscillator Technical Indicator class implementation.",
"type(short_period), 'short_period', 'int') if self._long_period <= self._short_period: raise WrongValueForInputParameter( long_period, 'long_period ', '>",
"set to True, missing values in the input data are being filled. Attributes:",
"WrongValueForInputParameter( long_period, 'long_period ', '> short_period [' + str(self._short_period) + ']') # Control",
"indicator for the given input data. The input data are taken from an",
"(pandas.DataFrame): The input data. Required input column is ``volume``. The index is of",
"the input data are being filled. Attributes: _input_data (pandas.DataFrame): The ``input_data`` after preprocessing.",
"``volume``. The index is of type ``pandas.DatetimeIndex``. long_period (int, default=5): The past periods",
"properties. _calling_instance (str): The name of the class. Raises: WrongTypeForInputParameter: Input argument has",
"class. Returns: pandas.DataFrame: The calculated indicator. Index is of type ``pandas.DatetimeIndex``. It contains",
"``pandas.DatetimeIndex``. It contains one column, the ``vosc``. Raises: NotEnoughInputData: Not enough data for",
"be used for the calculation of the short moving average. fill_missing_values (bool, default=True):",
"when validating the ``input_data``. \"\"\" def __init__(self, input_data, long_period=5, short_period=2, fill_missing_values=True): # Validate",
"data. Required input column is ``volume``. The index is of type ``pandas.DatetimeIndex``. long_period",
"(int, default=2): The past periods to be used for the calculation of the",
"The past periods to be used for the calculation of the short moving",
"']') # Control is passing to the parent class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values) def",
"input data. Required input column is ``volume``. The index is of type ``pandas.DatetimeIndex``.",
"long_period, 'long_period ', '> short_period [' + str(self._short_period) + ']') # Control is",
"The input data are taken from an attribute of the parent class. Returns:",
"pd from ._technical_indicator import TechnicalIndicator from ..utils.constants import TRADE_SIGNALS from ..utils.exceptions import NotEnoughInputData,",
"1)}: The calculated trading signal. \"\"\" # Not enough data for calculating trading",
"return TRADE_SIGNALS['hold'] if (0 < self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy'] if",
"for the given input data. The input data are taken from an attribute",
"NotEnoughInputData: Not enough data for calculating the indicator. TypeError: Type error occurred when",
"being filled. Attributes: _input_data (pandas.DataFrame): The ``input_data`` after preprocessing. _ti_data (pandas.DataFrame): The calculated",
"return vosc.round(4) def getTiSignal(self): \"\"\" Calculates and returns the trading signal for the",
"vosc = pd.DataFrame(index=self._input_data.index, columns=['vosc'], data=None, dtype='float64') vosc['vosc'] = self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period, center=False, win_type=None,",
"= self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period, center=False, win_type=None, on=None, axis=0, closed=None ).mean() - self._input_data['volume'].rolling( window=self._long_period,",
"default=True): If set to True, missing values in the input data are being",
"(pandas.DataFrame): The ``input_data`` after preprocessing. _ti_data (pandas.DataFrame): The calculated indicator. Index is of",
"parameters if isinstance(long_period, int): if long_period > 0: self._long_period = long_period else: raise",
"\"\"\" # Not enough data for the requested period if len(self._input_data.index) < self._long_period:",
"the Volume Oscillator technical indicator. \"\"\" import pandas as pd from ._technical_indicator import",
"occurred when validating the ``input_data``. \"\"\" def __init__(self, input_data, long_period=5, short_period=2, fill_missing_values=True): #",
"pandas as pd from ._technical_indicator import TechnicalIndicator from ..utils.constants import TRADE_SIGNALS from ..utils.exceptions",
"column is ``volume``. The index is of type ``pandas.DatetimeIndex``. long_period (int, default=5): The",
").mean() - self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period, center=False, win_type=None, on=None, axis=0, closed=None).mean() return vosc.round(4) def",
"vosc['vosc'] = self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period, center=False, win_type=None, on=None, axis=0, closed=None ).mean() - self._input_data['volume'].rolling(",
"'>0') else: raise WrongTypeForInputParameter( type(long_period), 'long_period', 'int') if isinstance(short_period, int): if short_period >",
"True, missing values in the input data are being filled. Attributes: _input_data (pandas.DataFrame):",
"``input_data``. ValueError: Value error occurred when validating the ``input_data``. \"\"\" def __init__(self, input_data,",
"data are being filled. Attributes: _input_data (pandas.DataFrame): The ``input_data`` after preprocessing. _ti_data (pandas.DataFrame):",
"of type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``. _properties (dict): Indicator properties.",
"store if needed, the input parameters if isinstance(long_period, int): if long_period > 0:",
"WrongTypeForInputParameter: Input argument has wrong type. WrongValueForInputParameter: Unsupported value for input argument. NotEnoughInputData:",
"indicator. \"\"\" # Not enough data for the requested period if len(self._input_data.index) <",
"TRADE_SIGNALS['hold'] if (0 < self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3]",
"# Not enough data for calculating trading signal if len(self._ti_data.index) < 3: return",
"int): if long_period > 0: self._long_period = long_period else: raise WrongValueForInputParameter( long_period, 'long_period',",
"\"\"\" Calculates and returns the trading signal for the calculated technical indicator. Returns:",
"calculated trading signal. \"\"\" # Not enough data for calculating trading signal if",
"short_period > 0: self._short_period = short_period else: raise WrongValueForInputParameter( short_period, 'short_period', '>0') else:",
"Calculates the technical indicator for the given input data. The input data are",
"period if len(self._input_data.index) < self._long_period: raise NotEnoughInputData('Volume Oscillator', self._long_period, len(self._input_data.index)) vosc = pd.DataFrame(index=self._input_data.index,",
"fill_missing_values=fill_missing_values) def _calculateTi(self): \"\"\" Calculates the technical indicator for the given input data.",
"if len(self._input_data.index) < self._long_period: raise NotEnoughInputData('Volume Oscillator', self._long_period, len(self._input_data.index)) vosc = pd.DataFrame(index=self._input_data.index, columns=['vosc'],",
"_volume_oscillator.py Implements the Volume Oscillator technical indicator. \"\"\" import pandas as pd from",
"Not enough data for calculating the indicator. \"\"\" # Not enough data for",
"center=False, win_type=None, on=None, axis=0, closed=None ).mean() - self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period, center=False, win_type=None, on=None,",
"is ``volume``. The index is of type ``pandas.DatetimeIndex``. long_period (int, default=5): The past",
"technical indicator for the given input data. The input data are taken from",
"calculating the indicator. TypeError: Type error occurred when validating the ``input_data``. ValueError: Value",
"trading signal if len(self._ti_data.index) < 3: return TRADE_SIGNALS['hold'] if (0 < self._ti_data['vosc'].iat[-3] <",
"Trading-Technical-Indicators (tti) python library File name: _volume_oscillator.py Implements the Volume Oscillator technical indicator.",
"input_data (pandas.DataFrame): The input data. Required input column is ``volume``. The index is",
"signal for the calculated technical indicator. Returns: {('hold', 0), ('buy', -1), ('sell', 1)}:",
"isinstance(short_period, int): if short_period > 0: self._short_period = short_period else: raise WrongValueForInputParameter( short_period,",
"the parent class. Returns: pandas.DataFrame: The calculated indicator. Index is of type ``pandas.DatetimeIndex``.",
"WrongTypeForInputParameter,\\ WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator): \"\"\" Volume Oscillator Technical Indicator class implementation. Args: input_data",
"short_period [' + str(self._short_period) + ']') # Control is passing to the parent",
"input_data=input_data, fill_missing_values=fill_missing_values) def _calculateTi(self): \"\"\" Calculates the technical indicator for the given input",
"WrongValueForInputParameter: Unsupported value for input argument. NotEnoughInputData: Not enough data for calculating the",
"short_period=2, fill_missing_values=True): # Validate and store if needed, the input parameters if isinstance(long_period,",
"type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``. Raises: NotEnoughInputData: Not enough data",
"(dict): Indicator properties. _calling_instance (str): The name of the class. Raises: WrongTypeForInputParameter: Input",
"short_period, 'short_period', '>0') else: raise WrongTypeForInputParameter( type(short_period), 'short_period', 'int') if self._long_period <= self._short_period:",
"..utils.exceptions import NotEnoughInputData, WrongTypeForInputParameter,\\ WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator): \"\"\" Volume Oscillator Technical Indicator class",
"technical indicator. Returns: {('hold', 0), ('buy', -1), ('sell', 1)}: The calculated trading signal.",
"'int') if self._long_period <= self._short_period: raise WrongValueForInputParameter( long_period, 'long_period ', '> short_period ['",
"else: raise WrongValueForInputParameter( long_period, 'long_period', '>0') else: raise WrongTypeForInputParameter( type(long_period), 'long_period', 'int') if",
"wrong type. WrongValueForInputParameter: Unsupported value for input argument. NotEnoughInputData: Not enough data for",
"preprocessing. _ti_data (pandas.DataFrame): The calculated indicator. Index is of type ``pandas.DatetimeIndex``. It contains",
"is of type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``. Raises: NotEnoughInputData: Not",
"if len(self._ti_data.index) < 3: return TRADE_SIGNALS['hold'] if (0 < self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2] <",
"self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period, center=False, win_type=None, on=None, axis=0, closed=None).mean() return vosc.round(4) def getTiSignal(self): \"\"\"",
"the technical indicator for the given input data. The input data are taken",
"the ``input_data``. \"\"\" def __init__(self, input_data, long_period=5, short_period=2, fill_missing_values=True): # Validate and store",
"used for the calculation of the short moving average. fill_missing_values (bool, default=True): If",
"requested period if len(self._input_data.index) < self._long_period: raise NotEnoughInputData('Volume Oscillator', self._long_period, len(self._input_data.index)) vosc =",
"data for the requested period if len(self._input_data.index) < self._long_period: raise NotEnoughInputData('Volume Oscillator', self._long_period,",
"win_type=None, on=None, axis=0, closed=None ).mean() - self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period, center=False, win_type=None, on=None, axis=0,",
"+ ']') # Control is passing to the parent class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values)",
"ValueError: Value error occurred when validating the ``input_data``. \"\"\" def __init__(self, input_data, long_period=5,",
"long_period else: raise WrongValueForInputParameter( long_period, 'long_period', '>0') else: raise WrongTypeForInputParameter( type(long_period), 'long_period', 'int')",
"Technical Indicator class implementation. Args: input_data (pandas.DataFrame): The input data. Required input column",
"indicator. Index is of type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``. Raises:",
"the input parameters if isinstance(long_period, int): if long_period > 0: self._long_period = long_period",
"getTiSignal(self): \"\"\" Calculates and returns the trading signal for the calculated technical indicator.",
"if short_period > 0: self._short_period = short_period else: raise WrongValueForInputParameter( short_period, 'short_period', '>0')",
"if needed, the input parameters if isinstance(long_period, int): if long_period > 0: self._long_period",
"\"\"\" # Not enough data for calculating trading signal if len(self._ti_data.index) < 3:",
"input_data, long_period=5, short_period=2, fill_missing_values=True): # Validate and store if needed, the input parameters",
"for calculating the indicator. \"\"\" # Not enough data for the requested period",
"class implementation. Args: input_data (pandas.DataFrame): The input data. Required input column is ``volume``.",
"The input data. Required input column is ``volume``. The index is of type",
"int): if short_period > 0: self._short_period = short_period else: raise WrongValueForInputParameter( short_period, 'short_period',",
"be used for the calculation of the long moving average. short_period (int, default=2):",
"str(self._short_period) + ']') # Control is passing to the parent class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data,",
"\"\"\" import pandas as pd from ._technical_indicator import TechnicalIndicator from ..utils.constants import TRADE_SIGNALS",
"type ``pandas.DatetimeIndex``. long_period (int, default=5): The past periods to be used for the",
"self._short_period: raise WrongValueForInputParameter( long_period, 'long_period ', '> short_period [' + str(self._short_period) + ']')",
"WrongValueForInputParameter( long_period, 'long_period', '>0') else: raise WrongTypeForInputParameter( type(long_period), 'long_period', 'int') if isinstance(short_period, int):",
"Volume Oscillator Technical Indicator class implementation. Args: input_data (pandas.DataFrame): The input data. Required",
"self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3] > self._ti_data['vosc'].iat[-2] > self._ti_data['vosc'].iat[-1]",
"center=False, win_type=None, on=None, axis=0, closed=None).mean() return vosc.round(4) def getTiSignal(self): \"\"\" Calculates and returns",
"The ``input_data`` after preprocessing. _ti_data (pandas.DataFrame): The calculated indicator. Index is of type",
"the ``vosc``. _properties (dict): Indicator properties. _calling_instance (str): The name of the class.",
"passing to the parent class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values) def _calculateTi(self): \"\"\" Calculates the",
"'> short_period [' + str(self._short_period) + ']') # Control is passing to the",
"class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values) def _calculateTi(self): \"\"\" Calculates the technical indicator for the",
"WrongValueForInputParameter class VolumeOscillator(TechnicalIndicator): \"\"\" Volume Oscillator Technical Indicator class implementation. Args: input_data (pandas.DataFrame):",
"', '> short_period [' + str(self._short_period) + ']') # Control is passing to",
"'long_period ', '> short_period [' + str(self._short_period) + ']') # Control is passing",
"type ``pandas.DatetimeIndex``. It contains one column, the ``vosc``. _properties (dict): Indicator properties. _calling_instance",
"= short_period else: raise WrongValueForInputParameter( short_period, 'short_period', '>0') else: raise WrongTypeForInputParameter( type(short_period), 'short_period',",
"data for calculating trading signal if len(self._ti_data.index) < 3: return TRADE_SIGNALS['hold'] if (0",
"if isinstance(long_period, int): if long_period > 0: self._long_period = long_period else: raise WrongValueForInputParameter(",
"long_period=5, short_period=2, fill_missing_values=True): # Validate and store if needed, the input parameters if",
"else: raise WrongTypeForInputParameter( type(short_period), 'short_period', 'int') if self._long_period <= self._short_period: raise WrongValueForInputParameter( long_period,",
"input column is ``volume``. The index is of type ``pandas.DatetimeIndex``. long_period (int, default=5):",
"if self._long_period <= self._short_period: raise WrongValueForInputParameter( long_period, 'long_period ', '> short_period [' +",
"missing values in the input data are being filled. Attributes: _input_data (pandas.DataFrame): The",
"signal. \"\"\" # Not enough data for calculating trading signal if len(self._ti_data.index) <",
"It contains one column, the ``vosc``. Raises: NotEnoughInputData: Not enough data for calculating",
"Indicator properties. _calling_instance (str): The name of the class. Raises: WrongTypeForInputParameter: Input argument",
"min_periods=self._long_period, center=False, win_type=None, on=None, axis=0, closed=None).mean() return vosc.round(4) def getTiSignal(self): \"\"\" Calculates and",
"window=self._short_period, min_periods=self._short_period, center=False, win_type=None, on=None, axis=0, closed=None ).mean() - self._input_data['volume'].rolling( window=self._long_period, min_periods=self._long_period, center=False,",
"of the short moving average. fill_missing_values (bool, default=True): If set to True, missing",
"trading signal. \"\"\" # Not enough data for calculating trading signal if len(self._ti_data.index)",
"if long_period > 0: self._long_period = long_period else: raise WrongValueForInputParameter( long_period, 'long_period', '>0')",
"closed=None).mean() return vosc.round(4) def getTiSignal(self): \"\"\" Calculates and returns the trading signal for",
"enough data for calculating the indicator. TypeError: Type error occurred when validating the",
"pandas.DataFrame: The calculated indicator. Index is of type ``pandas.DatetimeIndex``. It contains one column,",
"is passing to the parent class super().__init__(calling_instance=self.__class__.__name__, input_data=input_data, fill_missing_values=fill_missing_values) def _calculateTi(self): \"\"\" Calculates",
"Value error occurred when validating the ``input_data``. \"\"\" def __init__(self, input_data, long_period=5, short_period=2,",
"data=None, dtype='float64') vosc['vosc'] = self._input_data['volume'].rolling( window=self._short_period, min_periods=self._short_period, center=False, win_type=None, on=None, axis=0, closed=None ).mean()",
"self._long_period = long_period else: raise WrongValueForInputParameter( long_period, 'long_period', '>0') else: raise WrongTypeForInputParameter( type(long_period),",
"the calculation of the long moving average. short_period (int, default=2): The past periods",
"< self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy'] if (self._ti_data['vosc'].iat[-3] > self._ti_data['vosc'].iat[-2] > self._ti_data['vosc'].iat[-1] > 0): return",
"long_period (int, default=5): The past periods to be used for the calculation of",
"Args: input_data (pandas.DataFrame): The input data. Required input column is ``volume``. The index",
"3: return TRADE_SIGNALS['hold'] if (0 < self._ti_data['vosc'].iat[-3] < self._ti_data['vosc'].iat[-2] < self._ti_data['vosc'].iat[-1]): return TRADE_SIGNALS['buy']",
"enough data for the requested period if len(self._input_data.index) < self._long_period: raise NotEnoughInputData('Volume Oscillator',",
"for the calculation of the long moving average. short_period (int, default=2): The past",
"default=5): The past periods to be used for the calculation of the long",
"class VolumeOscillator(TechnicalIndicator): \"\"\" Volume Oscillator Technical Indicator class implementation. Args: input_data (pandas.DataFrame): The",
"``vosc``. _properties (dict): Indicator properties. _calling_instance (str): The name of the class. Raises:",
"Not enough data for calculating trading signal if len(self._ti_data.index) < 3: return TRADE_SIGNALS['hold']"
] |
[
"FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls, calls)",
"self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId;', {'tenantId': '101010'}, 1)",
"1) class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self): \"\"\"Return a single policy dict, rather",
"dict.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi', 'tenantId': '101010'} def execute(query,",
"self.client.execute.assert_called_once_with( 'INSERT INTO serverpolicies (\"serverId\", \"policyId\") VALUES (:serverId, :policyId);', {'serverId': 'server-abc', 'policyId': 'policy-def'},",
"self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self): \"\"\"Raises an error if more than one group is",
"False when the quorum is unhealthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId':",
"self.client.execute.side_effect = execute d = cass.delete_server(self.client, '101010', 'group-xyz', 'server-abc') self.successResultOf(d) calls = [",
"{'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'}, ])",
"'groupId': 'group-xyz'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def",
"'entityId': 'entity-ghi', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND",
"* FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) def",
"the quorum is healthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId':",
"\"groupId\")', 'VALUES (:serverId, :entityId, :groupId);']), {'serverId': 'server-abc', 'entityId': 'entity-ghi', 'groupId': 'group-def'}, 1), mock.call(",
"= defer.succeed(expected) d = cass.get_groups_by_tenant_id(self.client, '101010') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT",
"self.client.execute.side_effect = execute d = cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc') self.successResultOf(d) calls = [ mock.call(",
"mock.call( 'DELETE FROM policies WHERE \"groupId\"=:groupId AND \"policyId\"=:policyId;', {'policyId': 'policy-abc', 'groupId': 'group-xyz'}, 1),",
"self.client.execute.return_value = defer.succeed([expected]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.successResultOf(d) self.assertEqual(result,",
"'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} def execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None)",
":groupId);']), {'serverId': 'server-abc', 'entityId': 'entity-ghi', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM servers",
"expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}, {'policyId': 'policy-xyz', 'groupId':",
"expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi', 'tenantId': '101010'} def execute(query, data,",
"= {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_server_by_server_id(self.client,",
"\"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': 'group-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\"",
"than a single item list.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi',",
"bobby.cass.delete_group.\"\"\" def test_delete_group(self): \"\"\"Deletes a group.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_group(self.client, '101010',",
"group.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}, {'policyId': 'policy-xyz',",
"serverpolicies WHERE \"policyId\"=:policyId AND \"serverId\"=:serverId;', {'policyId': 'policy-abc', 'serverId': 'server-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls)",
"query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_policy(self.client, expected['policyId'], expected['groupId'], expected['alarmTemplate'], expected['checkTemplate'])",
"calls = [ mock.call( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-abc'}, 1),",
"= self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId;', {'tenantId': '101010'},",
"than a single item list.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi',",
"'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} def execute(query, data, consistency): if 'INSERT'",
"server dict, rather than a single item list.\"\"\" expected = {'serverId': 'server-abc', 'groupId':",
"an error if no policy is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_policy_by_policy_id(self.client,",
"in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_server(self.client, expected['tenantId'], expected['serverId'], expected['entityId'],",
"result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self): \"\"\"Raises an error if more than one",
"expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmId': 'alABCD', 'checkId': 'chABCD', 'state': 'false'}] self.client.execute.return_value",
"' '.join([ 'INSERT INTO policies', '(\"policyId\", \"groupId\", \"alarmTemplate\", \"checkTemplate\")', 'VALUES (:policyId, :groupId, :alarmTemplate,",
"\"\"\"Test bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self): \"\"\"Returns a single dict, rather than a single item",
"'alarmId': 'alABCD', 'checkId': 'chABCD'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) def test_deregister_policy_on_server(self): \"\"\"Registers a policy",
"mock from silverberg.client import CQLClient from twisted.internet import defer from twisted.trial import unittest",
"given tenant id.\"\"\" expected = [] self.client.execute.return_value = defer.succeed(expected) d = cass.get_groups_by_tenant_id(self.client, '101010')",
"test_delete_policy(self): \"\"\"Deletes a policy.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d",
"\"serverId\"=:serverId;', {'policyId': 'policy-abc', 'serverId': 'server-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server",
"server and creates a serverpolicy record.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmId':",
"= defer.succeed(expected) d = cass.get_policy_state(self.client, 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls =",
"def test_get_group_by_id(self): \"\"\"Returns a single dict, rather than a single item list.\"\"\" expected",
"than a single item list.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'}",
"self.client.execute.return_value = defer.succeed(['group1', 'group2']) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError))",
"self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': '101010'},",
"import defer from twisted.trial import unittest class _DBTestCase(unittest.TestCase): \"\"\"Abstract DB test case.\"\"\" def",
"database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.add_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT INTO",
"class TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_create_policy(self): \"\"\"Creates and returns a policy dict.\"\"\" expected",
"record.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmId': 'alABCD', 'checkId': 'chABCD', 'state': 'false'}]",
"= execute d = cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE",
"in query: return defer.succeed(policies) else: return defer.succeed(expected) self.client.execute.side_effect = execute d = cass.get_serverpolicies_by_server_id(self.client,",
"WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeleteServer(_DBTestCase):",
"= defer.succeed(None) d = cass.delete_group(self.client, '101010', 'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM groups WHERE",
"a given group_id.\"\"\" expected = [{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'}, {'serverId': 'server-xyz',",
"return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_policy(self.client, expected['policyId'], expected['groupId'], expected['alarmTemplate'], expected['checkTemplate']) result",
"test_delete_group(self): \"\"\"Deletes a group.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_group(self.client, '101010', 'group-abc') self.successResultOf(d)",
"test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an error if no policy is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d",
"\"\"\"Test bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self): \"\"\"Results in a False when the quorum is unhealthy.\"\"\"",
"'INSERT' in query: return defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect =",
"d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self): \"\"\"Raises",
"'checkTemplate-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.successResultOf(d) self.assertEqual(result,",
"defer.succeed(expected) d = cass.get_servers_by_group_id(self.client, '101010', 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT",
"'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'OK'},",
"all servers by a given group_id.\"\"\" expected = [{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId':",
"'server-abc', 'policies': 'policy-abc, policy-xyz'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\" def",
"\"\"\"Raises an error if no group is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d =",
"is found.\"\"\" self.client.execute.return_value = defer.succeed(['group1', 'group2']) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result =",
"rather than a single item list.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId':",
"group_id.\"\"\" expected = [{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'}, {'serverId': 'server-xyz', 'groupId': 'group-def',",
"self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_create_policy(self): \"\"\"Creates and returns a policy dict.\"\"\"",
"FROM serverpolicies WHERE \"serverId\"=:serverId AND \"policyId\"=:policyId;', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestGetPoliciesByGroupId(_DBTestCase):",
"= self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;',",
"policies = [{'policyId': 'policy-abc'}, {'policyId': 'policy-xyz'}] expected = [{'policyId': 'policy-abc', 'serverId': 'server-abc'}, {'policyId':",
"expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value = defer.succeed([expected])",
"'group-abc'}, 1) def test_get_group_by_id_no_such_id(self): \"\"\"Raises an error if no group is found.\"\"\" self.client.execute.return_value",
"expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} def execute(query, data,",
"{'policyId': 'policy-xyz', 'serverId': 'server-abc'}] def execute(query, args, consistency): if 'FROM policies' in query:",
"query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_server(self.client, expected['tenantId'], expected['serverId'], expected['entityId'], expected['groupId'])",
"no server is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc')",
"{'policyId': 'policy-abc', 'groupId': 'group-xyz'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and",
"false);'), {'policyId': 'policy-abc', 'serverId': 'server-abc', 'alarmId': 'alABCD', 'checkId': 'chABCD'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls)",
"d = cass.get_servers_by_group_id(self.client, '101010', 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT *",
"expected) self.assertEqual( self.client.execute.mock_calls, [mock.call( ' '.join([ 'INSERT INTO groups (\"tenantId\", \"groupId\", \"notification\", \"notificationPlan\")',",
"1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self): \"\"\"Adding a server",
"AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1)]) class TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\" def test_delete_group(self):",
"\"\"\"Raises an error if more than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['server-abc',",
"'INSERT INTO groups (\"tenantId\", \"groupId\", \"notification\", \"notificationPlan\")', 'VALUES (:tenantId, :groupId, :notification, :notificationPlan);']), {'notificationPlan':",
"self.successResultOf(d) calls = [ mock.call( 'DELETE FROM policies WHERE \"groupId\"=:groupId AND \"policyId\"=:policyId;', {'policyId':",
"INTO servers (\"serverId\", \"entityId\", \"groupId\")', 'VALUES (:serverId, :entityId, :groupId);']), {'serverId': 'server-abc', 'entityId': 'entity-ghi',",
"'notificationPlan-jkl'} def execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None) elif 'SELECT'",
"error if more than one policy is found.\"\"\" self.client.execute.return_value = defer.succeed(['policy-abc', 'policy-def']) d",
"test_create_server(self): \"\"\"Creates and returns a server dict.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def',",
"cascade to delete associated server policies.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect =",
"single policy dict, rather than a single item list.\"\"\" expected = {'policyId': 'policy-abc',",
"group is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result =",
"[{'policyId': 'policy-abc', 'serverId': 'server-abc'}, {'policyId': 'policy-xyz', 'serverId': 'server-abc'}] def execute(query, args, consistency): if",
"bobby.cass.create_policy.\"\"\" def test_create_policy(self): \"\"\"Creates and returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc',",
"self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'},",
"'group-def', 'entityId': 'entity-ghi'}, {'serverId': 'server-xyz', 'groupId': 'group-def', 'entityId': 'entity-uvw'}] self.client.execute.return_value = defer.succeed(expected) d",
"'policyId': 'policy-def'}, 1) class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self): \"\"\"Gets all policies from",
"self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self): \"\"\"Raises an error if more than one group is found.\"\"\"",
"mock.call( ('UPDATE serverpolicies SET state=:state WHERE \"policyId\"=:policyId AND ' '\"serverId\"=:serverId;'), {'state': False, 'policyId':",
"calls) class TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self): \"\"\"Adding a server policy is an",
"'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_group_by_id(self.client,",
"server policy is an insert in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d =",
"'checkTemplate-jkl', 'policyId': 'policy-abc', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM policies WHERE \"policyId\"=:policyId",
"FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1)]) class TestDeleteGroup(_DBTestCase):",
"self.assertEqual(calls, self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self): \"\"\"Creates and returns a policy",
"and returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi',",
"\"\"\"Returns a single dict, rather than a single item list.\"\"\" expected = {'groupId':",
"cass.delete_server(self.client, '101010', 'group-xyz', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM servers WHERE",
"test_get_server_by_id_integrity_problems(self): \"\"\"Raises an error if more than one group is found.\"\"\" self.client.execute.return_value =",
"def setUp(self): \"\"\"Patch CQLClient.\"\"\" self.client = mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self):",
"mock.call( ('INSERT INTO serverpolicies (\"serverId\", \"policyId\", \"alarmId\", \"checkId\", state)' ' VALUES (:serverId, :policyId,",
"expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId':",
"self.client.execute.return_value = defer.succeed(None) d = cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM serverpolicies",
"self.client.execute.assert_called_once_with( 'DELETE FROM serverpolicies WHERE \"serverId\"=:serverId AND \"policyId\"=:policyId;', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1)",
"d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self): \"\"\"Raises an",
"'group-def'}, 1) class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self): \"\"\"Return a single policy dict,",
"mock.call( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls)",
"from a provided group.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate':",
"'server-abc', 'alABCD', 'chABCD') self.successResultOf(d) calls = [ mock.call( ('INSERT INTO serverpolicies (\"serverId\", \"policyId\",",
"'notificationPlan-jkl', 'notification': 'notification-ghi', 'groupId': 'group-abc', 'tenantId': '101010'}, 1), mock.call( 'SELECT * FROM groups",
"than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['server-abc', 'server-def']) d = cass.get_server_by_server_id(self.client, '101010',",
"= [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}, {'policyId': 'policy-xyz', 'groupId': 'group-def',",
"* FROM servers WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def",
"'policy-xyz', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policies_by_group_id(self.client,",
"self.client.execute.return_value = defer.succeed([]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def",
"= cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self): \"\"\"Raises an error",
"result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND",
"data, consistency): if 'INSERT' in query: return defer.succeed(None) elif 'SELECT' in query: return",
"'tenantId': '101010'}, 1), mock.call( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId':",
"'serverId': 'server-ghi', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId':",
"no group is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result",
"\"policyId\"=:policyId AND \"serverId\"=:serverId;', {'policyId': 'policy-abc', 'serverId': 'server-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase):",
"'false'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policy_state(self.client, 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected)",
"**kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc', 'alABCD', 'chABCD')",
"test_get_group_by_id_no_such_id(self): \"\"\"Raises an error if no group is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d",
"\"\"\"Deletes a group.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_group(self.client, '101010', 'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with(",
"'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'},",
"self.assertEqual(result, ('policy-abc', 'server-def')) calls = [ mock.call( 'SELECT * FROM serverpolicies WHERE \"alarmId\"=:alarmId;',",
"policies WHERE \"groupId\"=:groupId AND \"policyId\"=:policyId;', {'policyId': 'policy-abc', 'groupId': 'group-xyz'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls)",
"\"groupId\"=:groupId AND \"policyId\"=:policyId;', {'policyId': 'policy-abc', 'groupId': 'group-xyz'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase):",
"'policy-abc', 'serverId': 'server-abc'}, {'policyId': 'policy-xyz', 'serverId': 'server-abc'}] def execute(query, args, consistency): if 'FROM",
"= execute d = cass.create_group(self.client, expected['tenantId'], expected['groupId'], expected['notification'], expected['notificationPlan']) result = self.successResultOf(d) self.assertEqual(result,",
"if 'UPDATE' in query: return defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect",
"self.assertEqual(self.client.execute.mock_calls, calls) class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self): \"\"\"Results in a False when",
"= defer.succeed([expected]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with(",
"defer.succeed(None) d = cass.delete_group(self.client, '101010', 'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM groups WHERE \"groupId\"=:groupId",
"self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_create_policy(self): \"\"\"Creates and returns a policy",
"FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': '101010'}, 1) def test_get_policy_by_policy_id_not_found(self):",
"elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_group(self.client, expected['tenantId'],",
"an error if no group is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_group_by_id(self.client,",
"expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetServerByServerId(_DBTestCase):",
"'group-def'}, 1), mock.call( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc',",
"'policy-abc', 'serverId': 'server-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\"",
"def test_get_server_by_id_integrity_problems(self): \"\"\"Raises an error if more than one group is found.\"\"\" self.client.execute.return_value",
"bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self): \"\"\"Results in a False when the quorum is unhealthy.\"\"\" def",
"single item list.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'} self.client.execute.return_value =",
":policyId);', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self): \"\"\"Deleting",
"'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId;',",
"\"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\" def",
"'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'alarm-uvwxyz') result =",
"than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['group1', 'group2']) d = cass.get_group_by_id(self.client, '101010',",
"'policy-abc', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM serverpolicies WHERE \"policyId\"=:policyId AND",
"'101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self): \"\"\"Raises an error if",
"TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self): \"\"\"Returns all servers by a given group_id.\"\"\" expected",
"'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1)",
"test_get_servers_by_group_id(self): \"\"\"Returns all servers by a given group_id.\"\"\" expected = [{'serverId': 'server-abc', 'groupId':",
"FROM groups WHERE \"groupId\"=:groupId AND \"tenantId\"=:tenantId;', {'groupId': 'group-abc', 'tenantId': '101010'}, 1) class TestGetServersByGroupId(_DBTestCase):",
"expected['alarmTemplate'], expected['checkTemplate']) result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( ' '.join([",
"'policy-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM policies WHERE \"groupId\"=:groupId AND \"policyId\"=:policyId;',",
"'server-def', 'alarmId': 'alghi', 'checkId': 'chjkl', 'state': True} def execute(query, data, consistency): if 'UPDATE'",
"'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'Critical'},",
"'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}, {'policyId': 'policy-xyz', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate':",
"'server-def']) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase):",
"'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'},",
"'101010', 'groupId': 'group-abc'}, 1)]) class TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\" def test_delete_group(self): \"\"\"Deletes a group.\"\"\"",
"= {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} def execute(query, data, consistency):",
"= self.successResultOf(d) self.assertEqual(result, expected) self.assertEqual( self.client.execute.mock_calls, [mock.call( ' '.join([ 'INSERT INTO groups (\"tenantId\",",
"= defer.succeed([]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def",
"self.client.execute.return_value = defer.succeed(expected) d = cass.get_policy_state(self.client, 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls",
"'checkId': 'chABCD'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) def test_deregister_policy_on_server(self): \"\"\"Registers a policy on a",
"{'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value = defer.succeed([expected]) d =",
"associated server policies.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d =",
"bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self): \"\"\"Registers a policy on a server and creates",
"1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\" def test_delete_policy(self): \"\"\"Deletes a policy.\"\"\"",
"'group-xyz', 'policy-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM policies WHERE \"groupId\"=:groupId AND",
"cass.check_quorum_health(self.client, 'alarm-uvwxyz') result = self.successResultOf(d) self.assertFalse(result) def test_healthy(self): \"\"\"Results in a False when",
"error if more than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['group1', 'group2']) d",
"TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self): \"\"\"Return all the groups by a given tenant",
"\"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self): \"\"\"Return a single server dict, rather than a single",
"[{'policyId': 'policy-abc'}, {'policyId': 'policy-xyz'}] expected = [{'policyId': 'policy-abc', 'serverId': 'server-abc'}, {'policyId': 'policy-xyz', 'serverId':",
"'server-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self): \"\"\"Results in",
"and bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self): \"\"\"Registers a policy on a server and creates a",
"def execute(query, args, consistency): if 'FROM policies' in query: return defer.succeed(policies) else: return",
"'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'OK'}, {'policyId': 'policy-uvwxyz',",
"'server-abc'}] def execute(query, args, consistency): if 'FROM policies' in query: return defer.succeed(policies) else:",
"defer.succeed([expected]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT",
"expected['tenantId'], expected['serverId'], expected['entityId'], expected['groupId']) result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call(",
"WHERE \"groupId\"=:groupId AND \"tenantId\"=:tenantId;', {'groupId': 'group-abc', 'tenantId': '101010'}, 1) class TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\"",
"= cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM",
"= cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc', 'alABCD', 'chABCD') self.successResultOf(d) calls = [ mock.call( ('INSERT INTO",
"a policy.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_policy(self.client,",
"'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result",
"record.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.deregister_policy_on_server(self.client, 'policy-abc',",
"'group-xyz'}, 1) ] self.assertEqual(calls, self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self): policies =",
"servers by a given group_id.\"\"\" expected = [{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'},",
"= cass.get_policy_state(self.client, 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( 'SELECT",
"'DELETE FROM serverpolicies WHERE \"policyId\"=:policyId AND \"serverId\"=:serverId;', {'policyId': 'policy-abc', 'serverId': 'server-abc'}, 1), ]",
"\"tenantId\"=:tenantId;', {'groupId': 'group-abc', 'tenantId': '101010'}, 1) class TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self): \"\"\"Returns",
"cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_create_policy(self):",
"= self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;',",
"execute d = cass.create_policy(self.client, expected['policyId'], expected['groupId'], expected['alarmTemplate'], expected['checkTemplate']) result = self.successResultOf(d) self.assertEqual(result, expected)",
"twisted.trial import unittest class _DBTestCase(unittest.TestCase): \"\"\"Abstract DB test case.\"\"\" def setUp(self): \"\"\"Patch CQLClient.\"\"\"",
"d = cass.alter_alarm_state(self.client, expected['alarmId'], False) result = self.successResultOf(d) self.assertEqual(result, ('policy-abc', 'server-def')) calls =",
"VALUES (:serverId, :policyId, :alarmId, :checkId, false);'), {'policyId': 'policy-abc', 'serverId': 'server-abc', 'alarmId': 'alABCD', 'checkId':",
"query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.alter_alarm_state(self.client, expected['alarmId'], False) result =",
"a False when the quorum is unhealthy.\"\"\" def execute(query, data, consistency): return defer.succeed([",
"'policyId': 'policy-abc', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND",
"(\"serverId\", \"entityId\", \"groupId\")', 'VALUES (:serverId, :entityId, :groupId);']), {'serverId': 'server-abc', 'entityId': 'entity-ghi', 'groupId': 'group-def'},",
"'group-def', 'entityId': 'entity-ghi'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result",
"\"\"\"Test bobby.cass.create_server.\"\"\" def test_create_server(self): \"\"\"Creates and returns a server dict.\"\"\" expected = {'serverId':",
"= cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an error",
"d = cass.delete_server(self.client, '101010', 'group-xyz', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM",
"defer.succeed([expected]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with(",
"\"\"\"Gets all policies from a provided group.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def',",
"(\"serverId\", \"policyId\", \"alarmId\", \"checkId\", state)' ' VALUES (:serverId, :policyId, :alarmId, :checkId, false);'), {'policyId':",
"\"\"\"Test bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self): \"\"\"Creates and returns a policy dict.\"\"\" expected = {'policyId':",
"serverpolicy record.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.register_policy_on_server(self.client,",
"to delete associated server policies.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute",
"= mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self): \"\"\"Return all the groups by",
"test_delete_server(self): \"\"\"Delete and cascade to delete associated server policies.\"\"\" def execute(*args, **kwargs): return",
"{'tenantId': '101010'}, 1) class TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self): \"\"\"Returns a single dict,",
"cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\" def test_create_group(self):",
"'policy-abc', 'groupId': '101010'}, 1) def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an error if no policy is",
"'serverId': 'server-def', 'alarmId': 'alghi', 'checkId': 'chjkl', 'state': True} def execute(query, data, consistency): if",
"FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': 'group-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls,",
"more than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['group1', 'group2']) d = cass.get_group_by_id(self.client,",
"TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self): \"\"\"Return a single policy dict, rather than a",
"expected['notificationPlan']) result = self.successResultOf(d) self.assertEqual(result, expected) self.assertEqual( self.client.execute.mock_calls, [mock.call( ' '.join([ 'INSERT INTO",
"\"policyId\"=:policyId;', {'policyId': 'policy-abc', 'groupId': 'group-xyz'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server",
"\"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': '101010'}, 1) def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an error if no",
"test case.\"\"\" def setUp(self): \"\"\"Patch CQLClient.\"\"\" self.client = mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\"",
"result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\" def test_create_server(self): \"\"\"Creates and returns",
"an insert in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.add_serverpolicy(self.client, 'server-abc', 'policy-def')",
"'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policies_by_group_id(self.client, 'group-def') result = self.successResultOf(d) self.assertEqual(result,",
"is found.\"\"\" self.client.execute.return_value = defer.succeed(['server-abc', 'server-def']) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result",
"WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) def test_get_server_by_server_id_not_found(self): \"\"\"Raises an",
"defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.alter_alarm_state(self.client,",
"'group-xyz', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE",
"the groups by a given tenant id.\"\"\" expected = [] self.client.execute.return_value = defer.succeed(expected)",
"def test_alter_alarm_state(self): \"\"\"Creates and returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'serverId':",
"self.client.execute.assert_called_once_with( 'DELETE FROM groups WHERE \"groupId\"=:groupId AND \"tenantId\"=:tenantId;', {'groupId': 'group-abc', 'tenantId': '101010'}, 1)",
"calls = [ mock.call( 'SELECT * FROM serverpolicies WHERE \"alarmId\"=:alarmId;', {'alarmId': 'alghi'}, 1),",
"'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} def execute(query, data, consistency): if 'INSERT' in query: return",
"'server-abc'}, {'policyId': 'policy-xyz', 'serverId': 'server-abc'}] def execute(query, args, consistency): if 'FROM policies' in",
"expected['groupId'], expected['alarmTemplate'], expected['checkTemplate']) result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( '",
"{'policyId': 'policy-abc', 'serverId': 'server-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and",
"mock.call( 'SELECT * FROM serverpolicies WHERE \"alarmId\"=:alarmId;', {'alarmId': 'alghi'}, 1), mock.call( ('UPDATE serverpolicies",
"Tests for bobby.cass \"\"\" from bobby import cass import mock from silverberg.client import",
"result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND",
"all the groups by a given tenant id.\"\"\" expected = [] self.client.execute.return_value =",
"'INSERT INTO serverpolicies (\"serverId\", \"policyId\") VALUES (:serverId, :policyId);', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1)",
"FROM policies WHERE \"groupId\"=:groupId AND \"policyId\"=:policyId;', {'policyId': 'policy-abc', 'groupId': 'group-xyz'}, 1), ] self.assertEqual(calls,",
"def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc')",
"def test_deregister_policy_on_server(self): \"\"\"Registers a policy on a server and creates a serverpolicy record.\"\"\"",
"'alarmId': 'alABCD', 'checkId': 'chABCD', 'state': 'false'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policy_state(self.client, 'policy-abc')",
"execute d = cass.check_quorum_health(self.client, 'policy-uvwxyz') result = self.successResultOf(d) self.assertTrue(result) self.client.execute.assert_called_once_with( 'SELECT * FROM",
"[ mock.call( ' '.join([ 'INSERT INTO servers (\"serverId\", \"entityId\", \"groupId\")', 'VALUES (:serverId, :entityId,",
"'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl',",
"\"\"\"Return a single policy dict, rather than a single item list.\"\"\" expected =",
"self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM serverpolicies WHERE \"serverId\"=:serverId AND \"policyId\"=:policyId;', {'serverId': 'server-abc', 'policyId': 'policy-def'},",
"returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate':",
"{'policyId': 'policy-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self): \"\"\"Creates",
"self.client.execute.mock_calls, [mock.call( ' '.join([ 'INSERT INTO groups (\"tenantId\", \"groupId\", \"notification\", \"notificationPlan\")', 'VALUES (:tenantId,",
"]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'alarm-uvwxyz') result = self.successResultOf(d) self.assertFalse(result) def",
"# Copyright 2013 Rackspace, Inc. \"\"\" Tests for bobby.cass \"\"\" from bobby import",
"(\"serverId\", \"policyId\") VALUES (:serverId, :policyId);', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test",
"1) def test_get_server_by_server_id_not_found(self): \"\"\"Raises an error if no server is found.\"\"\" self.client.execute.return_value =",
"class TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\" def test_create_server(self): \"\"\"Creates and returns a server dict.\"\"\" expected",
"'policy-uvwxyz') result = self.successResultOf(d) self.assertTrue(result) self.client.execute.assert_called_once_with( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId':",
"execute d = cass.delete_server(self.client, '101010', 'group-xyz', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE",
"\"\"\"Return a single server dict, rather than a single item list.\"\"\" expected =",
"test_get_server_by_server_id_not_found(self): \"\"\"Raises an error if no server is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d",
"'policy-abc', 'server-abc', 'alABCD', 'chABCD') self.successResultOf(d) calls = [ mock.call( ('INSERT INTO serverpolicies (\"serverId\",",
"'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_policy_by_policy_id(self.client, '101010',",
"elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_policy(self.client, expected['policyId'],",
"{'state': False, 'policyId': 'policy-abc', 'serverId': 'server-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test",
"self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self): \"\"\"Registers a policy on",
"'policy-abc', 'serverId': 'server-abc', 'alarmId': 'alABCD', 'checkId': 'chABCD'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) def test_deregister_policy_on_server(self):",
"serverpolicies (\"serverId\", \"policyId\") VALUES (:serverId, :policyId);', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestDeleteServerpolicy(_DBTestCase):",
"] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self): \"\"\"Registers a",
"execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc') self.successResultOf(d)",
"'entity-ghi', 'tenantId': '101010'} def execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None)",
"else: return defer.succeed(expected) self.client.execute.side_effect = execute d = cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc') result =",
"= cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM serverpolicies WHERE \"serverId\"=:serverId AND \"policyId\"=:policyId;',",
"1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self): \"\"\"Registers",
"= self.successResultOf(d) self.assertFalse(result) def test_healthy(self): \"\"\"Results in a False when the quorum is",
"TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self): \"\"\"Returns a single dict, rather than a single",
"bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self): \"\"\"Registers a policy on a server and creates a serverpolicy",
"= self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\" def test_create_server(self): \"\"\"Creates and returns a",
"d = cass.add_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT INTO serverpolicies (\"serverId\", \"policyId\") VALUES",
"d = cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls = [",
"defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_server(self.client, '101010', 'group-xyz', 'server-abc') self.successResultOf(d) calls =",
"'entityId': 'entity-ghi'}, {'serverId': 'server-xyz', 'groupId': 'group-def', 'entityId': 'entity-uvw'}] self.client.execute.return_value = defer.succeed(expected) d =",
"all policies from a provided group.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate':",
"WHERE \"serverId\"=:serverId AND \"policyId\"=:policyId;', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\"",
"\"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self): \"\"\"Gets all policies from a provided group.\"\"\" expected =",
"(:tenantId, :groupId, :notification, :notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl', 'notification': 'notification-ghi', 'groupId': 'group-abc', 'tenantId': '101010'}, 1),",
"'.join([ 'INSERT INTO servers (\"serverId\", \"entityId\", \"groupId\")', 'VALUES (:serverId, :entityId, :groupId);']), {'serverId': 'server-abc',",
"= self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;',",
"'.join([ 'INSERT INTO groups (\"tenantId\", \"groupId\", \"notification\", \"notificationPlan\")', 'VALUES (:tenantId, :groupId, :notification, :notificationPlan);']),",
"[{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}, {'policyId': 'policy-xyz', 'groupId': 'group-def', 'alarmTemplate':",
"defer.succeed(None) self.client.execute.side_effect = execute d = cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc') self.successResultOf(d) calls = [",
"self.assertEqual(result, expected) calls = [ mock.call( ' '.join([ 'INSERT INTO policies', '(\"policyId\", \"groupId\",",
"TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self): \"\"\"Creates and returns a policy dict.\"\"\" expected =",
"self.client.execute.return_value = defer.succeed(expected) d = cass.get_policies_by_group_id(self.client, 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with(",
"def test_healthy(self): \"\"\"Results in a False when the quorum is healthy.\"\"\" def execute(query,",
"\"entityId\", \"groupId\")', 'VALUES (:serverId, :entityId, :groupId);']), {'serverId': 'server-abc', 'entityId': 'entity-ghi', 'groupId': 'group-def'}, 1),",
"found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError))",
"'group-def', 'entityId': 'entity-uvw'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_servers_by_group_id(self.client, '101010', 'group-def') result =",
"calls) class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self): \"\"\"Results in a False when the",
"1)] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\" def test_delete_server(self): \"\"\"Delete and cascade to",
"INTO serverpolicies (\"serverId\", \"policyId\") VALUES (:serverId, :policyId);', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class",
"when the quorum is unhealthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz',",
"2013 Rackspace, Inc. \"\"\" Tests for bobby.cass \"\"\" from bobby import cass import",
"AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': 'group-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeletePolicy(_DBTestCase): \"\"\"Test",
"'tenantId': '101010'} def execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None) elif",
"[ mock.call( 'SELECT * FROM serverpolicies WHERE \"alarmId\"=:alarmId;', {'alarmId': 'alghi'}, 1), mock.call( ('UPDATE",
"\"\"\"Raises an error if more than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['group1',",
"returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'serverId': 'server-def', 'alarmId': 'alghi', 'checkId':",
"import CQLClient from twisted.internet import defer from twisted.trial import unittest class _DBTestCase(unittest.TestCase): \"\"\"Abstract",
"TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\" def test_create_group(self): \"\"\"Creates a group in Cassandra.\"\"\" expected = {'groupId':",
"* FROM policies WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def",
"execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_server(self.client, '101010', 'group-xyz', 'server-abc')",
"def test_register_policy_on_server(self): \"\"\"Registers a policy on a server and creates a serverpolicy record.\"\"\"",
"1) class TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self): \"\"\"Returns a single dict, rather than",
"self.client.execute.side_effect = execute d = cass.create_server(self.client, expected['tenantId'], expected['serverId'], expected['entityId'], expected['groupId']) result = self.successResultOf(d)",
"FROM serverpolicies WHERE \"policyId\" IN (:policies) AND \"serverId\"=:serverId', {'serverId': 'server-abc', 'policies': 'policy-abc, policy-xyz'},",
"policy is an insert in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.add_serverpolicy(self.client,",
"def test_get_server_by_server_id_not_found(self): \"\"\"Raises an error if no server is found.\"\"\" self.client.execute.return_value = defer.succeed([])",
":groupId, :notification, :notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl', 'notification': 'notification-ghi', 'groupId': 'group-abc', 'tenantId': '101010'}, 1), mock.call(",
"{'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId':",
"= defer.succeed([expected]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with(",
"than one policy is found.\"\"\" self.client.execute.return_value = defer.succeed(['policy-abc', 'policy-def']) d = cass.get_policy_by_policy_id(self.client, '101010',",
"self.client.execute.mock_calls) def test_deregister_policy_on_server(self): \"\"\"Registers a policy on a server and creates a serverpolicy",
"False) result = self.successResultOf(d) self.assertEqual(result, ('policy-abc', 'server-def')) calls = [ mock.call( 'SELECT *",
"mock.call( ' '.join([ 'INSERT INTO servers (\"serverId\", \"entityId\", \"groupId\")', 'VALUES (:serverId, :entityId, :groupId);']),",
"expected) calls = [ mock.call( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-abc'},",
"'entity-ghi', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;',",
"= cass.delete_server(self.client, '101010', 'group-xyz', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM servers",
"TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self): policies = [{'policyId': 'policy-abc'}, {'policyId': 'policy-xyz'}] expected =",
"\"\"\"Deletes a policy.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d =",
"a server policy is an insert in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d",
"'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.successResultOf(d)",
"'101010', 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE",
"= defer.succeed([]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self):",
"* FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': 'group-def'}, 1) ]",
"provided group.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}, {'policyId':",
"bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self): \"\"\"Registers a policy on a server and creates a serverpolicy",
"mock.call('SELECT * FROM serverpolicies WHERE \"policyId\" IN (:policies) AND \"serverId\"=:serverId', {'serverId': 'server-abc', 'policies':",
"self.successResultOf(d) calls = [ mock.call( 'DELETE FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId':",
"by a given group_id.\"\"\" expected = [{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'}, {'serverId':",
"[ mock.call( ' '.join([ 'INSERT INTO policies', '(\"policyId\", \"groupId\", \"alarmTemplate\", \"checkTemplate\")', 'VALUES (:policyId,",
"self.assertEqual(result, expected) calls = [ mock.call('SELECT * FROM policies WHERE \"groupId\"=:groupId', {'groupId': 'group-abc'},",
"'SELECT * FROM servers WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\"",
"\"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': '101010'}, 1) def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an error",
"[ mock.call( 'DELETE FROM serverpolicies WHERE \"policyId\"=:policyId AND \"serverId\"=:serverId;', {'policyId': 'policy-abc', 'serverId': 'server-abc'},",
"= [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmId': 'alABCD', 'checkId': 'chABCD', 'state': 'false'}] self.client.execute.return_value =",
"'entityId': 'entity-ghi', 'tenantId': '101010'} def execute(query, data, consistency): if 'INSERT' in query: return",
"WHERE \"tenantId\"=:tenantId;', {'tenantId': '101010'}, 1) class TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self): \"\"\"Returns a",
"'entity-ghi'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.successResultOf(d)",
"'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': 'group-def'}, 1)",
"'group-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId",
"result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call('SELECT * FROM policies WHERE",
"expected['entityId'], expected['groupId']) result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( ' '.join([",
"'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz',",
"self.assertEqual(self.client.execute.mock_calls, calls) class TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\" def test_delete_server(self): \"\"\"Delete and cascade to delete",
"def test_get_policy_by_policy_id(self): \"\"\"Return a single policy dict, rather than a single item list.\"\"\"",
"self.client.execute.return_value = defer.succeed(expected) d = cass.get_servers_by_group_id(self.client, '101010', 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected)",
"'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\" def test_create_group(self): \"\"\"Creates a",
"1)]) class TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\" def test_delete_group(self): \"\"\"Deletes a group.\"\"\" self.client.execute.return_value = defer.succeed(None)",
"= execute d = cass.delete_server(self.client, '101010', 'group-xyz', 'server-abc') self.successResultOf(d) calls = [ mock.call(",
"\"\"\"Raises an error if more than one policy is found.\"\"\" self.client.execute.return_value = defer.succeed(['policy-abc',",
"self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;',",
"'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc')",
"'.join([ 'INSERT INTO policies', '(\"policyId\", \"groupId\", \"alarmTemplate\", \"checkTemplate\")', 'VALUES (:policyId, :groupId, :alarmTemplate, :checkTemplate);']),",
"expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId;', {'tenantId': '101010'}, 1) class TestGetGroupById(_DBTestCase):",
"'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': '101010'}, 1)",
"'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self): \"\"\"Raises an error if more than",
"healthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state': 'OK'},",
"calls = [ mock.call( ' '.join([ 'INSERT INTO servers (\"serverId\", \"entityId\", \"groupId\")', 'VALUES",
"from silverberg.client import CQLClient from twisted.internet import defer from twisted.trial import unittest class",
"WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': 'group-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class",
"test_healthy(self): \"\"\"Results in a False when the quorum is healthy.\"\"\" def execute(query, data,",
"\"\"\"Test bobby.cass.create_policy.\"\"\" def test_create_policy(self): \"\"\"Creates and returns a policy dict.\"\"\" expected = {'policyId':",
"'group-abc', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call('SELECT * FROM",
"AND \"tenantId\"=:tenantId;', {'groupId': 'group-abc', 'tenantId': '101010'}, 1) class TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self):",
"= [ mock.call( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-abc'}, 1), ]",
"from bobby import cass import mock from silverberg.client import CQLClient from twisted.internet import",
"delete in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d)",
"class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self): \"\"\"Registers a policy on a",
"= self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( ' '.join([ 'INSERT INTO servers",
"self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class",
"]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'policy-uvwxyz') result = self.successResultOf(d) self.assertTrue(result) self.client.execute.assert_called_once_with(",
"'alarm-uvwxyz') result = self.successResultOf(d) self.assertFalse(result) def test_healthy(self): \"\"\"Results in a False when the",
"def test_get_server_by_server_id(self): \"\"\"Return a single server dict, rather than a single item list.\"\"\"",
"single item list.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}",
"the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE",
"class TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self): \"\"\"Returns a single dict, rather than a",
"\"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self): \"\"\"Return a single",
"serverpolicies WHERE \"policyId\" IN (:policies) AND \"serverId\"=:serverId', {'serverId': 'server-abc', 'policies': 'policy-abc, policy-xyz'}, 1)",
"self.client.execute.return_value = defer.succeed([expected]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected)",
"AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1) def test_get_group_by_id_no_such_id(self): \"\"\"Raises an error if",
"self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetServerByServerId(_DBTestCase): \"\"\"Test",
"'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} def execute(query, data, consistency): if 'INSERT' in",
"\"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1) def test_get_group_by_id_no_such_id(self): \"\"\"Raises an error if no",
"'SELECT * FROM serverpolicies WHERE \"alarmId\"=:alarmId;', {'alarmId': 'alghi'}, 1), mock.call( ('UPDATE serverpolicies SET",
"cass.delete_policy(self.client, 'group-xyz', 'policy-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM policies WHERE \"groupId\"=:groupId",
"item list.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value",
"'101010', 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE",
"\"\"\"Registers a policy on a server and creates a serverpolicy record.\"\"\" expected =",
":notification, :notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl', 'notification': 'notification-ghi', 'groupId': 'group-abc', 'tenantId': '101010'}, 1), mock.call( 'SELECT",
"calls = [ mock.call( 'DELETE FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc',",
"'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM serverpolicies WHERE \"policyId\"=:policyId AND \"serverId\"=:serverId;',",
"'policy-uvwxyz', 'serverId': 'server-abc', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz',",
"found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d)",
"cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM serverpolicies WHERE \"serverId\"=:serverId AND \"policyId\"=:policyId;', {'serverId':",
"if no policy is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc')",
"bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self): \"\"\"Deleting a server policy is a delete in the database.\"\"\"",
"self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010',",
"expected = [] self.client.execute.return_value = defer.succeed(expected) d = cass.get_groups_by_tenant_id(self.client, '101010') result = self.successResultOf(d)",
"TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\" def test_delete_group(self): \"\"\"Deletes a group.\"\"\" self.client.execute.return_value = defer.succeed(None) d =",
"'groupId': 'group-abc', 'tenantId': '101010'}, 1), mock.call( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND",
"cass.create_server(self.client, expected['tenantId'], expected['serverId'], expected['entityId'], expected['groupId']) result = self.successResultOf(d) self.assertEqual(result, expected) calls = [",
"test_delete_serverpolicy(self): \"\"\"Deleting a server policy is a delete in the database.\"\"\" self.client.execute.return_value =",
"'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect",
"= cass.alter_alarm_state(self.client, expected['alarmId'], False) result = self.successResultOf(d) self.assertEqual(result, ('policy-abc', 'server-def')) calls = [",
"in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with(",
"= defer.succeed(['group1', 'group2']) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class",
"self.assertEqual(result, expected) self.assertEqual( self.client.execute.mock_calls, [mock.call( ' '.join([ 'INSERT INTO groups (\"tenantId\", \"groupId\", \"notification\",",
"a delete in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def')",
"AND \"serverId\"=:serverId;', {'policyId': 'policy-abc', 'serverId': 'server-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase): \"\"\"Test",
"by a given tenant id.\"\"\" expected = [] self.client.execute.return_value = defer.succeed(expected) d =",
"test_get_server_by_server_id(self): \"\"\"Return a single server dict, rather than a single item list.\"\"\" expected",
"\"groupId\"=:groupId', {'groupId': 'group-abc'}, 1), mock.call('SELECT * FROM serverpolicies WHERE \"policyId\" IN (:policies) AND",
"test_create_policy(self): \"\"\"Creates and returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def',",
"test_get_group_by_id_integrity_problems(self): \"\"\"Raises an error if more than one group is found.\"\"\" self.client.execute.return_value =",
"group.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_group(self.client, '101010', 'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM",
"execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None) elif 'SELECT' in query:",
"calls = [ mock.call( 'DELETE FROM serverpolicies WHERE \"policyId\"=:policyId AND \"serverId\"=:serverId;', {'policyId': 'policy-abc',",
"= cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\" def",
"found.\"\"\" self.client.execute.return_value = defer.succeed(['policy-abc', 'policy-def']) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d)",
"d = cass.get_policies_by_group_id(self.client, 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM",
"result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND",
"'group-abc', 'tenantId': '101010'}, 1), mock.call( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;',",
"a serverpolicy record.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmId': 'alABCD', 'checkId': 'chABCD',",
"defer.succeed([]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises",
"'INSERT INTO policies', '(\"policyId\", \"groupId\", \"alarmTemplate\", \"checkTemplate\")', 'VALUES (:policyId, :groupId, :alarmTemplate, :checkTemplate);']), {'alarmTemplate':",
"TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self): \"\"\"Gets all policies from a provided group.\"\"\" expected",
"one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['server-abc', 'server-def']) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz',",
"] self.assertEqual(self.client.execute.mock_calls, calls) class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self): \"\"\"Results in a False",
"'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} def execute(query, data, consistency): if 'INSERT' in",
"WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) ] self.assertEqual(calls, self.client.execute.mock_calls) class",
"'groupId': 'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\" def test_delete_server(self): \"\"\"Delete and",
"class TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self): \"\"\"Creates and returns a policy dict.\"\"\" expected",
"'serverId': 'server-abc'}] def execute(query, args, consistency): if 'FROM policies' in query: return defer.succeed(policies)",
"self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc',",
"d = cass.delete_group(self.client, '101010', 'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM groups WHERE \"groupId\"=:groupId AND",
"'101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an error if more",
"{'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self): \"\"\"Deleting a",
"'checkId': 'chjkl', 'state': True} def execute(query, data, consistency): if 'UPDATE' in query: return",
"{'groupId': 'group-abc', 'tenantId': '101010'}, 1) class TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self): \"\"\"Returns all",
"'group-def'}, 1), mock.call( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc',",
"1) class TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self): \"\"\"Return a single server dict, rather",
"groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1) def test_get_group_by_id_no_such_id(self): \"\"\"Raises",
"import unittest class _DBTestCase(unittest.TestCase): \"\"\"Abstract DB test case.\"\"\" def setUp(self): \"\"\"Patch CQLClient.\"\"\" self.client",
"def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state': 'OK'}, {'policyId':",
"return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state':",
"WHERE \"groupId\"=:groupId', {'groupId': 'group-abc'}, 1), mock.call('SELECT * FROM serverpolicies WHERE \"policyId\" IN (:policies)",
"{'notificationPlan': 'notificationPlan-jkl', 'notification': 'notification-ghi', 'groupId': 'group-abc', 'tenantId': '101010'}, 1), mock.call( 'SELECT * FROM",
"test_add_serverpolicy(self): \"\"\"Adding a server policy is an insert in the database.\"\"\" self.client.execute.return_value =",
"test_get_policy_by_policy_id(self): \"\"\"Return a single policy dict, rather than a single item list.\"\"\" expected",
"= cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\"",
"{'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId':",
"result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId;', {'tenantId':",
"'FROM policies' in query: return defer.succeed(policies) else: return defer.succeed(expected) self.client.execute.side_effect = execute d",
"= defer.succeed(None) d = cass.add_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT INTO serverpolicies (\"serverId\",",
"{'serverId': 'server-abc', 'policies': 'policy-abc, policy-xyz'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\"",
"\"\"\"Test bobby.cass.delete_group.\"\"\" def test_delete_group(self): \"\"\"Deletes a group.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_group(self.client,",
"self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc',",
"'server-ghi', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno',",
"' VALUES (:serverId, :policyId, :alarmId, :checkId, false);'), {'policyId': 'policy-abc', 'serverId': 'server-abc', 'alarmId': 'alABCD',",
"'group-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\" def test_delete_policy(self): \"\"\"Deletes a",
"'groupId': 'group-def', 'entityId': 'entity-ghi'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc')",
"self.client.execute.return_value = defer.succeed(['policy-abc', 'policy-def']) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError))",
"rather than a single item list.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification':",
"self.client.execute.side_effect = execute d = cass.alter_alarm_state(self.client, expected['alarmId'], False) result = self.successResultOf(d) self.assertEqual(result, ('policy-abc',",
"'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz',",
"'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}, {'policyId': 'policy-xyz', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value =",
"\"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeleteServer(_DBTestCase): \"\"\"Test",
"defer.succeed(expected) d = cass.get_groups_by_tenant_id(self.client, '101010') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT *",
"= [] self.client.execute.return_value = defer.succeed(expected) d = cass.get_groups_by_tenant_id(self.client, '101010') result = self.successResultOf(d) self.assertEqual(result,",
"WHERE \"policyId\"=:policyId AND ' '\"serverId\"=:serverId;'), {'state': False, 'policyId': 'policy-abc', 'serverId': 'server-def'}, 1) ]",
"data, consistency): if 'UPDATE' in query: return defer.succeed(None) elif 'SELECT' in query: return",
"execute d = cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM",
"def test_get_group_by_id_no_such_id(self): \"\"\"Raises an error if no group is found.\"\"\" self.client.execute.return_value = defer.succeed([])",
"\"groupId\", \"notification\", \"notificationPlan\")', 'VALUES (:tenantId, :groupId, :notification, :notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl', 'notification': 'notification-ghi', 'groupId':",
"'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'policy-uvwxyz')",
"return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.alter_alarm_state(self.client, expected['alarmId'], False) result = self.successResultOf(d)",
"\"\"\"Return all the groups by a given tenant id.\"\"\" expected = [] self.client.execute.return_value",
"is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d)",
"bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self): \"\"\"Return a single policy dict, rather than a single item",
"server dict.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi', 'tenantId': '101010'} def",
"\"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self): \"\"\"Registers a policy on a server and",
"self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self): \"\"\"Raises an error if more than one group is found.\"\"\"",
"('UPDATE serverpolicies SET state=:state WHERE \"policyId\"=:policyId AND ' '\"serverId\"=:serverId;'), {'state': False, 'policyId': 'policy-abc',",
"{'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'OK'}, {'policyId':",
"dict, rather than a single item list.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010',",
"result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId;', {'groupId':",
"TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self): \"\"\"Adding a server policy is an insert in",
"dict, rather than a single item list.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def',",
"def test_create_server(self): \"\"\"Creates and returns a server dict.\"\"\" expected = {'serverId': 'server-abc', 'groupId':",
"def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_server(self.client, '101010', 'group-xyz',",
"'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId':",
"CQLClient.\"\"\" self.client = mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self): \"\"\"Return all the",
"\"policyId\" IN (:policies) AND \"serverId\"=:serverId', {'serverId': 'server-abc', 'policies': 'policy-abc, policy-xyz'}, 1) ] self.assertEqual(self.client.execute.mock_calls,",
"'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\" def test_create_server(self): \"\"\"Creates and",
"self.assertEqual(calls, self.client.execute.mock_calls) def test_deregister_policy_on_server(self): \"\"\"Registers a policy on a server and creates a",
"'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM serverpolicies WHERE \"serverId\"=:serverId AND \"policyId\"=:policyId;', {'serverId': 'server-abc',",
"in Cassandra.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} def",
"[ mock.call( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-abc'}, 1), ] self.assertEqual(calls,",
"(:policies) AND \"serverId\"=:serverId', {'serverId': 'server-abc', 'policies': 'policy-abc, policy-xyz'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class",
"AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': '101010'}, 1) def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an error if",
"calls) class TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\" def test_delete_policy(self): \"\"\"Deletes a policy.\"\"\" def execute(*args, **kwargs):",
"mock.call( ' '.join([ 'INSERT INTO policies', '(\"policyId\", \"groupId\", \"alarmTemplate\", \"checkTemplate\")', 'VALUES (:policyId, :groupId,",
"'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} def execute(query, data, consistency): if 'INSERT' in query:",
"query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_group(self.client, expected['tenantId'], expected['groupId'], expected['notification'], expected['notificationPlan'])",
"groups by a given tenant id.\"\"\" expected = [] self.client.execute.return_value = defer.succeed(expected) d",
"policies' in query: return defer.succeed(policies) else: return defer.succeed(expected) self.client.execute.side_effect = execute d =",
"expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetPolicyByPolicyId(_DBTestCase):",
"d = cass.get_groups_by_tenant_id(self.client, '101010') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM",
"'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId':",
"= [ mock.call( ('INSERT INTO serverpolicies (\"serverId\", \"policyId\", \"alarmId\", \"checkId\", state)' ' VALUES",
"'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.alter_alarm_state(self.client, expected['alarmId'], False)",
"d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\"",
"= [{'policyId': 'policy-abc'}, {'policyId': 'policy-xyz'}] expected = [{'policyId': 'policy-abc', 'serverId': 'server-abc'}, {'policyId': 'policy-xyz',",
"{'policyId': 'policy-abc', 'serverId': 'server-abc', 'alarmId': 'alABCD', 'checkId': 'chABCD'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) def",
"{'serverId': 'server-abc', 'groupId': 'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\" def test_delete_server(self):",
"delete associated server policies.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d",
"cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self): \"\"\"Raises an error",
"'chABCD'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) def test_deregister_policy_on_server(self): \"\"\"Registers a policy on a server",
"(:serverId, :policyId, :alarmId, :checkId, false);'), {'policyId': 'policy-abc', 'serverId': 'server-abc', 'alarmId': 'alABCD', 'checkId': 'chABCD'},",
"self.client.execute.side_effect = execute d = cass.create_group(self.client, expected['tenantId'], expected['groupId'], expected['notification'], expected['notificationPlan']) result = self.successResultOf(d)",
"result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\" def test_create_group(self): \"\"\"Creates a group",
"**kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_policy(self.client, 'group-xyz', 'policy-abc') self.successResultOf(d) calls",
"self.client.execute.side_effect = execute d = cass.create_policy(self.client, expected['policyId'], expected['groupId'], expected['alarmTemplate'], expected['checkTemplate']) result = self.successResultOf(d)",
"'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId",
"\"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self): \"\"\"Registers a policy on a server and",
"'DELETE FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) ]",
"1) def test_get_group_by_id_no_such_id(self): \"\"\"Raises an error if no group is found.\"\"\" self.client.execute.return_value =",
"WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': '101010'}, 1) def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an",
"FROM groups WHERE \"tenantId\"=:tenantId;', {'tenantId': '101010'}, 1) class TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self):",
"d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT *",
"'policy-abc'}, {'policyId': 'policy-xyz'}] expected = [{'policyId': 'policy-abc', 'serverId': 'server-abc'}, {'policyId': 'policy-xyz', 'serverId': 'server-abc'}]",
"return defer.succeed(policies) else: return defer.succeed(expected) self.client.execute.side_effect = execute d = cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc')",
"quorum is unhealthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc',",
"'SELECT * FROM policies WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\"",
"\"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self): \"\"\"Return all the groups by a given tenant id.\"\"\"",
"'alghi'}, 1), mock.call( ('UPDATE serverpolicies SET state=:state WHERE \"policyId\"=:policyId AND ' '\"serverId\"=:serverId;'), {'state':",
"{'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client,",
"'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result =",
"elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_server(self.client, expected['tenantId'],",
"'server-abc', 'alarmId': 'alABCD', 'checkId': 'chABCD'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) def test_deregister_policy_on_server(self): \"\"\"Registers a",
"'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_group_by_id(self.client, '101010',",
"self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId;', {'tenantId': '101010'}, 1) class",
"self.assertEqual(result, expected) calls = [ mock.call( ' '.join([ 'INSERT INTO servers (\"serverId\", \"entityId\",",
"defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_policy(self.client,",
"'serverId': 'server-abc'}, {'policyId': 'policy-xyz', 'serverId': 'server-abc'}] def execute(query, args, consistency): if 'FROM policies'",
"d = cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM serverpolicies",
"'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl', 'policyId': 'policy-abc', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM policies",
"state=:state WHERE \"policyId\"=:policyId AND ' '\"serverId\"=:serverId;'), {'state': False, 'policyId': 'policy-abc', 'serverId': 'server-def'}, 1)",
"result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an error if more than one",
"{'tenantId': '101010', 'groupId': 'group-abc'}, 1) def test_get_group_by_id_no_such_id(self): \"\"\"Raises an error if no group",
"on a server and creates a serverpolicy record.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId':",
"= [ mock.call( ' '.join([ 'INSERT INTO policies', '(\"policyId\", \"groupId\", \"alarmTemplate\", \"checkTemplate\")', 'VALUES",
"* FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': '101010'}, 1) def",
"= defer.succeed(expected) d = cass.get_servers_by_group_id(self.client, '101010', 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with(",
"server policy is a delete in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d =",
"defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.alter_alarm_state(self.client, expected['alarmId'], False) result = self.successResultOf(d) self.assertEqual(result,",
"serverpolicies SET state=:state WHERE \"policyId\"=:policyId AND ' '\"serverId\"=:serverId;'), {'state': False, 'policyId': 'policy-abc', 'serverId':",
"when the quorum is healthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz',",
"return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_policy(self.client, 'group-xyz', 'policy-abc') self.successResultOf(d) calls =",
"WHERE \"groupId\"=:groupId AND \"policyId\"=:policyId;', {'policyId': 'policy-abc', 'groupId': 'group-xyz'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class",
"database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM",
"self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\" def test_create_server(self): \"\"\"Creates and returns a server",
"a single server dict, rather than a single item list.\"\"\" expected = {'serverId':",
"(:serverId, :entityId, :groupId);']), {'serverId': 'server-abc', 'entityId': 'entity-ghi', 'groupId': 'group-def'}, 1), mock.call( 'SELECT *",
"import mock from silverberg.client import CQLClient from twisted.internet import defer from twisted.trial import",
"\"policyId\"=:policyId;', {'policyId': 'policy-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self):",
"{'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId':",
"d = cass.create_server(self.client, expected['tenantId'], expected['serverId'], expected['entityId'], expected['groupId']) result = self.successResultOf(d) self.assertEqual(result, expected) calls",
"'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'alarm-uvwxyz')",
"bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self): \"\"\"Returns all servers by a given group_id.\"\"\" expected = [{'serverId':",
"execute d = cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls =",
"1), mock.call( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId':",
"= cass.create_policy(self.client, expected['policyId'], expected['groupId'], expected['alarmTemplate'], expected['checkTemplate']) result = self.successResultOf(d) self.assertEqual(result, expected) calls =",
"FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) def test_get_server_by_server_id_not_found(self):",
"the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.add_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT",
"'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state':",
"'group-def', 'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policies_by_group_id(self.client, 'group-def') result",
"= self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'},",
"in query: return defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute",
"**kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_server(self.client, '101010', 'group-xyz', 'server-abc') self.successResultOf(d)",
"defer.succeed([]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self):",
"self.client.execute.return_value = defer.succeed(None) d = cass.add_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT INTO serverpolicies",
"self.assertEqual(self.client.execute.mock_calls, calls) class TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self): \"\"\"Adding a server policy is",
":checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl', 'policyId': 'policy-abc', 'groupId': 'group-def'}, 1), mock.call( 'SELECT *",
"'policy-xyz'}] expected = [{'policyId': 'policy-abc', 'serverId': 'server-abc'}, {'policyId': 'policy-xyz', 'serverId': 'server-abc'}] def execute(query,",
"serverpolicy record.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmId': 'alABCD', 'checkId': 'chABCD', 'state':",
"[ mock.call( ('INSERT INTO serverpolicies (\"serverId\", \"policyId\", \"alarmId\", \"checkId\", state)' ' VALUES (:serverId,",
"\"\"\"Abstract DB test case.\"\"\" def setUp(self): \"\"\"Patch CQLClient.\"\"\" self.client = mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase):",
"cass.check_quorum_health(self.client, 'policy-uvwxyz') result = self.successResultOf(d) self.assertTrue(result) self.client.execute.assert_called_once_with( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;',",
"execute d = cass.check_quorum_health(self.client, 'alarm-uvwxyz') result = self.successResultOf(d) self.assertFalse(result) def test_healthy(self): \"\"\"Results in",
"DB test case.\"\"\" def setUp(self): \"\"\"Patch CQLClient.\"\"\" self.client = mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test",
"\"policyId\"=:policyId AND ' '\"serverId\"=:serverId;'), {'state': False, 'policyId': 'policy-abc', 'serverId': 'server-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls,",
"' '\"serverId\"=:serverId;'), {'state': False, 'policyId': 'policy-abc', 'serverId': 'server-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class",
"serverpolicies WHERE \"serverId\"=:serverId AND \"policyId\"=:policyId;', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test",
"server and creates a serverpolicy record.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect =",
"bobby.cass.delete_policy.\"\"\" def test_delete_policy(self): \"\"\"Deletes a policy.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect =",
"= defer.succeed(expected) d = cass.get_policies_by_group_id(self.client, 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT",
"self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self): \"\"\"Registers a policy",
"'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect = execute",
"\"\"\"Test bobby.cass.create_group.\"\"\" def test_create_group(self): \"\"\"Creates a group in Cassandra.\"\"\" expected = {'groupId': 'group-abc',",
"\"serverId\"=:serverId', {'serverId': 'server-abc', 'policies': 'policy-abc, policy-xyz'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestAddServerpolicy(_DBTestCase): \"\"\"Test",
"defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_server(self.client,",
"self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId':",
"data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId':",
"expected['notification'], expected['notificationPlan']) result = self.successResultOf(d) self.assertEqual(result, expected) self.assertEqual( self.client.execute.mock_calls, [mock.call( ' '.join([ 'INSERT",
"policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} def",
"\"alarmTemplate\", \"checkTemplate\")', 'VALUES (:policyId, :groupId, :alarmTemplate, :checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl', 'policyId': 'policy-abc',",
"expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId':",
"cass.get_policy_state(self.client, 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( 'SELECT *",
"'101010'}, 1) def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an error if no policy is found.\"\"\" self.client.execute.return_value",
"creates a serverpolicy record.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmId': 'alABCD', 'checkId':",
"a serverpolicy record.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d =",
"= self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\" def test_create_group(self): \"\"\"Creates a group in",
"= cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM serverpolicies WHERE",
"policies', '(\"policyId\", \"groupId\", \"alarmTemplate\", \"checkTemplate\")', 'VALUES (:policyId, :groupId, :alarmTemplate, :checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate':",
"from twisted.internet import defer from twisted.trial import unittest class _DBTestCase(unittest.TestCase): \"\"\"Abstract DB test",
"= self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self): \"\"\"Raises an error if more than one group",
"] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self): \"\"\"Registers a",
"] self.assertEqual(self.client.execute.mock_calls, calls) class TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self): \"\"\"Adding a server policy",
"return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_server(self.client, expected['tenantId'], expected['serverId'], expected['entityId'], expected['groupId']) result",
"1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self): \"\"\"Registers",
"'notificationPlan-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.successResultOf(d) self.assertEqual(result,",
"= cass.delete_group(self.client, '101010', 'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM groups WHERE \"groupId\"=:groupId AND \"tenantId\"=:tenantId;',",
"self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\" def test_create_group(self): \"\"\"Creates a group in Cassandra.\"\"\"",
"{'groupId': 'group-abc'}, 1), mock.call('SELECT * FROM serverpolicies WHERE \"policyId\" IN (:policies) AND \"serverId\"=:serverId',",
"1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self): \"\"\"Results in a",
"return defer.succeed(None) self.client.execute.side_effect = execute d = cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc') self.successResultOf(d) calls =",
"= cass.create_server(self.client, expected['tenantId'], expected['serverId'], expected['entityId'], expected['groupId']) result = self.successResultOf(d) self.assertEqual(result, expected) calls =",
"'group-abc'}, 1)]) class TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\" def test_delete_group(self): \"\"\"Deletes a group.\"\"\" self.client.execute.return_value =",
"policy is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result =",
"and returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'serverId': 'server-def', 'alarmId': 'alghi',",
"'state': 'false'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policy_state(self.client, 'policy-abc') result = self.successResultOf(d) self.assertEqual(result,",
"'groupId': 'group-xyz'}, 1) def test_get_server_by_server_id_not_found(self): \"\"\"Raises an error if no server is found.\"\"\"",
"in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.alter_alarm_state(self.client, expected['alarmId'], False) result",
"execute d = cass.alter_alarm_state(self.client, expected['alarmId'], False) result = self.successResultOf(d) self.assertEqual(result, ('policy-abc', 'server-def')) calls",
"test_get_group_by_id(self): \"\"\"Returns a single dict, rather than a single item list.\"\"\" expected =",
"execute d = cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc', 'alABCD', 'chABCD') self.successResultOf(d) calls = [ mock.call(",
"class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self): \"\"\"Results in a False when the quorum",
"'policy-abc', 'groupId': 'group-def', 'alarmId': 'alABCD', 'checkId': 'chABCD', 'state': 'false'}] self.client.execute.return_value = defer.succeed(expected) d",
"return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_server(self.client, '101010', 'group-xyz', 'server-abc') self.successResultOf(d) calls",
"cass.get_groups_by_tenant_id(self.client, '101010') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE",
"execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc', 'alABCD',",
"[{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmId': 'alABCD', 'checkId': 'chABCD', 'state': 'false'}] self.client.execute.return_value = defer.succeed(expected)",
"{'policyId': 'policy-abc', 'groupId': '101010'}, 1) def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an error if no policy",
"] self.assertEqual(calls, self.client.execute.mock_calls) def test_deregister_policy_on_server(self): \"\"\"Registers a policy on a server and creates",
"self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1)",
"d = cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM serverpolicies WHERE \"serverId\"=:serverId AND",
"('policy-abc', 'server-def')) calls = [ mock.call( 'SELECT * FROM serverpolicies WHERE \"alarmId\"=:alarmId;', {'alarmId':",
"self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test",
"'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-def'}, 1)]",
"defer.succeed(expected) self.client.execute.side_effect = execute d = cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc') result = self.successResultOf(d) self.assertEqual(result,",
"test_deregister_policy_on_server(self): \"\"\"Registers a policy on a server and creates a serverpolicy record.\"\"\" def",
"defer.succeed(['server-abc', 'server-def']) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class",
"= execute d = cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls",
"= [ mock.call('SELECT * FROM policies WHERE \"groupId\"=:groupId', {'groupId': 'group-abc'}, 1), mock.call('SELECT *",
"expected['checkTemplate']) result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( ' '.join([ 'INSERT",
"'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect = execute d",
"'server-abc', 'groupId': 'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\" def test_delete_server(self): \"\"\"Delete",
"result = self.successResultOf(d) self.assertTrue(result) self.client.execute.assert_called_once_with( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-uvwxyz'},",
"test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an error if more than one policy is found.\"\"\" self.client.execute.return_value =",
"\"\"\"Adding a server policy is an insert in the database.\"\"\" self.client.execute.return_value = defer.succeed(None)",
"defer.succeed(None) d = cass.add_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT INTO serverpolicies (\"serverId\", \"policyId\")",
"self.successResultOf(d) self.assertEqual(result, ('policy-abc', 'server-def')) calls = [ mock.call( 'SELECT * FROM serverpolicies WHERE",
"an error if no server is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_server_by_server_id(self.client,",
"1) class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self): \"\"\"Gets all policies from a provided",
"self.assertEqual(result, expected) calls = [ mock.call( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId':",
"bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self): \"\"\"Gets all policies from a provided group.\"\"\" expected = [{'policyId':",
"if more than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['group1', 'group2']) d =",
"'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'policy-uvwxyz') result = self.successResultOf(d) self.assertTrue(result)",
"bobby.cass \"\"\" from bobby import cass import mock from silverberg.client import CQLClient from",
"defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_policy(self.client, 'group-xyz', 'policy-abc') self.successResultOf(d) calls = [",
"'101010'}, 1) class TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self): \"\"\"Returns a single dict, rather",
"groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1)]) class TestDeleteGroup(_DBTestCase): \"\"\"Test",
"calls = [ mock.call( 'DELETE FROM policies WHERE \"groupId\"=:groupId AND \"policyId\"=:policyId;', {'policyId': 'policy-abc',",
"'101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} def execute(query, data, consistency): if 'INSERT' in query:",
"= execute d = cass.alter_alarm_state(self.client, expected['alarmId'], False) result = self.successResultOf(d) self.assertEqual(result, ('policy-abc', 'server-def'))",
"if no server is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz',",
"= execute d = cass.delete_policy(self.client, 'group-xyz', 'policy-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE",
"servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) ] self.assertEqual(calls, self.client.execute.mock_calls)",
"def test_get_grous_by_tenant_id(self): \"\"\"Return all the groups by a given tenant id.\"\"\" expected =",
"self.client.execute.return_value = defer.succeed([expected]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.successResultOf(d) self.assertEqual(result, expected)",
"AND ' '\"serverId\"=:serverId;'), {'state': False, 'policyId': 'policy-abc', 'serverId': 'server-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls)",
"test_register_policy_on_server(self): \"\"\"Registers a policy on a server and creates a serverpolicy record.\"\"\" def",
"def execute(query, data, consistency): if 'UPDATE' in query: return defer.succeed(None) elif 'SELECT' in",
"'alghi', 'checkId': 'chjkl', 'state': True} def execute(query, data, consistency): if 'UPDATE' in query:",
"a group.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_group(self.client, '101010', 'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE",
"FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase): \"\"\"Test",
"self.client.execute.return_value = defer.succeed([]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError))",
"IN (:policies) AND \"serverId\"=:serverId', {'serverId': 'server-abc', 'policies': 'policy-abc, policy-xyz'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls)",
"'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect =",
"defer.succeed(['group1', 'group2']) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase):",
"{'serverId': 'server-abc', 'entityId': 'entity-ghi', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM servers WHERE",
"[ mock.call('SELECT * FROM policies WHERE \"groupId\"=:groupId', {'groupId': 'group-abc'}, 1), mock.call('SELECT * FROM",
"\"\"\" Tests for bobby.cass \"\"\" from bobby import cass import mock from silverberg.client",
"= cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM",
"= cass.check_quorum_health(self.client, 'alarm-uvwxyz') result = self.successResultOf(d) self.assertFalse(result) def test_healthy(self): \"\"\"Results in a False",
"\"notification\", \"notificationPlan\")', 'VALUES (:tenantId, :groupId, :notification, :notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl', 'notification': 'notification-ghi', 'groupId': 'group-abc',",
"\"\"\"Deleting a server policy is a delete in the database.\"\"\" self.client.execute.return_value = defer.succeed(None)",
"'policy-abc, policy-xyz'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self): \"\"\"Adding",
"\"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self): \"\"\"Return a single policy dict, rather than a single",
"expected) calls = [ mock.call( ' '.join([ 'INSERT INTO servers (\"serverId\", \"entityId\", \"groupId\")',",
"\"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) ] self.assertEqual(calls, self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase):",
"item list.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value",
"self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT INTO serverpolicies (\"serverId\", \"policyId\") VALUES (:serverId, :policyId);', {'serverId': 'server-abc', 'policyId':",
"= cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def",
"\"\"\"Creates and returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'serverId': 'server-def', 'alarmId':",
"group is found.\"\"\" self.client.execute.return_value = defer.succeed(['group1', 'group2']) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result",
"'101010', 'group-xyz', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM servers WHERE \"groupId\"=:groupId",
"\"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1)]) class TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\" def test_delete_group(self): \"\"\"Deletes",
"cass.get_servers_by_group_id(self.client, '101010', 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers",
"self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\" def test_create_group(self): \"\"\"Creates a group in Cassandra.\"\"\" expected",
"state)' ' VALUES (:serverId, :policyId, :alarmId, :checkId, false);'), {'policyId': 'policy-abc', 'serverId': 'server-abc', 'alarmId':",
"execute d = cass.create_group(self.client, expected['tenantId'], expected['groupId'], expected['notification'], expected['notificationPlan']) result = self.successResultOf(d) self.assertEqual(result, expected)",
"return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_group(self.client, expected['tenantId'], expected['groupId'], expected['notification'], expected['notificationPlan']) result",
"'serverId': 'server-abc', 'alarmId': 'alABCD', 'checkId': 'chABCD'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) def test_deregister_policy_on_server(self): \"\"\"Registers",
"consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-def',",
"'groupId': 'group-abc'}, 1)]) class TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\" def test_delete_group(self): \"\"\"Deletes a group.\"\"\" self.client.execute.return_value",
"{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value = defer.succeed([expected]) d =",
"'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policies_by_group_id(self.client, 'group-def') result = self.successResultOf(d)",
"= self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( ' '.join([ 'INSERT INTO policies',",
"\"checkId\", state)' ' VALUES (:serverId, :policyId, :alarmId, :checkId, false);'), {'policyId': 'policy-abc', 'serverId': 'server-abc',",
"group is found.\"\"\" self.client.execute.return_value = defer.succeed(['server-abc', 'server-def']) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc')",
"'policy-abc', 'serverId': 'server-def', 'alarmId': 'alghi', 'checkId': 'chjkl', 'state': True} def execute(query, data, consistency):",
"CQLClient from twisted.internet import defer from twisted.trial import unittest class _DBTestCase(unittest.TestCase): \"\"\"Abstract DB",
"self.assertEqual( self.client.execute.mock_calls, [mock.call( ' '.join([ 'INSERT INTO groups (\"tenantId\", \"groupId\", \"notification\", \"notificationPlan\")', 'VALUES",
"execute d = cass.create_server(self.client, expected['tenantId'], expected['serverId'], expected['entityId'], expected['groupId']) result = self.successResultOf(d) self.assertEqual(result, expected)",
"list.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value =",
"'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect = execute d =",
"expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} def execute(query, data,",
"from twisted.trial import unittest class _DBTestCase(unittest.TestCase): \"\"\"Abstract DB test case.\"\"\" def setUp(self): \"\"\"Patch",
":policyId, :alarmId, :checkId, false);'), {'policyId': 'policy-abc', 'serverId': 'server-abc', 'alarmId': 'alABCD', 'checkId': 'chABCD'}, 1),",
"d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\"",
"= defer.succeed(None) d = cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM serverpolicies WHERE",
"'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'}, {'serverId': 'server-xyz', 'groupId': 'group-def', 'entityId': 'entity-uvw'}] self.client.execute.return_value =",
"'server-abc', 'groupId': 'group-xyz'}, 1) def test_get_server_by_server_id_not_found(self): \"\"\"Raises an error if no server is",
"policy on a server and creates a serverpolicy record.\"\"\" def execute(*args, **kwargs): return",
"\"\"\"Raises an error if no server is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d =",
"'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class",
"def test_delete_server(self): \"\"\"Delete and cascade to delete associated server policies.\"\"\" def execute(*args, **kwargs):",
"class TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\" def test_create_group(self): \"\"\"Creates a group in Cassandra.\"\"\" expected =",
"AND \"policyId\"=:policyId;', {'policyId': 'policy-abc', 'groupId': 'group-xyz'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test",
"\"\"\"Creates a group in Cassandra.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi',",
"return defer.succeed(expected) self.client.execute.side_effect = execute d = cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc') result = self.successResultOf(d)",
"'policy-def']) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase): \"\"\"Test",
"policies WHERE \"groupId\"=:groupId', {'groupId': 'group-abc'}, 1), mock.call('SELECT * FROM serverpolicies WHERE \"policyId\" IN",
"'state': True} def execute(query, data, consistency): if 'UPDATE' in query: return defer.succeed(None) elif",
"'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM serverpolicies WHERE \"serverId\"=:serverId AND \"policyId\"=:policyId;', {'serverId': 'server-abc', 'policyId':",
"'serverId': 'server-ghi', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId':",
"= cass.get_groups_by_tenant_id(self.client, '101010') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups",
"'101010', 'group-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE",
"class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self): \"\"\"Return a single policy dict, rather than",
"policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'serverId': 'server-def', 'alarmId': 'alghi', 'checkId': 'chjkl', 'state':",
"one policy is found.\"\"\" self.client.execute.return_value = defer.succeed(['policy-abc', 'policy-def']) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc')",
"'group-xyz'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self):",
"= self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( 'SELECT * FROM serverpolicies WHERE",
"* FROM groups WHERE \"tenantId\"=:tenantId;', {'tenantId': '101010'}, 1) class TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\" def",
"cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an error if",
"expected = {'policyId': 'policy-abc', 'serverId': 'server-def', 'alarmId': 'alghi', 'checkId': 'chjkl', 'state': True} def",
"defer.succeed([]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self): \"\"\"Raises",
"\"groupId\", \"alarmTemplate\", \"checkTemplate\")', 'VALUES (:policyId, :groupId, :alarmTemplate, :checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl', 'policyId':",
"* FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls,",
"found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError))",
"given group_id.\"\"\" expected = [{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'}, {'serverId': 'server-xyz', 'groupId':",
"item list.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'} self.client.execute.return_value = defer.succeed([expected])",
"groups (\"tenantId\", \"groupId\", \"notification\", \"notificationPlan\")', 'VALUES (:tenantId, :groupId, :notification, :notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl', 'notification':",
"execute(query, data, consistency): if 'UPDATE' in query: return defer.succeed(None) elif 'SELECT' in query:",
"\"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) def test_get_server_by_server_id_not_found(self): \"\"\"Raises an error if no",
"quorum is healthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc',",
"= self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self): \"\"\"Raises an error if more than one group",
"unittest class _DBTestCase(unittest.TestCase): \"\"\"Abstract DB test case.\"\"\" def setUp(self): \"\"\"Patch CQLClient.\"\"\" self.client =",
"WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self): \"\"\"Return a",
"'policies': 'policy-abc, policy-xyz'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self):",
"bobby.cass.create_group.\"\"\" def test_create_group(self): \"\"\"Creates a group in Cassandra.\"\"\" expected = {'groupId': 'group-abc', 'tenantId':",
"'alarmId': 'alghi', 'checkId': 'chjkl', 'state': True} def execute(query, data, consistency): if 'UPDATE' in",
"and creates a serverpolicy record.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute",
"AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) ] self.assertEqual(calls, self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test",
"'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self): \"\"\"Raises an error if more",
"INTO groups (\"tenantId\", \"groupId\", \"notification\", \"notificationPlan\")', 'VALUES (:tenantId, :groupId, :notification, :notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl',",
"{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} def execute(query, data, consistency): if",
"'group-abc', 'tenantId': '101010'}, 1) class TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self): \"\"\"Returns all servers",
"1) class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self): \"\"\"Deleting a server policy is a",
"'checkTemplate-jkl'} def execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None) elif 'SELECT'",
"* FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1) def",
"def test_get_group_by_id_integrity_problems(self): \"\"\"Raises an error if more than one group is found.\"\"\" self.client.execute.return_value",
"'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state':",
"'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.successResultOf(d)",
"groups WHERE \"tenantId\"=:tenantId;', {'tenantId': '101010'}, 1) class TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self): \"\"\"Returns",
"consistency): if 'FROM policies' in query: return defer.succeed(policies) else: return defer.succeed(expected) self.client.execute.side_effect =",
"'groupId': 'group-def', 'entityId': 'entity-uvw'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_servers_by_group_id(self.client, '101010', 'group-def') result",
"TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\" def test_delete_policy(self): \"\"\"Deletes a policy.\"\"\" def execute(*args, **kwargs): return defer.succeed(None)",
"TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\" def test_create_server(self): \"\"\"Creates and returns a server dict.\"\"\" expected =",
"'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( 'SELECT * FROM",
"d = cass.check_quorum_health(self.client, 'alarm-uvwxyz') result = self.successResultOf(d) self.assertFalse(result) def test_healthy(self): \"\"\"Results in a",
"\"serverId\"=:serverId AND \"policyId\"=:policyId;', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def",
"if 'FROM policies' in query: return defer.succeed(policies) else: return defer.succeed(expected) self.client.execute.side_effect = execute",
"cass.get_policies_by_group_id(self.client, 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE",
"unhealthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state': 'OK'},",
"consistency): if 'UPDATE' in query: return defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected])",
"calls = [ mock.call( ('INSERT INTO serverpolicies (\"serverId\", \"policyId\", \"alarmId\", \"checkId\", state)' '",
"record.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.register_policy_on_server(self.client, 'policy-abc',",
"'DELETE FROM policies WHERE \"groupId\"=:groupId AND \"policyId\"=:policyId;', {'policyId': 'policy-abc', 'groupId': 'group-xyz'}, 1), ]",
"'server-abc', 'policyId': 'policy-def'}, 1) class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self): \"\"\"Gets all policies",
"bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self): \"\"\"Adding a server policy is an insert in the database.\"\"\"",
"def test_get_policies_by_group_id(self): \"\"\"Gets all policies from a provided group.\"\"\" expected = [{'policyId': 'policy-abc',",
"{'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} def execute(query, data, consistency): if",
"[mock.call( ' '.join([ 'INSERT INTO groups (\"tenantId\", \"groupId\", \"notification\", \"notificationPlan\")', 'VALUES (:tenantId, :groupId,",
"'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call('SELECT * FROM policies",
"policy.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_policy(self.client, 'group-xyz',",
"'policy-def'}, 1) class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self): \"\"\"Gets all policies from a",
"policies.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_server(self.client, '101010',",
"'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1)])",
"'groupId': 'group-def', 'entityId': 'entity-ghi'}, {'serverId': 'server-xyz', 'groupId': 'group-def', 'entityId': 'entity-uvw'}] self.client.execute.return_value = defer.succeed(expected)",
"\"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1)]) class TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\" def",
"a single policy dict, rather than a single item list.\"\"\" expected = {'policyId':",
"d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase): \"\"\"Test",
"cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups",
"mock.call('SELECT * FROM policies WHERE \"groupId\"=:groupId', {'groupId': 'group-abc'}, 1), mock.call('SELECT * FROM serverpolicies",
"d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT *",
"self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( ' '.join([ 'INSERT INTO servers (\"serverId\",",
"True} def execute(query, data, consistency): if 'UPDATE' in query: return defer.succeed(None) elif 'SELECT'",
"'groupId': 'group-def', 'entityId': 'entity-ghi', 'tenantId': '101010'} def execute(query, data, consistency): if 'INSERT' in",
"'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'policy-uvwxyz') result =",
"d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT",
"= [{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'}, {'serverId': 'server-xyz', 'groupId': 'group-def', 'entityId': 'entity-uvw'}]",
"1), mock.call( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId':",
"= [ mock.call( 'SELECT * FROM serverpolicies WHERE \"alarmId\"=:alarmId;', {'alarmId': 'alghi'}, 1), mock.call(",
"\"alarmId\", \"checkId\", state)' ' VALUES (:serverId, :policyId, :alarmId, :checkId, false);'), {'policyId': 'policy-abc', 'serverId':",
"is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result =",
"{'policyId': 'policy-xyz', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value = defer.succeed(expected) d =",
"a policy on a server and creates a serverpolicy record.\"\"\" expected = [{'policyId':",
"'group-def'}, 1) class TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self): \"\"\"Return a single server dict,",
"result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"groupId\"=:groupId;', {'groupId':",
"calls = [ mock.call( ' '.join([ 'INSERT INTO policies', '(\"policyId\", \"groupId\", \"alarmTemplate\", \"checkTemplate\")',",
"'server-ghi', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno',",
"defer.succeed([expected]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT",
"defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_group(self.client, expected['tenantId'], expected['groupId'], expected['notification'], expected['notificationPlan']) result =",
"expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value = defer.succeed([expected])",
"expected = [{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'}, {'serverId': 'server-xyz', 'groupId': 'group-def', 'entityId':",
"{'alarmId': 'alghi'}, 1), mock.call( ('UPDATE serverpolicies SET state=:state WHERE \"policyId\"=:policyId AND ' '\"serverId\"=:serverId;'),",
"= [ mock.call( 'DELETE FROM policies WHERE \"groupId\"=:groupId AND \"policyId\"=:policyId;', {'policyId': 'policy-abc', 'groupId':",
"def test_delete_policy(self): \"\"\"Deletes a policy.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute",
"self.client.execute.side_effect = execute d = cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc', 'alABCD', 'chABCD') self.successResultOf(d) calls =",
"single item list.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'}",
"cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\" def",
"'\"serverId\"=:serverId;'), {'state': False, 'policyId': 'policy-abc', 'serverId': 'server-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestCheckQuorumHealth(_DBTestCase):",
"FROM serverpolicies WHERE \"policyId\"=:policyId AND \"serverId\"=:serverId;', {'policyId': 'policy-abc', 'serverId': 'server-abc'}, 1), ] self.assertEqual(calls,",
"self.client.execute.side_effect = execute d = cass.delete_policy(self.client, 'group-xyz', 'policy-abc') self.successResultOf(d) calls = [ mock.call(",
"Cassandra.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} def execute(query,",
"(:policyId, :groupId, :alarmTemplate, :checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl', 'policyId': 'policy-abc', 'groupId': 'group-def'}, 1),",
"'policy-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self): \"\"\"Creates and",
"and creates a serverpolicy record.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmId': 'alABCD',",
"defer.succeed(None) self.client.execute.side_effect = execute d = cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc', 'alABCD', 'chABCD') self.successResultOf(d) calls",
"'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} def execute(query, data, consistency): if 'INSERT'",
"'DELETE FROM groups WHERE \"groupId\"=:groupId AND \"tenantId\"=:tenantId;', {'groupId': 'group-abc', 'tenantId': '101010'}, 1) class",
"servers (\"serverId\", \"entityId\", \"groupId\")', 'VALUES (:serverId, :entityId, :groupId);']), {'serverId': 'server-abc', 'entityId': 'entity-ghi', 'groupId':",
"'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} def execute(query, data, consistency): if 'INSERT' in query: return",
"= {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value = defer.succeed([expected]) d",
"a server and creates a serverpolicy record.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def',",
"self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self): \"\"\"Registers a policy on",
"is found.\"\"\" self.client.execute.return_value = defer.succeed(['policy-abc', 'policy-def']) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result =",
"AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) def test_get_server_by_server_id_not_found(self): \"\"\"Raises an error if",
"'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'alarm-uvwxyz') result = self.successResultOf(d) self.assertFalse(result)",
"one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['group1', 'group2']) d = cass.get_group_by_id(self.client, '101010', 'group-abc')",
"if more than one policy is found.\"\"\" self.client.execute.return_value = defer.succeed(['policy-abc', 'policy-def']) d =",
"AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\"",
"] self.assertEqual(calls, self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self): \"\"\"Creates and returns a",
"def test_delete_serverpolicy(self): \"\"\"Deleting a server policy is a delete in the database.\"\"\" self.client.execute.return_value",
"def test_policy_state(self): \"\"\"Registers a policy on a server and creates a serverpolicy record.\"\"\"",
"= [ mock.call( 'DELETE FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId':",
"'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl',",
"a provided group.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'},",
"self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( ' '.join([ 'INSERT INTO policies', '(\"policyId\",",
"cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies",
"AND \"serverId\"=:serverId', {'serverId': 'server-abc', 'policies': 'policy-abc, policy-xyz'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestAddServerpolicy(_DBTestCase):",
"returns a server dict.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi', 'tenantId':",
"bobby import cass import mock from silverberg.client import CQLClient from twisted.internet import defer",
"'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\" def test_create_server(self): \"\"\"Creates",
"{'serverId': 'server-xyz', 'groupId': 'group-def', 'entityId': 'entity-uvw'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_servers_by_group_id(self.client, '101010',",
"= defer.succeed(['server-abc', 'server-def']) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError))",
"'101010', 'group-xyz', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers",
"elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.alter_alarm_state(self.client, expected['alarmId'],",
"Rackspace, Inc. \"\"\" Tests for bobby.cass \"\"\" from bobby import cass import mock",
"import cass import mock from silverberg.client import CQLClient from twisted.internet import defer from",
"silverberg.client import CQLClient from twisted.internet import defer from twisted.trial import unittest class _DBTestCase(unittest.TestCase):",
"policy on a server and creates a serverpolicy record.\"\"\" expected = [{'policyId': 'policy-abc',",
"TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self): \"\"\"Registers a policy on a server",
"self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'},",
"{'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) def test_get_server_by_server_id_not_found(self): \"\"\"Raises an error if no server",
"bobby.cass.delete_server.\"\"\" def test_delete_server(self): \"\"\"Delete and cascade to delete associated server policies.\"\"\" def execute(*args,",
"insert in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.add_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d)",
"self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call('SELECT * FROM policies WHERE \"groupId\"=:groupId', {'groupId':",
"result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self): \"\"\"Raises an error if more than one",
"\"\"\"Test bobby.cass.delete_server.\"\"\" def test_delete_server(self): \"\"\"Delete and cascade to delete associated server policies.\"\"\" def",
"error if no policy is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_policy_by_policy_id(self.client, '101010',",
"**kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc') self.successResultOf(d) calls",
"mock.call( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': 'group-def'},",
"cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc', 'alABCD', 'chABCD') self.successResultOf(d) calls = [ mock.call( ('INSERT INTO serverpolicies",
"result = self.successResultOf(d) self.assertEqual(result, expected) self.assertEqual( self.client.execute.mock_calls, [mock.call( ' '.join([ 'INSERT INTO groups",
"'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}, {'policyId': 'policy-xyz', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}]",
"self.successResultOf(d) self.assertFalse(result) def test_healthy(self): \"\"\"Results in a False when the quorum is healthy.\"\"\"",
"'checkTemplate': 'checkTemplate-jkl'}, {'policyId': 'policy-xyz', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value = defer.succeed(expected)",
"list.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'} self.client.execute.return_value = defer.succeed([expected]) d",
"a single item list.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'} self.client.execute.return_value",
"FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) ] self.assertEqual(calls,",
"'notification': 'notification-ghi', 'groupId': 'group-abc', 'tenantId': '101010'}, 1), mock.call( 'SELECT * FROM groups WHERE",
"defer.succeed(None) d = cass.delete_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM serverpolicies WHERE \"serverId\"=:serverId",
"def test_create_policy(self): \"\"\"Creates and returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'groupId':",
"servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls, calls) class",
"execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state': 'OK'}, {'policyId': 'policy-uvwxyz',",
"single dict, rather than a single item list.\"\"\" expected = {'groupId': 'group-abc', 'tenantId':",
"_DBTestCase(unittest.TestCase): \"\"\"Abstract DB test case.\"\"\" def setUp(self): \"\"\"Patch CQLClient.\"\"\" self.client = mock.create_autospec(CQLClient) class",
"execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_policy(self.client, 'group-xyz', 'policy-abc') self.successResultOf(d)",
"and returns a server dict.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi',",
"self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM groups WHERE \"groupId\"=:groupId AND \"tenantId\"=:tenantId;', {'groupId': 'group-abc', 'tenantId': '101010'},",
"and bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self): \"\"\"Registers a policy on a server and creates a",
"\"\"\"Raises an error if no policy is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d =",
"expected['groupId']) result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( ' '.join([ 'INSERT",
"bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self): \"\"\"Creates and returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc',",
"class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self): policies = [{'policyId': 'policy-abc'}, {'policyId': 'policy-xyz'}] expected",
"= self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call('SELECT * FROM policies WHERE \"groupId\"=:groupId',",
"'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT INTO serverpolicies (\"serverId\", \"policyId\") VALUES (:serverId, :policyId);', {'serverId':",
"\"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self): \"\"\"Returns all servers by a given group_id.\"\"\" expected =",
"'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an error if more than",
"test_get_grous_by_tenant_id(self): \"\"\"Return all the groups by a given tenant id.\"\"\" expected = []",
"'policyId': 'policy-abc', 'serverId': 'server-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\" def",
"on a server and creates a serverpolicy record.\"\"\" def execute(*args, **kwargs): return defer.succeed(None)",
"'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"groupId\"=:groupId;',",
"self.assertEqual(calls, self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self): policies = [{'policyId': 'policy-abc'}, {'policyId':",
"self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an error if more than one policy is",
"query: return defer.succeed(policies) else: return defer.succeed(expected) self.client.execute.side_effect = execute d = cass.get_serverpolicies_by_server_id(self.client, 'group-abc',",
"self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self): \"\"\"Registers a policy",
"if more than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['server-abc', 'server-def']) d =",
"'SELECT * FROM groups WHERE \"tenantId\"=:tenantId;', {'tenantId': '101010'}, 1) class TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\"",
"def test_delete_group(self): \"\"\"Deletes a group.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_group(self.client, '101010', 'group-abc')",
"def test_create_group(self): \"\"\"Creates a group in Cassandra.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010',",
"cass.deregister_policy_on_server(self.client, 'policy-abc', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM serverpolicies WHERE \"policyId\"=:policyId",
"'group2']) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase): \"\"\"Test",
"defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_server(self.client, expected['tenantId'], expected['serverId'], expected['entityId'], expected['groupId']) result =",
"self.successResultOf(d) self.assertEqual(result, expected) self.assertEqual( self.client.execute.mock_calls, [mock.call( ' '.join([ 'INSERT INTO groups (\"tenantId\", \"groupId\",",
"in a False when the quorum is unhealthy.\"\"\" def execute(query, data, consistency): return",
"twisted.internet import defer from twisted.trial import unittest class _DBTestCase(unittest.TestCase): \"\"\"Abstract DB test case.\"\"\"",
"'state': 'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'alarm-uvwxyz') result = self.successResultOf(d)",
"[ mock.call( 'DELETE FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'},",
"test_unhealthy(self): \"\"\"Results in a False when the quorum is unhealthy.\"\"\" def execute(query, data,",
"= cass.check_quorum_health(self.client, 'policy-uvwxyz') result = self.successResultOf(d) self.assertTrue(result) self.client.execute.assert_called_once_with( 'SELECT * FROM serverpolicies WHERE",
"'policy-def'}, 1) class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self): \"\"\"Deleting a server policy is",
"[ mock.call( 'DELETE FROM policies WHERE \"groupId\"=:groupId AND \"policyId\"=:policyId;', {'policyId': 'policy-abc', 'groupId': 'group-xyz'},",
"\"\"\"Test bobby.cass.delete_policy.\"\"\" def test_delete_policy(self): \"\"\"Deletes a policy.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect",
"test_policy_state(self): \"\"\"Registers a policy on a server and creates a serverpolicy record.\"\"\" expected",
"'101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateGroup(_DBTestCase): \"\"\"Test bobby.cass.create_group.\"\"\" def test_create_group(self): \"\"\"Creates",
"'group-xyz'}, 1) def test_get_server_by_server_id_not_found(self): \"\"\"Raises an error if no server is found.\"\"\" self.client.execute.return_value",
"\"\"\"Results in a False when the quorum is healthy.\"\"\" def execute(query, data, consistency):",
"WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1)]) class TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\"",
"TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_register_policy_on_server(self): \"\"\"Registers a policy on a server",
"\"\"\"Delete and cascade to delete associated server policies.\"\"\" def execute(*args, **kwargs): return defer.succeed(None)",
"serverpolicies WHERE \"alarmId\"=:alarmId;', {'alarmId': 'alghi'}, 1), mock.call( ('UPDATE serverpolicies SET state=:state WHERE \"policyId\"=:policyId",
"self.client.execute.return_value = defer.succeed(['server-abc', 'server-def']) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d)",
"' '.join([ 'INSERT INTO groups (\"tenantId\", \"groupId\", \"notification\", \"notificationPlan\")', 'VALUES (:tenantId, :groupId, :notification,",
"a server policy is a delete in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d",
"<gh_stars>0 # Copyright 2013 Rackspace, Inc. \"\"\" Tests for bobby.cass \"\"\" from bobby",
"'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz',",
"'server-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self):",
"self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class",
"'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz',",
"result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( 'SELECT * FROM serverpolicies",
"self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an error if more than one policy is found.\"\"\"",
"'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_create_policy(self): \"\"\"Creates and",
"'serverId': 'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'alarm-uvwxyz') result",
"= defer.succeed(['policy-abc', 'policy-def']) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class",
"\"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self): \"\"\"Deleting a server policy is a delete in the",
"case.\"\"\" def setUp(self): \"\"\"Patch CQLClient.\"\"\" self.client = mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def",
"self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1)",
"in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.add_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with(",
"] self.assertEqual(calls, self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self): policies = [{'policyId': 'policy-abc'},",
"WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self): \"\"\"Return a",
"serverpolicies (\"serverId\", \"policyId\", \"alarmId\", \"checkId\", state)' ' VALUES (:serverId, :policyId, :alarmId, :checkId, false);'),",
"the quorum is unhealthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId':",
"'101010') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId;',",
"expected) self.client.execute.assert_called_once_with( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId':",
"= self.successResultOf(d) self.assertEqual(result, ('policy-abc', 'server-def')) calls = [ mock.call( 'SELECT * FROM serverpolicies",
"1), mock.call( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId':",
"'alABCD', 'checkId': 'chABCD'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) def test_deregister_policy_on_server(self): \"\"\"Registers a policy on",
"policy is a delete in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_serverpolicy(self.client,",
"'serverId': 'server-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def",
"is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d)",
"FROM servers WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self):",
"server is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result",
"'101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_group_by_id(self.client, '101010', 'group-abc')",
"'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state': 'Critical'},",
"bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self): policies = [{'policyId': 'policy-abc'}, {'policyId': 'policy-xyz'}] expected = [{'policyId': 'policy-abc',",
"1) ] self.assertEqual(calls, self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self): policies = [{'policyId':",
"groups WHERE \"groupId\"=:groupId AND \"tenantId\"=:tenantId;', {'groupId': 'group-abc', 'tenantId': '101010'}, 1) class TestGetServersByGroupId(_DBTestCase): \"\"\"Test",
"mock.call( 'DELETE FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1)",
"'policy-abc', 'serverId': 'server-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self):",
"'INSERT INTO servers (\"serverId\", \"entityId\", \"groupId\")', 'VALUES (:serverId, :entityId, :groupId);']), {'serverId': 'server-abc', 'entityId':",
"defer from twisted.trial import unittest class _DBTestCase(unittest.TestCase): \"\"\"Abstract DB test case.\"\"\" def setUp(self):",
":alarmId, :checkId, false);'), {'policyId': 'policy-abc', 'serverId': 'server-abc', 'alarmId': 'alABCD', 'checkId': 'chABCD'}, 1), ]",
"'checkId': 'chABCD', 'state': 'false'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policy_state(self.client, 'policy-abc') result =",
"class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self): \"\"\"Deleting a server policy is a delete",
"'group-xyz', 'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM servers WHERE \"groupId\"=:groupId AND",
"'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_server(self.client, expected['tenantId'], expected['serverId'],",
"'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_group(self.client, expected['tenantId'], expected['groupId'],",
"VALUES (:serverId, :policyId);', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def",
"def test_unhealthy(self): \"\"\"Results in a False when the quorum is unhealthy.\"\"\" def execute(query,",
"id.\"\"\" expected = [] self.client.execute.return_value = defer.succeed(expected) d = cass.get_groups_by_tenant_id(self.client, '101010') result =",
"'DELETE FROM serverpolicies WHERE \"serverId\"=:serverId AND \"policyId\"=:policyId;', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class",
"test_alter_alarm_state(self): \"\"\"Creates and returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'serverId': 'server-def',",
"* FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1)]) class",
"found.\"\"\" self.client.execute.return_value = defer.succeed(['server-abc', 'server-def']) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result =",
"{'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) ] self.assertEqual(calls, self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def",
"'entity-ghi'}, {'serverId': 'server-xyz', 'groupId': 'group-def', 'entityId': 'entity-uvw'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_servers_by_group_id(self.client,",
"\"policyId\", \"alarmId\", \"checkId\", state)' ' VALUES (:serverId, :policyId, :alarmId, :checkId, false);'), {'policyId': 'policy-abc',",
"d = cass.create_group(self.client, expected['tenantId'], expected['groupId'], expected['notification'], expected['notificationPlan']) result = self.successResultOf(d) self.assertEqual(result, expected) self.assertEqual(",
"test_create_group(self): \"\"\"Creates a group in Cassandra.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification':",
"'entityId': 'entity-uvw'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_servers_by_group_id(self.client, '101010', 'group-def') result = self.successResultOf(d)",
"WHERE \"policyId\"=:policyId AND \"serverId\"=:serverId;', {'policyId': 'policy-abc', 'serverId': 'server-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class",
"self.client.execute.return_value = defer.succeed(None) d = cass.delete_group(self.client, '101010', 'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM groups",
"in a False when the quorum is healthy.\"\"\" def execute(query, data, consistency): return",
"('INSERT INTO serverpolicies (\"serverId\", \"policyId\", \"alarmId\", \"checkId\", state)' ' VALUES (:serverId, :policyId, :alarmId,",
"more than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['server-abc', 'server-def']) d = cass.get_server_by_server_id(self.client,",
"result = self.successResultOf(d) self.assertEqual(result, ('policy-abc', 'server-def')) calls = [ mock.call( 'SELECT * FROM",
"group in Cassandra.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'}",
"FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1) def test_get_group_by_id_no_such_id(self):",
"WHERE \"policyId\" IN (:policies) AND \"serverId\"=:serverId', {'serverId': 'server-abc', 'policies': 'policy-abc, policy-xyz'}, 1) ]",
"mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self): \"\"\"Return all the groups by a",
"self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'policy-uvwxyz') result = self.successResultOf(d) self.assertTrue(result) self.client.execute.assert_called_once_with( 'SELECT",
"'checkTemplate-rst'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policies_by_group_id(self.client, 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected)",
"\"\"\"Returns all servers by a given group_id.\"\"\" expected = [{'serverId': 'server-abc', 'groupId': 'group-def',",
"calls) class TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\" def test_delete_server(self): \"\"\"Delete and cascade to delete associated",
"{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_server_by_server_id(self.client, '101010',",
"'policy-abc', 'groupId': 'group-xyz'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestServerPoliciesCreateDestroy(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\"",
"'checkTemplate': 'checkTemplate-jkl', 'policyId': 'policy-abc', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM policies WHERE",
"\"\"\"Test bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self): \"\"\"Adding a server policy is an insert in the",
"= execute d = cass.check_quorum_health(self.client, 'alarm-uvwxyz') result = self.successResultOf(d) self.assertFalse(result) def test_healthy(self): \"\"\"Results",
"INTO policies', '(\"policyId\", \"groupId\", \"alarmTemplate\", \"checkTemplate\")', 'VALUES (:policyId, :groupId, :alarmTemplate, :checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi',",
"class TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\" def test_delete_server(self): \"\"\"Delete and cascade to delete associated server",
"'serverId': 'server-abc', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId':",
"TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\" def test_delete_server(self): \"\"\"Delete and cascade to delete associated server policies.\"\"\"",
"class TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self): \"\"\"Returns all servers by a given group_id.\"\"\"",
"'101010', 'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM groups WHERE \"groupId\"=:groupId AND \"tenantId\"=:tenantId;', {'groupId': 'group-abc',",
"return defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d =",
"Inc. \"\"\" Tests for bobby.cass \"\"\" from bobby import cass import mock from",
"def test_get_servers_by_group_id(self): \"\"\"Returns all servers by a given group_id.\"\"\" expected = [{'serverId': 'server-abc',",
"\"groupId\"=:groupId AND \"tenantId\"=:tenantId;', {'groupId': 'group-abc', 'tenantId': '101010'}, 1) class TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def",
"a given tenant id.\"\"\" expected = [] self.client.execute.return_value = defer.succeed(expected) d = cass.get_groups_by_tenant_id(self.client,",
"1), mock.call( ('UPDATE serverpolicies SET state=:state WHERE \"policyId\"=:policyId AND ' '\"serverId\"=:serverId;'), {'state': False,",
"'checkTemplate': 'checkTemplate-jkl'} def execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None) elif",
"'notification-ghi', 'groupId': 'group-abc', 'tenantId': '101010'}, 1), mock.call( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId",
"\"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1) def test_get_group_by_id_no_such_id(self): \"\"\"Raises an error",
"'101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self): \"\"\"Raises an error if more",
"a False when the quorum is healthy.\"\"\" def execute(query, data, consistency): return defer.succeed([",
"\"policyId\"=:policyId;', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self): \"\"\"Gets",
"self.successResultOf(d) calls = [ mock.call( 'DELETE FROM serverpolicies WHERE \"policyId\"=:policyId AND \"serverId\"=:serverId;', {'policyId':",
"[{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'}, {'serverId': 'server-xyz', 'groupId': 'group-def', 'entityId': 'entity-uvw'}] self.client.execute.return_value",
"'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_policy(self.client, expected['policyId'], expected['groupId'],",
"tenant id.\"\"\" expected = [] self.client.execute.return_value = defer.succeed(expected) d = cass.get_groups_by_tenant_id(self.client, '101010') result",
"\"notificationPlan\")', 'VALUES (:tenantId, :groupId, :notification, :notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl', 'notification': 'notification-ghi', 'groupId': 'group-abc', 'tenantId':",
"\"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) ] self.assertEqual(calls, self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\"",
"'groupId': 'group-xyz'}, 1) ] self.assertEqual(calls, self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self): policies",
"= self.successResultOf(d) self.assertTrue(result) self.client.execute.assert_called_once_with( 'SELECT * FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-uvwxyz'}, 1)",
"class TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self): \"\"\"Adding a server policy is an insert",
"policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': 'group-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls)",
"'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state':",
"WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1) def test_get_group_by_id_no_such_id(self): \"\"\"Raises an",
"class TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\" def test_delete_policy(self): \"\"\"Deletes a policy.\"\"\" def execute(*args, **kwargs): return",
"is an insert in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.add_serverpolicy(self.client, 'server-abc',",
"= [{'policyId': 'policy-abc', 'serverId': 'server-abc'}, {'policyId': 'policy-xyz', 'serverId': 'server-abc'}] def execute(query, args, consistency):",
"error if no group is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_group_by_id(self.client, '101010',",
"* FROM serverpolicies WHERE \"alarmId\"=:alarmId;', {'alarmId': 'alghi'}, 1), mock.call( ('UPDATE serverpolicies SET state=:state",
"expected['serverId'], expected['entityId'], expected['groupId']) result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( '",
"\"tenantId\"=:tenantId;', {'tenantId': '101010'}, 1) class TestGetGroupById(_DBTestCase): \"\"\"Test bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self): \"\"\"Returns a single",
"'101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\" def test_create_server(self):",
"'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId':",
"'policy-xyz', 'serverId': 'server-abc'}] def execute(query, args, consistency): if 'FROM policies' in query: return",
"def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc',",
"self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self): \"\"\"Raises an error if more than one group is",
"'notificationPlan': 'notificationPlan-jkl'} def execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None) elif",
"'server-abc', 'policyId': 'policy-def'}, 1) class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self): \"\"\"Deleting a server",
"more than one policy is found.\"\"\" self.client.execute.return_value = defer.succeed(['policy-abc', 'policy-def']) d = cass.get_policy_by_policy_id(self.client,",
"'tenantId': '101010'}, 1) class TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self): \"\"\"Returns all servers by",
"cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self): \"\"\"Raises an error if",
"= execute d = cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc', 'alABCD', 'chABCD') self.successResultOf(d) calls = [",
":groupId, :alarmTemplate, :checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl', 'policyId': 'policy-abc', 'groupId': 'group-def'}, 1), mock.call(",
"'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi', 'tenantId': '101010'} def execute(query, data, consistency): if 'INSERT'",
"'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result =",
"args, consistency): if 'FROM policies' in query: return defer.succeed(policies) else: return defer.succeed(expected) self.client.execute.side_effect",
"policy dict, rather than a single item list.\"\"\" expected = {'policyId': 'policy-abc', 'groupId':",
"self.client = mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self): \"\"\"Return all the groups",
"cass.add_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT INTO serverpolicies (\"serverId\", \"policyId\") VALUES (:serverId, :policyId);',",
"if no group is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_group_by_id(self.client, '101010', 'group-abc')",
"= cass.add_serverpolicy(self.client, 'server-abc', 'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT INTO serverpolicies (\"serverId\", \"policyId\") VALUES (:serverId,",
"'policy-abc', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;',",
"self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'alarm-uvwxyz') result = self.successResultOf(d) self.assertFalse(result) def test_healthy(self):",
"= execute d = cass.check_quorum_health(self.client, 'policy-uvwxyz') result = self.successResultOf(d) self.assertTrue(result) self.client.execute.assert_called_once_with( 'SELECT *",
"'policy-def') self.successResultOf(d) self.client.execute.assert_called_once_with( 'INSERT INTO serverpolicies (\"serverId\", \"policyId\") VALUES (:serverId, :policyId);', {'serverId': 'server-abc',",
"\"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self): policies = [{'policyId': 'policy-abc'}, {'policyId': 'policy-xyz'}] expected = [{'policyId':",
"a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'serverId': 'server-def', 'alarmId': 'alghi', 'checkId': 'chjkl',",
"defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'},",
"TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self): \"\"\"Return a single server dict, rather than a",
"d = cass.delete_policy(self.client, 'group-xyz', 'policy-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM policies",
"serverpolicy record.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.deregister_policy_on_server(self.client,",
"if 'INSERT' in query: return defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect",
"dict.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} def execute(query,",
"= {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} def execute(query, data, consistency):",
"[] self.client.execute.return_value = defer.succeed(expected) d = cass.get_groups_by_tenant_id(self.client, '101010') result = self.successResultOf(d) self.assertEqual(result, expected)",
"= self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'},",
"'group-def', 'alarmId': 'alABCD', 'checkId': 'chABCD', 'state': 'false'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policy_state(self.client,",
"d = cass.create_policy(self.client, expected['policyId'], expected['groupId'], expected['alarmTemplate'], expected['checkTemplate']) result = self.successResultOf(d) self.assertEqual(result, expected) calls",
"\"\"\"Creates and returns a server dict.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId':",
"defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_group(self.client,",
"* FROM serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase):",
"serverpolicies WHERE \"policyId\"=:policyId;', {'policyId': 'policy-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\"",
"self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId;', {'tenantId': '101010'}, 1) class TestGetGroupById(_DBTestCase): \"\"\"Test",
"self.client.execute.return_value = defer.succeed([]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def",
"'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}, {'policyId': 'policy-xyz', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-uvw',",
"= {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi', 'tenantId': '101010'} def execute(query, data, consistency):",
"= defer.succeed([]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self):",
"rather than a single item list.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate':",
"'server-abc', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi',",
"expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi'} self.client.execute.return_value = defer.succeed([expected]) d =",
"a server dict.\"\"\" expected = {'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi', 'tenantId': '101010'}",
"= [ mock.call( ' '.join([ 'INSERT INTO servers (\"serverId\", \"entityId\", \"groupId\")', 'VALUES (:serverId,",
"dict, rather than a single item list.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def',",
"'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state':",
"defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_policy(self.client, expected['policyId'], expected['groupId'], expected['alarmTemplate'], expected['checkTemplate']) result =",
"'group-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_group_by_id_integrity_problems(self): \"\"\"Raises an error if more than",
"expected) calls = [ mock.call( ' '.join([ 'INSERT INTO policies', '(\"policyId\", \"groupId\", \"alarmTemplate\",",
"'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-mno', 'state':",
"def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an error if more than one policy is found.\"\"\" self.client.execute.return_value",
"class _DBTestCase(unittest.TestCase): \"\"\"Abstract DB test case.\"\"\" def setUp(self): \"\"\"Patch CQLClient.\"\"\" self.client = mock.create_autospec(CQLClient)",
"cass.delete_group(self.client, '101010', 'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM groups WHERE \"groupId\"=:groupId AND \"tenantId\"=:tenantId;', {'groupId':",
"\"checkTemplate\")', 'VALUES (:policyId, :groupId, :alarmTemplate, :checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl', 'policyId': 'policy-abc', 'groupId':",
"'group-abc'}, 1), mock.call('SELECT * FROM serverpolicies WHERE \"policyId\" IN (:policies) AND \"serverId\"=:serverId', {'serverId':",
"policy-xyz'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestAddServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.add_serverpolicy\"\"\" def test_add_serverpolicy(self): \"\"\"Adding a",
"self.assertFalse(result) def test_healthy(self): \"\"\"Results in a False when the quorum is healthy.\"\"\" def",
"error if no server is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_server_by_server_id(self.client, '101010',",
"cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call('SELECT *",
"a single item list.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate':",
"= self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_create_policy(self): \"\"\"Creates and returns a",
"{'policyId': 'policy-abc', 'groupId': 'group-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\" def",
"bobby.cass.get_group_by_id.\"\"\" def test_get_group_by_id(self): \"\"\"Returns a single dict, rather than a single item list.\"\"\"",
"bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self): \"\"\"Return a single server dict, rather than a single item",
"a single dict, rather than a single item list.\"\"\" expected = {'groupId': 'group-abc',",
"policies WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self): \"\"\"Return",
"= cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_server_by_id_integrity_problems(self): \"\"\"Raises an",
"mock.call( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'},",
"in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_group(self.client, expected['tenantId'], expected['groupId'], expected['notification'],",
"d = cass.check_quorum_health(self.client, 'policy-uvwxyz') result = self.successResultOf(d) self.assertTrue(result) self.client.execute.assert_called_once_with( 'SELECT * FROM serverpolicies",
"defer.succeed(expected) d = cass.get_policy_state(self.client, 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls = [",
"'groupId': 'group-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\" def test_delete_policy(self): \"\"\"Deletes",
"'101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_create_policy(self): \"\"\"Creates",
"self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId':",
"'chABCD', 'state': 'false'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policy_state(self.client, 'policy-abc') result = self.successResultOf(d)",
"'chABCD') self.successResultOf(d) calls = [ mock.call( ('INSERT INTO serverpolicies (\"serverId\", \"policyId\", \"alarmId\", \"checkId\",",
"is healthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state':",
"= cass.get_servers_by_group_id(self.client, '101010', 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM",
":alarmTemplate, :checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl', 'policyId': 'policy-abc', 'groupId': 'group-def'}, 1), mock.call( 'SELECT",
"\"\"\" from bobby import cass import mock from silverberg.client import CQLClient from twisted.internet",
"found.\"\"\" self.client.execute.return_value = defer.succeed(['group1', 'group2']) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result = self.failureResultOf(d)",
"for bobby.cass \"\"\" from bobby import cass import mock from silverberg.client import CQLClient",
"def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_policy(self.client, 'group-xyz', 'policy-abc')",
"a single item list.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan':",
"mock.call( 'DELETE FROM serverpolicies WHERE \"policyId\"=:policyId AND \"serverId\"=:serverId;', {'policyId': 'policy-abc', 'serverId': 'server-abc'}, 1),",
"1), mock.call('SELECT * FROM serverpolicies WHERE \"policyId\" IN (:policies) AND \"serverId\"=:serverId', {'serverId': 'server-abc',",
"self.successResultOf(d) calls = [ mock.call( ('INSERT INTO serverpolicies (\"serverId\", \"policyId\", \"alarmId\", \"checkId\", state)'",
"consistency): if 'INSERT' in query: return defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected])",
"is unhealthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId': 'policy-uvwxyz', 'serverId': 'server-abc', 'state':",
"INTO serverpolicies (\"serverId\", \"policyId\", \"alarmId\", \"checkId\", state)' ' VALUES (:serverId, :policyId, :alarmId, :checkId,",
"TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self): \"\"\"Results in a False when the quorum is",
"] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\" def test_delete_policy(self): \"\"\"Deletes a policy.\"\"\" def",
"= cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT *",
"expected['alarmId'], False) result = self.successResultOf(d) self.assertEqual(result, ('policy-abc', 'server-def')) calls = [ mock.call( 'SELECT",
"'101010'}, 1), mock.call( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010',",
"'chjkl', 'state': True} def execute(query, data, consistency): if 'UPDATE' in query: return defer.succeed(None)",
"TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_create_policy(self): \"\"\"Creates and returns a policy dict.\"\"\" expected =",
"(:serverId, :policyId);', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self):",
"{'policyId': 'policy-xyz'}] expected = [{'policyId': 'policy-abc', 'serverId': 'server-abc'}, {'policyId': 'policy-xyz', 'serverId': 'server-abc'}] def",
"= cass.delete_policy(self.client, 'group-xyz', 'policy-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM policies WHERE",
"query: return defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d",
"= defer.succeed([expected]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected)",
"setUp(self): \"\"\"Patch CQLClient.\"\"\" self.client = mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self): \"\"\"Return",
"def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an error if no policy is found.\"\"\" self.client.execute.return_value = defer.succeed([])",
"d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an",
"'101010', 'groupId': 'group-abc'}, 1) def test_get_group_by_id_no_such_id(self): \"\"\"Raises an error if no group is",
"= self.failureResultOf(d) self.assertTrue(result.check(cass.ResultNotFoundError)) def test_get_policy_by_policy_id_integrity_problems(self): \"\"\"Raises an error if more than one policy",
"defer.succeed(policies) else: return defer.succeed(expected) self.client.execute.side_effect = execute d = cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc') result",
"* FROM serverpolicies WHERE \"policyId\" IN (:policies) AND \"serverId\"=:serverId', {'serverId': 'server-abc', 'policies': 'policy-abc,",
"single server dict, rather than a single item list.\"\"\" expected = {'serverId': 'server-abc',",
"bobby.cass.create_server.\"\"\" def test_create_server(self): \"\"\"Creates and returns a server dict.\"\"\" expected = {'serverId': 'server-abc',",
"\"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) def test_get_server_by_server_id_not_found(self): \"\"\"Raises an error",
"{'groupId': 'group-def'}, 1) class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self): \"\"\"Return a single policy",
"d = cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc', 'alABCD', 'chABCD') self.successResultOf(d) calls = [ mock.call( ('INSERT",
"'group-abc') self.successResultOf(d) self.client.execute.assert_called_once_with( 'DELETE FROM groups WHERE \"groupId\"=:groupId AND \"tenantId\"=:tenantId;', {'groupId': 'group-abc', 'tenantId':",
"1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self): \"\"\"Creates and returns",
"SET state=:state WHERE \"policyId\"=:policyId AND ' '\"serverId\"=:serverId;'), {'state': False, 'policyId': 'policy-abc', 'serverId': 'server-def'},",
"1) class TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self): \"\"\"Returns all servers by a given",
"policies WHERE \"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': '101010'}, 1) def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises",
"{'serverId': 'server-abc', 'groupId': 'group-def', 'entityId': 'entity-ghi', 'tenantId': '101010'} def execute(query, data, consistency): if",
"defer.succeed(['policy-abc', 'policy-def']) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase):",
"'entityId': 'entity-ghi'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result =",
"WHERE \"alarmId\"=:alarmId;', {'alarmId': 'alghi'}, 1), mock.call( ('UPDATE serverpolicies SET state=:state WHERE \"policyId\"=:policyId AND",
"self.client.execute.side_effect = execute d = cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected)",
"\"\"\"Creates and returns a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate':",
"expected['tenantId'], expected['groupId'], expected['notification'], expected['notificationPlan']) result = self.successResultOf(d) self.assertEqual(result, expected) self.assertEqual( self.client.execute.mock_calls, [mock.call( '",
"'101010'}, 1) class TestGetServersByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_servers_by_group_id.\"\"\" def test_get_servers_by_group_id(self): \"\"\"Returns all servers by a",
"'serverId': 'server-mno', 'state': 'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'policy-uvwxyz') result",
"result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call( ' '.join([ 'INSERT INTO",
"policies from a provided group.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi',",
"Copyright 2013 Rackspace, Inc. \"\"\" Tests for bobby.cass \"\"\" from bobby import cass",
"calls = [ mock.call('SELECT * FROM policies WHERE \"groupId\"=:groupId', {'groupId': 'group-abc'}, 1), mock.call('SELECT",
"def test_add_serverpolicy(self): \"\"\"Adding a server policy is an insert in the database.\"\"\" self.client.execute.return_value",
"'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policies_by_group_id(self.client, 'group-def') result =",
"error if more than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['server-abc', 'server-def']) d",
"'UPDATE' in query: return defer.succeed(None) elif 'SELECT' in query: return defer.succeed([expected]) self.client.execute.side_effect =",
"'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policies_by_group_id(self.client, 'group-def')",
"\"policyId\"=:policyId AND \"groupId\"=:groupId;', {'policyId': 'policy-abc', 'groupId': 'group-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeletePolicy(_DBTestCase):",
"'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-jkl', 'state': 'Critical'},",
"cass.get_server_by_server_id(self.client, '101010', 'group-xyz', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM",
"is a delete in the database.\"\"\" self.client.execute.return_value = defer.succeed(None) d = cass.delete_serverpolicy(self.client, 'server-abc',",
"class TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self): \"\"\"Return a single server dict, rather than",
"'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'Critical'}, {'policyId': 'policy-uvwxyz', 'serverId':",
"{'tenantId': '101010', 'groupId': 'group-abc'}, 1)]) class TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\" def test_delete_group(self): \"\"\"Deletes a",
"'serverId': 'server-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\" def test_unhealthy(self): \"\"\"Results",
"an error if more than one policy is found.\"\"\" self.client.execute.return_value = defer.succeed(['policy-abc', 'policy-def'])",
"'server-abc', 'groupId': 'group-xyz'}, 1) ] self.assertEqual(calls, self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self):",
"execute(query, args, consistency): if 'FROM policies' in query: return defer.succeed(policies) else: return defer.succeed(expected)",
"FROM policies WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self):",
"'VALUES (:policyId, :groupId, :alarmTemplate, :checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl', 'policyId': 'policy-abc', 'groupId': 'group-def'},",
"cass import mock from silverberg.client import CQLClient from twisted.internet import defer from twisted.trial",
"= {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value = defer.succeed([expected]) d",
"'alABCD', 'chABCD') self.successResultOf(d) calls = [ mock.call( ('INSERT INTO serverpolicies (\"serverId\", \"policyId\", \"alarmId\",",
"expected['policyId'], expected['groupId'], expected['alarmTemplate'], expected['checkTemplate']) result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call(",
"'server-def')) calls = [ mock.call( 'SELECT * FROM serverpolicies WHERE \"alarmId\"=:alarmId;', {'alarmId': 'alghi'},",
"self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreateServer(_DBTestCase): \"\"\"Test bobby.cass.create_server.\"\"\" def test_create_server(self): \"\"\"Creates and returns a server dict.\"\"\"",
"{'groupId': 'group-def'}, 1) class TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self): \"\"\"Return a single server",
"an error if more than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['server-abc', 'server-def'])",
"(\"tenantId\", \"groupId\", \"notification\", \"notificationPlan\")', 'VALUES (:tenantId, :groupId, :notification, :notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl', 'notification': 'notification-ghi',",
"defer.succeed(expected) d = cass.get_policies_by_group_id(self.client, 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT *",
"'group-def'}, 1)] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeleteServer(_DBTestCase): \"\"\"Test bobby.cass.delete_server.\"\"\" def test_delete_server(self): \"\"\"Delete and cascade",
"False when the quorum is healthy.\"\"\" def execute(query, data, consistency): return defer.succeed([ {'policyId':",
"'group-def', 'entityId': 'entity-ghi', 'tenantId': '101010'} def execute(query, data, consistency): if 'INSERT' in query:",
"'policy-abc', 'groupId': 'group-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\" def test_delete_policy(self):",
"'groupId': 'group-def', 'alarmId': 'alABCD', 'checkId': 'chABCD', 'state': 'false'}] self.client.execute.return_value = defer.succeed(expected) d =",
"FROM serverpolicies WHERE \"alarmId\"=:alarmId;', {'alarmId': 'alghi'}, 1), mock.call( ('UPDATE serverpolicies SET state=:state WHERE",
"expected) calls = [ mock.call('SELECT * FROM policies WHERE \"groupId\"=:groupId', {'groupId': 'group-abc'}, 1),",
"\"policyId\") VALUES (:serverId, :policyId);', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\"",
"def test_get_serverpolicies_by_server_id(self): policies = [{'policyId': 'policy-abc'}, {'policyId': 'policy-xyz'}] expected = [{'policyId': 'policy-abc', 'serverId':",
"creates a serverpolicy record.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d",
"server policies.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect = execute d = cass.delete_server(self.client,",
"'state': 'Critical'}, ]) self.client.execute.side_effect = execute d = cass.check_quorum_health(self.client, 'policy-uvwxyz') result = self.successResultOf(d)",
"'VALUES (:serverId, :entityId, :groupId);']), {'serverId': 'server-abc', 'entityId': 'entity-ghi', 'groupId': 'group-def'}, 1), mock.call( 'SELECT",
":entityId, :groupId);']), {'serverId': 'server-abc', 'entityId': 'entity-ghi', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM",
"= cass.get_policies_by_group_id(self.client, 'group-def') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies",
"expected = [{'policyId': 'policy-abc', 'serverId': 'server-abc'}, {'policyId': 'policy-xyz', 'serverId': 'server-abc'}] def execute(query, args,",
"a policy dict.\"\"\" expected = {'policyId': 'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}",
"def execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None) elif 'SELECT' in",
"'VALUES (:tenantId, :groupId, :notification, :notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl', 'notification': 'notification-ghi', 'groupId': 'group-abc', 'tenantId': '101010'},",
"{'policyId': 'policy-abc', 'serverId': 'server-def', 'alarmId': 'alghi', 'checkId': 'chjkl', 'state': True} def execute(query, data,",
"class TestServerPolicies(_DBTestCase): \"\"\"Test bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self): \"\"\"Registers a policy on a",
"= execute d = cass.create_server(self.client, expected['tenantId'], expected['serverId'], expected['entityId'], expected['groupId']) result = self.successResultOf(d) self.assertEqual(result,",
"'(\"policyId\", \"groupId\", \"alarmTemplate\", \"checkTemplate\")', 'VALUES (:policyId, :groupId, :alarmTemplate, :checkTemplate);']), {'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl',",
"'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId': '101010', 'groupId': 'group-abc'}, 1)",
"self.client.execute.return_value = defer.succeed(expected) d = cass.get_groups_by_tenant_id(self.client, '101010') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with(",
"list.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value =",
"{'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self): \"\"\"Gets all",
"class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self): \"\"\"Gets all policies from a provided group.\"\"\"",
"TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self): \"\"\"Deleting a server policy is a delete in",
"d = cass.get_policy_state(self.client, 'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call(",
"self.assertEqual(self.client.execute.mock_calls, calls) class TestDeletePolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_policy.\"\"\" def test_delete_policy(self): \"\"\"Deletes a policy.\"\"\" def execute(*args,",
"= [ mock.call( 'DELETE FROM serverpolicies WHERE \"policyId\"=:policyId AND \"serverId\"=:serverId;', {'policyId': 'policy-abc', 'serverId':",
"self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_alter_alarm_state(self): \"\"\"Creates and returns a policy dict.\"\"\"",
"AND \"policyId\"=:policyId;', {'serverId': 'server-abc', 'policyId': 'policy-def'}, 1) class TestGetPoliciesByGroupId(_DBTestCase): \"\"\"Test bobby.cass.get_policies_by_group_id.\"\"\" def test_get_policies_by_group_id(self):",
"\"\"\"Patch CQLClient.\"\"\" self.client = mock.create_autospec(CQLClient) class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self): \"\"\"Return all",
"self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM groups WHERE \"tenantId\"=:tenantId AND \"groupId\"=:groupId;', {'tenantId':",
"\"\"\"Registers a policy on a server and creates a serverpolicy record.\"\"\" def execute(*args,",
"test_get_serverpolicies_by_server_id(self): policies = [{'policyId': 'policy-abc'}, {'policyId': 'policy-xyz'}] expected = [{'policyId': 'policy-abc', 'serverId': 'server-abc'},",
"= cass.create_group(self.client, expected['tenantId'], expected['groupId'], expected['notification'], expected['notificationPlan']) result = self.successResultOf(d) self.assertEqual(result, expected) self.assertEqual( self.client.execute.mock_calls,",
"and cascade to delete associated server policies.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect",
"'server-abc', 'entityId': 'entity-ghi', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM servers WHERE \"groupId\"=:groupId",
"= cass.get_serverpolicies_by_server_id(self.client, 'group-abc', 'server-abc') result = self.successResultOf(d) self.assertEqual(result, expected) calls = [ mock.call('SELECT",
"class TestGetGroupsByTenantId(_DBTestCase): \"\"\"Test bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self): \"\"\"Return all the groups by a given",
"WHERE \"policyId\"=:policyId;', {'policyId': 'policy-abc'}, 1), ] self.assertEqual(calls, self.client.execute.mock_calls) class TestAlterAlarmState(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def",
"bobby.cass.register_policy_on_server and bobby.cass.deregister_policy_on_server.\"\"\" def test_policy_state(self): \"\"\"Registers a policy on a server and creates",
"result = self.successResultOf(d) self.assertFalse(result) def test_healthy(self): \"\"\"Results in a False when the quorum",
"'entity-uvw'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_servers_by_group_id(self.client, '101010', 'group-def') result = self.successResultOf(d) self.assertEqual(result,",
"* FROM policies WHERE \"groupId\"=:groupId', {'groupId': 'group-abc'}, 1), mock.call('SELECT * FROM serverpolicies WHERE",
"\"\"\"Results in a False when the quorum is unhealthy.\"\"\" def execute(query, data, consistency):",
"'groupId': '101010'}, 1) def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an error if no policy is found.\"\"\"",
"'policy-abc', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_policy_by_policy_id(self.client,",
"cass.create_policy(self.client, expected['policyId'], expected['groupId'], expected['alarmTemplate'], expected['checkTemplate']) result = self.successResultOf(d) self.assertEqual(result, expected) calls = [",
"cass.alter_alarm_state(self.client, expected['alarmId'], False) result = self.successResultOf(d) self.assertEqual(result, ('policy-abc', 'server-def')) calls = [ mock.call(",
"an error if more than one group is found.\"\"\" self.client.execute.return_value = defer.succeed(['group1', 'group2'])",
"bobby.cass.get_groups_by_tenant_id.\"\"\" def test_get_grous_by_tenant_id(self): \"\"\"Return all the groups by a given tenant id.\"\"\" expected",
"False, 'policyId': 'policy-abc', 'serverId': 'server-def'}, 1) ] self.assertEqual(self.client.execute.mock_calls, calls) class TestCheckQuorumHealth(_DBTestCase): \"\"\"Test bobby.cass.check_quorum_health.\"\"\"",
"1), ] self.assertEqual(calls, self.client.execute.mock_calls) def test_deregister_policy_on_server(self): \"\"\"Registers a policy on a server and",
"in query: return defer.succeed([expected]) self.client.execute.side_effect = execute d = cass.create_policy(self.client, expected['policyId'], expected['groupId'], expected['alarmTemplate'],",
"class TestDeleteGroup(_DBTestCase): \"\"\"Test bobby.cass.delete_group.\"\"\" def test_delete_group(self): \"\"\"Deletes a group.\"\"\" self.client.execute.return_value = defer.succeed(None) d",
"'101010'} def execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None) elif 'SELECT'",
"dict.\"\"\" expected = {'policyId': 'policy-abc', 'serverId': 'server-def', 'alarmId': 'alghi', 'checkId': 'chjkl', 'state': True}",
"a server and creates a serverpolicy record.\"\"\" def execute(*args, **kwargs): return defer.succeed(None) self.client.execute.side_effect",
"result = self.failureResultOf(d) self.assertTrue(result.check(cass.ExcessiveResultsError)) class TestCreatePolicy(_DBTestCase): \"\"\"Test bobby.cass.create_policy.\"\"\" def test_create_policy(self): \"\"\"Creates and returns",
"mock.call( 'SELECT * FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-def'},",
"= {'policyId': 'policy-abc', 'serverId': 'server-def', 'alarmId': 'alghi', 'checkId': 'chjkl', 'state': True} def execute(query,",
"' '.join([ 'INSERT INTO servers (\"serverId\", \"entityId\", \"groupId\")', 'VALUES (:serverId, :entityId, :groupId);']), {'serverId':",
"\"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetPolicyByPolicyId(_DBTestCase): \"\"\"Test bobby.cass.get_policy_by_policy_id.\"\"\" def test_get_policy_by_policy_id(self): \"\"\"Return a single",
"no policy is found.\"\"\" self.client.execute.return_value = defer.succeed([]) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result",
"servers WHERE \"groupId\"=:groupId;', {'groupId': 'group-def'}, 1) class TestGetServerByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_server_by_server_id.\"\"\" def test_get_server_by_server_id(self): \"\"\"Return",
"'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} def execute(query, data, consistency): if 'INSERT' in query: return defer.succeed(None)",
"{'policyId': 'policy-uvwxyz', 'serverId': 'server-def', 'state': 'OK'}, {'policyId': 'policy-uvwxyz', 'serverId': 'server-ghi', 'state': 'Critical'}, {'policyId':",
"cass.create_group(self.client, expected['tenantId'], expected['groupId'], expected['notification'], expected['notificationPlan']) result = self.successResultOf(d) self.assertEqual(result, expected) self.assertEqual( self.client.execute.mock_calls, [mock.call(",
"servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;', {'serverId': 'server-abc', 'groupId': 'group-xyz'}, 1) def test_get_server_by_server_id_not_found(self): \"\"\"Raises",
"{'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl', 'policyId': 'policy-abc', 'groupId': 'group-def'}, 1), mock.call( 'SELECT * FROM",
"\"alarmId\"=:alarmId;', {'alarmId': 'alghi'}, 1), mock.call( ('UPDATE serverpolicies SET state=:state WHERE \"policyId\"=:policyId AND '",
"1) def test_get_policy_by_policy_id_not_found(self): \"\"\"Raises an error if no policy is found.\"\"\" self.client.execute.return_value =",
"policy is found.\"\"\" self.client.execute.return_value = defer.succeed(['policy-abc', 'policy-def']) d = cass.get_policy_by_policy_id(self.client, '101010', 'policy-abc') result",
"= execute d = cass.create_policy(self.client, expected['policyId'], expected['groupId'], expected['alarmTemplate'], expected['checkTemplate']) result = self.successResultOf(d) self.assertEqual(result,",
"a policy on a server and creates a serverpolicy record.\"\"\" def execute(*args, **kwargs):",
"execute d = cass.delete_policy(self.client, 'group-xyz', 'policy-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM",
"'server-abc') self.successResultOf(d) calls = [ mock.call( 'DELETE FROM servers WHERE \"groupId\"=:groupId AND \"serverId\"=:serverId;',",
"FROM policies WHERE \"groupId\"=:groupId', {'groupId': 'group-abc'}, 1), mock.call('SELECT * FROM serverpolicies WHERE \"policyId\"",
"'server-xyz', 'groupId': 'group-def', 'entityId': 'entity-uvw'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_servers_by_group_id(self.client, '101010', 'group-def')",
"expected['groupId'], expected['notification'], expected['notificationPlan']) result = self.successResultOf(d) self.assertEqual(result, expected) self.assertEqual( self.client.execute.mock_calls, [mock.call( ' '.join([",
":notificationPlan);']), {'notificationPlan': 'notificationPlan-jkl', 'notification': 'notification-ghi', 'groupId': 'group-abc', 'tenantId': '101010'}, 1), mock.call( 'SELECT *",
"'checkTemplate-jkl'}, {'policyId': 'policy-xyz', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value = defer.succeed(expected) d",
"'policyId': 'policy-def'}, 1) class TestDeleteServerpolicy(_DBTestCase): \"\"\"Test bobby.cass.delete_serverpolicy\"\"\" def test_delete_serverpolicy(self): \"\"\"Deleting a server policy",
":checkId, false);'), {'policyId': 'policy-abc', 'serverId': 'server-abc', 'alarmId': 'alABCD', 'checkId': 'chABCD'}, 1), ] self.assertEqual(calls,",
"'alarmTemplate': 'alarmTemplate-ghi', 'checkTemplate': 'checkTemplate-jkl'}, {'policyId': 'policy-xyz', 'groupId': 'group-def', 'alarmTemplate': 'alarmTemplate-uvw', 'checkTemplate': 'checkTemplate-rst'}] self.client.execute.return_value",
"a group in Cassandra.\"\"\" expected = {'groupId': 'group-abc', 'tenantId': '101010', 'notification': 'notification-ghi', 'notificationPlan':",
"'groupId': 'group-abc'}, 1) def test_get_group_by_id_no_such_id(self): \"\"\"Raises an error if no group is found.\"\"\"",
"self.client.execute.mock_calls) class TestGetServerPoliciesByServerId(_DBTestCase): \"\"\"Test bobby.cass.get_serverpolicies_by_server_id.\"\"\" def test_get_serverpolicies_by_server_id(self): policies = [{'policyId': 'policy-abc'}, {'policyId': 'policy-xyz'}]",
"'policy-abc') result = self.successResultOf(d) self.assertEqual(result, expected) self.client.execute.assert_called_once_with( 'SELECT * FROM policies WHERE \"policyId\"=:policyId",
"test_get_policies_by_group_id(self): \"\"\"Gets all policies from a provided group.\"\"\" expected = [{'policyId': 'policy-abc', 'groupId':",
"'alABCD', 'checkId': 'chABCD', 'state': 'false'}] self.client.execute.return_value = defer.succeed(expected) d = cass.get_policy_state(self.client, 'policy-abc') result",
"return defer.succeed(None) self.client.execute.side_effect = execute d = cass.register_policy_on_server(self.client, 'policy-abc', 'server-abc', 'alABCD', 'chABCD') self.successResultOf(d)",
"'notification': 'notification-ghi', 'notificationPlan': 'notificationPlan-jkl'} self.client.execute.return_value = defer.succeed([expected]) d = cass.get_group_by_id(self.client, '101010', 'group-abc') result"
] |
[
"data = response.json() # print(data) longitude = data[\"iss_position\"][\"longitude\"] latitude = data[\"iss_position\"][\"latitude\"] iss_position =",
"# print(data) longitude = data[\"iss_position\"][\"longitude\"] latitude = data[\"iss_position\"][\"latitude\"] iss_position = (longitude, latitude) print(iss_position)",
"requests.get(url=\"http://api.open-notify.org/iss-now.json\") response.raise_for_status() data = response.json() # print(data) longitude = data[\"iss_position\"][\"longitude\"] latitude = data[\"iss_position\"][\"latitude\"]",
"requests response = requests.get(url=\"http://api.open-notify.org/iss-now.json\") response.raise_for_status() data = response.json() # print(data) longitude = data[\"iss_position\"][\"longitude\"]",
"= requests.get(url=\"http://api.open-notify.org/iss-now.json\") response.raise_for_status() data = response.json() # print(data) longitude = data[\"iss_position\"][\"longitude\"] latitude =",
"<gh_stars>1-10 import requests response = requests.get(url=\"http://api.open-notify.org/iss-now.json\") response.raise_for_status() data = response.json() # print(data) longitude",
"response = requests.get(url=\"http://api.open-notify.org/iss-now.json\") response.raise_for_status() data = response.json() # print(data) longitude = data[\"iss_position\"][\"longitude\"] latitude",
"response.raise_for_status() data = response.json() # print(data) longitude = data[\"iss_position\"][\"longitude\"] latitude = data[\"iss_position\"][\"latitude\"] iss_position",
"= response.json() # print(data) longitude = data[\"iss_position\"][\"longitude\"] latitude = data[\"iss_position\"][\"latitude\"] iss_position = (longitude,",
"import requests response = requests.get(url=\"http://api.open-notify.org/iss-now.json\") response.raise_for_status() data = response.json() # print(data) longitude =",
"response.json() # print(data) longitude = data[\"iss_position\"][\"longitude\"] latitude = data[\"iss_position\"][\"latitude\"] iss_position = (longitude, latitude)"
] |
[
"\"0.0.0\" setup( name=\"pyfastg\", version=version, license=\"MIT\", description=description, long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\",",
"\"\"\" Development Status :: 3 - Alpha Topic :: Software Development :: Libraries",
"Alpha Topic :: Software Development :: Libraries Topic :: Scientific/Engineering Topic :: Scientific/Engineering",
"from https://github.com/biocore/qurro/blob/master/setup.py from setuptools import find_packages, setup classes = \"\"\" Development Status ::",
"Scientific/Engineering Topic :: Scientific/Engineering :: Bio-Informatics Programming Language :: Python :: 3 Programming",
":: Bio-Informatics Programming Language :: Python :: 3 Programming Language :: Python ::",
"s in classes.split(\"\\n\") if s] description = \"Minimal Python library for parsing SPAdes",
"= \"0.0.0\" setup( name=\"pyfastg\", version=version, license=\"MIT\", description=description, long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\",",
"Programming Language :: Python :: 3 Programming Language :: Python :: 3 ::",
"Language :: Python :: 3 :: Only \"\"\" classifiers = [s.strip() for s",
"Topic :: Scientific/Engineering Topic :: Scientific/Engineering :: Bio-Informatics Programming Language :: Python ::",
":: 3 - Alpha Topic :: Software Development :: Libraries Topic :: Scientific/Engineering",
"files\" with open(\"README.md\") as f: long_description = f.read() version = \"0.0.0\" setup( name=\"pyfastg\",",
":: Scientific/Engineering Topic :: Scientific/Engineering :: Bio-Informatics Programming Language :: Python :: 3",
"long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\", classifiers=classifiers, packages=find_packages(), install_requires=[\"networkx\", \"scikit-bio\"], extras_require={\"dev\": [\"pytest\",",
"open(\"README.md\") as f: long_description = f.read() version = \"0.0.0\" setup( name=\"pyfastg\", version=version, license=\"MIT\",",
"description=description, long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\", classifiers=classifiers, packages=find_packages(), install_requires=[\"networkx\", \"scikit-bio\"], extras_require={\"dev\":",
":: Python :: 3 Programming Language :: Python :: 3 :: Only \"\"\"",
"Software Development :: Libraries Topic :: Scientific/Engineering Topic :: Scientific/Engineering :: Bio-Informatics Programming",
"\"Minimal Python library for parsing SPAdes FASTG files\" with open(\"README.md\") as f: long_description",
"if s] description = \"Minimal Python library for parsing SPAdes FASTG files\" with",
"long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\", classifiers=classifiers, packages=find_packages(), install_requires=[\"networkx\", \"scikit-bio\"], extras_require={\"dev\": [\"pytest\", \"pytest-cov\",",
"name=\"pyfastg\", version=version, license=\"MIT\", description=description, long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\", classifiers=classifiers, packages=find_packages(),",
"classes = \"\"\" Development Status :: 3 - Alpha Topic :: Software Development",
"Python :: 3 :: Only \"\"\" classifiers = [s.strip() for s in classes.split(\"\\n\")",
"3 - Alpha Topic :: Software Development :: Libraries Topic :: Scientific/Engineering Topic",
"Topic :: Software Development :: Libraries Topic :: Scientific/Engineering Topic :: Scientific/Engineering ::",
"parsing SPAdes FASTG files\" with open(\"README.md\") as f: long_description = f.read() version =",
"version=version, license=\"MIT\", description=description, long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\", classifiers=classifiers, packages=find_packages(), install_requires=[\"networkx\",",
"https://github.com/biocore/qurro/blob/master/setup.py from setuptools import find_packages, setup classes = \"\"\" Development Status :: 3",
"f.read() version = \"0.0.0\" setup( name=\"pyfastg\", version=version, license=\"MIT\", description=description, long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\",",
"Derived from https://github.com/biocore/qurro/blob/master/setup.py from setuptools import find_packages, setup classes = \"\"\" Development Status",
":: 3 Programming Language :: Python :: 3 :: Only \"\"\" classifiers =",
":: Software Development :: Libraries Topic :: Scientific/Engineering Topic :: Scientific/Engineering :: Bio-Informatics",
"setuptools import find_packages, setup classes = \"\"\" Development Status :: 3 - Alpha",
"Python library for parsing SPAdes FASTG files\" with open(\"README.md\") as f: long_description =",
":: Scientific/Engineering :: Bio-Informatics Programming Language :: Python :: 3 Programming Language ::",
"import find_packages, setup classes = \"\"\" Development Status :: 3 - Alpha Topic",
"as f: long_description = f.read() version = \"0.0.0\" setup( name=\"pyfastg\", version=version, license=\"MIT\", description=description,",
":: 3 :: Only \"\"\" classifiers = [s.strip() for s in classes.split(\"\\n\") if",
":: Libraries Topic :: Scientific/Engineering Topic :: Scientific/Engineering :: Bio-Informatics Programming Language ::",
"Python :: 3 Programming Language :: Python :: 3 :: Only \"\"\" classifiers",
"Programming Language :: Python :: 3 :: Only \"\"\" classifiers = [s.strip() for",
"= f.read() version = \"0.0.0\" setup( name=\"pyfastg\", version=version, license=\"MIT\", description=description, long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>,",
"setup( name=\"pyfastg\", version=version, license=\"MIT\", description=description, long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\", classifiers=classifiers,",
"classes.split(\"\\n\") if s] description = \"Minimal Python library for parsing SPAdes FASTG files\"",
"<NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\", classifiers=classifiers, packages=find_packages(), install_requires=[\"networkx\", \"scikit-bio\"], extras_require={\"dev\": [\"pytest\", \"pytest-cov\", \"flake8\", \"black\"]},",
"for s in classes.split(\"\\n\") if s] description = \"Minimal Python library for parsing",
"for parsing SPAdes FASTG files\" with open(\"README.md\") as f: long_description = f.read() version",
"with open(\"README.md\") as f: long_description = f.read() version = \"0.0.0\" setup( name=\"pyfastg\", version=version,",
"NOTE: Derived from https://github.com/biocore/qurro/blob/master/setup.py from setuptools import find_packages, setup classes = \"\"\" Development",
"description = \"Minimal Python library for parsing SPAdes FASTG files\" with open(\"README.md\") as",
":: Only \"\"\" classifiers = [s.strip() for s in classes.split(\"\\n\") if s] description",
"classifiers = [s.strip() for s in classes.split(\"\\n\") if s] description = \"Minimal Python",
"FASTG files\" with open(\"README.md\") as f: long_description = f.read() version = \"0.0.0\" setup(",
"license=\"MIT\", description=description, long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\", classifiers=classifiers, packages=find_packages(), install_requires=[\"networkx\", \"scikit-bio\"],",
"Status :: 3 - Alpha Topic :: Software Development :: Libraries Topic ::",
"\"\"\" classifiers = [s.strip() for s in classes.split(\"\\n\") if s] description = \"Minimal",
"maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\", classifiers=classifiers, packages=find_packages(), install_requires=[\"networkx\", \"scikit-bio\"], extras_require={\"dev\": [\"pytest\", \"pytest-cov\", \"flake8\", \"black\"]}, )",
"[s.strip() for s in classes.split(\"\\n\") if s] description = \"Minimal Python library for",
"Language :: Python :: 3 Programming Language :: Python :: 3 :: Only",
"find_packages, setup classes = \"\"\" Development Status :: 3 - Alpha Topic ::",
"# NOTE: Derived from https://github.com/biocore/qurro/blob/master/setup.py from setuptools import find_packages, setup classes = \"\"\"",
"3 :: Only \"\"\" classifiers = [s.strip() for s in classes.split(\"\\n\") if s]",
"library for parsing SPAdes FASTG files\" with open(\"README.md\") as f: long_description = f.read()",
"- Alpha Topic :: Software Development :: Libraries Topic :: Scientific/Engineering Topic ::",
"in classes.split(\"\\n\") if s] description = \"Minimal Python library for parsing SPAdes FASTG",
"Scientific/Engineering :: Bio-Informatics Programming Language :: Python :: 3 Programming Language :: Python",
"= \"Minimal Python library for parsing SPAdes FASTG files\" with open(\"README.md\") as f:",
"Topic :: Scientific/Engineering :: Bio-Informatics Programming Language :: Python :: 3 Programming Language",
"Development Status :: 3 - Alpha Topic :: Software Development :: Libraries Topic",
"f: long_description = f.read() version = \"0.0.0\" setup( name=\"pyfastg\", version=version, license=\"MIT\", description=description, long_description=long_description,",
"setup classes = \"\"\" Development Status :: 3 - Alpha Topic :: Software",
"3 Programming Language :: Python :: 3 :: Only \"\"\" classifiers = [s.strip()",
"= \"\"\" Development Status :: 3 - Alpha Topic :: Software Development ::",
"Development :: Libraries Topic :: Scientific/Engineering Topic :: Scientific/Engineering :: Bio-Informatics Programming Language",
"SPAdes FASTG files\" with open(\"README.md\") as f: long_description = f.read() version = \"0.0.0\"",
"Only \"\"\" classifiers = [s.strip() for s in classes.split(\"\\n\") if s] description =",
"= [s.strip() for s in classes.split(\"\\n\") if s] description = \"Minimal Python library",
"long_description = f.read() version = \"0.0.0\" setup( name=\"pyfastg\", version=version, license=\"MIT\", description=description, long_description=long_description, long_description_content_type=\"text/markdown\",",
"author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\", maintainer_email=\"<EMAIL>\", url=\"https://github.com/fedarko/pyfastg\", classifiers=classifiers, packages=find_packages(), install_requires=[\"networkx\", \"scikit-bio\"], extras_require={\"dev\": [\"pytest\", \"pytest-cov\", \"flake8\",",
"version = \"0.0.0\" setup( name=\"pyfastg\", version=version, license=\"MIT\", description=description, long_description=long_description, long_description_content_type=\"text/markdown\", author=\"<NAME>, <NAME>\", maintainer=\"<NAME>\",",
"from setuptools import find_packages, setup classes = \"\"\" Development Status :: 3 -",
"Libraries Topic :: Scientific/Engineering Topic :: Scientific/Engineering :: Bio-Informatics Programming Language :: Python",
"s] description = \"Minimal Python library for parsing SPAdes FASTG files\" with open(\"README.md\")",
"Bio-Informatics Programming Language :: Python :: 3 Programming Language :: Python :: 3",
":: Python :: 3 :: Only \"\"\" classifiers = [s.strip() for s in"
] |
[
"bl_info = { \"name\": \"Instant Collada Export\", \"blender\": (2, 80, 0), \"category\": \"Import-Export\",",
"= { \"name\": \"Instant Collada Export\", \"blender\": (2, 80, 0), \"category\": \"Import-Export\", }",
"(2, 80, 0), \"category\": \"Import-Export\", } import bpy import os class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly",
"as collada\"\"\" bl_idname = \"object.instant_collada_export\" bl_label = \"Instant Collada Export\" def execute(self, context):",
"{ \"name\": \"Instant Collada Export\", \"blender\": (2, 80, 0), \"category\": \"Import-Export\", } import",
"Export\" def execute(self, context): filepath = os.path.splitext(bpy.data.filepath)[0] if not filepath: self.report({'ERROR'}, \"Save the",
"def execute(self, context): filepath = os.path.splitext(bpy.data.filepath)[0] if not filepath: self.report({'ERROR'}, \"Save the file!\")",
"menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname) def register(): bpy.utils.register_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): bpy.utils.unregister_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.remove(menu_func) if __name__",
"bpy.ops.wm.collada_export(filepath=filepath + '.dae', apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True) return {'FINISHED'} def menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname)",
"file!\") return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath + '.dae', apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True) return {'FINISHED'} def",
"class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export the current scene as collada\"\"\" bl_idname = \"object.instant_collada_export\" bl_label",
"return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath + '.dae', apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True) return {'FINISHED'} def menu_func(self,",
"the current scene as collada\"\"\" bl_idname = \"object.instant_collada_export\" bl_label = \"Instant Collada Export\"",
"import os class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export the current scene as collada\"\"\" bl_idname =",
"export_global_up_selection='Y', apply_global_orientation=True) return {'FINISHED'} def menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname) def register(): bpy.utils.register_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.append(menu_func) def",
"} import bpy import os class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export the current scene as",
"\"blender\": (2, 80, 0), \"category\": \"Import-Export\", } import bpy import os class InstantColladaExport(bpy.types.Operator):",
"\"Import-Export\", } import bpy import os class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export the current scene",
"collada\"\"\" bl_idname = \"object.instant_collada_export\" bl_label = \"Instant Collada Export\" def execute(self, context): filepath",
"Collada Export\", \"blender\": (2, 80, 0), \"category\": \"Import-Export\", } import bpy import os",
"+ '.dae', apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True) return {'FINISHED'} def menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname) def",
"apply_global_orientation=True) return {'FINISHED'} def menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname) def register(): bpy.utils.register_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister():",
"filepath = os.path.splitext(bpy.data.filepath)[0] if not filepath: self.report({'ERROR'}, \"Save the file!\") return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath",
"if not filepath: self.report({'ERROR'}, \"Save the file!\") return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath + '.dae', apply_modifiers=True,",
"os class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export the current scene as collada\"\"\" bl_idname = \"object.instant_collada_export\"",
"\"Instant Collada Export\" def execute(self, context): filepath = os.path.splitext(bpy.data.filepath)[0] if not filepath: self.report({'ERROR'},",
"bpy import os class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export the current scene as collada\"\"\" bl_idname",
"execute(self, context): filepath = os.path.splitext(bpy.data.filepath)[0] if not filepath: self.report({'ERROR'}, \"Save the file!\") return",
"'.dae', apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True) return {'FINISHED'} def menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname) def register():",
"apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True) return {'FINISHED'} def menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname) def register(): bpy.utils.register_class(InstantColladaExport)",
"0), \"category\": \"Import-Export\", } import bpy import os class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export the",
"return {'FINISHED'} def menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname) def register(): bpy.utils.register_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): bpy.utils.unregister_class(InstantColladaExport)",
"def register(): bpy.utils.register_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): bpy.utils.unregister_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.remove(menu_func) if __name__ == \"__main__\": register()",
"filepath: self.report({'ERROR'}, \"Save the file!\") return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath + '.dae', apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y',",
"\"Save the file!\") return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath + '.dae', apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True) return",
"bl_idname = \"object.instant_collada_export\" bl_label = \"Instant Collada Export\" def execute(self, context): filepath =",
"{'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath + '.dae', apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True) return {'FINISHED'} def menu_func(self, context):",
"context): self.layout.operator(InstantColladaExport.bl_idname) def register(): bpy.utils.register_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): bpy.utils.unregister_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.remove(menu_func) if __name__ ==",
"{'FINISHED'} def menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname) def register(): bpy.utils.register_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): bpy.utils.unregister_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.remove(menu_func)",
"the file!\") return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath + '.dae', apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True) return {'FINISHED'}",
"\"\"\"Instantly export the current scene as collada\"\"\" bl_idname = \"object.instant_collada_export\" bl_label = \"Instant",
"Collada Export\" def execute(self, context): filepath = os.path.splitext(bpy.data.filepath)[0] if not filepath: self.report({'ERROR'}, \"Save",
"\"Instant Collada Export\", \"blender\": (2, 80, 0), \"category\": \"Import-Export\", } import bpy import",
"import bpy import os class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export the current scene as collada\"\"\"",
"= \"object.instant_collada_export\" bl_label = \"Instant Collada Export\" def execute(self, context): filepath = os.path.splitext(bpy.data.filepath)[0]",
"current scene as collada\"\"\" bl_idname = \"object.instant_collada_export\" bl_label = \"Instant Collada Export\" def",
"self.report({'ERROR'}, \"Save the file!\") return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath + '.dae', apply_modifiers=True, export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True)",
"scene as collada\"\"\" bl_idname = \"object.instant_collada_export\" bl_label = \"Instant Collada Export\" def execute(self,",
"export the current scene as collada\"\"\" bl_idname = \"object.instant_collada_export\" bl_label = \"Instant Collada",
"Export\", \"blender\": (2, 80, 0), \"category\": \"Import-Export\", } import bpy import os class",
"InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export the current scene as collada\"\"\" bl_idname = \"object.instant_collada_export\" bl_label =",
"<reponame>maggo007/Raygun bl_info = { \"name\": \"Instant Collada Export\", \"blender\": (2, 80, 0), \"category\":",
"\"name\": \"Instant Collada Export\", \"blender\": (2, 80, 0), \"category\": \"Import-Export\", } import bpy",
"= \"Instant Collada Export\" def execute(self, context): filepath = os.path.splitext(bpy.data.filepath)[0] if not filepath:",
"bl_label = \"Instant Collada Export\" def execute(self, context): filepath = os.path.splitext(bpy.data.filepath)[0] if not",
"= os.path.splitext(bpy.data.filepath)[0] if not filepath: self.report({'ERROR'}, \"Save the file!\") return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath +",
"not filepath: self.report({'ERROR'}, \"Save the file!\") return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath + '.dae', apply_modifiers=True, export_global_forward_selection='-Z',",
"export_global_forward_selection='-Z', export_global_up_selection='Y', apply_global_orientation=True) return {'FINISHED'} def menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname) def register(): bpy.utils.register_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.append(menu_func)",
"self.layout.operator(InstantColladaExport.bl_idname) def register(): bpy.utils.register_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): bpy.utils.unregister_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.remove(menu_func) if __name__ == \"__main__\":",
"\"category\": \"Import-Export\", } import bpy import os class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export the current",
"80, 0), \"category\": \"Import-Export\", } import bpy import os class InstantColladaExport(bpy.types.Operator): \"\"\"Instantly export",
"os.path.splitext(bpy.data.filepath)[0] if not filepath: self.report({'ERROR'}, \"Save the file!\") return {'CANCELLED'} bpy.ops.wm.collada_export(filepath=filepath + '.dae',",
"def menu_func(self, context): self.layout.operator(InstantColladaExport.bl_idname) def register(): bpy.utils.register_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): bpy.utils.unregister_class(InstantColladaExport) bpy.types.TOPBAR_MT_file_export.remove(menu_func) if",
"context): filepath = os.path.splitext(bpy.data.filepath)[0] if not filepath: self.report({'ERROR'}, \"Save the file!\") return {'CANCELLED'}",
"\"object.instant_collada_export\" bl_label = \"Instant Collada Export\" def execute(self, context): filepath = os.path.splitext(bpy.data.filepath)[0] if"
] |
[
"color=(1,0,0), mode='arrow',scale_factor=1.0) elif color == 'blue': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:,",
"np.eye(3) * 0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if __name__ == '__main__': #save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name =",
"= '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper = np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin()",
"#save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name = 'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show()",
"import numpy as np import os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color == 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0))",
"'red': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2],",
"plot_origin() mayalab.show() gripper_name = 'robotiq_3f_1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir",
"= '/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a = np.load(save_dir) plot_pc(a)",
"pcs_n[:, 1], pcs_n[:, 2], color=(0,1,0), mode='arrow',scale_factor=1.0) def plot_origin(): origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs",
"for i in range(0,199): save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name = 'robotiq_3f_'+str(i)+'.npy'",
"np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'middle0.npy' print(gripper_name) gripper =",
"origin_pcns = np.eye(3) * 0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if __name__ == '__main__': #save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056'",
"'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color == 'red': mayalab.quiver3d(pcs[:,",
"elif color == 'blue': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:,",
"gripper_name = 'middle0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'middle1.npy'",
"#gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper = np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show() #sle",
"mayalab.show() save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 = 'kinova_kg3_0.npy' print(gripper_name) gripper1 = np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin()",
"mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,1,0),",
"= np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs = np.tile(origin_pc,(3,1)) origin_pcns = np.eye(3) * 0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if",
"pcs_n[:, 1], pcs_n[:, 2], color=(0,0,1), mode='arrow',scale_factor=1.0) elif color == 'green': mayalab.quiver3d(pcs[:, 0], pcs[:,",
"gripper_name = 'f2_'+str(i)+'_middel.npy' #print(gripper_name) # gripper = np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin() #",
"#save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0: for i in range(0,199):",
"mlab as mayalab import numpy as np import os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color",
"plot_origin() # mayalab.show() #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0: for",
"pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,0,1), mode='arrow',scale_factor=1.0) elif color ==",
"1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(1,0,0), mode='arrow',scale_factor=1.0) elif color",
"save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name = 'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name))",
"# plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin() # mayalab.show() #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002)",
"plot_origin() mayalab.show() gripper_name = 'middle1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir",
"== 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color == 'red':",
"'/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b = np.load(save_dirb) plot_pc(b,color='red') mayalab.show() #for i in range(10001,10300): # gripper_name =",
"mayavi import mlab as mayalab import numpy as np import os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'):",
"color=(0,0,1), mode='arrow',scale_factor=1.0) elif color == 'green': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:,",
"range(10001,10300): # gripper_name = 'f2_'+str(i)+'_middel.npy' #print(gripper_name) # gripper = np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) #",
"= '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name = 'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() if",
"print(gripper_name) gripper1 = np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name2 = 'robotiq_3f_1.npy' print(gripper_name) gripper2 =",
"color=(0,1,0), mode='arrow',scale_factor=1.0) def plot_origin(): origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs = np.tile(origin_pc,(3,1)) origin_pcns =",
"2], color=(1,0,0), mode='arrow',scale_factor=1.0) elif color == 'blue': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2],",
"np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() if 0: save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'kinova_kg3_0.npy' print(gripper_name)",
"color == 'green': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1],",
"= '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'kinova_kg3_0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name",
"elif color == 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color == 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color ==",
"'middle0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'middle1.npy' print(gripper_name) gripper",
"gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 = 'kinova_kg3_0.npy' print(gripper_name)",
"mayalab import numpy as np import os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color == 'red':",
"'/home/lins/MetaGrasp/Data/Gripper/Data' save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a = np.load(save_dir) plot_pc(a) save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b =",
"'056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper = np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show() #sle = np.array([1494,1806])",
"# #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a = np.load(save_dir) plot_pc(a) save_dirb =",
"save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a = np.load(save_dir) plot_pc(a) save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b = np.load(save_dirb)",
"= '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b = np.load(save_dirb) plot_pc(b,color='red') mayalab.show() #for i in range(10001,10300): # gripper_name",
"b = np.load(save_dirb) plot_pc(b,color='red') mayalab.show() #for i in range(10001,10300): # gripper_name = 'f2_'+str(i)+'_middel.npy'",
"mayalab.show() gripper_name = 'robotiq_3f_1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir =",
"mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,0,1),",
"pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(1,0,0), mode='arrow',scale_factor=1.0) elif color ==",
"2], color=(0,1,0), mode='arrow',scale_factor=1.0) def plot_origin(): origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs = np.tile(origin_pc,(3,1)) origin_pcns",
"np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'robotiq_3f_1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin()",
"#mayalab.show() #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir =",
"= '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name = 'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01)",
"color == 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif color == 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color ==",
"#save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy'",
"#print(gripper_name) # gripper = np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin() # mayalab.show() #save_dir_gt =",
"np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'middle1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin()",
"mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color == 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color == 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown",
"color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color == 'red': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:,",
"plot_pc(a) save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b = np.load(save_dirb) plot_pc(b,color='red') mayalab.show() #for i in range(10001,10300):",
"plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'middle0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name))",
"'kinova_kg3_0.npy' print(gripper_name) gripper1 = np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name2 = 'robotiq_3f_1.npy' print(gripper_name) gripper2",
"= np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name2 = 'robotiq_3f_1.npy' print(gripper_name) gripper2 = np.load(os.path.join(save_dir,gripper_name2)) plot_pc(gripper2,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01)",
"pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,1,0), mode='arrow',scale_factor=1.0) def",
"mode='arrow',scale_factor=1.0) elif color == 'blue': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0],",
"np.load(save_dirb) plot_pc(b,color='red') mayalab.show() #for i in range(10001,10300): # gripper_name = 'f2_'+str(i)+'_middel.npy' #print(gripper_name) #",
"__name__ == '__main__': #save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper =",
"pcs_n[:, 1], pcs_n[:, 2], color=(1,0,0), mode='arrow',scale_factor=1.0) elif color == 'blue': mayalab.quiver3d(pcs[:, 0], pcs[:,",
"= np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'robotiq_3f_1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01)",
"plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'middle1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show()",
"mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(1,0,0),",
"np import os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color == 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif color",
"plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name2 = 'robotiq_3f_1.npy' print(gripper_name) gripper2 = np.load(os.path.join(save_dir,gripper_name2)) plot_pc(gripper2,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show()",
"'f2_'+str(i)+'_middel.npy' #print(gripper_name) # gripper = np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin() # mayalab.show() #save_dir_gt",
"= 'f2_'+str(i)+'_middel.npy' #print(gripper_name) # gripper = np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin() # mayalab.show()",
"mayalab.show() #for i in range(10001,10300): # gripper_name = 'f2_'+str(i)+'_middel.npy' #print(gripper_name) # gripper =",
"color == 'red': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1],",
"range(0,199): save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name = 'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper =",
"= 'kinova_kg3_0.npy' print(gripper_name) gripper1 = np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name2 = 'robotiq_3f_1.npy' print(gripper_name)",
"np.load(save_dir) plot_pc(a) save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b = np.load(save_dirb) plot_pc(b,color='red') mayalab.show() #for i in",
"# gripper_name = 'f2_'+str(i)+'_middel.npy' #print(gripper_name) # gripper = np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin()",
"print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'middle0.npy'",
"save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 = 'kinova_kg3_0.npy' print(gripper_name) gripper1 = np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show()",
"pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,1,0), mode='arrow',scale_factor=1.0) def plot_origin(): origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3))",
"= '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a = np.load(save_dir) plot_pc(a) save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b = np.load(save_dirb) plot_pc(b,color='red')",
"== 'green': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:,",
"== 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif color == 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color == 'green':",
"origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs = np.tile(origin_pc,(3,1)) origin_pcns = np.eye(3) * 0.01 plot_pc_with_normal(origin_pcs,origin_pcns)",
"plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color == 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif color == 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif",
"= np.load(save_dir) plot_pc(a) save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b = np.load(save_dirb) plot_pc(b,color='red') mayalab.show() #for i",
"elif color == 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color == 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown color\")",
"* 0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if __name__ == '__main__': #save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy'",
"np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data'",
"plot_origin() mayalab.show() #sle = np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3'",
"gripper_name1 = 'kinova_kg3_0.npy' print(gripper_name) gripper1 = np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name2 = 'robotiq_3f_1.npy'",
"os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color == 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif color == 'blue':",
"from mayavi import mlab as mayalab import numpy as np import os def",
"#for i in range(10001,10300): # gripper_name = 'f2_'+str(i)+'_middel.npy' #print(gripper_name) # gripper = np.load(os.path.join(save_dir,gripper_name))",
"'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color == 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'):",
"np.tile(origin_pc,(3,1)) origin_pcns = np.eye(3) * 0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if __name__ == '__main__': #save_dir =",
"plot_origin(): origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs = np.tile(origin_pc,(3,1)) origin_pcns = np.eye(3) * 0.01",
"= np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show() #sle = np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir =",
"= np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0: for i in range(0,199): save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir",
"#plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0: for i in range(0,199): save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old'",
"in range(0,199): save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name = 'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper",
"'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif color == 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color == 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0))",
"0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,0,1), mode='arrow',scale_factor=1.0)",
"np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin() # mayalab.show() #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name))",
"= 'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() if 0: save_dir =",
"color == 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color == 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color)",
"0], pcs_n[:, 1], pcs_n[:, 2], color=(0,1,0), mode='arrow',scale_factor=1.0) def plot_origin(): origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01)",
"print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'robotiq_3f_1.npy' print(gripper_name) gripper =",
"mayalab.show() #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0: for i in",
"import mlab as mayalab import numpy as np import os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if",
"2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,0,1), mode='arrow',scale_factor=1.0) elif color == 'green':",
"gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'robotiq_3f_1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name))",
"print(\"color\",color) elif color == 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color == 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color",
"'__main__': #save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper = np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002)",
"== '__main__': #save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper = np.load(os.path.join(\"robotiq2f_open.npy\"))",
"if color == 'red': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:,",
"= '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper = np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show() #sle =",
"np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show() #sle = np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp'",
"'kinova_kg3_0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'robotiq_3f_1.npy' print(gripper_name) gripper",
"def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color == 'red': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:,",
"='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper = np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show() #sle = np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show()",
"== 'red': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:,",
"as mayalab import numpy as np import os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color ==",
"in range(10001,10300): # gripper_name = 'f2_'+str(i)+'_middel.npy' #print(gripper_name) # gripper = np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002)",
"print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color == 'red': mayalab.quiver3d(pcs[:, 0], pcs[:, 1],",
"0: for i in range(0,199): save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name =",
"save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'kinova_kg3_0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show()",
"plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs = np.tile(origin_pc,(3,1)) origin_pcns = np.eye(3) * 0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if __name__ ==",
"'/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a = np.load(save_dir) plot_pc(a) save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b = np.load(save_dirb) plot_pc(b,color='red') mayalab.show()",
"== 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color == 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def",
"2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(1,0,0), mode='arrow',scale_factor=1.0) elif color == 'blue':",
"'/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a = np.load(save_dir) plot_pc(a) save_dirb",
"0: save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'kinova_kg3_0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin()",
"= 'robotiq_3f_1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name",
"= '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'middle0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name",
"if 0: save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'kinova_kg3_0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01)",
"pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(1,0,0), mode='arrow',scale_factor=1.0) elif color == 'blue': mayalab.quiver3d(pcs[:,",
"= '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a = np.load(save_dir) plot_pc(a) save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b",
"color == 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color ==",
"numpy as np import os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color == 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color)",
"#save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a = np.load(save_dir) plot_pc(a) save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy'",
"gripper1 = np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name2 = 'robotiq_3f_1.npy' print(gripper_name) gripper2 = np.load(os.path.join(save_dir,gripper_name2))",
"elif color == 'green': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:,",
"plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'robotiq_3f_1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show()",
"gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() if 0: save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name =",
"else: print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color == 'red': mayalab.quiver3d(pcs[:, 0], pcs[:,",
"0], pcs_n[:, 1], pcs_n[:, 2], color=(0,0,1), mode='arrow',scale_factor=1.0) elif color == 'green': mayalab.quiver3d(pcs[:, 0],",
"'/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name = 'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin()",
"plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 = 'kinova_kg3_0.npy' print(gripper_name) gripper1 = np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01)",
"pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,0,1), mode='arrow',scale_factor=1.0) elif",
"np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 = 'kinova_kg3_0.npy' print(gripper_name) gripper1 =",
"'/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name = 'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() if 0:",
"import os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color == 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif color ==",
"'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() if 0: save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp'",
"mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif color == 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color == 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif",
"i in range(0,199): save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name = 'robotiq_3f_'+str(i)+'.npy' print(gripper_name)",
"= '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a",
"plot_pc_with_normal(origin_pcs,origin_pcns) if __name__ == '__main__': #save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz'",
"2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,1,0), mode='arrow',scale_factor=1.0) def plot_origin(): origin_pc =",
"if 0: for i in range(0,199): save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/recon_old' gripper_name",
"# plot_origin() # mayalab.show() #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0:",
"0], pcs_n[:, 1], pcs_n[:, 2], color=(1,0,0), mode='arrow',scale_factor=1.0) elif color == 'blue': mayalab.quiver3d(pcs[:, 0],",
"0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if __name__ == '__main__': #save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name",
"#save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper = np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002)",
"'/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper = np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show()",
"'/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a =",
"print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() if 0: save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name",
"= np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'middle1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01)",
"'/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0: for i in range(0,199): save_dir =",
"'robotiq_3f_1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name =",
"gripper_name = 'middle1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR'",
"gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'middle0.npy' print(gripper_name)",
"'/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 = 'kinova_kg3_0.npy' print(gripper_name) gripper1 = np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name2 =",
"#sle = np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt",
"== 'blue': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:,",
"np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs = np.tile(origin_pc,(3,1)) origin_pcns = np.eye(3) * 0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if __name__",
"= np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() if 0: save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'kinova_kg3_0.npy'",
"pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,1,0), mode='arrow',scale_factor=1.0) def plot_origin(): origin_pc",
"plot_pc(b,color='red') mayalab.show() #for i in range(10001,10300): # gripper_name = 'f2_'+str(i)+'_middel.npy' #print(gripper_name) # gripper",
"gripper_name = 'kinova_kg3_0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'robotiq_3f_1.npy'",
"#plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show() #sle = np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir",
"def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color == 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif color == 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1))",
"def plot_origin(): origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs = np.tile(origin_pc,(3,1)) origin_pcns = np.eye(3) *",
"0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,1,0), mode='arrow',scale_factor=1.0)",
"'green': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2],",
"= np.load(save_dirb) plot_pc(b,color='red') mayalab.show() #for i in range(10001,10300): # gripper_name = 'f2_'+str(i)+'_middel.npy' #print(gripper_name)",
"save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'middle0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show()",
"origin_pcs = np.tile(origin_pc,(3,1)) origin_pcns = np.eye(3) * 0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if __name__ == '__main__':",
"mode='arrow',scale_factor=1.0) def plot_origin(): origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs = np.tile(origin_pc,(3,1)) origin_pcns = np.eye(3)",
"= np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt =",
"i in range(10001,10300): # gripper_name = 'f2_'+str(i)+'_middel.npy' #print(gripper_name) # gripper = np.load(os.path.join(save_dir,gripper_name)) #",
"'blue': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2],",
"print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'middle1.npy' print(gripper_name) gripper =",
"if color == 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif color == 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color",
"# gripper = np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin() # mayalab.show() #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data'",
"1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,1,0), mode='arrow',scale_factor=1.0) def plot_origin():",
"plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show() #sle = np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir =",
"print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 = 'kinova_kg3_0.npy'",
"= np.eye(3) * 0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if __name__ == '__main__': #save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name",
"mayalab.show() if 0: save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'kinova_kg3_0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name))",
"'/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'middle0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name =",
"#plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir",
"0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(1,0,0), mode='arrow',scale_factor=1.0)",
"mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color == 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if",
"pcs_n[:, 2], color=(0,1,0), mode='arrow',scale_factor=1.0) def plot_origin(): origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs = np.tile(origin_pc,(3,1))",
"1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,0,1), mode='arrow',scale_factor=1.0) elif color",
"gripper_name = 'robotiq_3f_1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp'",
"'middle1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 =",
"pcs_n[:, 2], color=(1,0,0), mode='arrow',scale_factor=1.0) elif color == 'blue': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:,",
"1], pcs_n[:, 2], color=(0,0,1), mode='arrow',scale_factor=1.0) elif color == 'green': mayalab.quiver3d(pcs[:, 0], pcs[:, 1],",
"= '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 = 'kinova_kg3_0.npy' print(gripper_name) gripper1 = np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name2",
"save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b = np.load(save_dirb) plot_pc(b,color='red') mayalab.show() #for i in range(10001,10300): #",
"gripper = np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin() # mayalab.show() #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt",
"plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color == 'red': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0],",
"as np import os def plot_pc(pcs,color=None,scale_factor=.05,mode='point'): if color == 'red': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(1,0,0)) print(\"color\",color) elif",
"mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color == 'red': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2],",
"elif color == 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color",
"mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else: print(\"unkown color\") mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=color) def plot_pc_with_normal(pcs,pcs_n,scale_factor=1.0,color='red'): if color == 'red': mayalab.quiver3d(pcs[:, 0],",
"= 'middle0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'middle1.npy' print(gripper_name)",
"#gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0: for i in range(0,199): save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR'",
"mayalab.show() save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'middle0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin()",
"gripper = np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show() #sle = np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir",
"gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'middle1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name))",
"= np.tile(origin_pc,(3,1)) origin_pcns = np.eye(3) * 0.01 plot_pc_with_normal(origin_pcs,origin_pcns) if __name__ == '__main__': #save_dir",
"= np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 = 'kinova_kg3_0.npy' print(gripper_name) gripper1",
"'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color == 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color == 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1)) else:",
"np.load(os.path.join(save_dir,gripper_name1)) plot_pc(gripper1,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name2 = 'robotiq_3f_1.npy' print(gripper_name) gripper2 = np.load(os.path.join(save_dir,gripper_name2)) plot_pc(gripper2,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin()",
"== 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color == 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color == 'ycan': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,1))",
"pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(1,0,0), mode='arrow',scale_factor=1.0) elif",
"plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() if 0: save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'kinova_kg3_0.npy' print(gripper_name) gripper",
"pcs_n[:, 2], color=(0,0,1), mode='arrow',scale_factor=1.0) elif color == 'green': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:,",
"plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin() # mayalab.show() #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if",
"mode='arrow',scale_factor=1.0) elif color == 'green': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0],",
"a = np.load(save_dir) plot_pc(a) save_dirb = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G3/f2_3_close.npy' b = np.load(save_dirb) plot_pc(b,color='red') mayalab.show() #for",
"plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'middle0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01)",
"# mayalab.show() #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0: for i",
"plot_origin() mayalab.show() if 0: save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'kinova_kg3_0.npy' print(gripper_name) gripper =",
"= np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'middle0.npy' print(gripper_name) gripper",
"gripper_name = 'robotiq_3f_'+str(i)+'.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() if 0: save_dir",
"mayalab.show() gripper_name = 'middle1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir =",
"2], color=(0,0,1), mode='arrow',scale_factor=1.0) elif color == 'green': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2],",
"1], pcs_n[:, 2], color=(0,1,0), mode='arrow',scale_factor=1.0) def plot_origin(): origin_pc = np.array([0.0,0.0,0.0]).reshape((-1,3)) plot_pc(origin_pc,color='ycan',mode='sphere',scale_factor=.01) origin_pcs =",
"= np.load(os.path.join(save_dir,gripper_name)) # plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) # plot_origin() # mayalab.show() #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt =",
"= 'kinova_kg3_0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name = 'robotiq_3f_1.npy' print(gripper_name)",
"#save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3' # #save_dir_gt = '/home/lins/MetaGrasp/Data/Gripper/Data' save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_DB/G5/f2_5_close.npy' a = np.load(save_dir)",
"= 'middle1.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1",
"pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], color=(0,0,1), mode='arrow',scale_factor=1.0) elif color == 'green': mayalab.quiver3d(pcs[:,",
"= '/home/lins/MetaGrasp/Data/Gripper/Data' #gripper_gt = np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0: for i in range(0,199): save_dir",
"'/home/lins/MetaGrasp/meta_grasping/saved_results/interp' gripper_name = 'kinova_kg3_0.npy' print(gripper_name) gripper = np.load(os.path.join(save_dir,gripper_name)) plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() gripper_name =",
"if __name__ == '__main__': #save_dir = '/home/lins/MetaGrasp/Data/BlensorResult/2056' #gripper_name = '056_rho0.384015_azi1.000000_ele89.505854_theta0.092894_xcam0.000000_ycam0.000000_zcam0.384015_scale0.146439_xdim0.084960_ydim0.084567_zdim0.08411000000_pcn_new.npz.npy' #gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper",
"1], pcs_n[:, 2], color=(1,0,0), mode='arrow',scale_factor=1.0) elif color == 'blue': mayalab.quiver3d(pcs[:, 0], pcs[:, 1],",
"color == 'blue': mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1],",
"#gripper_name ='339_rho0.308024_azi6.000000_ele89.850030_theta-0.013403_xcam0.000000_ycam0.000000_zcam0.308024_scale0.061975_xdim0.048725_ydim0.036192_zdim0.01252500000_pcn.npz' gripper = np.load(os.path.join(\"robotiq2f_open.npy\")) #plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.002) plot_pc(gripper,color=(209/255.0,64/255.0,109/255.0),mode='sphere',scale_factor=0.002) plot_origin() mayalab.show() #sle = np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002)",
"mayalab.show() #sle = np.array([1494,1806]) #plot_pc(gripper[sle],color='red',mode='sphere',scale_factor=0.002) #mayalab.show() #save_dir = '/home/lins/MetaGrasp/meta_grasping/saved_results/interp' #save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data3' #",
"color == 'blue': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,0,1)) elif color == 'green': mayalab.points3d(pcs[:,0],pcs[:,1],pcs[:,2],mode=mode,scale_factor=scale_factor,color=(0,1,0)) elif color == 'ycan':",
"np.load(os.path.join(save_dir_gt,gripper_name)) #plot_pc(gripper_gt,color='red',mode='sphere',scale_factor=0.002) if 0: for i in range(0,199): save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' #save_dir =",
"plot_pc(gripper,color=(139/255.0,177/255.0,212/255.0),mode='sphere',scale_factor=0.01) plot_origin() mayalab.show() save_dir = '/home/lins/MetaGrasp/Data/Gripper/Data_noR' gripper_name1 = 'kinova_kg3_0.npy' print(gripper_name) gripper1 = np.load(os.path.join(save_dir,gripper_name1))"
] |
[
"came_from = request.params.get('came_from', referrer) request.model_state.data['came_from'] = came_from return self._get_edit_info() def _get_edit_info(self): request =",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"import validators from offlinetools.syslanguage import _culture_list, default_culture DEFAULT_REPEAT = 100000 class LoginSchema(Schema): allow_extra_fields",
"referrer == login_url: referrer = request.route_url('search') # never use the login form itself",
"from pyramid.httpexceptions import HTTPFound from pyramid.security import remember, forget from formencode import Schema",
"== login_url: referrer = request.route_url('search') # never use the login form itself as",
"LoginSchema(Schema): allow_extra_fields = True filter_extra_fields = True LoginName = validators.UnicodeString(max=50, not_empty=True) LoginPwd =",
"not config.last_update return {'has_data': has_data, 'failed_updates': failed_updates, 'has_updated': has_updated} def logout(request): headers =",
"user.UserName) start_ln = [x.Culture for x in _culture_list if x.LangID == user.LangID and",
"= True if not has_data: config = request.config failed_updates = not not config.update_failure_count",
"this file except in compliance with the License. # You may obtain a",
"session = request.dbsession user_count = session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data = any(user_count) failed_updates = False",
"config = request.config failed_updates = not not config.update_failure_count has_updated = not not config.last_update",
"pyramid.httpexceptions import HTTPFound from pyramid.security import remember, forget from formencode import Schema from",
"or Password')) return self._get_edit_info() hash = Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat) if hash != user.PasswordHash:",
"and x.Active] if not start_ln: start_ln = [default_culture()] return HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])), headers=headers)",
"permissions and # limitations under the License. # ========================================================================================= from __future__ import absolute_import",
"headers=headers) def get(self): request = self.request login_url = request.route_url('login') referrer = request.url if",
"ANY KIND, either express or implied. # See the License for the specific",
"= request.model_state model_state.schema = LoginSchema() if not model_state.validate(): return self._get_edit_info() LoginName = model_state.value('LoginName')",
"not user: model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info() hash = Crypt(user.PasswordHashSalt,",
"class Login(ViewBase): def post(self): request = self.request _ = request.translate model_state = request.model_state",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"License. # ========================================================================================= from __future__ import absolute_import from hashlib import pbkdf2_hmac from base64",
"x in _culture_list if x.LangID == user.LangID and x.Active] if not start_ln: start_ln",
"from pyramid.security import remember, forget from formencode import Schema from sqlalchemy import func",
"Software Solutions # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"absolute_import from hashlib import pbkdf2_hmac from base64 import standard_b64encode from pyramid.httpexceptions import HTTPFound",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"if referrer == login_url: referrer = request.route_url('search') # never use the login form",
"_('Invalid User Name or Password')) return self._get_edit_info() headers = remember(request, user.UserName) start_ln =",
"remember, forget from formencode import Schema from sqlalchemy import func from offlinetools import",
"ViewBase from offlinetools.views import validators from offlinetools.syslanguage import _culture_list, default_culture DEFAULT_REPEAT = 100000",
"OF ANY KIND, either express or implied. # See the License for the",
"2016 Community Information Online Consortium (CIOC) and KCL Software Solutions # # Licensed",
"not start_ln: start_ln = [default_culture()] return HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])), headers=headers) def get(self): request",
"_('Invalid User Name or Password')) return self._get_edit_info() hash = Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat) if",
"Password')) return self._get_edit_info() hash = Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat) if hash != user.PasswordHash: model_state.add_error_for('*',",
"failed_updates = False has_updated = True if not has_data: config = request.config failed_updates",
"# ========================================================================================= from __future__ import absolute_import from hashlib import pbkdf2_hmac from base64 import",
"the login form itself as came_from came_from = request.params.get('came_from', referrer) request.model_state.data['came_from'] = came_from",
"self.request login_url = request.route_url('login') referrer = request.url if referrer == login_url: referrer =",
"return HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])), headers=headers) def get(self): request = self.request login_url = request.route_url('login')",
"import func from offlinetools import models from offlinetools.views.base import ViewBase from offlinetools.views import",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"for x in _culture_list if x.LangID == user.LangID and x.Active] if not start_ln:",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"from hashlib import pbkdf2_hmac from base64 import standard_b64encode from pyramid.httpexceptions import HTTPFound from",
"request.model_state model_state.schema = LoginSchema() if not model_state.validate(): return self._get_edit_info() LoginName = model_state.value('LoginName') user",
"_get_edit_info(self): request = self.request session = request.dbsession user_count = session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data =",
"offlinetools.syslanguage import _culture_list, default_culture DEFAULT_REPEAT = 100000 class LoginSchema(Schema): allow_extra_fields = True filter_extra_fields",
"# ========================================================================================= # Copyright 2016 Community Information Online Consortium (CIOC) and KCL Software",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"= request.config failed_updates = not not config.update_failure_count has_updated = not not config.last_update return",
"= request.route_url('search') # never use the login form itself as came_from came_from =",
"has_updated} def logout(request): headers = forget(request) return HTTPFound(location=request.route_url('login'), headers=headers) def Crypt(salt, password, repeat=DEFAULT_REPEAT):",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"has_data = any(user_count) failed_updates = False has_updated = True if not has_data: config",
"not has_data: config = request.config failed_updates = not not config.update_failure_count has_updated = not",
"request.route_url('search', ln=start_ln[0])), headers=headers) def get(self): request = self.request login_url = request.route_url('login') referrer =",
"if not has_data: config = request.config failed_updates = not not config.update_failure_count has_updated =",
"required by applicable law or agreed to in writing, software # distributed under",
"========================================================================================= from __future__ import absolute_import from hashlib import pbkdf2_hmac from base64 import standard_b64encode",
"if not model_state.validate(): return self._get_edit_info() LoginName = model_state.value('LoginName') user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not",
"allow_extra_fields = True filter_extra_fields = True LoginName = validators.UnicodeString(max=50, not_empty=True) LoginPwd = validators.String(not_empty=True)",
"language governing permissions and # limitations under the License. # ========================================================================================= from __future__",
"applicable law or agreed to in writing, software # distributed under the License",
"forget from formencode import Schema from sqlalchemy import func from offlinetools import models",
"HTTPFound from pyramid.security import remember, forget from formencode import Schema from sqlalchemy import",
"Copyright 2016 Community Information Online Consortium (CIOC) and KCL Software Solutions # #",
"# limitations under the License. # ========================================================================================= from __future__ import absolute_import from hashlib",
"user.LangID and x.Active] if not start_ln: start_ln = [default_culture()] return HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])),",
"or agreed to in writing, software # distributed under the License is distributed",
"standard_b64encode from pyramid.httpexceptions import HTTPFound from pyramid.security import remember, forget from formencode import",
"return self._get_edit_info() LoginName = model_state.value('LoginName') user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not user: model_state.add_error_for('*', _('Invalid",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"from sqlalchemy import func from offlinetools import models from offlinetools.views.base import ViewBase from",
"!= user.PasswordHash: model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info() headers = remember(request,",
"forget(request) return HTTPFound(location=request.route_url('login'), headers=headers) def Crypt(salt, password, repeat=DEFAULT_REPEAT): return standard_b64encode(pbkdf2_hmac('sha1', password.encode('utf-8'), salt.encode('utf-8'), repeat,",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data = any(user_count) failed_updates = False has_updated = True if not",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"validators.String(not_empty=True) came_from = validators.UnicodeString() class Login(ViewBase): def post(self): request = self.request _ =",
"License. # You may obtain a copy of the License at # #",
"validators from offlinetools.syslanguage import _culture_list, default_culture DEFAULT_REPEAT = 100000 class LoginSchema(Schema): allow_extra_fields =",
"True LoginName = validators.UnicodeString(max=50, not_empty=True) LoginPwd = validators.String(not_empty=True) came_from = validators.UnicodeString() class Login(ViewBase):",
"as came_from came_from = request.params.get('came_from', referrer) request.model_state.data['came_from'] = came_from return self._get_edit_info() def _get_edit_info(self):",
"use the login form itself as came_from came_from = request.params.get('came_from', referrer) request.model_state.data['came_from'] =",
"if not user: model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info() hash =",
"def get(self): request = self.request login_url = request.route_url('login') referrer = request.url if referrer",
"compliance with the License. # You may obtain a copy of the License",
"{'has_data': has_data, 'failed_updates': failed_updates, 'has_updated': has_updated} def logout(request): headers = forget(request) return HTTPFound(location=request.route_url('login'),",
"import HTTPFound from pyramid.security import remember, forget from formencode import Schema from sqlalchemy",
"and # limitations under the License. # ========================================================================================= from __future__ import absolute_import from",
"model_state.value('LoginPwd'), user.PasswordHashRepeat) if hash != user.PasswordHash: model_state.add_error_for('*', _('Invalid User Name or Password')) return",
"post(self): request = self.request _ = request.translate model_state = request.model_state model_state.schema = LoginSchema()",
"LoginName = validators.UnicodeString(max=50, not_empty=True) LoginPwd = validators.String(not_empty=True) came_from = validators.UnicodeString() class Login(ViewBase): def",
"not config.update_failure_count has_updated = not not config.last_update return {'has_data': has_data, 'failed_updates': failed_updates, 'has_updated':",
"limitations under the License. # ========================================================================================= from __future__ import absolute_import from hashlib import",
"= remember(request, user.UserName) start_ln = [x.Culture for x in _culture_list if x.LangID ==",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"form itself as came_from came_from = request.params.get('came_from', referrer) request.model_state.data['came_from'] = came_from return self._get_edit_info()",
"if x.LangID == user.LangID and x.Active] if not start_ln: start_ln = [default_culture()] return",
"user_count = session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data = any(user_count) failed_updates = False has_updated = True",
"not use this file except in compliance with the License. # You may",
"request.config failed_updates = not not config.update_failure_count has_updated = not not config.last_update return {'has_data':",
"headers = remember(request, user.UserName) start_ln = [x.Culture for x in _culture_list if x.LangID",
"return HTTPFound(location=request.route_url('login'), headers=headers) def Crypt(salt, password, repeat=DEFAULT_REPEAT): return standard_b64encode(pbkdf2_hmac('sha1', password.encode('utf-8'), salt.encode('utf-8'), repeat, 33)).decode('utf-8').strip()",
"self._get_edit_info() def _get_edit_info(self): request = self.request session = request.dbsession user_count = session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one()",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info() headers = remember(request, user.UserName) start_ln",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"def _get_edit_info(self): request = self.request session = request.dbsession user_count = session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data",
"login_url = request.route_url('login') referrer = request.url if referrer == login_url: referrer = request.route_url('search')",
"# you may not use this file except in compliance with the License.",
"class LoginSchema(Schema): allow_extra_fields = True filter_extra_fields = True LoginName = validators.UnicodeString(max=50, not_empty=True) LoginPwd",
"= True filter_extra_fields = True LoginName = validators.UnicodeString(max=50, not_empty=True) LoginPwd = validators.String(not_empty=True) came_from",
"agreed to in writing, software # distributed under the License is distributed on",
"model_state.validate(): return self._get_edit_info() LoginName = model_state.value('LoginName') user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not user: model_state.add_error_for('*',",
"has_updated = not not config.last_update return {'has_data': has_data, 'failed_updates': failed_updates, 'has_updated': has_updated} def",
"_ = request.translate model_state = request.model_state model_state.schema = LoginSchema() if not model_state.validate(): return",
"= request.dbsession user_count = session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data = any(user_count) failed_updates = False has_updated",
"(the \"License\"); # you may not use this file except in compliance with",
"governing permissions and # limitations under the License. # ========================================================================================= from __future__ import",
"= validators.String(not_empty=True) came_from = validators.UnicodeString() class Login(ViewBase): def post(self): request = self.request _",
"return self._get_edit_info() headers = remember(request, user.UserName) start_ln = [x.Culture for x in _culture_list",
"request = self.request _ = request.translate model_state = request.model_state model_state.schema = LoginSchema() if",
"# Unless required by applicable law or agreed to in writing, software #",
"import standard_b64encode from pyramid.httpexceptions import HTTPFound from pyramid.security import remember, forget from formencode",
"by applicable law or agreed to in writing, software # distributed under the",
"= [x.Culture for x in _culture_list if x.LangID == user.LangID and x.Active] if",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"DEFAULT_REPEAT = 100000 class LoginSchema(Schema): allow_extra_fields = True filter_extra_fields = True LoginName =",
"the specific language governing permissions and # limitations under the License. # =========================================================================================",
"offlinetools.views import validators from offlinetools.syslanguage import _culture_list, default_culture DEFAULT_REPEAT = 100000 class LoginSchema(Schema):",
"model_state = request.model_state model_state.schema = LoginSchema() if not model_state.validate(): return self._get_edit_info() LoginName =",
"headers = forget(request) return HTTPFound(location=request.route_url('login'), headers=headers) def Crypt(salt, password, repeat=DEFAULT_REPEAT): return standard_b64encode(pbkdf2_hmac('sha1', password.encode('utf-8'),",
"'has_updated': has_updated} def logout(request): headers = forget(request) return HTTPFound(location=request.route_url('login'), headers=headers) def Crypt(salt, password,",
"Community Information Online Consortium (CIOC) and KCL Software Solutions # # Licensed under",
"file except in compliance with the License. # You may obtain a copy",
"remember(request, user.UserName) start_ln = [x.Culture for x in _culture_list if x.LangID == user.LangID",
"Login(ViewBase): def post(self): request = self.request _ = request.translate model_state = request.model_state model_state.schema",
"License for the specific language governing permissions and # limitations under the License.",
"from __future__ import absolute_import from hashlib import pbkdf2_hmac from base64 import standard_b64encode from",
"= LoginSchema() if not model_state.validate(): return self._get_edit_info() LoginName = model_state.value('LoginName') user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first()",
"to in writing, software # distributed under the License is distributed on an",
"implied. # See the License for the specific language governing permissions and #",
"\"License\"); # you may not use this file except in compliance with the",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"referrer = request.url if referrer == login_url: referrer = request.route_url('search') # never use",
"self._get_edit_info() headers = remember(request, user.UserName) start_ln = [x.Culture for x in _culture_list if",
"request.dbsession user_count = session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data = any(user_count) failed_updates = False has_updated =",
"LoginSchema() if not model_state.validate(): return self._get_edit_info() LoginName = model_state.value('LoginName') user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if",
"or implied. # See the License for the specific language governing permissions and",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"user.PasswordHash: model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info() headers = remember(request, user.UserName)",
"func from offlinetools import models from offlinetools.views.base import ViewBase from offlinetools.views import validators",
"from offlinetools.views import validators from offlinetools.syslanguage import _culture_list, default_culture DEFAULT_REPEAT = 100000 class",
"def post(self): request = self.request _ = request.translate model_state = request.model_state model_state.schema =",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"model_state.value('LoginName') user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not user: model_state.add_error_for('*', _('Invalid User Name or Password'))",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"from formencode import Schema from sqlalchemy import func from offlinetools import models from",
"model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info() hash = Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat)",
"came_from return self._get_edit_info() def _get_edit_info(self): request = self.request session = request.dbsession user_count =",
"def logout(request): headers = forget(request) return HTTPFound(location=request.route_url('login'), headers=headers) def Crypt(salt, password, repeat=DEFAULT_REPEAT): return",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"sqlalchemy import func from offlinetools import models from offlinetools.views.base import ViewBase from offlinetools.views",
"start_ln = [default_culture()] return HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])), headers=headers) def get(self): request = self.request",
"return self._get_edit_info() def _get_edit_info(self): request = self.request session = request.dbsession user_count = session.query(func.count(models.Users.UserName),",
"has_updated = True if not has_data: config = request.config failed_updates = not not",
"= request.url if referrer == login_url: referrer = request.route_url('search') # never use the",
"use this file except in compliance with the License. # You may obtain",
"request.route_url('login') referrer = request.url if referrer == login_url: referrer = request.route_url('search') # never",
"= any(user_count) failed_updates = False has_updated = True if not has_data: config =",
"logout(request): headers = forget(request) return HTTPFound(location=request.route_url('login'), headers=headers) def Crypt(salt, password, repeat=DEFAULT_REPEAT): return standard_b64encode(pbkdf2_hmac('sha1',",
"came_from came_from = request.params.get('came_from', referrer) request.model_state.data['came_from'] = came_from return self._get_edit_info() def _get_edit_info(self): request",
"request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not user: model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info() hash",
"'failed_updates': failed_updates, 'has_updated': has_updated} def logout(request): headers = forget(request) return HTTPFound(location=request.route_url('login'), headers=headers) def",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"Name or Password')) return self._get_edit_info() headers = remember(request, user.UserName) start_ln = [x.Culture for",
"Solutions # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"= validators.UnicodeString() class Login(ViewBase): def post(self): request = self.request _ = request.translate model_state",
"login_url: referrer = request.route_url('search') # never use the login form itself as came_from",
"start_ln: start_ln = [default_culture()] return HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])), headers=headers) def get(self): request =",
"not not config.last_update return {'has_data': has_data, 'failed_updates': failed_updates, 'has_updated': has_updated} def logout(request): headers",
"under the License. # ========================================================================================= from __future__ import absolute_import from hashlib import pbkdf2_hmac",
"= self.request _ = request.translate model_state = request.model_state model_state.schema = LoginSchema() if not",
"func.count(models.Record.NUM)).one() has_data = any(user_count) failed_updates = False has_updated = True if not has_data:",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"self.request session = request.dbsession user_count = session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data = any(user_count) failed_updates =",
"(CIOC) and KCL Software Solutions # # Licensed under the Apache License, Version",
"request = self.request login_url = request.route_url('login') referrer = request.url if referrer == login_url:",
"= came_from return self._get_edit_info() def _get_edit_info(self): request = self.request session = request.dbsession user_count",
"HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])), headers=headers) def get(self): request = self.request login_url = request.route_url('login') referrer",
"for the specific language governing permissions and # limitations under the License. #",
"request.route_url('search') # never use the login form itself as came_from came_from = request.params.get('came_from',",
"from base64 import standard_b64encode from pyramid.httpexceptions import HTTPFound from pyramid.security import remember, forget",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"request.translate model_state = request.model_state model_state.schema = LoginSchema() if not model_state.validate(): return self._get_edit_info() LoginName",
"Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat) if hash != user.PasswordHash: model_state.add_error_for('*', _('Invalid User Name or Password'))",
"hash = Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat) if hash != user.PasswordHash: model_state.add_error_for('*', _('Invalid User Name",
"if not start_ln: start_ln = [default_culture()] return HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])), headers=headers) def get(self):",
"True filter_extra_fields = True LoginName = validators.UnicodeString(max=50, not_empty=True) LoginPwd = validators.String(not_empty=True) came_from =",
"# # Unless required by applicable law or agreed to in writing, software",
"import remember, forget from formencode import Schema from sqlalchemy import func from offlinetools",
"offlinetools import models from offlinetools.views.base import ViewBase from offlinetools.views import validators from offlinetools.syslanguage",
"any(user_count) failed_updates = False has_updated = True if not has_data: config = request.config",
"express or implied. # See the License for the specific language governing permissions",
"login form itself as came_from came_from = request.params.get('came_from', referrer) request.model_state.data['came_from'] = came_from return",
"= self.request session = request.dbsession user_count = session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data = any(user_count) failed_updates",
"came_from = validators.UnicodeString() class Login(ViewBase): def post(self): request = self.request _ = request.translate",
"formencode import Schema from sqlalchemy import func from offlinetools import models from offlinetools.views.base",
"either express or implied. # See the License for the specific language governing",
"x.LangID == user.LangID and x.Active] if not start_ln: start_ln = [default_culture()] return HTTPFound(location=model_state.value('came_from',",
"_culture_list if x.LangID == user.LangID and x.Active] if not start_ln: start_ln = [default_culture()]",
"the License. # ========================================================================================= from __future__ import absolute_import from hashlib import pbkdf2_hmac from",
"get(self): request = self.request login_url = request.route_url('login') referrer = request.url if referrer ==",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"request = self.request session = request.dbsession user_count = session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data = any(user_count)",
"config.last_update return {'has_data': has_data, 'failed_updates': failed_updates, 'has_updated': has_updated} def logout(request): headers = forget(request)",
"Information Online Consortium (CIOC) and KCL Software Solutions # # Licensed under the",
"not model_state.validate(): return self._get_edit_info() LoginName = model_state.value('LoginName') user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not user:",
"Name or Password')) return self._get_edit_info() hash = Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat) if hash !=",
"and KCL Software Solutions # # Licensed under the Apache License, Version 2.0",
"config.update_failure_count has_updated = not not config.last_update return {'has_data': has_data, 'failed_updates': failed_updates, 'has_updated': has_updated}",
"never use the login form itself as came_from came_from = request.params.get('came_from', referrer) request.model_state.data['came_from']",
"user: model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info() hash = Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'),",
"the License. # You may obtain a copy of the License at #",
"offlinetools.views.base import ViewBase from offlinetools.views import validators from offlinetools.syslanguage import _culture_list, default_culture DEFAULT_REPEAT",
"= self.request login_url = request.route_url('login') referrer = request.url if referrer == login_url: referrer",
"referrer) request.model_state.data['came_from'] = came_from return self._get_edit_info() def _get_edit_info(self): request = self.request session =",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"pyramid.security import remember, forget from formencode import Schema from sqlalchemy import func from",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"x.Active] if not start_ln: start_ln = [default_culture()] return HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])), headers=headers) def",
"default_culture DEFAULT_REPEAT = 100000 class LoginSchema(Schema): allow_extra_fields = True filter_extra_fields = True LoginName",
"= validators.UnicodeString(max=50, not_empty=True) LoginPwd = validators.String(not_empty=True) came_from = validators.UnicodeString() class Login(ViewBase): def post(self):",
"User Name or Password')) return self._get_edit_info() hash = Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat) if hash",
"in _culture_list if x.LangID == user.LangID and x.Active] if not start_ln: start_ln =",
"or Password')) return self._get_edit_info() headers = remember(request, user.UserName) start_ln = [x.Culture for x",
"referrer = request.route_url('search') # never use the login form itself as came_from came_from",
"# never use the login form itself as came_from came_from = request.params.get('came_from', referrer)",
"= not not config.last_update return {'has_data': has_data, 'failed_updates': failed_updates, 'has_updated': has_updated} def logout(request):",
"True if not has_data: config = request.config failed_updates = not not config.update_failure_count has_updated",
"request.params.get('came_from', referrer) request.model_state.data['came_from'] = came_from return self._get_edit_info() def _get_edit_info(self): request = self.request session",
"with the License. # You may obtain a copy of the License at",
"base64 import standard_b64encode from pyramid.httpexceptions import HTTPFound from pyramid.security import remember, forget from",
"import absolute_import from hashlib import pbkdf2_hmac from base64 import standard_b64encode from pyramid.httpexceptions import",
"pbkdf2_hmac from base64 import standard_b64encode from pyramid.httpexceptions import HTTPFound from pyramid.security import remember,",
"= False has_updated = True if not has_data: config = request.config failed_updates =",
"validators.UnicodeString() class Login(ViewBase): def post(self): request = self.request _ = request.translate model_state =",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"self.request _ = request.translate model_state = request.model_state model_state.schema = LoginSchema() if not model_state.validate():",
"User Name or Password')) return self._get_edit_info() headers = remember(request, user.UserName) start_ln = [x.Culture",
"========================================================================================= # Copyright 2016 Community Information Online Consortium (CIOC) and KCL Software Solutions",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"from offlinetools.syslanguage import _culture_list, default_culture DEFAULT_REPEAT = 100000 class LoginSchema(Schema): allow_extra_fields = True",
"return {'has_data': has_data, 'failed_updates': failed_updates, 'has_updated': has_updated} def logout(request): headers = forget(request) return",
"has_data: config = request.config failed_updates = not not config.update_failure_count has_updated = not not",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"self._get_edit_info() hash = Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat) if hash != user.PasswordHash: model_state.add_error_for('*', _('Invalid User",
"KCL Software Solutions # # Licensed under the Apache License, Version 2.0 (the",
"import Schema from sqlalchemy import func from offlinetools import models from offlinetools.views.base import",
"from offlinetools.views.base import ViewBase from offlinetools.views import validators from offlinetools.syslanguage import _culture_list, default_culture",
"= 100000 class LoginSchema(Schema): allow_extra_fields = True filter_extra_fields = True LoginName = validators.UnicodeString(max=50,",
"= True LoginName = validators.UnicodeString(max=50, not_empty=True) LoginPwd = validators.String(not_empty=True) came_from = validators.UnicodeString() class",
"not not config.update_failure_count has_updated = not not config.last_update return {'has_data': has_data, 'failed_updates': failed_updates,",
"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",
"specific language governing permissions and # limitations under the License. # ========================================================================================= from",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"Schema from sqlalchemy import func from offlinetools import models from offlinetools.views.base import ViewBase",
"if hash != user.PasswordHash: model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info() headers",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"models from offlinetools.views.base import ViewBase from offlinetools.views import validators from offlinetools.syslanguage import _culture_list,",
"# Copyright 2016 Community Information Online Consortium (CIOC) and KCL Software Solutions #",
"= not not config.update_failure_count has_updated = not not config.last_update return {'has_data': has_data, 'failed_updates':",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"LoginPwd = validators.String(not_empty=True) came_from = validators.UnicodeString() class Login(ViewBase): def post(self): request = self.request",
"= [default_culture()] return HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])), headers=headers) def get(self): request = self.request login_url",
"start_ln = [x.Culture for x in _culture_list if x.LangID == user.LangID and x.Active]",
"= Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat) if hash != user.PasswordHash: model_state.add_error_for('*', _('Invalid User Name or",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"[default_culture()] return HTTPFound(location=model_state.value('came_from', request.route_url('search', ln=start_ln[0])), headers=headers) def get(self): request = self.request login_url =",
"from offlinetools import models from offlinetools.views.base import ViewBase from offlinetools.views import validators from",
"model_state.schema = LoginSchema() if not model_state.validate(): return self._get_edit_info() LoginName = model_state.value('LoginName') user =",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"[x.Culture for x in _culture_list if x.LangID == user.LangID and x.Active] if not",
"not_empty=True) LoginPwd = validators.String(not_empty=True) came_from = validators.UnicodeString() class Login(ViewBase): def post(self): request =",
"user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not user: model_state.add_error_for('*', _('Invalid User Name or Password')) return",
"request.url if referrer == login_url: referrer = request.route_url('search') # never use the login",
"_culture_list, default_culture DEFAULT_REPEAT = 100000 class LoginSchema(Schema): allow_extra_fields = True filter_extra_fields = True",
"hashlib import pbkdf2_hmac from base64 import standard_b64encode from pyramid.httpexceptions import HTTPFound from pyramid.security",
"itself as came_from came_from = request.params.get('came_from', referrer) request.model_state.data['came_from'] = came_from return self._get_edit_info() def",
"= request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not user: model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info()",
"filter_extra_fields = True LoginName = validators.UnicodeString(max=50, not_empty=True) LoginPwd = validators.String(not_empty=True) came_from = validators.UnicodeString()",
"request.model_state.data['came_from'] = came_from return self._get_edit_info() def _get_edit_info(self): request = self.request session = request.dbsession",
"= request.params.get('came_from', referrer) request.model_state.data['came_from'] = came_from return self._get_edit_info() def _get_edit_info(self): request = self.request",
"__future__ import absolute_import from hashlib import pbkdf2_hmac from base64 import standard_b64encode from pyramid.httpexceptions",
"Password')) return self._get_edit_info() headers = remember(request, user.UserName) start_ln = [x.Culture for x in",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"except in compliance with the License. # You may obtain a copy of",
"= request.translate model_state = request.model_state model_state.schema = LoginSchema() if not model_state.validate(): return self._get_edit_info()",
"Consortium (CIOC) and KCL Software Solutions # # Licensed under the Apache License,",
"== user.LangID and x.Active] if not start_ln: start_ln = [default_culture()] return HTTPFound(location=model_state.value('came_from', request.route_url('search',",
"import models from offlinetools.views.base import ViewBase from offlinetools.views import validators from offlinetools.syslanguage import",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"hash != user.PasswordHash: model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info() headers =",
"validators.UnicodeString(max=50, not_empty=True) LoginPwd = validators.String(not_empty=True) came_from = validators.UnicodeString() class Login(ViewBase): def post(self): request",
"self._get_edit_info() LoginName = model_state.value('LoginName') user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not user: model_state.add_error_for('*', _('Invalid User",
"LoginName = model_state.value('LoginName') user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not user: model_state.add_error_for('*', _('Invalid User Name",
"= session.query(func.count(models.Users.UserName), func.count(models.Record.NUM)).one() has_data = any(user_count) failed_updates = False has_updated = True if",
"ln=start_ln[0])), headers=headers) def get(self): request = self.request login_url = request.route_url('login') referrer = request.url",
"Online Consortium (CIOC) and KCL Software Solutions # # Licensed under the Apache",
"= forget(request) return HTTPFound(location=request.route_url('login'), headers=headers) def Crypt(salt, password, repeat=DEFAULT_REPEAT): return standard_b64encode(pbkdf2_hmac('sha1', password.encode('utf-8'), salt.encode('utf-8'),",
"user.PasswordHashRepeat) if hash != user.PasswordHash: model_state.add_error_for('*', _('Invalid User Name or Password')) return self._get_edit_info()",
"import pbkdf2_hmac from base64 import standard_b64encode from pyramid.httpexceptions import HTTPFound from pyramid.security import",
"has_data, 'failed_updates': failed_updates, 'has_updated': has_updated} def logout(request): headers = forget(request) return HTTPFound(location=request.route_url('login'), headers=headers)",
"failed_updates, 'has_updated': has_updated} def logout(request): headers = forget(request) return HTTPFound(location=request.route_url('login'), headers=headers) def Crypt(salt,",
"failed_updates = not not config.update_failure_count has_updated = not not config.last_update return {'has_data': has_data,",
"import ViewBase from offlinetools.views import validators from offlinetools.syslanguage import _culture_list, default_culture DEFAULT_REPEAT =",
"= model_state.value('LoginName') user = request.dbsession.query(models.Users).filter_by(UserName=LoginName).first() if not user: model_state.add_error_for('*', _('Invalid User Name or",
"import _culture_list, default_culture DEFAULT_REPEAT = 100000 class LoginSchema(Schema): allow_extra_fields = True filter_extra_fields =",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"return self._get_edit_info() hash = Crypt(user.PasswordHashSalt, model_state.value('LoginPwd'), user.PasswordHashRepeat) if hash != user.PasswordHash: model_state.add_error_for('*', _('Invalid",
"False has_updated = True if not has_data: config = request.config failed_updates = not",
"100000 class LoginSchema(Schema): allow_extra_fields = True filter_extra_fields = True LoginName = validators.UnicodeString(max=50, not_empty=True)",
"= request.route_url('login') referrer = request.url if referrer == login_url: referrer = request.route_url('search') #"
] |
[
"p.returncode == 0: printer.write('\\nVisaulforce Component created') file = os.path.join(self.class_dir, self.page_name + '.component') sublime.active_window().open_file(file)",
"class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0",
"'Upgrading Project', 'Project Upgraded') printer.write('\\nUpgrading Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Upgraded') def is_enabled(self,",
"mdpopups import time from collections import OrderedDict from .lib.printer import PanelPrinter from .lib.threads",
"Opened') printer.write('\\nOpening Auth Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Auth Page Opened') def is_enabled(self, paths=[]):",
"'-n', self.app_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo =",
"save the interface') return self.event_name = 'InterfaceName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Interface Name',",
"view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener): def on_window_commad(self, window, command_name, args): if command_name ==",
"printer.write('\\nCreating Visualforce Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Component Created') def run_command(self): dx_folder =",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nProject created') else: printer.write('\\nError",
"return completionProvider = client.get_capability('completionProvider') if not completionProvider: return autocomplete_triggers = completionProvider.get('triggerCharacters') if locations[0]",
"format_symbol(detail) insertText = label if item.get(\"insertTextFormat\") == 2: insertText = item.get(\"insertText\") if insertText[0]",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning App created') file =",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running anonymous",
"DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0 and",
"'utf-8')) else: printErr = err if err is None or err == '':",
"created') file = os.path.join(self.class_dir, self.app_name, self.app_name + '.app') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning",
"printer.write('\\nPlease select a single folder save the class') return self.class_name = 'ApexClassName' self.class_dir",
"App Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:app:create', '-n', self.app_name,",
"if err is None or err == '': printErr = out printer.write('\\n' +",
"run') printer.write('\\nRunning anonymous apex') printer.write('\\nResult: ') PanelThreadProgress(t, 'Anonymous apex run') def is_enabled(self, paths=[]):",
"Class Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:apex:class:create', '-n', self.class_name,",
"show multiple rows \"\"\" # file_path = uri_to_filename(location.get(\"uri\")) # kind = format_symbol_kind(item.get(\"kind\")) #",
"util.isDXProject() == False: return False return True def run_command(self): args = ['sfdx', 'force:org:create',",
"= input sublime.active_window().show_input_panel('Project Path', self.project_path, self.create_project_namespace, None, None) def create_project_namespace(self, input): self.project_path =",
"edit, text, erase=False, *args, **kwargs): size = self.view.size() self.view.set_read_only(False) if erase == True:",
"p.wait() out,err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nProject created')",
"'', self.run_query, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"folder to save the component') return self.page_name = 'ComponentName' self.page_label = 'Component Label'",
"if locations[0] > 0: self.completions = [] purge_did_change(view.buffer_id()) client.send_request( Request.complete( util.get_document_position(view, locations[0])), self.handle_response)",
"'exit': plugin_unloaded() class EventHandlers(sublime_plugin.EventListener): def __init__(self): self.completions = [] # type: List[Tuple[str, str]]",
"else response for item in items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def run_auto_complete(self): self.refreshing =",
"'-d', self.project_path] if self.namespace is not None and self.namespace != '': args.push('-s') args.push(self.namespace)",
".lib.languageServer import * from .lib.event_hub import EventHub from .lib.util import util from .lib.diagnostic",
"for region in self.view.sel(): if not region.empty(): self.selection += self.view.substr(region) if self.selection ==",
"if err is None or err == '': printErr = out printer.write('\\nError running",
"and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the class') return self.app_name",
"plugin_unloaded(): if lsClient: lsClient.kill() def set_syntax(view): if util.is_apex_file(view): util.debug('setting syntax for file') if",
"sublime_plugin import os import subprocess import threading import sys import json import mdpopups",
"return False return True def create_class(self, input): self.class_name = input printer.show() t =",
"In the latter case, each entry in the quick panel will show multiple",
"Component Created') printer.write('\\nCreating Lightning Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Component Created') def run_command(self):",
"self.completions, (sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self, item) -> 'Tuple[str, str]': label = item.get(\"label\")",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running anonymous apex', 'Anonymous apex run') printer.write('\\nRunning",
"subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait() out,err = p.communicate() r =",
"') PanelThreadProgress(t, 'Org Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"else: printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self,",
"'Apex Class Created') printer.write('\\nCreating Apex Class') printer.write('\\nResult: ') PanelThreadProgress(t, 'Apex Class Created') def",
"+ str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or",
"self.create_project_namespace, None, None) def create_project_namespace(self, input): self.project_path = input sublime.active_window().show_input_panel( 'Project Namespace', '',",
"plugin_unloaded() class EventHandlers(sublime_plugin.EventListener): def __init__(self): self.completions = [] # type: List[Tuple[str, str]] self.refreshing",
"Scratch Org', 'Scratch Org Created') printer.write('\\nCreatin Scratch Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Scratch Org",
"point, hover_zone) def on_window_command(self, window, command_name, *args): if command_name == 'exit': EventHub.publish('exit', window,",
"select a single folder save the component') return self.cmp_name = 'ComponentName' self.class_dir =",
"= self.view.size() self.view.set_read_only(False) self.view.replace(edit, status_region, text) self.view.set_read_only(True) # self.view.show(size) def is_visible(self): return False",
"# self.view.show(size) def is_visible(self): return False def is_enabled(self): return True def description(self): return",
"printer if util.dxProjectFolder() != '': lsClient = start_client() if lsClient is None: util.debug('Unable",
"edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d",
"os.path.isfile(paths[0])): return False return True def create_app(self, input): self.app_name = input printer.show() t",
"Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:component:create', '-n', self.cmp_name, '-d',",
"import ThreadProgress from .lib.threads import PanelThreadProgress from .lib.languageServer import * from .lib.event_hub import",
"run(self, edit): self.edit = edit self.project_name = '' self.template = 'Defaultsfdx-project.json' self.project_path =",
"None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p =",
"plugin_loaded(): global lsClient global printer if util.dxProjectFolder() != '': lsClient = start_client() if",
"run') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False",
"#try: # parsed = json.loads(content) # content = json.dumps(parsed, sort_keys=True,indent=1, separators=(',', ':')) #",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pulling Source', 'Source Pulled') printer.write('\\nPulling Source') printer.write('\\nResult: ') PanelThreadProgress(t,",
"os.path.join( self.dx_folder, 'config', 'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class Name', self.def_file, self.create_org, None, None) def create_org(self,",
"PanelThreadProgress(t, 'Project Created') def run_command(self): args = ['sfdx', 'force:project:create', '-n', self.project_name, '-t', self.template,",
"True def run_command(self): args = ['sfdx', 'force:source:push'] startupinfo = None if os.name ==",
"r = p.returncode if p.returncode == 0: printer.write('\\nProject created') else: printer.write('\\nError creating project:')",
"SymbolKind.Package: \"package\", SymbolKind.Class: \"class\", SymbolKind.Method: \"method\", SymbolKind.Function: \"function\", SymbolKind.Field: \"field\", SymbolKind.Variable: \"variable\", SymbolKind.Constant:",
"EventHub.publish('exit', window, *args) elif command_name == 'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window,",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Page', 'Visualforce Page Created') printer.write('\\nCreating Visualforce Page') printer.write('\\nResult:",
"Test') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Test Created') def run_command(self): dx_folder = util.dxProjectFolder() args",
"global printer if util.dxProjectFolder() != '': lsClient = start_client() if lsClient is None:",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nDevHub authorized') else: printer.write('\\nError",
"if \"linux\" in sys.platform or \"darwin\" in sys.platform: syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path",
"'-l', 'RunSpecifiedTests', '-n', self.class_name] startupinfo = None if os.name == 'nt': startupinfo =",
"and not err == '': printErr = out else: printer.write('\\nError pushing source') printer.write('\\n'",
"1 or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_app(self,",
"sublime.active_window().show_input_panel( 'Org (leave blank for default)', '', self.run_tests, None, None) def run_tests(self, input):",
"Property = 7 Field = 8 Constructor = 9 Enum = 10 Interface",
"r = p.returncode if p.returncode == 0: printer.write('\\n' + str(out, 'utf-8')) else: printErr",
"sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning App:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def",
"time.localtime()) ThreadProgress(t, 'Opening Org', 'Org Opened') printer.write('\\nOpening Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Org Opened')",
"self.def_file = os.path.join( self.dx_folder, 'config', 'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class Name', self.def_file, self.create_org, None, None)",
"file = os.path.join(self.class_dir, self.app_name, self.app_name + '.app') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning App:')",
"sys.platform or \"darwin\" in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener): def on_window_commad(self, window,",
"paths[0] sublime.active_window().show_input_panel( 'App Name', self.cmp_name, self.create_cmp, None, None) def is_enabled(self, paths=[]): #dx_folder =",
"self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Class Name', self.class_name, self.create_class, None, None) def is_enabled(self, paths=[]):",
"sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self, item) -> 'Tuple[str, str]': label = item.get(\"label\") # kind =",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Upgraded') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"= os.path.join(self.class_dir, self.event_name, self.event_name + '.evt') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Event:') printer.write('\\n'",
"'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_text_command(self, window, command_name,",
"Lightning Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Component Created') def run_command(self): dx_folder = util.dxProjectFolder()",
"= 'EventName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Event Name', self.event_name, self.create_event, None, None) def",
"= ['sfdx', 'force:source:pull'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"= threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\",",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Test created')",
"util from .lib.diagnostic import * import ntpath class SymbolKind(object): File = 1 Module",
"r = p.returncode if p.returncode == 0: printer.write('\\nLightning App created') file = os.path.join(self.class_dir,",
"= os.path.join(self.class_dir, self.event_name, self.event_name + '.intf') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Interface:') printer.write('\\n'",
"the class') return self.class_name = 'ApexClassName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Class Name', self.class_name,",
"= self.view.substr(sublime.Region(0, self.view.size())) self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls') with open(self.file_path, 'w+') as file_obj:",
"def create_project_template(self, input): self.project_template = input sublime.active_window().show_input_panel('Project Path', self.project_path, self.create_project_namespace, None, None) def",
"= os.path.join(self.class_dir, self.app_name, self.app_name + '.app') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning App:') printer.write('\\n'",
"file') content = str(out,'UTF-8') #try: # parsed = json.loads(content) # content = json.dumps(parsed,",
"Upgraded') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False",
"0 and os.path.isfile(paths[0])): return False return True def create_app(self, input): self.app_name = input",
"a list of strings, or a list of string lists. In the latter",
"printer.write('\\nPlease select a single folder to save the page') return self.page_name = 'PageName'",
"= PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin loaded\", erase=True) def plugin_unloaded(): if lsClient: lsClient.kill() def set_syntax(view):",
"False if not util.file_is_test(self.window.active_view()): return False return True def run_command(self): args = ['sfdx',",
"True def create_app(self, input): self.app_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pushing Source', 'Source Pushed')",
"List[Tuple[str, str]] self.refreshing = False def on_pre_close(self, view): EventHub.publish('on_pre_close', view) def on_close(self, view):",
"p.returncode == 0: printer.write('\\nApex class created') file = os.path.join(self.class_dir, self.class_name + '.cls') sublime.active_window().open_file(file)",
".lib.util import util from .lib.diagnostic import * import ntpath class SymbolKind(object): File =",
"blank for default)', '', self.run_tests, None, None) def run_tests(self, input): self.test_org = input",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce Component created') file =",
"str(out, 'utf-8')) else: printErr = err if not err is None and not",
"util.debug(content) #except Exception as e: # util.debug('could not format query results\\n', e) file",
"{ 'disable_auto_insert': True, 'api_completions_only': False, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True, }) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def",
"DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org (leave blank for default)',",
"run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() printer.write('\\nPushing Source') t = threading.Thread(target=self.run_command) t.start() t.printer",
"printer.show() printer.write('\\nPlease select a single folder save the class') return self.class_name = 'ApexClassName'",
"view): EventHub.publish('on_load_async', view) def on_activated_async(self, view): EventHub.publish('on_activated_async', view) def on_post_save_async(self, view): EventHub.publish('on_post_save_async', view)",
"Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Page API Name', self.page_name, self.get_label, None, None) def",
"5 Method = 6 Property = 7 Field = 8 Constructor = 9",
"-> 'Tuple[str, str]': label = item.get(\"label\") # kind = item.get(\"kind\") detail = item.get(\"kind\")",
"PanelThreadProgress(t, 'Visualforce Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:component:create',",
"err == '': printErr = out else: printer.write('\\nError pushing source') printer.write('\\n' + str(printErr,",
"printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]):",
"False: return False return True def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx',",
"+ insertText[1:] return (\"{}\\t{}\".format(label, detail), insertText) def handle_response(self, response): self.completions = [] items",
"self.view.set_read_only(True) # self.view.show(size) def is_visible(self): return False def is_enabled(self): return True def description(self):",
"p.returncode if p.returncode == 0: printer.write('\\nLightning Event created') file = os.path.join(self.class_dir, self.event_name, self.event_name",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Component",
"== False: return False return True def run_command(self): args = ['sfdx', 'force:org:open'] startupinfo",
"select a single folder save the interface') return self.event_name = 'InterfaceName' self.class_dir =",
"def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer =",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running Org Tests', 'Org tests run') PanelThreadProgress(t, 'Running Org Tests')",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Created') def run_command(self): args = ['sfdx', 'force:project:create', '-n', self.project_name,",
"util.dxProjectFolder() args = ['sfdx', 'force:lightning:event:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if",
"== 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,",
"r = p.returncode if p.returncode == 0: printer.write('\\nProject upgraded') else: printer.write('\\nError upgrading project:')",
"DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self, edit): self.edit = edit self.project_name = '' self.template = 'Defaultsfdx-project.json'",
"= subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait() out,err",
"'force:lightning:interface:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo",
"printer.write('\\nRunning anonymous apex') printer.write('\\nResult: ') PanelThreadProgress(t, 'Anonymous apex run') def is_enabled(self, paths=[]): #dx_folder",
"True def run_command(self): args = ['sfdx', 'force:org:open'] startupinfo = None if os.name ==",
"DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"+ str(printErr, 'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t",
"r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce page created') file = os.path.join(self.class_dir,",
"self.selection += self.view.substr(region) if self.selection == '': self.selection = self.view.substr(sublime.Region(0, self.view.size())) self.file_path =",
"os import subprocess import threading import sys import json import mdpopups import time",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Auth",
"= os.path.join(self.class_dir, self.page_name + '.component') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce Component:') printer.write('\\n' +",
"printer.write('\\nError upgrading project:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self, edit): self.edit",
"= input sublime.active_window().show_input_panel( 'Page Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder",
"rows \"\"\" # file_path = uri_to_filename(location.get(\"uri\")) # kind = format_symbol_kind(item.get(\"kind\")) # return [item.get(\"name\"),",
"printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder",
"printer.write('\\nCreating Visualforce Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Page Created') def run_command(self): dx_folder =",
"= False return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self, item) -> 'Tuple[str, str]':",
"{\"characters\":content}) else: printer.write('\\nError running query:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self,",
"'Class Name', self.class_name, self.create_class, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"def plugin_loaded(): global lsClient global printer if util.dxProjectFolder() != '': lsClient = start_client()",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1",
"if util.isDXProject() == False: return False if len(paths) != 1 or (len(paths) >",
"') PanelThreadProgress(t, 'Project Created') def run_command(self): args = ['sfdx', 'force:project:create', '-n', self.project_name, '-t',",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running Org Tests', 'Org tests run') PanelThreadProgress(t, 'Running Org",
"= util.dxProjectFolder() self.active_file = util.active_file() self.active_file = ntpath.split(self.active_file)[ 1].replace('.cls', '') self.class_name = 'ApexClassName'",
"startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait() out,err = p.communicate()",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nOpening results file') content",
"and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder to save the component') return",
"') PanelThreadProgress(t, 'Source Pulled') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"locations[0] > 0: self.completions = [] purge_did_change(view.buffer_id()) client.send_request( Request.complete( util.get_document_position(view, locations[0])), self.handle_response) self.refreshing",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running tests', 'Tests run') PanelThreadProgress(t, 'Running Tests') def",
"lsClient if not client: return completionProvider = client.get_capability('completionProvider') if not completionProvider: return autocomplete_triggers",
"= label if item.get(\"insertTextFormat\") == 2: insertText = item.get(\"insertText\") if insertText[0] == '$':",
"def on_query_completions(self, view, prefix, locations): active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and",
"False return True def create_page(self, input): self.page_label = input printer.show() t = threading.Thread(target=self.run_command)",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pulled') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"self.refreshing = True sublime.active_window().active_view().run_command( \"auto_complete\", { 'disable_auto_insert': True, 'api_completions_only': False, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab':",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pushed') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"Event created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.evt') sublime.active_window().open_file(file) else: printer.write('\\nError creating",
"not self.refreshing: client = lsClient if not client: return completionProvider = client.get_capability('completionProvider') if",
"startupinfo=startupinfo, cwd=self.dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode ==",
"util.dxProjectFolder() if util.isDXProject() == False: return False return True def run_command(self): dx_folder =",
"= client.get_capability('completionProvider') if not completionProvider: return autocomplete_triggers = completionProvider.get('triggerCharacters') if locations[0] > 0:",
"a single folder save the interface') return self.event_name = 'InterfaceName' self.class_dir = paths[0]",
"'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self): sublime.active_window().show_input_panel( 'Query', '', self.run_query, None, None) def is_enabled(self,",
"<gh_stars>1-10 import sublime import sublime_plugin import os import subprocess import threading import sys",
"self.view.set_read_only(False) if erase == True: size = sublime.Region(0, self.view.size()) self.view.replace(edit, size, text) else:",
"True def create_page(self, input): self.page_label = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer",
"EventHub.publish('on_pre_close', view) def on_close(self, view): EventHub.publish('on_close', view) def on_load_async(self, view): EventHub.publish('on_load_async', view) def",
"['sfdx', 'force:lightning:component:create', '-n', self.cmp_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt':",
"util.dxProjectFolder() args = ['sfdx', 'force:lightning:component:create', '-n', self.cmp_name, '-d', self.class_dir] startupinfo = None if",
"1 or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_page(self,",
"') PanelThreadProgress(t, 'Scratch Org Created') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"a single folder save the class') return self.event_name = 'EventName' self.class_dir = paths[0]",
"return True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human'] if not self.test_org",
"printer.write('\\n' + str(out, 'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self, edit): self.selection = '' for",
"0: printer.write('\\nVisaulforce Component created') file = os.path.join(self.class_dir, self.page_name + '.component') sublime.active_window().open_file(file) else: printer.write('\\nError",
"util.isDXProject() == False: return False return True def run_command(self): args = ['sfdx', 'force:apex:execute',",
"else: EventHub.publish('on_window_command', window, command_name, *args) def on_text_command(self, window, command_name, *args): if command_name ==",
"None, None) def run_tests(self, input): self.test_org = input printer.show() printer.write('\\nRunning Org Tests') printer.write('\\nResult:",
"Exception as e: # util.debug('could not format query results\\n', e) file = sublime.active_window().new_file()",
"window, command_name, *args) def on_text_command(self, window, command_name, *args): if command_name == 'exit': EventHub.publish('exit',",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Scratch Org Created') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Apex Class',",
"9 Enum = 10 Interface = 11 Function = 12 Variable = 13",
"Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label,",
"SymbolKind.Namespace: \"namespace\", SymbolKind.Package: \"package\", SymbolKind.Class: \"class\", SymbolKind.Method: \"method\", SymbolKind.Function: \"function\", SymbolKind.Field: \"field\", SymbolKind.Variable:",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Query run') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx',",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Component', 'Lightning Component Created')",
"Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return",
"+ '.evt') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Event:') printer.write('\\n' + str(err, 'utf-8')) class",
"if item.get(\"insertTextFormat\") == 2: insertText = item.get(\"insertText\") if insertText[0] == '$': # sublime",
"= item.get(\"kind\") detail = item.get(\"kind\") detail = format_symbol_kind(detail) #detail = format_symbol(detail) insertText =",
"= util.dxProjectFolder() args = ['sfdx', 'force:data:soql:query', '-q', self.query] startupinfo = None if os.name",
"self.page_name + '.component') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce Component:') printer.write('\\n' + str(err, 'utf-8'))",
"ready for code completion yet lsClient = None printer = None def plugin_loaded():",
"PanelThreadProgress(t, 'Lightning App Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:app:create',",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pulling Source', 'Source Pulled')",
"json import mdpopups import time from collections import OrderedDict from .lib.printer import PanelPrinter",
"def on_close(self, view): EventHub.publish('on_close', view) def on_load_async(self, view): EventHub.publish('on_load_async', view) def on_activated_async(self, view):",
"'.page') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce page:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand):",
"Namespace', '', self.create_project, None, None) def create_project(self, input): printer.show() self.namespace = input t",
"if not region.empty(): self.selection += self.view.substr(region) if self.selection == '': self.selection = self.view.substr(sublime.Region(0,",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Event', 'Lightning Event Created')",
"self.active_file = util.active_file() if not self.active_file.endswith('.cls'): return False if not util.file_is_test(self.window.active_view()): return False",
"p.returncode if p.returncode == 0: printer.write('\\nVisaulforce page created') file = os.path.join(self.class_dir, self.page_name +",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nProject upgraded') else: printer.write('\\nError",
"Lightning Test', 'Lightning Interface Test') printer.write('\\nCreating Lightning Test') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Test",
"self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls') with open(self.file_path, 'w+') as file_obj: file_obj.write(self.selection) printer.show() self.namespace",
"is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False return True",
"r = p.returncode if p.returncode == 0: printer.write('\\nLightning Component created') file = os.path.join(self.class_dir,",
"= err if not err is None and not err == '': printErr",
"self.view.substr(sublime.Region(0, self.view.size())) self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls') with open(self.file_path, 'w+') as file_obj: file_obj.write(self.selection)",
"edit): self.selection = '' for region in self.view.sel(): if not region.empty(): self.selection +=",
"Tests') printer.write('\\nResult: ') t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\",",
"SymbolKind.Method: \"method\", SymbolKind.Function: \"function\", SymbolKind.Field: \"field\", SymbolKind.Variable: \"variable\", SymbolKind.Constant: \"constant\" } def format_symbol_kind(kind):",
"threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())",
"(len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_page(self, input): self.page_label",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Apex Class', 'Apex Class Created') printer.write('\\nCreating Apex Class') printer.write('\\nResult:",
"self.view.size()) self.view.replace(edit, size, text) else: self.view.insert(edit, size, text) self.view.set_read_only(True) self.view.show(size) def is_visible(self): return",
"apex', 'Anonymous apex run') printer.write('\\nRunning anonymous apex') printer.write('\\nResult: ') PanelThreadProgress(t, 'Anonymous apex run')",
"locations[0])), self.handle_response) self.refreshing = False return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self, item)",
"'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo,",
"printer.write('\\nCreating Lightning Interface') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Interface Created') def run_command(self): dx_folder =",
"text) self.view.set_read_only(True) self.view.show(size) def is_visible(self): return False def is_enabled(self): return True def description(self):",
"= os.path.join(self.class_dir, self.class_name + '.cls') sublime.active_window().open_file(file) else: printer.write('\\nError creating Apex Class:') printer.write('\\n' +",
"test') return self.event_name = 'TestName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Test Name', self.event_name, self.create_event,",
"Event') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Event Created') def run_command(self): dx_folder = util.dxProjectFolder() args",
"!= '.trigger': return None if not self.refreshing: client = lsClient if not client:",
"'Component Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Component API Name', self.page_name, self.get_label, None, None)",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Test created') file =",
"'' for region in self.view.sel(): if not region.empty(): self.selection += self.view.substr(region) if self.selection",
"self.get_label, None, None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Component Label', self.page_label,",
"page created') file = os.path.join(self.class_dir, self.page_name + '.page') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Scratch Org', 'Scratch Org",
"= p.returncode if p.returncode == 0: printer.write('\\nLightning Component created') file = os.path.join(self.class_dir, self.cmp_name,",
"start langauge server') EventHub.subscribe('on_load_async', set_syntax) active_window_id = sublime.active_window().id() printer = PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin",
"'Running anonymous apex', 'Anonymous apex run') printer.write('\\nRunning anonymous apex') printer.write('\\nResult: ') PanelThreadProgress(t, 'Anonymous",
"args.push('-u') args.push(self.input) startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"ExitHandler(sublime_plugin.EventListener): def on_window_commad(self, window, command_name, args): if command_name == 'exit': plugin_unloaded() class EventHandlers(sublime_plugin.EventListener):",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce page created') file =",
"view): EventHub.publish('on_post_save_async', view) def on_close(self, view): EventHub.publish('on_close', view) def on_hover(self, view, point, hover_zone):",
"'': printErr = out else: printer.write('\\nError pushing source') printer.write('\\n' + str(printErr, 'utf-8')) class",
"a single folder save the test') return self.event_name = 'TestName' self.class_dir = paths[0]",
"**kwargs): size = self.view.size() self.view.set_read_only(False) if erase == True: size = sublime.Region(0, self.view.size())",
"len(self.test_org) > 0: args.push('-u') args.push(self.input) startupinfo = None if os.name == 'nt': startupinfo",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Interface created') file",
"created') file = os.path.join(self.class_dir, self.event_name + '.resource') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Test:')",
"0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the component') return",
"subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait() out,err = p.communicate() r = p.returncode if p.returncode",
"def format_completion(self, item) -> 'Tuple[str, str]': label = item.get(\"label\") # kind = item.get(\"kind\")",
"= err if err is None or err == '': printErr = out",
"util.debug('could not format query results\\n', e) file = sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL') syntax_path =",
"self.event_name + '.evt') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Event:') printer.write('\\n' + str(err, 'utf-8'))",
"= subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder) p.wait()",
"= p.returncode if p.returncode == 0: printer.write('\\nVisaulforce page created') file = os.path.join(self.class_dir, self.page_name",
"'.cls' and active_file_extension != '.trigger': return None if not self.refreshing: client = lsClient",
"util.isDXProject() == False: return False return True def run_command(self): args = ['sfdx', 'force:source:push']",
"file = os.path.join(self.class_dir, self.page_name + '.page') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce page:') printer.write('\\n'",
"r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce Component created') file = os.path.join(self.class_dir,",
"args = ['sfdx', 'force:apex:execute', '-f', self.file_path] startupinfo = None if os.name == 'nt':",
"Event Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:event:create', '-n', self.event_name,",
"else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener): def on_window_commad(self, window, command_name, args): if command_name == 'exit':",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Test",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running query', 'Query run') printer.write('\\nRunning query')",
"'Source Pulled') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return",
"0 and os.path.isfile(paths[0])): return False return True def create_page(self, input): self.page_label = input",
"'force:lightning:app:create', '-n', self.app_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo",
"self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Component API Name', self.page_name, self.get_label, None, None) def get_label(self,",
"11 Function = 12 Variable = 13 Constant = 14 String = 15",
"detail), insertText) def handle_response(self, response): self.completions = [] items = response[\"items\"] if isinstance(response,",
"SymbolKind.Function: \"function\", SymbolKind.Field: \"field\", SymbolKind.Variable: \"variable\", SymbolKind.Constant: \"constant\" } def format_symbol_kind(kind): return symbol_kind_names.get(kind,",
"'-s', '-a', 'DevHub'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"util.active_file() if not self.active_file.endswith('.cls'): return False if not util.file_is_test(self.window.active_view()): return False return True",
"= ['sfdx', 'force:lightning:app:create', '-n', self.app_name, '-d', self.class_dir] startupinfo = None if os.name ==",
"return self.class_name = 'ApexClassName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Class Name', self.class_name, self.create_class, None,",
"p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nDevHub",
"return False return True def create_cmp(self, input): self.cmp_name = input printer.show() t =",
"if p.returncode == 0: printer.write('\\nOpening results file') content = str(out,'UTF-8') #try: # parsed",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning App created') file",
"DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0 and",
"Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:apex:class:create', '-n', self.class_name, '-d',",
"sublime.active_window().id() printer = PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin loaded\", erase=True) def plugin_unloaded(): if lsClient: lsClient.kill()",
"if p.returncode == 0: printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if",
"not util.file_is_test(self.window.active_view()): return False return True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r',",
"'-r', 'human', '-l', 'RunSpecifiedTests', '-n', self.class_name] startupinfo = None if os.name == 'nt':",
"Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Scratch Org Created') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"= None def plugin_loaded(): global lsClient global printer if util.dxProjectFolder() != '': lsClient",
"Page Created') printer.write('\\nCreating Visualforce Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Page Created') def run_command(self):",
"err == '': printErr = out else: printer.write('\\nError pulling source') printer.write('\\n' + str(printErr,",
"= util.active_file() self.active_file = ntpath.split(self.active_file)[ 1].replace('.cls', '') self.class_name = 'ApexClassName' t = threading.Thread(target=self.run_command)",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pushing Source', 'Source Pushed') printer.write('\\nResult: ') PanelThreadProgress(t,",
"self.query = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pushing",
"'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_modified_async(self, view): active_file_extension",
"command_name, args): if command_name == 'exit': plugin_unloaded() class EventHandlers(sublime_plugin.EventListener): def __init__(self): self.completions =",
"item.get(\"insertTextFormat\") == 2: insertText = item.get(\"insertText\") if insertText[0] == '$': # sublime needs",
"self.app_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"if(self.dx_folder == ''): return False self.active_file = util.active_file() if not self.active_file.endswith('.cls'): return False",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nProject upgraded') else: printer.write('\\nError upgrading",
"DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0 and",
"'Creating Apex Class', 'Apex Class Created') printer.write('\\nCreating Apex Class') printer.write('\\nResult: ') PanelThreadProgress(t, 'Apex",
"active_file_extension != '.trigger': return None if not self.refreshing: client = lsClient if not",
"= kwargs.get('region', [0, 0]) status_region = sublime.Region(kw_region[0], kw_region[1]) size = self.view.size() self.view.set_read_only(False) self.view.replace(edit,",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Upgrading Project', 'Project Upgraded') printer.write('\\nUpgrading Project') printer.write('\\nResult:",
"else: printer.write('\\nError creating Visualforce page:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self,",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Scratch Org', 'Scratch",
"import PanelPrinter from .lib.threads import ThreadProgress from .lib.threads import PanelThreadProgress from .lib.languageServer import",
"content = str(out,'UTF-8') #try: # parsed = json.loads(content) # content = json.dumps(parsed, sort_keys=True,indent=1,",
"Class') printer.write('\\nResult: ') PanelThreadProgress(t, 'Apex Class Created') def run_command(self): dx_folder = util.dxProjectFolder() args",
"'Event Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False:",
"args = ['sfdx', 'force:org:create', '-f', self.def_file, '-a', 'ScratchOrg', '-s'] startupinfo = None if",
"Opened') printer.write('\\nOpening Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Org Opened') def is_enabled(self, paths=[]): #dx_folder =",
"DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0 and",
"org') printer.write('\\n' + str(err, 'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t =",
"'-q', self.query] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Upgrading Project', 'Project Upgraded') printer.write('\\nUpgrading",
"import subprocess import threading import sys import json import mdpopups import time from",
"} def format_symbol_kind(kind): return symbol_kind_names.get(kind, str(kind)) def format_symbol(item): \"\"\" items may be a",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nApex class",
"create_event(self, input): self.event_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"+ str(err, 'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() self.def_file =",
"+ '.app') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning App:') printer.write('\\n' + str(err, 'utf-8')) class",
"\"linux\" in sys.platform or \"darwin\" in sys.platform: syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path =",
"args.push(self.namespace) startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:component:create', '-n', self.cmp_name, '-d', self.class_dir] startupinfo",
"single folder save the class') return self.app_name = 'AppName' self.class_dir = paths[0] sublime.active_window().show_input_panel(",
"creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if",
"return True def create_event(self, input): self.event_name = input printer.show() t = threading.Thread(target=self.run_command) t.start()",
"0: printer.write('\\nProject upgraded') else: printer.write('\\nError upgrading project:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand):",
"create_project_name(self, input): self.project_name = input sublime.active_window().show_input_panel('Project Template', self.template, self.create_project_template, None, None) def create_project_template(self,",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Apex",
"'TestName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Test Name', self.event_name, self.create_event, None, None) def is_enabled(self,",
"if isinstance(response, dict) else response for item in items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def",
"p.returncode if p.returncode == 0: printer.write('\\nLightning Component created') file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name",
"if util.isDXProject() == False: return False util.debug(paths) if len(paths) != 1 or (len(paths)",
"stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait() out,err = p.communicate() r = p.returncode if p.returncode == 0:",
"self.def_file = input t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a,",
"sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def run_auto_complete(self): self.refreshing = True sublime.active_window().active_view().run_command( \"auto_complete\", { 'disable_auto_insert': True, 'api_completions_only':",
"Lightning App') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning App Created') def run_command(self): dx_folder = util.dxProjectFolder()",
"in items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def run_auto_complete(self): self.refreshing = True sublime.active_window().active_view().run_command( \"auto_complete\", {",
"a single folder save the class') return self.app_name = 'AppName' self.class_dir = paths[0]",
"ThreadProgress(t, 'Creating Lightning App', 'Lightning App Created') printer.write('\\nCreating Lightning App') printer.write('\\nResult: ') PanelThreadProgress(t,",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nScratch org created') else: printer.write('\\nError",
"return False def is_enabled(self): return True def description(self): return # not ready for",
"return False return True def run_command(self): args = ['sfdx', 'force:source:pull'] startupinfo = None",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Component', 'Lightning Component Created') printer.write('\\nCreating Lightning",
"'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) >",
"else: printer.write('\\nError creating Apex Class:') printer.write('\\n' + str(err, 'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self,",
"description(self): return # not ready for code completion yet lsClient = None printer",
"> 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the test')",
"Org Created') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return",
"sys.platform: syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content}) else: printer.write('\\nError",
"util.isDXProject() == False: return False return True def run_command(self): args = ['sfdx', 'force:source:pull']",
"'force:source:pull'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"== 0: printer.write('\\nDevHub authorized') else: printer.write('\\nError authorizing Dev Hub:') printer.write('\\n' + str(err, 'utf-8'))",
"ThreadProgress(t, 'Upgrading Project', 'Project Upgraded') printer.write('\\nUpgrading Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Upgraded') def",
"Source') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pulled') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"str]] self.refreshing = False def on_pre_close(self, view): EventHub.publish('on_pre_close', view) def on_close(self, view): EventHub.publish('on_close',",
"printErr = out else: printer.write('\\nError pushing source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand):",
"ThreadProgress(t, 'Creating Apex Class', 'Apex Class Created') printer.write('\\nCreating Apex Class') printer.write('\\nResult: ') PanelThreadProgress(t,",
"run(self, edit, text, *args, **kwargs): kw_region = kwargs.get('region', [0, 0]) status_region = sublime.Region(kw_region[0],",
"0: printer.write('\\nVisaulforce page created') file = os.path.join(self.class_dir, self.page_name + '.page') sublime.active_window().open_file(file) else: printer.write('\\nError",
"'Running Org Tests') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"os.path.join(self.class_dir, self.event_name + '.resource') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Test:') printer.write('\\n' + str(err,",
"return [item.get(\"name\"), kind] return [item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand): def run(self, edit, text, erase=False, *args,",
"1].replace('.cls', '') self.class_name = 'ApexClassName' t = threading.Thread(target=self.run_command) t.start() printer.show() printer.write('\\nRunning Tests') printer.write('\\nResult:",
"if p.returncode == 0: printer.write('\\nLightning Component created') file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name +",
"run_auto_complete(self): self.refreshing = True sublime.active_window().active_view().run_command( \"auto_complete\", { 'disable_auto_insert': True, 'api_completions_only': False, 'next_completion_if_showing': False,",
"== 0: printer.write('\\nLightning App created') file = os.path.join(self.class_dir, self.app_name, self.app_name + '.app') sublime.active_window().open_file(file)",
"apex run') printer.write('\\nRunning anonymous apex') printer.write('\\nResult: ') PanelThreadProgress(t, 'Anonymous apex run') def is_enabled(self,",
"run_tests(self, input): self.test_org = input printer.show() printer.write('\\nRunning Org Tests') printer.write('\\nResult: ') t =",
"detail = format_symbol_kind(detail) #detail = format_symbol(detail) insertText = label if item.get(\"insertTextFormat\") == 2:",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if",
"Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pushing Source', 'Source Pushed') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pushed') def",
"sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def",
"ThreadProgress(t, 'Creating Project', 'Project Created') printer.write('\\nCreating Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Created') def",
"Name', self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Component",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pulling Source', 'Source",
"Upgraded') printer.write('\\nUpgrading Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Upgraded') def is_enabled(self, paths=[]): #dx_folder =",
"= paths[0] sublime.active_window().show_input_panel( 'Event Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if",
"return self.app_name = 'AppName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.app_name, self.create_app, None,",
"class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self, edit): self.selection = '' for region in self.view.sel(): if",
"def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])):",
"def handle_response(self, response): self.completions = [] items = response[\"items\"] if isinstance(response, dict) else",
"self.selection = '' for region in self.view.sel(): if not region.empty(): self.selection += self.view.substr(region)",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Component created') file",
"Created') printer.write('\\nCreating Lightning Interface') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Interface Created') def run_command(self): dx_folder",
"(len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_event(self, input): self.event_name",
"== False: return False return True def run_command(self): args = ['sfdx', 'force:apex:execute', '-f',",
"parsed = json.loads(content) # content = json.dumps(parsed, sort_keys=True,indent=1, separators=(',', ':')) # util.debug(content) #except",
"'.sfdx', 'tmpFile.cls') with open(self.file_path, 'w+') as file_obj: file_obj.write(self.selection) printer.show() self.namespace = input t",
"['sfdx', 'force:visualforce:component:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if os.name ==",
"paths=[]): if util.isDXProject() == False: return False if len(paths) != 1 or (len(paths)",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pushing Source', 'Source Pushed') printer.write('\\nResult: ')",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning App',",
"if p.returncode == 0: printer.write('\\nLightning Event created') file = os.path.join(self.class_dir, self.event_name, self.event_name +",
"else: printer.write('\\nError creating Visualforce Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self,",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Component created') file =",
"import mdpopups import time from collections import OrderedDict from .lib.printer import PanelPrinter from",
"util.isDXProject() == False: return False return True def run_query(self, input): self.query = input",
"PanelThreadProgress(t, 'Running Org Tests') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"view) def on_close(self, view): EventHub.publish('on_close', view) def on_hover(self, view, point, hover_zone): EventHub.publish('on_hover', view,",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:data:soql:query', '-q', self.query] startupinfo =",
"os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content}) else: printer.write('\\nError running query:') printer.write('\\n'",
"= p.returncode if p.returncode == 0: printer.write('\\nScratch org opened') else: printer.write('\\nError opening') printer.write('\\n'",
"= 16 Boolean = 17 Array = 18 symbol_kind_names = { SymbolKind.File: \"file\",",
"*args, **kwargs): kw_region = kwargs.get('region', [0, 0]) status_region = sublime.Region(kw_region[0], kw_region[1]) size =",
"printer.write('\\nOpening Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Org Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:project:upgrade', '-f'] startupinfo = None if",
"will show multiple rows \"\"\" # file_path = uri_to_filename(location.get(\"uri\")) # kind = format_symbol_kind(item.get(\"kind\"))",
"self.project_template = input sublime.active_window().show_input_panel('Project Path', self.project_path, self.create_project_namespace, None, None) def create_project_namespace(self, input): self.project_path",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running query', 'Query run') printer.write('\\nRunning query') printer.write('\\nResult: ') PanelThreadProgress(t, 'Query",
"str(err, 'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() self.def_file = os.path.join(",
"langauge server') EventHub.subscribe('on_load_async', set_syntax) active_window_id = sublime.active_window().id() printer = PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin loaded\",",
"{ SymbolKind.File: \"file\", SymbolKind.Module: \"module\", SymbolKind.Namespace: \"namespace\", SymbolKind.Package: \"package\", SymbolKind.Class: \"class\", SymbolKind.Method: \"method\",",
"Created') printer.write('\\nCreating Lightning Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Component Created') def run_command(self): dx_folder",
"os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the test') return self.event_name =",
"Lightning App:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths)",
"Request.complete( util.get_document_position(view, locations[0])), self.handle_response) self.refreshing = False return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) def",
"= 8 Constructor = 9 Enum = 10 Interface = 11 Function =",
"7 Field = 8 Constructor = 9 Enum = 10 Interface = 11",
"'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class Name', self.def_file, self.create_org, None, None) def create_org(self, input): printer.show() self.def_file",
"paths[0] sublime.active_window().show_input_panel( 'Event Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject()",
"'-t', self.template, '-d', self.project_path] if self.namespace is not None and self.namespace != '':",
"return (\"{}\\t{}\".format(label, detail), insertText) def handle_response(self, response): self.completions = [] items = response[\"items\"]",
"'Apex Class Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:apex:class:create', '-n',",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\n' +",
"= sublime.Region(0, self.view.size()) self.view.replace(edit, size, text) else: self.view.insert(edit, size, text) self.view.set_read_only(True) self.view.show(size) def",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:app:create', '-n', self.app_name, '-d', self.class_dir] startupinfo",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Component', 'Lightning Component Created') printer.write('\\nCreating Lightning Component')",
"= format_symbol_kind(detail) #detail = format_symbol(detail) insertText = label if item.get(\"insertTextFormat\") == 2: insertText",
"printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self, paths=[]):",
"response for item in items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def run_auto_complete(self): self.refreshing = True",
"API Name', self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel(",
"time.localtime()) ThreadProgress(t, 'Pulling Source', 'Source Pulled') printer.write('\\nPulling Source') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pulled')",
"'Org Opened') printer.write('\\nOpening Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Org Opened') def is_enabled(self, paths=[]): #dx_folder",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1",
"== 0: printer.write('\\nFinished running apex') printer.write('\\n' + str(out, 'utf-8')) else: printErr = err",
"['sfdx', 'force:lightning:app:create', '-n', self.app_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt':",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Component', 'Visualforce Component Created') printer.write('\\nCreating",
"self.completions = [] items = response[\"items\"] if isinstance(response, dict) else response for item",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nFinished running",
"creating Lightning Interface:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if",
"symbol_kind_names.get(kind, str(kind)) def format_symbol(item): \"\"\" items may be a list of strings, or",
"Auth Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Auth Page Opened') def is_enabled(self, paths=[]): #dx_folder =",
"'': lsClient = start_client() if lsClient is None: util.debug('Unable start langauge server') EventHub.subscribe('on_load_async',",
"def run(self): sublime.active_window().show_input_panel( 'Query', '', self.run_query, None, None) def is_enabled(self, paths=[]): #dx_folder =",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nApex class created')",
"== 0: printer.write('\\nLightning Interface created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.intf') sublime.active_window().open_file(file)",
"None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return",
"None and not err == '': printErr = out else: printer.write('\\nError pushing source')",
"args = ['sfdx', 'force:apex:class:create', '-n', self.class_name, '-d', self.class_dir] startupinfo = None if os.name",
"if self.namespace is not None and self.namespace != '': args.push('-s') args.push(self.namespace) startupinfo =",
"size = sublime.Region(0, self.view.size()) self.view.replace(edit, size, text) else: self.view.insert(edit, size, text) self.view.set_read_only(True) self.view.show(size)",
"on_close(self, view): EventHub.publish('on_close', view) def on_load_async(self, view): EventHub.publish('on_load_async', view) def on_activated_async(self, view): EventHub.publish('on_activated_async',",
"# util.debug(content) #except Exception as e: # util.debug('could not format query results\\n', e)",
"elif command_name == 'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def",
"p.returncode == 0: printer.write('\\nLightning Interface created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.intf')",
"err is None or err == '': printErr = out printer.write('\\nError running apex')",
"stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode",
"printer.write('\\nError running query:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if",
"# kind = item.get(\"kind\") detail = item.get(\"kind\") detail = format_symbol_kind(detail) #detail = format_symbol(detail)",
"Interface = 11 Function = 12 Variable = 13 Constant = 14 String",
"active_file_extension != '.cls' and active_file_extension != '.trigger': return None EventHub.publish(\"on_modified_async\", view) def on_query_completions(self,",
"'Project Created') printer.write('\\nCreating Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Created') def run_command(self): args =",
"= ['sfdx', 'force:auth:web:login', '-d', '-s', '-a', 'DevHub'] startupinfo = None if os.name ==",
"'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo)",
"util.isDXProject() == False: return False return True def run_command(self): dx_folder = util.dxProjectFolder() args",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:event:create', '-n', self.event_name, '-d', self.class_dir] startupinfo =",
"Field = 8 Constructor = 9 Enum = 10 Interface = 11 Function",
"Boolean = 17 Array = 18 symbol_kind_names = { SymbolKind.File: \"file\", SymbolKind.Module: \"module\",",
"sublime import sublime_plugin import os import subprocess import threading import sys import json",
"= 'Defaultsfdx-project.json' self.project_path = '' self.namespace = None sublime.active_window().show_input_panel( 'Project Name', self.project_name, self.create_project_name,",
"= util.dxProjectFolder() args = ['sfdx', 'force:lightning:event:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None",
"'Creating Visualforce Component', 'Visualforce Component Created') printer.write('\\nCreating Visualforce Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce",
"subprocess import threading import sys import json import mdpopups import time from collections",
"True: size = sublime.Region(0, self.view.size()) self.view.replace(edit, size, text) else: self.view.insert(edit, size, text) self.view.set_read_only(True)",
"single folder save the test') return self.event_name = 'TestName' self.class_dir = paths[0] sublime.active_window().show_input_panel(",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Auth Page', 'Auth Page Opened') printer.write('\\nOpening Auth",
"return None if not self.refreshing: client = lsClient if not client: return completionProvider",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Scratch Org', 'Scratch Org Created') printer.write('\\nCreatin",
"time.localtime()) ThreadProgress(t, 'Creating Visualforce Page', 'Visualforce Page Created') printer.write('\\nCreating Visualforce Page') printer.write('\\nResult: ')",
"return False self.active_file = util.active_file() if not self.active_file.endswith('.cls'): return False if not util.file_is_test(self.window.active_view()):",
"== 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,",
"str(printErr, 'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t =",
"completionProvider.get('triggerCharacters') if locations[0] > 0: self.completions = [] purge_did_change(view.buffer_id()) client.send_request( Request.complete( util.get_document_position(view, locations[0])),",
"Tests') def is_enabled(self): self.dx_folder = util.dxProjectFolder() if(self.dx_folder == ''): return False self.active_file =",
"None EventHub.publish(\"on_modified_async\", view) def on_query_completions(self, view, prefix, locations): active_file_extension = util.file_extension(view) if active_file_extension",
"'-f', self.file_path] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Page',",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Auth Page', 'Auth Page Opened') printer.write('\\nOpening Auth Page')",
"subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder) p.wait() out,",
"if p.returncode == 0: printer.write('\\nProject created') else: printer.write('\\nError creating project:') printer.write('\\n' + str(out,",
"printer.write('\\nPlease select a single folder save the class') return self.event_name = 'EventName' self.class_dir",
"'force:org:create', '-f', self.def_file, '-a', 'ScratchOrg', '-s'] startupinfo = None if os.name == 'nt':",
"def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human', '-l', 'RunSpecifiedTests', '-n', self.class_name] startupinfo",
"time.localtime()) ThreadProgress(t, 'Running anonymous apex', 'Anonymous apex run') printer.write('\\nRunning anonymous apex') printer.write('\\nResult: ')",
"'Auth Page Opened') printer.write('\\nOpening Auth Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Auth Page Opened') def",
"def on_load_async(self, view): EventHub.publish('on_load_async', view) def on_activated_async(self, view): EventHub.publish('on_activated_async', view) def on_post_save_async(self, view):",
"results\\n', e) file = sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL') syntax_path = None if \"linux\" in",
".lib.diagnostic import * import ntpath class SymbolKind(object): File = 1 Module = 2",
"> 0: self.completions = [] purge_did_change(view.buffer_id()) client.send_request( Request.complete( util.get_document_position(view, locations[0])), self.handle_response) self.refreshing =",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running tests', 'Tests run') PanelThreadProgress(t, 'Running Tests') def is_enabled(self): self.dx_folder",
"import OrderedDict from .lib.printer import PanelPrinter from .lib.threads import ThreadProgress from .lib.threads import",
"status_region, text) self.view.set_read_only(True) # self.view.show(size) def is_visible(self): return False def is_enabled(self): return True",
"len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a",
"EventHandlers(sublime_plugin.EventListener): def __init__(self): self.completions = [] # type: List[Tuple[str, str]] self.refreshing = False",
"DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0 and",
"time.localtime()) ThreadProgress(t, 'Running query', 'Query run') printer.write('\\nRunning query') printer.write('\\nResult: ') PanelThreadProgress(t, 'Query run')",
"Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Upgraded') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"}) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self): self.dx_folder = util.dxProjectFolder() self.active_file = util.active_file() self.active_file =",
"None, None) def create_org(self, input): printer.show() self.def_file = input t = threading.Thread(target=self.run_command) t.start()",
"16 Boolean = 17 Array = 18 symbol_kind_names = { SymbolKind.File: \"file\", SymbolKind.Module:",
"import PanelThreadProgress from .lib.languageServer import * from .lib.event_hub import EventHub from .lib.util import",
"== 'exit': EventHub.publish('exit', window, *args) elif command_name == 'close_window': EventHub.publish('close_window', window, *args) else:",
"active_file_extension != '.trigger': return None EventHub.publish(\"on_modified_async\", view) def on_query_completions(self, view, prefix, locations): active_file_extension",
"App', 'Lightning App Created') printer.write('\\nCreating Lightning App') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning App Created')",
"sublime.active_window().show_input_panel( 'Page API Name', self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name =",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:component:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir]",
"class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0",
"is None or err == '': printErr = out printer.write('\\n' + str(printErr, 'utf-8'))",
"None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return False util.debug(paths) if",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running query', 'Query run') printer.write('\\nRunning query') printer.write('\\nResult:",
"Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:app:create', '-n', self.app_name, '-d',",
"10 Interface = 11 Function = 12 Variable = 13 Constant = 14",
"'': printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self, edit):",
"14 String = 15 Number = 16 Boolean = 17 Array = 18",
"is_enabled(self): return True def description(self): return # not ready for code completion yet",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nProject upgraded') else:",
"'Running Tests') def is_enabled(self): self.dx_folder = util.dxProjectFolder() if(self.dx_folder == ''): return False self.active_file",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\n' + str(out,",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running anonymous apex', 'Anonymous apex run')",
"run(self): self.dx_folder = util.dxProjectFolder() self.active_file = util.active_file() self.active_file = ntpath.split(self.active_file)[ 1].replace('.cls', '') self.class_name",
"= 18 symbol_kind_names = { SymbolKind.File: \"file\", SymbolKind.Module: \"module\", SymbolKind.Namespace: \"namespace\", SymbolKind.Package: \"package\",",
"autocomplete_triggers = completionProvider.get('triggerCharacters') if locations[0] > 0: self.completions = [] purge_did_change(view.buffer_id()) client.send_request( Request.complete(",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Apex Class', 'Apex Class",
"self.dx_folder, 'config', 'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class Name', self.def_file, self.create_org, None, None) def create_org(self, input):",
"Apex Class:') printer.write('\\n' + str(err, 'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Apex Class', 'Apex Class Created')",
"SymbolKind.File: \"file\", SymbolKind.Module: \"module\", SymbolKind.Namespace: \"namespace\", SymbolKind.Package: \"package\", SymbolKind.Class: \"class\", SymbolKind.Method: \"method\", SymbolKind.Function:",
"util.isDXProject() == False: return False if len(paths) != 1 or (len(paths) > 0",
"p.returncode == 0: printer.write('\\nDevHub authorized') else: printer.write('\\nError authorizing Dev Hub:') printer.write('\\n' + str(err,",
"view) def on_activated_async(self, view): EventHub.publish('on_activated_async', view) def on_post_save_async(self, view): EventHub.publish('on_post_save_async', view) def on_close(self,",
"command_name == 'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_text_command(self,",
"t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t,",
"startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce page created')",
"return False def is_enabled(self): return True def description(self): return class WriteOperationStatus(sublime_plugin.TextCommand): def run(self,",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:auth:web:login', '-d', '-s', '-a', 'DevHub'] startupinfo =",
"'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) >",
"Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Created') def run_command(self): args = ['sfdx', 'force:project:create', '-n',",
"paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False return True def",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:app:create', '-n', self.app_name, '-d', self.class_dir]",
"> 0 and os.path.isfile(paths[0])): return False return True def create_page(self, input): self.page_label =",
"in sys.platform: syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content}) else:",
"args = ['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if",
"\"darwin\" in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener): def on_window_commad(self, window, command_name, args):",
"def is_visible(self): return False def is_enabled(self): return True def description(self): return class WriteOperationStatus(sublime_plugin.TextCommand):",
"if insertText[0] == '$': # sublime needs leading '$' escaped. insertText = '\\$'",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Component', 'Visualforce Component Created') printer.write('\\nCreating Visualforce Component')",
"'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self, edit): self.edit = edit self.project_name = '' self.template",
"# util.debug('could not format query results\\n', e) file = sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL') syntax_path",
"hover_zone) def on_window_command(self, window, command_name, *args): if command_name == 'exit': EventHub.publish('exit', window, *args)",
"Interface Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:interface:create', '-n', self.event_name,",
"upgrading project:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self, edit): self.edit =",
"'Pulling Source', 'Source Pulled') printer.write('\\nPulling Source') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pulled') def is_enabled(self,",
"return True def create_class(self, input): self.class_name = input printer.show() t = threading.Thread(target=self.run_command) t.start()",
"+ str(err, 'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or",
"if erase == True: size = sublime.Region(0, self.view.size()) self.view.replace(edit, size, text) else: self.view.insert(edit,",
"'ComponentName' self.page_label = 'Component Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Component API Name', self.page_name,",
"+ '.cls') sublime.active_window().open_file(file) else: printer.write('\\nError creating Apex Class:') printer.write('\\n' + str(err, 'utf-8')) class",
"input): self.project_path = input sublime.active_window().show_input_panel( 'Project Namespace', '', self.create_project, None, None) def create_project(self,",
"str(kind)) def format_symbol(item): \"\"\" items may be a list of strings, or a",
"on_pre_close(self, view): EventHub.publish('on_pre_close', view) def on_close(self, view): EventHub.publish('on_close', view) def on_load_async(self, view): EventHub.publish('on_load_async',",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce page created') file",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Component', 'Visualforce",
"self.create_org, None, None) def create_org(self, input): printer.show() self.def_file = input t = threading.Thread(target=self.run_command)",
"out else: printer.write('\\nError pushing source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self,",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nOpening results file')",
"return True def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:project:upgrade', '-f'] startupinfo",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nDevHub authorized') else: printer.write('\\nError authorizing",
"else: printer.write('\\nError creating project:') printer.write('\\n' + str(out, 'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self, edit):",
"self.project_name = input sublime.active_window().show_input_panel('Project Template', self.template, self.create_project_template, None, None) def create_project_template(self, input): self.project_template",
"== 0: printer.write('\\nVisaulforce Component created') file = os.path.join(self.class_dir, self.page_name + '.component') sublime.active_window().open_file(file) else:",
"'Project Created') def run_command(self): args = ['sfdx', 'force:project:create', '-n', self.project_name, '-t', self.template, '-d',",
"'Project Namespace', '', self.create_project, None, None) def create_project(self, input): printer.show() self.namespace = input",
"threading.Thread(target=self.run_command) t.start() printer.show() printer.write('\\nRunning Tests') printer.write('\\nResult: ') t.printer = printer t.process_id = time.strftime(\"%a,",
"else: syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content}) else: printer.write('\\nError running query:') printer.write('\\n' +",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Interface',",
"single folder to save the component') return self.page_name = 'ComponentName' self.page_label = 'Component",
"org created') else: printer.write('\\nError creating scratch org') printer.write('\\n' + str(err, 'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand):",
"= paths[0] sublime.active_window().show_input_panel( 'Test Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if",
"symbol_kind_names = { SymbolKind.File: \"file\", SymbolKind.Module: \"module\", SymbolKind.Namespace: \"namespace\", SymbolKind.Package: \"package\", SymbolKind.Class: \"class\",",
"'utf-8')) else: printErr = err if not err is None and not err",
"t = threading.Thread(target=self.run_command) t.start() printer.show() printer.write('\\nRunning Tests') printer.write('\\nResult: ') t.printer = printer t.process_id",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:interface:create', '-n', self.event_name, '-d', self.class_dir] startupinfo",
"= out else: printer.write('\\nError pushing source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand): def",
"single folder to save the page') return self.page_name = 'PageName' self.page_label = 'Page",
"if p.returncode == 0: printer.write('\\nFinished running apex') printer.write('\\n' + str(out, 'utf-8')) else: printErr",
"None) def create_org(self, input): printer.show() self.def_file = input t = threading.Thread(target=self.run_command) t.start() t.printer",
"\"file\", SymbolKind.Module: \"module\", SymbolKind.Namespace: \"namespace\", SymbolKind.Package: \"package\", SymbolKind.Class: \"class\", SymbolKind.Method: \"method\", SymbolKind.Function: \"function\",",
"Name', self.class_name, self.create_class, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"item.get(\"label\") # kind = item.get(\"kind\") detail = item.get(\"kind\") detail = format_symbol_kind(detail) #detail =",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running anonymous apex', 'Anonymous apex",
"Org Tests') printer.write('\\nResult: ') t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"True def run_command(self): args = ['sfdx', 'force:source:pull'] startupinfo = None if os.name ==",
"self.dx_folder = util.dxProjectFolder() if(self.dx_folder == ''): return False self.active_file = util.active_file() if not",
"not format query results\\n', e) file = sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL') syntax_path = None",
"is None: util.debug('Unable start langauge server') EventHub.subscribe('on_load_async', set_syntax) active_window_id = sublime.active_window().id() printer =",
"self.page_label = 'Component Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Component API Name', self.page_name, self.get_label,",
"str(err, 'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer",
"def run(self): self.dx_folder = util.dxProjectFolder() self.active_file = util.active_file() self.active_file = ntpath.split(self.active_file)[ 1].replace('.cls', '')",
"'.intf') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Interface:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand):",
"class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self): sublime.active_window().show_input_panel( 'Query', '', self.run_query, None, None) def is_enabled(self, paths=[]):",
"p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nScratch",
"Auth Page', 'Auth Page Opened') printer.write('\\nOpening Auth Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Auth Page",
"the class') return self.app_name = 'AppName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.app_name,",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() self.def_file",
"time.localtime()) ThreadProgress(t, 'Running tests', 'Tests run') PanelThreadProgress(t, 'Running Tests') def is_enabled(self): self.dx_folder =",
"or \"darwin\" in sys.platform: syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\",",
"self.view.show(size) def is_visible(self): return False def is_enabled(self): return True def description(self): return #",
"self.namespace != '': args.push('-s') args.push(self.namespace) startupinfo = None if os.name == 'nt': startupinfo",
"'human', '-l', 'RunSpecifiedTests', '-n', self.class_name] startupinfo = None if os.name == 'nt': startupinfo",
"printer.write('\\nError creating Lightning App:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self, paths=[]):",
"> 0 and os.path.isfile(paths[0])): return False return True def create_app(self, input): self.app_name =",
"time from collections import OrderedDict from .lib.printer import PanelPrinter from .lib.threads import ThreadProgress",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running Org",
"startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode ==",
"org opened') else: printer.write('\\nError opening') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self,",
"on_load_async(self, view): EventHub.publish('on_load_async', view) def on_activated_async(self, view): EventHub.publish('on_activated_async', view) def on_post_save_async(self, view): EventHub.publish('on_post_save_async',",
"'-n', self.cmp_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo =",
"PanelThreadProgress(t, 'Lightning Test Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:test:create',",
"== 0: printer.write('\\nProject upgraded') else: printer.write('\\nError upgrading project:') printer.write('\\n' + str(err, 'utf-8')) class",
"== 0: printer.write('\\nVisaulforce page created') file = os.path.join(self.class_dir, self.page_name + '.page') sublime.active_window().open_file(file) else:",
"def format_symbol_kind(kind): return symbol_kind_names.get(kind, str(kind)) def format_symbol(item): \"\"\" items may be a list",
"== 0: printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if not err",
"sublime.Region(0, self.view.size()) self.view.replace(edit, size, text) else: self.view.insert(edit, size, text) self.view.set_read_only(True) self.view.show(size) def is_visible(self):",
"def is_visible(self): return False def is_enabled(self): return True def description(self): return # not",
"sublime.active_window().show_input_panel( 'Project Name', self.project_name, self.create_project_name, None, None) def create_project_name(self, input): self.project_name = input",
"os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the class') return self.class_name =",
"== 0: printer.write('\\nScratch org opened') else: printer.write('\\nError opening') printer.write('\\n' + str(err, 'utf-8')) class",
"class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self): self.dx_folder = util.dxProjectFolder() self.active_file = util.active_file() self.active_file = ntpath.split(self.active_file)[",
"time.localtime()) ThreadProgress(t, 'Creating Lightning Component', 'Lightning Component Created') printer.write('\\nCreating Lightning Component') printer.write('\\nResult: ')",
"code completion yet lsClient = None printer = None def plugin_loaded(): global lsClient",
"printer.show() printer.write('\\nPlease select a single folder save the test') return self.event_name = 'TestName'",
"p.returncode == 0: printer.write('\\nProject created') else: printer.write('\\nError creating project:') printer.write('\\n' + str(out, 'UTF-8'))",
"if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args,",
"def create_project(self, input): printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start() t.printer =",
"self.dx_folder = util.dxProjectFolder() printer.show() printer.write('\\nPushing Source') t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"a single folder to save the component') return self.page_name = 'ComponentName' self.page_label =",
"'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer =",
"False def on_pre_close(self, view): EventHub.publish('on_pre_close', view) def on_close(self, view): EventHub.publish('on_close', view) def on_load_async(self,",
"'Creating Project', 'Project Created') printer.write('\\nCreating Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Created') def run_command(self):",
"= paths[0] sublime.active_window().show_input_panel( 'Component API Name', self.page_name, self.get_label, None, None) def get_label(self, input):",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Project', 'Project",
"view) def on_hover(self, view, point, hover_zone): EventHub.publish('on_hover', view, point, hover_zone) def on_window_command(self, window,",
"util.dxProjectFolder() args = ['sfdx', 'force:data:soql:query', '-q', self.query] startupinfo = None if os.name ==",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Project', 'Project Created')",
"latter case, each entry in the quick panel will show multiple rows \"\"\"",
"Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths)",
"subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder) p.wait() out, err = p.communicate() r = p.returncode",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Apex Class', 'Apex Class Created') printer.write('\\nCreating",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Org',",
"err is None or err == '': printErr = out printer.write('\\n' + str(printErr,",
"util.dxProjectFolder() != '': lsClient = start_client() if lsClient is None: util.debug('Unable start langauge",
"run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human'] if not self.test_org is None and",
"or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_page(self, input):",
"ThreadProgress(t, 'Running Org Tests', 'Org tests run') PanelThreadProgress(t, 'Running Org Tests') def is_enabled(self,",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Test', 'Lightning Interface Test') printer.write('\\nCreating Lightning Test') printer.write('\\nResult:",
"self.class_name, self.create_class, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False",
"if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])): return False return",
"def create_page(self, input): self.page_label = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer =",
"= item.get(\"label\") # kind = item.get(\"kind\") detail = item.get(\"kind\") detail = format_symbol_kind(detail) #detail",
"query results\\n', e) file = sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL') syntax_path = None if \"linux\"",
"kw_region[1]) size = self.view.size() self.view.set_read_only(False) self.view.replace(edit, status_region, text) self.view.set_read_only(True) # self.view.show(size) def is_visible(self):",
"Event:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) !=",
"self.view.substr(region) if self.selection == '': self.selection = self.view.substr(sublime.Region(0, self.view.size())) self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx',",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:apex:class:create', '-n', self.class_name, '-d', self.class_dir] startupinfo =",
"**kwargs): kw_region = kwargs.get('region', [0, 0]) status_region = sublime.Region(kw_region[0], kw_region[1]) size = self.view.size()",
"'ScratchOrg', '-s'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"file = os.path.join(self.class_dir, self.event_name, self.event_name + '.intf') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Interface:')",
"'Project Name', self.project_name, self.create_project_name, None, None) def create_project_name(self, input): self.project_name = input sublime.active_window().show_input_panel('Project",
"def on_post_save_async(self, view): EventHub.publish('on_post_save_async', view) def on_close(self, view): EventHub.publish('on_close', view) def on_hover(self, view,",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:auth:web:login', '-d', '-s', '-a', 'DevHub']",
"'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if os.name == 'nt':",
"r = p.returncode if p.returncode == 0: printer.write('\\nScratch org created') else: printer.write('\\nError creating",
"open(self.file_path, 'w+') as file_obj: file_obj.write(self.selection) printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start()",
"printer.write('\\nError creating project:') printer.write('\\n' + str(out, 'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self, edit): self.selection",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Interface created')",
"Page', 'Auth Page Opened') printer.write('\\nOpening Auth Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Auth Page Opened')",
"'Tests run') PanelThreadProgress(t, 'Running Tests') def is_enabled(self): self.dx_folder = util.dxProjectFolder() if(self.dx_folder == ''):",
"def create_cmp(self, input): self.cmp_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer =",
"creating Lightning Event:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if",
"p.returncode if p.returncode == 0: printer.write('\\nProject upgraded') else: printer.write('\\nError upgrading project:') printer.write('\\n' +",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running query', 'Query run') printer.write('\\nRunning",
"sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Event:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def",
"self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"self.view.sel(): if not region.empty(): self.selection += self.view.substr(region) if self.selection == '': self.selection =",
"start_client() if lsClient is None: util.debug('Unable start langauge server') EventHub.subscribe('on_load_async', set_syntax) active_window_id =",
"0 and os.path.isfile(paths[0])): return False return True def create_event(self, input): self.event_name = input",
"self.app_name, self.app_name + '.app') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning App:') printer.write('\\n' + str(err,",
"'force:project:upgrade', '-f'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"sublime.active_window().show_input_panel( 'Component API Name', self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name =",
"t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Upgrading",
"Event Created') printer.write('\\nCreating Lightning Event') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Event Created') def run_command(self):",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\n' + str(out, 'utf-8'))",
"input): self.page_label = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Interface:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def",
"= util.dxProjectFolder() if util.isDXProject() == False: return False return True def run_command(self): args",
"or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_class(self, input):",
"'-a', 'DevHub'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"input): self.project_name = input sublime.active_window().show_input_panel('Project Template', self.template, self.create_project_template, None, None) def create_project_template(self, input):",
"return True def run_command(self): args = ['sfdx', 'force:source:pull'] startupinfo = None if os.name",
"json.loads(content) # content = json.dumps(parsed, sort_keys=True,indent=1, separators=(',', ':')) # util.debug(content) #except Exception as",
"json.dumps(parsed, sort_keys=True,indent=1, separators=(',', ':')) # util.debug(content) #except Exception as e: # util.debug('could not",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args =",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Event created') file =",
"time.localtime()) ThreadProgress(t, 'Creating Project', 'Project Created') printer.write('\\nCreating Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Created')",
"> 0 and os.path.isfile(paths[0])): return False return True def create_class(self, input): self.class_name =",
"False util.debug(paths) if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])): return",
"util.isDXProject() == False: return False return True def run_command(self): args = ['sfdx', 'force:apex:test:run',",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nFinished running apex')",
"self.create_project_name, None, None) def create_project_name(self, input): self.project_name = input sublime.active_window().show_input_panel('Project Template', self.template, self.create_project_template,",
"for item in items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def run_auto_complete(self): self.refreshing = True sublime.active_window().active_view().run_command(",
"created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.intf') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning",
"def on_text_command(self, window, command_name, *args): if command_name == 'exit': EventHub.publish('exit', window, *args) elif",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pushing Source', 'Source Pushed') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pushed')",
"Tests') printer.write('\\nResult: ') t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a,",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running Org Tests', 'Org tests run') PanelThreadProgress(t, 'Running",
"and len(self.test_org) > 0: args.push('-u') args.push(self.input) startupinfo = None if os.name == 'nt':",
"printer.write('\\nLightning Test created') file = os.path.join(self.class_dir, self.event_name + '.resource') sublime.active_window().open_file(file) else: printer.write('\\nError creating",
"Created') printer.write('\\nCreating Visualforce Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Component Created') def run_command(self): dx_folder",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning App', 'Lightning",
"= sublime.active_window().id() printer = PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin loaded\", erase=True) def plugin_unloaded(): if lsClient:",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nScratch org opened')",
"printer.write('\\nError creating Lightning Event:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self, paths=[]):",
"def create_app(self, input): self.app_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer =",
"input): self.test_org = input printer.show() printer.write('\\nRunning Org Tests') printer.write('\\nResult: ') t = threading.Thread(target=self.run_command)",
"printer.write('\\nError pulling source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder",
"0: printer.write('\\nLightning Component created') file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp') sublime.active_window().open_file(file) else:",
"self.refreshing = False def on_pre_close(self, view): EventHub.publish('on_pre_close', view) def on_close(self, view): EventHub.publish('on_close', view)",
"apex run') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return",
"self.class_name = 'ApexClassName' t = threading.Thread(target=self.run_command) t.start() printer.show() printer.write('\\nRunning Tests') printer.write('\\nResult: ') t.printer",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running query', 'Query run') printer.write('\\nRunning query') printer.write('\\nResult: ') PanelThreadProgress(t,",
"!= '.cls' and active_file_extension != '.trigger': return None EventHub.publish(\"on_modified_async\", view) def on_query_completions(self, view,",
"ThreadProgress(t, 'Running query', 'Query run') printer.write('\\nRunning query') printer.write('\\nResult: ') PanelThreadProgress(t, 'Query run') def",
"# kind = format_symbol_kind(item.get(\"kind\")) # return [item.get(\"name\"), kind] return [item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand): def",
"Visualforce Page', 'Visualforce Page Created') printer.write('\\nCreating Visualforce Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Page",
"def run_command(self): args = ['sfdx', 'force:org:create', '-f', self.def_file, '-a', 'ScratchOrg', '-s'] startupinfo =",
"= format_symbol_kind(item.get(\"kind\")) # return [item.get(\"name\"), kind] return [item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand): def run(self, edit,",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce Component created') file",
"') PanelThreadProgress(t, 'Visualforce Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx',",
"self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.app_name, self.create_app, None, None) def is_enabled(self, paths=[]):",
"label if item.get(\"insertTextFormat\") == 2: insertText = item.get(\"insertText\") if insertText[0] == '$': #",
"from .lib.event_hub import EventHub from .lib.util import util from .lib.diagnostic import * import",
"os.path.join(self.class_dir, self.app_name, self.app_name + '.app') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning App:') printer.write('\\n' +",
"+ '.page') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce page:') printer.write('\\n' + str(err, 'utf-8')) class",
"Class', 'Apex Class Created') printer.write('\\nCreating Apex Class') printer.write('\\nResult: ') PanelThreadProgress(t, 'Apex Class Created')",
"= util.dxProjectFolder() args = ['sfdx', 'force:lightning:app:create', '-n', self.app_name, '-d', self.class_dir] startupinfo = None",
"ThreadProgress(t, 'Creating Lightning Component', 'Lightning Component Created') printer.write('\\nCreating Lightning Component') printer.write('\\nResult: ') PanelThreadProgress(t,",
"= out printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder =",
"def format_symbol(item): \"\"\" items may be a list of strings, or a list",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running anonymous apex', 'Anonymous apex run') printer.write('\\nRunning anonymous",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Auth Page', 'Auth Page Opened') printer.write('\\nOpening",
"+ str(out, 'utf-8')) else: printErr = err if err is None or err",
"str(err, 'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self): sublime.active_window().show_input_panel( 'Query', '', self.run_query, None, None) def",
"Created') printer.write('\\nCreating Lightning App') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning App Created') def run_command(self): dx_folder",
"window, *args) elif command_name == 'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name,",
"'force:apex:test:run', '-r', 'human', '-l', 'RunSpecifiedTests', '-n', self.class_name] startupinfo = None if os.name ==",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Anonymous apex run') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"input t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d %b",
"interface') return self.event_name = 'InterfaceName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Interface Name', self.event_name, self.create_event,",
"err if err is None or err == '': printErr = out printer.write('\\n'",
"if active_file_extension != '.cls' and active_file_extension != '.trigger': return None EventHub.publish(\"on_modified_async\", view) def",
"= 2 Namespace = 3 Package = 4 Class = 5 Method =",
"args = ['sfdx', 'force:lightning:component:create', '-n', self.cmp_name, '-d', self.class_dir] startupinfo = None if os.name",
"cwd=self.dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0:",
"err if not err is None and not err == '': printErr =",
"Component created') file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError creating",
"'Scratch Org Created') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"self.namespace = None sublime.active_window().show_input_panel( 'Project Name', self.project_name, self.create_project_name, None, None) def create_project_name(self, input):",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning App Created') def run_command(self): dx_folder = util.dxProjectFolder() args =",
"(len(paths) > 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the",
"lsClient is None: util.debug('Unable start langauge server') EventHub.subscribe('on_load_async', set_syntax) active_window_id = sublime.active_window().id() printer",
"get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Component Label', self.page_label, self.create_page, None, None) def",
"from .lib.threads import ThreadProgress from .lib.threads import PanelThreadProgress from .lib.languageServer import * from",
"input): self.query = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"if p.returncode == 0: printer.write('\\nLightning App created') file = os.path.join(self.class_dir, self.app_name, self.app_name +",
"time.localtime()) ThreadProgress(t, 'Opening Auth Page', 'Auth Page Opened') printer.write('\\nOpening Auth Page') printer.write('\\nResult: ')",
"Org Tests') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return",
"return False return True def create_page(self, input): self.page_label = input printer.show() t =",
"insertText[0] == '$': # sublime needs leading '$' escaped. insertText = '\\$' +",
"printer.write('\\nFinished running apex') printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if err",
"= ['sfdx', 'force:source:push'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Interface', 'Lightning Interface Created') printer.write('\\nCreating",
"def create_event(self, input): self.event_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer =",
"self.active_file = ntpath.split(self.active_file)[ 1].replace('.cls', '') self.class_name = 'ApexClassName' t = threading.Thread(target=self.run_command) t.start() printer.show()",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Org', 'Org",
"file_obj.write(self.selection) printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"else: printer.write('\\nError creating scratch org') printer.write('\\n' + str(err, 'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self,",
"handle_response(self, response): self.completions = [] items = response[\"items\"] if isinstance(response, dict) else response",
"str(err, 'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths)",
"args = ['sfdx', 'force:apex:test:run', '-r', 'human', '-l', 'RunSpecifiedTests', '-n', self.class_name] startupinfo = None",
"erase=False, *args, **kwargs): size = self.view.size() self.view.set_read_only(False) if erase == True: size =",
"startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder)",
"subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode",
"Lightning Event') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Event Created') def run_command(self): dx_folder = util.dxProjectFolder()",
"Enum = 10 Interface = 11 Function = 12 Variable = 13 Constant",
"def create_class(self, input): self.class_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer =",
"active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and active_file_extension != '.trigger': return None",
"sublime.Region(kw_region[0], kw_region[1]) size = self.view.size() self.view.set_read_only(False) self.view.replace(edit, status_region, text) self.view.set_read_only(True) # self.view.show(size) def",
"ThreadProgress(t, 'Running tests', 'Tests run') PanelThreadProgress(t, 'Running Tests') def is_enabled(self): self.dx_folder = util.dxProjectFolder()",
"'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() self.def_file = os.path.join( self.dx_folder,",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Project', 'Project Created') printer.write('\\nCreating Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project",
"if not client: return completionProvider = client.get_capability('completionProvider') if not completionProvider: return autocomplete_triggers =",
"if active_file_extension != '.cls' and active_file_extension != '.trigger': return None if not self.refreshing:",
"kind = format_symbol_kind(item.get(\"kind\")) # return [item.get(\"name\"), kind] return [item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand): def run(self,",
"2 Namespace = 3 Package = 4 Class = 5 Method = 6",
"= ['sfdx', 'force:data:soql:query', '-q', self.query] startupinfo = None if os.name == 'nt': startupinfo",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nApex class created') file",
"= ['sfdx', 'force:project:upgrade', '-f'] startupinfo = None if os.name == 'nt': startupinfo =",
"= os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content}) else: printer.write('\\nError running query:') printer.write('\\n' + str(err, 'utf-8'))",
"input): self.class_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pulling Source',",
"sys.platform or \"darwin\" in sys.platform: syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path)",
"'' self.namespace = None sublime.active_window().show_input_panel( 'Project Name', self.project_name, self.create_project_name, None, None) def create_project_name(self,",
"items may be a list of strings, or a list of string lists.",
"Created') printer.write('\\nCreating Apex Class') printer.write('\\nResult: ') PanelThreadProgress(t, 'Apex Class Created') def run_command(self): dx_folder",
"'': printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self, edit):",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Component', 'Lightning Component Created') printer.write('\\nCreating Lightning Component') printer.write('\\nResult:",
"completion yet lsClient = None printer = None def plugin_loaded(): global lsClient global",
"create_class(self, input): self.class_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"if lsClient: lsClient.kill() def set_syntax(view): if util.is_apex_file(view): util.debug('setting syntax for file') if \"linux\"",
"EventHub.publish('on_close', view) def on_hover(self, view, point, hover_zone): EventHub.publish('on_hover', view, point, hover_zone) def on_window_command(self,",
"'Org tests run') PanelThreadProgress(t, 'Running Org Tests') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show()",
"= str(out,'UTF-8') #try: # parsed = json.loads(content) # content = json.dumps(parsed, sort_keys=True,indent=1, separators=(',',",
"Visualforce page:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths)",
"self.event_name = 'InterfaceName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Interface Name', self.event_name, self.create_event, None, None)",
"file = os.path.join(self.class_dir, self.class_name + '.cls') sublime.active_window().open_file(file) else: printer.write('\\nError creating Apex Class:') printer.write('\\n'",
"if not completionProvider: return autocomplete_triggers = completionProvider.get('triggerCharacters') if locations[0] > 0: self.completions =",
"a list of string lists. In the latter case, each entry in the",
"case, each entry in the quick panel will show multiple rows \"\"\" #",
"edit): self.dx_folder = util.dxProjectFolder() printer.show() printer.write('\\nPushing Source') t = threading.Thread(target=self.run_command) t.start() t.printer =",
"'.cls' and active_file_extension != '.trigger': return None EventHub.publish(\"on_modified_async\", view) def on_query_completions(self, view, prefix,",
"True, 'api_completions_only': False, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True, }) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self): self.dx_folder",
"and os.path.isfile(paths[0])): return False return True def create_cmp(self, input): self.cmp_name = input printer.show()",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Apex Class Created') def run_command(self): dx_folder = util.dxProjectFolder() args =",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:apex:class:create', '-n', self.class_name, '-d', self.class_dir]",
"self.create_project_template, None, None) def create_project_template(self, input): self.project_template = input sublime.active_window().show_input_panel('Project Path', self.project_path, self.create_project_namespace,",
"Interface:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) !=",
"+ '.resource') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Test:') printer.write('\\n' + str(err, 'utf-8')) class",
"p.returncode if p.returncode == 0: printer.write('\\nProject created') else: printer.write('\\nError creating project:') printer.write('\\n' +",
"else: printer.write('\\nError pushing source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self, edit):",
"ThreadProgress(t, 'Creating Visualforce Component', 'Visualforce Component Created') printer.write('\\nCreating Visualforce Component') printer.write('\\nResult: ') PanelThreadProgress(t,",
"util.dxProjectFolder() args = ['sfdx', 'force:lightning:test:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if",
"') PanelThreadProgress(t, 'Lightning Test Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx',",
"create_cmp(self, input): self.cmp_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"pulling source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder =",
"Page', 'Visualforce Page Created') printer.write('\\nCreating Visualforce Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Page Created')",
"False if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])): return False",
"def on_window_command(self, window, command_name, *args): if command_name == 'exit': EventHub.publish('exit', window, *args) elif",
"self.view.insert(edit, size, text) self.view.set_read_only(True) self.view.show(size) def is_visible(self): return False def is_enabled(self): return True",
"True sublime.active_window().active_view().run_command( \"auto_complete\", { 'disable_auto_insert': True, 'api_completions_only': False, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True, })",
"= paths[0] sublime.active_window().show_input_panel( 'Page API Name', self.page_name, self.get_label, None, None) def get_label(self, input):",
"'Creating Lightning Component', 'Lightning Component Created') printer.write('\\nCreating Lightning Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning",
"self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Event Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]):",
"= 9 Enum = 10 Interface = 11 Function = 12 Variable =",
"== 0: printer.write('\\nLightning Event created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.evt') sublime.active_window().open_file(file)",
"['sfdx', 'force:source:pull'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"as file_obj: file_obj.write(self.selection) printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start() t.printer =",
"6 Property = 7 Field = 8 Constructor = 9 Enum = 10",
"= subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait() out,err = p.communicate() r = p.returncode if",
"if p.returncode == 0: printer.write('\\nDevHub authorized') else: printer.write('\\nError authorizing Dev Hub:') printer.write('\\n' +",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Scratch",
"String = 15 Number = 16 Boolean = 17 Array = 18 symbol_kind_names",
"util.get_document_position(view, locations[0])), self.handle_response) self.refreshing = False return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self,",
"uri_to_filename(location.get(\"uri\")) # kind = format_symbol_kind(item.get(\"kind\")) # return [item.get(\"name\"), kind] return [item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand):",
"size, text) else: self.view.insert(edit, size, text) self.view.set_read_only(True) self.view.show(size) def is_visible(self): return False def",
"def run_command(self): args = ['sfdx', 'force:source:pull'] startupinfo = None if os.name == 'nt':",
"os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content}) else: printer.write('\\nError running query:') printer.write('\\n' + str(err, 'utf-8')) class",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:test:create', '-n', self.event_name, '-d', self.class_dir] startupinfo =",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pulling Source', 'Source Pulled') printer.write('\\nPulling Source') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running Org Tests', 'Org tests run')",
"') PanelThreadProgress(t, 'Auth Page Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"and self.namespace != '': args.push('-s') args.push(self.namespace) startupinfo = None if os.name == 'nt':",
"DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self): self.dx_folder = util.dxProjectFolder() self.active_file = util.active_file() self.active_file = ntpath.split(self.active_file)[ 1].replace('.cls',",
"'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) >",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Page', 'Visualforce Page",
"view): EventHub.publish('on_close', view) def on_hover(self, view, point, hover_zone): EventHub.publish('on_hover', view, point, hover_zone) def",
"== False: return False return True def run_command(self): args = ['sfdx', 'force:source:pull'] startupinfo",
"is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False if len(paths)",
"os.path.join(self.class_dir, self.event_name, self.event_name + '.intf') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Interface:') printer.write('\\n' +",
"'Source Pulled') printer.write('\\nPulling Source') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pulled') def is_enabled(self, paths=[]): #dx_folder",
"'App Name', self.app_name, self.create_app, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False:",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running Org Tests', 'Org tests",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Test created') file",
"util.active_file() self.active_file = ntpath.split(self.active_file)[ 1].replace('.cls', '') self.class_name = 'ApexClassName' t = threading.Thread(target=self.run_command) t.start()",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Upgrading Project', 'Project Upgraded') printer.write('\\nUpgrading Project') printer.write('\\nResult: ') PanelThreadProgress(t,",
"t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1",
"Function = 12 Variable = 13 Constant = 14 String = 15 Number",
"return True def description(self): return class WriteOperationStatus(sublime_plugin.TextCommand): def run(self, edit, text, *args, **kwargs):",
"True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human'] if not self.test_org is",
"Created') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False",
"# file_path = uri_to_filename(location.get(\"uri\")) # kind = format_symbol_kind(item.get(\"kind\")) # return [item.get(\"name\"), kind] return",
"or err == '': printErr = out printer.write('\\nError running apex') printer.write('\\n' + str(printErr,",
"DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer",
"printer.write('\\nLightning Event created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.evt') sublime.active_window().open_file(file) else: printer.write('\\nError",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running Org Tests', 'Org",
"else: printer.write('\\nError authorizing Dev Hub:') printer.write('\\n' + str(err, 'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self):",
"anonymous apex', 'Anonymous apex run') printer.write('\\nRunning anonymous apex') printer.write('\\nResult: ') PanelThreadProgress(t, 'Anonymous apex",
"description(self): return class WriteOperationStatus(sublime_plugin.TextCommand): def run(self, edit, text, *args, **kwargs): kw_region = kwargs.get('region',",
"paths[0] sublime.active_window().show_input_panel( 'Interface Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject()",
"PanelThreadProgress(t, 'Lightning Event Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:event:create',",
"= 4 Class = 5 Method = 6 Property = 7 Field =",
"single folder save the interface') return self.event_name = 'InterfaceName' self.class_dir = paths[0] sublime.active_window().show_input_panel(",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Test', 'Lightning",
"threading import sys import json import mdpopups import time from collections import OrderedDict",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pulling Source', 'Source Pulled') printer.write('\\nPulling Source')",
"def __init__(self): self.completions = [] # type: List[Tuple[str, str]] self.refreshing = False def",
"None sublime.active_window().show_input_panel( 'Project Name', self.project_name, self.create_project_name, None, None) def create_project_name(self, input): self.project_name =",
"def run(self, edit, text, erase=False, *args, **kwargs): size = self.view.size() self.view.set_read_only(False) if erase",
"printer.write('\\nUpgrading Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Upgraded') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"file_path = uri_to_filename(location.get(\"uri\")) # kind = format_symbol_kind(item.get(\"kind\")) # return [item.get(\"name\"), kind] return [item.get(\"name\")]",
"> 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the component')",
"'-f'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"PanelThreadProgress(t, 'Lightning Interface Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:interface:create',",
"__init__(self): self.completions = [] # type: List[Tuple[str, str]] self.refreshing = False def on_pre_close(self,",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1",
"['sfdx', 'force:org:create', '-f', self.def_file, '-a', 'ScratchOrg', '-s'] startupinfo = None if os.name ==",
"printer.write('\\nPushing Source') t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d",
"= ['sfdx', 'force:org:create', '-f', self.def_file, '-a', 'ScratchOrg', '-s'] startupinfo = None if os.name",
"= ['sfdx', 'force:org:open'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"status_region = sublime.Region(kw_region[0], kw_region[1]) size = self.view.size() self.view.set_read_only(False) self.view.replace(edit, status_region, text) self.view.set_read_only(True) #",
"p.returncode == 0: printer.write('\\nLightning Event created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.evt')",
"\"class\", SymbolKind.Method: \"method\", SymbolKind.Function: \"function\", SymbolKind.Field: \"field\", SymbolKind.Variable: \"variable\", SymbolKind.Constant: \"constant\" } def",
"PanelThreadProgress(t, 'Scratch Org Created') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_app(self, input):",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Project', 'Project Created') printer.write('\\nCreating",
"sublime.active_window().show_input_panel( 'App Name', self.cmp_name, self.create_cmp, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"= p.returncode if p.returncode == 0: printer.write('\\nDevHub authorized') else: printer.write('\\nError authorizing Dev Hub:')",
"None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Component Label', self.page_label, self.create_page, None,",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1",
"[] # type: List[Tuple[str, str]] self.refreshing = False def on_pre_close(self, view): EventHub.publish('on_pre_close', view)",
"') PanelThreadProgress(t, 'Lightning Event Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx',",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Test', 'Lightning Interface",
"13 Constant = 14 String = 15 Number = 16 Boolean = 17",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Org', 'Org Opened') printer.write('\\nOpening Org')",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Org', 'Org Opened')",
"0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the test') return",
"self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return False util.debug(paths)",
"= self.view.size() self.view.set_read_only(False) if erase == True: size = sublime.Region(0, self.view.size()) self.view.replace(edit, size,",
"Org Created') printer.write('\\nCreatin Scratch Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Scratch Org Created') def is_enabled(self,",
"command_name == 'exit': EventHub.publish('exit', window, *args) elif command_name == 'close_window': EventHub.publish('close_window', window, *args)",
"self.cmp_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a,",
"0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the class') return",
"os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the interface') return self.event_name =",
"None def plugin_loaded(): global lsClient global printer if util.dxProjectFolder() != '': lsClient =",
"the class') return self.event_name = 'EventName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Event Name', self.event_name,",
"+ str(out, 'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self, edit): self.selection = '' for region",
"printer.show() printer.write('\\nRunning Tests') printer.write('\\nResult: ') t.printer = printer t.process_id = time.strftime(\"%a, %d %b",
"= input sublime.active_window().show_input_panel('Project Template', self.template, self.create_project_template, None, None) def create_project_template(self, input): self.project_template =",
"self.test_org is None and len(self.test_org) > 0: args.push('-u') args.push(self.input) startupinfo = None if",
"'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) >",
"single folder save the component') return self.cmp_name = 'ComponentName' self.class_dir = paths[0] sublime.active_window().show_input_panel(",
"printer.write('\\nError authorizing Dev Hub:') printer.write('\\n' + str(err, 'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self): sublime.active_window().show_input_panel(",
"class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0",
"size = self.view.size() self.view.set_read_only(False) if erase == True: size = sublime.Region(0, self.view.size()) self.view.replace(edit,",
"t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pulling",
"to save the page') return self.page_name = 'PageName' self.page_label = 'Page Label' self.class_dir",
"'Class Name', self.def_file, self.create_org, None, None) def create_org(self, input): printer.show() self.def_file = input",
"Created') def run_command(self): args = ['sfdx', 'force:project:create', '-n', self.project_name, '-t', self.template, '-d', self.project_path]",
"!= 1 or (len(paths) > 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single",
"or \"darwin\" in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener): def on_window_commad(self, window, command_name,",
"Class:') printer.write('\\n' + str(err, 'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t =",
"str(err, 'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths)",
"self.run_auto_complete() def run_auto_complete(self): self.refreshing = True sublime.active_window().active_view().run_command( \"auto_complete\", { 'disable_auto_insert': True, 'api_completions_only': False,",
"completionProvider = client.get_capability('completionProvider') if not completionProvider: return autocomplete_triggers = completionProvider.get('triggerCharacters') if locations[0] >",
"== False: return False util.debug(paths) if len(paths) != 1 or (len(paths) > 0",
"or (len(paths) > 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save",
"escaped. insertText = '\\$' + insertText[1:] return (\"{}\\t{}\".format(label, detail), insertText) def handle_response(self, response):",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Org', 'Org Opened') printer.write('\\nOpening Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Org",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running anonymous apex',",
"printer.show() printer.write('\\nPlease select a single folder save the class') return self.event_name = 'EventName'",
"DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0 and",
"PanelThreadProgress(t, 'Apex Class Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:apex:class:create',",
"self.class_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"Component created') file = os.path.join(self.class_dir, self.page_name + '.component') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce",
"def run_auto_complete(self): self.refreshing = True sublime.active_window().active_view().run_command( \"auto_complete\", { 'disable_auto_insert': True, 'api_completions_only': False, 'next_completion_if_showing':",
"locations): active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and active_file_extension != '.trigger': return",
".lib.threads import ThreadProgress from .lib.threads import PanelThreadProgress from .lib.languageServer import * from .lib.event_hub",
"on_window_command(self, window, command_name, *args): if command_name == 'exit': EventHub.publish('exit', window, *args) elif command_name",
"EventHub.publish('on_load_async', view) def on_activated_async(self, view): EventHub.publish('on_activated_async', view) def on_post_save_async(self, view): EventHub.publish('on_post_save_async', view) def",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Component', 'Visualforce Component",
"'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self, edit): self.selection = '' for region in self.view.sel():",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Interface",
"self.project_path] if self.namespace is not None and self.namespace != '': args.push('-s') args.push(self.namespace) startupinfo",
"True def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:auth:web:login', '-d', '-s', '-a',",
"created') else: printer.write('\\nError creating project:') printer.write('\\n' + str(out, 'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self,",
"0: printer.write('\\nDevHub authorized') else: printer.write('\\nError authorizing Dev Hub:') printer.write('\\n' + str(err, 'utf-8')) class",
"printer.write('\\nLightning Component created') file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError",
"'-d', '-s', '-a', 'DevHub'] startupinfo = None if os.name == 'nt': startupinfo =",
"class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self, edit): self.edit = edit self.project_name = '' self.template =",
"printer.write('\\n' + str(printErr, 'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show()",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Interface created') file =",
"= util.dxProjectFolder() args = ['sfdx', 'force:project:upgrade', '-f'] startupinfo = None if os.name ==",
"= paths[0] sublime.active_window().show_input_panel( 'App Name', self.cmp_name, self.create_cmp, None, None) def is_enabled(self, paths=[]): #dx_folder",
"is None or err == '': printErr = out printer.write('\\nError running apex') printer.write('\\n'",
"self.run_query, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"and os.path.isfile(paths[0])): return False return True def create_event(self, input): self.event_name = input printer.show()",
"return False return True def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:project:upgrade',",
"p.returncode == 0: printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if not",
"= { SymbolKind.File: \"file\", SymbolKind.Module: \"module\", SymbolKind.Namespace: \"namespace\", SymbolKind.Package: \"package\", SymbolKind.Class: \"class\", SymbolKind.Method:",
"t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y",
"12 Variable = 13 Constant = 14 String = 15 Number = 16",
"run(self, edit): self.selection = '' for region in self.view.sel(): if not region.empty(): self.selection",
"\"variable\", SymbolKind.Constant: \"constant\" } def format_symbol_kind(kind): return symbol_kind_names.get(kind, str(kind)) def format_symbol(item): \"\"\" items",
"'force:apex:test:run', '-r', 'human'] if not self.test_org is None and len(self.test_org) > 0: args.push('-u')",
"Test created') file = os.path.join(self.class_dir, self.event_name + '.resource') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running tests', 'Tests run') PanelThreadProgress(t, 'Running Tests') def is_enabled(self):",
"sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Test:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Upgrading Project', 'Project Upgraded') printer.write('\\nUpgrading Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project",
"page') return self.page_name = 'PageName' self.page_label = 'Page Label' self.class_dir = paths[0] sublime.active_window().show_input_panel(",
"Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Org Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"return False return True def run_command(self): args = ['sfdx', 'force:source:push'] startupinfo = None",
"!= '.trigger': return None EventHub.publish(\"on_modified_async\", view) def on_query_completions(self, view, prefix, locations): active_file_extension =",
"syntax for file') if \"linux\" in sys.platform or \"darwin\" in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else:",
"== False: return False return True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r',",
"None and len(self.test_org) > 0: args.push('-u') args.push(self.input) startupinfo = None if os.name ==",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Interface', 'Lightning Interface",
"def create_project_namespace(self, input): self.project_path = input sublime.active_window().show_input_panel( 'Project Namespace', '', self.create_project, None, None)",
"view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener): def on_window_commad(self, window, command_name, args): if command_name == 'exit': plugin_unloaded()",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Apex Class', 'Apex",
"save the test') return self.event_name = 'TestName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Test Name',",
"scratch org') printer.write('\\n' + str(err, 'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t",
"folder save the class') return self.app_name = 'AppName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App",
"Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:test:create', '-n', self.event_name, '-d',",
"self.event_name = 'EventName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Event Name', self.event_name, self.create_event, None, None)",
"if self.selection == '': self.selection = self.view.substr(sublime.Region(0, self.view.size())) self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls')",
"is_enabled(self, paths=[]): if util.isDXProject() == False: return False if len(paths) != 1 or",
"printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder",
"class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nApex",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning App', 'Lightning App",
"err if err is None or err == '': printErr = out printer.write('\\nError",
"the latter case, each entry in the quick panel will show multiple rows",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Project',",
"p.returncode == 0: printer.write('\\nFinished running apex') printer.write('\\n' + str(out, 'utf-8')) else: printErr =",
"not None and self.namespace != '': args.push('-s') args.push(self.namespace) startupinfo = None if os.name",
"def on_modified_async(self, view): active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and active_file_extension !=",
"class DxmateOutputText(sublime_plugin.TextCommand): def run(self, edit, text, erase=False, *args, **kwargs): size = self.view.size() self.view.set_read_only(False)",
"== 0: printer.write('\\nProject created') else: printer.write('\\nError creating project:') printer.write('\\n' + str(out, 'UTF-8')) class",
"for code completion yet lsClient = None printer = None def plugin_loaded(): global",
"= input sublime.active_window().show_input_panel( 'Component Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder",
"sort_keys=True,indent=1, separators=(',', ':')) # util.debug(content) #except Exception as e: # util.debug('could not format",
"None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return False if len(paths) !=",
"'Page API Name', self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name = input",
"return self.event_name = 'TestName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Test Name', self.event_name, self.create_event, None,",
"+ '.intf') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Interface:') printer.write('\\n' + str(err, 'utf-8')) class",
"+ '.component') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce Component:') printer.write('\\n' + str(err, 'utf-8')) class",
"class ExitHandler(sublime_plugin.EventListener): def on_window_commad(self, window, command_name, args): if command_name == 'exit': plugin_unloaded() class",
"create_org(self, input): printer.show() self.def_file = input t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"self.completions = [] # type: List[Tuple[str, str]] self.refreshing = False def on_pre_close(self, view):",
"'.trigger': return None EventHub.publish(\"on_modified_async\", view) def on_query_completions(self, view, prefix, locations): active_file_extension = util.file_extension(view)",
"args = ['sfdx', 'force:source:pull'] startupinfo = None if os.name == 'nt': startupinfo =",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Scratch Org', 'Scratch Org Created') printer.write('\\nCreatin Scratch",
"startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait()",
"= lsClient if not client: return completionProvider = client.get_capability('completionProvider') if not completionProvider: return",
"= 12 Variable = 13 Constant = 14 String = 15 Number =",
"lists. In the latter case, each entry in the quick panel will show",
"default)', '', self.run_tests, None, None) def run_tests(self, input): self.test_org = input printer.show() printer.write('\\nRunning",
"= '' for region in self.view.sel(): if not region.empty(): self.selection += self.view.substr(region) if",
"input): printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"e) file = sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL') syntax_path = None if \"linux\" in sys.platform",
"time.localtime()) ThreadProgress(t, 'Running Org Tests', 'Org tests run') PanelThreadProgress(t, 'Running Org Tests') def",
"run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning App created')",
"p.returncode if p.returncode == 0: printer.write('\\nLightning Test created') file = os.path.join(self.class_dir, self.event_name +",
"'Opening Auth Page', 'Auth Page Opened') printer.write('\\nOpening Auth Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Auth",
"#dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False return True def run_command(self):",
"in self.view.sel(): if not region.empty(): self.selection += self.view.substr(region) if self.selection == '': self.selection",
"and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the test') return self.event_name",
"= 5 Method = 6 Property = 7 Field = 8 Constructor =",
"return False return True def create_app(self, input): self.app_name = input printer.show() t =",
"self.template, '-d', self.project_path] if self.namespace is not None and self.namespace != '': args.push('-s')",
"class') return self.event_name = 'EventName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Event Name', self.event_name, self.create_event,",
"erase=True) def plugin_unloaded(): if lsClient: lsClient.kill() def set_syntax(view): if util.is_apex_file(view): util.debug('setting syntax for",
"p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait() out,err = p.communicate() r = p.returncode",
"'.trigger': return None if not self.refreshing: client = lsClient if not client: return",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running tests', 'Tests run') PanelThreadProgress(t, 'Running Tests')",
"#file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content}) else: printer.write('\\nError running query:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand):",
"= util.dxProjectFolder() args = ['sfdx', 'force:apex:class:create', '-n', self.class_name, '-d', self.class_dir] startupinfo = None",
"def on_activated_async(self, view): EventHub.publish('on_activated_async', view) def on_post_save_async(self, view): EventHub.publish('on_post_save_async', view) def on_close(self, view):",
"None or err == '': printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class",
"0: printer.write('\\nScratch org opened') else: printer.write('\\nError opening') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand):",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self): sublime.active_window().show_input_panel( 'Query', '', self.run_query, None,",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Event created') file",
"if p.returncode == 0: printer.write('\\nVisaulforce Component created') file = os.path.join(self.class_dir, self.page_name + '.component')",
"printer.write('\\nError creating Lightning Test:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self, paths=[]):",
"run_command(self): args = ['sfdx', 'force:source:pull'] startupinfo = None if os.name == 'nt': startupinfo",
"self.event_name + '.resource') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Test:') printer.write('\\n' + str(err, 'utf-8'))",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Test', 'Lightning Interface Test') printer.write('\\nCreating Lightning Test')",
"self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"None, None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Page Label', self.page_label, self.create_page,",
"= '\\$' + insertText[1:] return (\"{}\\t{}\".format(label, detail), insertText) def handle_response(self, response): self.completions =",
"import os import subprocess import threading import sys import json import mdpopups import",
"project:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self, edit): self.edit = edit",
"self.refreshing: client = lsClient if not client: return completionProvider = client.get_capability('completionProvider') if not",
"True def description(self): return # not ready for code completion yet lsClient =",
"class DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() printer.write('\\nPushing Source') t =",
"return None EventHub.publish(\"on_modified_async\", view) def on_query_completions(self, view, prefix, locations): active_file_extension = util.file_extension(view) if",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning App",
"p.returncode if p.returncode == 0: printer.write('\\nFinished running apex') printer.write('\\n' + str(out, 'utf-8')) else:",
"'InterfaceName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Interface Name', self.event_name, self.create_event, None, None) def is_enabled(self,",
"self.page_name = input sublime.active_window().show_input_panel( 'Component Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]):",
"args = ['sfdx', 'force:lightning:test:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name",
"= ['sfdx', 'force:lightning:interface:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name ==",
"return True def run_command(self): args = ['sfdx', 'force:org:open'] startupinfo = None if os.name",
"created') else: printer.write('\\nError creating scratch org') printer.write('\\n' + str(err, 'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def",
"= p.returncode if p.returncode == 0: printer.write('\\nApex class created') file = os.path.join(self.class_dir, self.class_name",
"= ['sfdx', 'force:lightning:component:create', '-n', self.cmp_name, '-d', self.class_dir] startupinfo = None if os.name ==",
"and os.path.isfile(paths[0])): return False return True def create_class(self, input): self.class_name = input printer.show()",
"lsClient global printer if util.dxProjectFolder() != '': lsClient = start_client() if lsClient is",
"import * from .lib.event_hub import EventHub from .lib.util import util from .lib.diagnostic import",
"creating Visualforce Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if",
"True def create_event(self, input): self.event_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer",
"select a single folder save the class') return self.app_name = 'AppName' self.class_dir =",
"SymbolKind(object): File = 1 Module = 2 Namespace = 3 Package = 4",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running query', 'Query run')",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Upgrading Project',",
"Name', self.def_file, self.create_org, None, None) def create_org(self, input): printer.show() self.def_file = input t",
"plugin loaded\", erase=True) def plugin_unloaded(): if lsClient: lsClient.kill() def set_syntax(view): if util.is_apex_file(view): util.debug('setting",
"printer.write('\\nCreatin Scratch Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Scratch Org Created') def is_enabled(self, paths=[]): #dx_folder",
"= os.path.join( self.dx_folder, 'config', 'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class Name', self.def_file, self.create_org, None, None) def",
"== ''): return False self.active_file = util.active_file() if not self.active_file.endswith('.cls'): return False if",
"'-s'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder to save the component')",
"Pulled') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False",
"run(self, edit): self.dx_folder = util.dxProjectFolder() self.def_file = os.path.join( self.dx_folder, 'config', 'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class",
"a single folder save the class') return self.class_name = 'ApexClassName' self.class_dir = paths[0]",
"printer.write('\\nError creating Visualforce Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self, paths=[]):",
"self.app_name = 'AppName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.app_name, self.create_app, None, None)",
"PanelThreadProgress from .lib.languageServer import * from .lib.event_hub import EventHub from .lib.util import util",
"cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0:",
"util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d",
"util.dxProjectFolder() args = ['sfdx', 'force:project:upgrade', '-f'] startupinfo = None if os.name == 'nt':",
"= util.dxProjectFolder() printer.show() printer.write('\\nPushing Source') t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating",
"authorizing Dev Hub:') printer.write('\\n' + str(err, 'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self): sublime.active_window().show_input_panel( 'Query',",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command)",
"= util.file_extension(view) if active_file_extension != '.cls' and active_file_extension != '.trigger': return None if",
"each entry in the quick panel will show multiple rows \"\"\" # file_path",
"def is_enabled(self): self.dx_folder = util.dxProjectFolder() if(self.dx_folder == ''): return False self.active_file = util.active_file()",
"False self.active_file = util.active_file() if not self.active_file.endswith('.cls'): return False if not util.file_is_test(self.window.active_view()): return",
"edit self.project_name = '' self.template = 'Defaultsfdx-project.json' self.project_path = '' self.namespace = None",
"# sublime needs leading '$' escaped. insertText = '\\$' + insertText[1:] return (\"{}\\t{}\".format(label,",
"printer.write('\\n' + str(printErr, 'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() sublime.active_window().show_input_panel(",
"0: printer.write('\\nLightning App created') file = os.path.join(self.class_dir, self.app_name, self.app_name + '.app') sublime.active_window().open_file(file) else:",
"'Opening Org', 'Org Opened') printer.write('\\nOpening Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Org Opened') def is_enabled(self,",
"creating scratch org') printer.write('\\n' + str(err, 'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show()",
"= None if \"linux\" in sys.platform or \"darwin\" in sys.platform: syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\")",
"EventHub.publish('on_window_command', window, command_name, *args) def on_text_command(self, window, command_name, *args): if command_name == 'exit':",
"= None printer = None def plugin_loaded(): global lsClient global printer if util.dxProjectFolder()",
"time.localtime()) ThreadProgress(t, 'Creating Lightning Interface', 'Lightning Interface Created') printer.write('\\nCreating Lightning Interface') printer.write('\\nResult: ')",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running Org Tests', 'Org tests run') PanelThreadProgress(t,",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nOpening results file') content =",
"= util.dxProjectFolder() self.def_file = os.path.join( self.dx_folder, 'config', 'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class Name', self.def_file, self.create_org,",
"self.view.set_read_only(True) self.view.show(size) def is_visible(self): return False def is_enabled(self): return True def description(self): return",
"completionProvider: return autocomplete_triggers = completionProvider.get('triggerCharacters') if locations[0] > 0: self.completions = [] purge_did_change(view.buffer_id())",
"ThreadProgress(t, 'Opening Auth Page', 'Auth Page Opened') printer.write('\\nOpening Auth Page') printer.write('\\nResult: ') PanelThreadProgress(t,",
"DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self, edit): self.selection = '' for region in self.view.sel(): if not",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nProject created') else: printer.write('\\nError creating",
"window, command_name, *args): if command_name == 'exit': EventHub.publish('exit', window, *args) elif command_name ==",
"'force:data:soql:query', '-q', self.query] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"+ str(err, 'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or",
"= paths[0] sublime.active_window().show_input_panel( 'App Name', self.app_name, self.create_app, None, None) def is_enabled(self, paths=[]): if",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Page', 'Visualforce Page Created') printer.write('\\nCreating Visualforce",
"Interface created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.intf') sublime.active_window().open_file(file) else: printer.write('\\nError creating",
"str(printErr, 'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t =",
"sublime.active_window().show_input_panel('Project Path', self.project_path, self.create_project_namespace, None, None) def create_project_namespace(self, input): self.project_path = input sublime.active_window().show_input_panel(",
"save the class') return self.class_name = 'ApexClassName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Class Name',",
"Template', self.template, self.create_project_template, None, None) def create_project_template(self, input): self.project_template = input sublime.active_window().show_input_panel('Project Path',",
"r = p.returncode if p.returncode == 0: printer.write('\\nFinished running apex') printer.write('\\n' + str(out,",
"ThreadProgress(t, 'Creating Visualforce Page', 'Visualforce Page Created') printer.write('\\nCreating Visualforce Page') printer.write('\\nResult: ') PanelThreadProgress(t,",
"def is_enabled(self): return True def description(self): return class WriteOperationStatus(sublime_plugin.TextCommand): def run(self, edit, text,",
"Test:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) !=",
"kwargs.get('region', [0, 0]) status_region = sublime.Region(kw_region[0], kw_region[1]) size = self.view.size() self.view.set_read_only(False) self.view.replace(edit, status_region,",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Apex Class', 'Apex Class Created') printer.write('\\nCreating Apex Class')",
"and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the interface') return self.event_name",
"ThreadProgress(t, 'Creating Scratch Org', 'Scratch Org Created') printer.write('\\nCreatin Scratch Org') printer.write('\\nResult: ') PanelThreadProgress(t,",
"util.is_apex_file(view): util.debug('setting syntax for file') if \"linux\" in sys.platform or \"darwin\" in sys.platform:",
"isinstance(response, dict) else response for item in items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def run_auto_complete(self):",
"True def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:project:upgrade', '-f'] startupinfo =",
"select a single folder to save the page') return self.page_name = 'PageName' self.page_label",
"content = json.dumps(parsed, sort_keys=True,indent=1, separators=(',', ':')) # util.debug(content) #except Exception as e: #",
"args): if command_name == 'exit': plugin_unloaded() class EventHandlers(sublime_plugin.EventListener): def __init__(self): self.completions = []",
"== '': printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self,",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Event",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Upgrading Project', 'Project",
"Apex Class', 'Apex Class Created') printer.write('\\nCreating Apex Class') printer.write('\\nResult: ') PanelThreadProgress(t, 'Apex Class",
"in sys.platform or \"darwin\" in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener): def on_window_commad(self,",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Auth Page', 'Auth",
"= p.returncode if p.returncode == 0: printer.write('\\nFinished running apex') printer.write('\\n' + str(out, 'utf-8'))",
"self.completions = [] purge_did_change(view.buffer_id()) client.send_request( Request.complete( util.get_document_position(view, locations[0])), self.handle_response) self.refreshing = False return",
"and active_file_extension != '.trigger': return None if not self.refreshing: client = lsClient if",
"input): self.app_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"None) def create_project_namespace(self, input): self.project_path = input sublime.active_window().show_input_panel( 'Project Namespace', '', self.create_project, None,",
"pushing source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder =",
"Source', 'Source Pushed') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pushed') def is_enabled(self, paths=[]): #dx_folder =",
"self.event_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"= p.returncode if p.returncode == 0: printer.write('\\nVisaulforce Component created') file = os.path.join(self.class_dir, self.page_name",
"self.page_label = 'Page Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Page API Name', self.page_name, self.get_label,",
"printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show()",
"+ str(err, 'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or",
"= p.returncode if p.returncode == 0: printer.write('\\n' + str(out, 'utf-8')) else: printErr =",
"util.dxProjectFolder() args = ['sfdx', 'force:apex:class:create', '-n', self.class_name, '-d', self.class_dir] startupinfo = None if",
"if command_name == 'exit': EventHub.publish('exit', window, *args) elif command_name == 'close_window': EventHub.publish('close_window', window,",
"region in self.view.sel(): if not region.empty(): self.selection += self.view.substr(region) if self.selection == '':",
"view, prefix, locations): active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and active_file_extension !=",
"str(err, 'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning App', 'Lightning App Created') printer.write('\\nCreating Lightning App') printer.write('\\nResult:",
"active_file_extension != '.cls' and active_file_extension != '.trigger': return None if not self.refreshing: client",
"def run_query(self, input): self.query = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer =",
"source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder()",
"'-n', self.class_name] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"input sublime.active_window().show_input_panel( 'Project Namespace', '', self.create_project, None, None) def create_project(self, input): printer.show() self.namespace",
"+ str(err, 'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self): sublime.active_window().show_input_panel( 'Query', '', self.run_query, None, None)",
"'Lightning Test Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:test:create', '-n',",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Upgrading Project', 'Project Upgraded') printer.write('\\nUpgrading Project')",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Test Created') def run_command(self): dx_folder = util.dxProjectFolder() args =",
"SymbolKind.Field: \"field\", SymbolKind.Variable: \"variable\", SymbolKind.Constant: \"constant\" } def format_symbol_kind(kind): return symbol_kind_names.get(kind, str(kind)) def",
"not err is None and not err == '': printErr = out else:",
"= p.returncode if p.returncode == 0: printer.write('\\nLightning Interface created') file = os.path.join(self.class_dir, self.event_name,",
"'force:auth:web:login', '-d', '-s', '-a', 'DevHub'] startupinfo = None if os.name == 'nt': startupinfo",
"Interface') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Interface Created') def run_command(self): dx_folder = util.dxProjectFolder() args",
"Constructor = 9 Enum = 10 Interface = 11 Function = 12 Variable",
"run_command(self): args = ['sfdx', 'force:source:push'] startupinfo = None if os.name == 'nt': startupinfo",
"Component', 'Visualforce Component Created') printer.write('\\nCreating Visualforce Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Component Created')",
"insertText) def handle_response(self, response): self.completions = [] items = response[\"items\"] if isinstance(response, dict)",
"Namespace = 3 Package = 4 Class = 5 Method = 6 Property",
"'Source Pushed') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return",
"apex') printer.write('\\nResult: ') PanelThreadProgress(t, 'Anonymous apex run') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"def run(self, edit): self.selection = '' for region in self.view.sel(): if not region.empty():",
"else: printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self,",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:component:create', '-n', self.page_name,'-l', self.page_label, '-d',",
"SymbolKind.Class: \"class\", SymbolKind.Method: \"method\", SymbolKind.Function: \"function\", SymbolKind.Field: \"field\", SymbolKind.Variable: \"variable\", SymbolKind.Constant: \"constant\" }",
"Array = 18 symbol_kind_names = { SymbolKind.File: \"file\", SymbolKind.Module: \"module\", SymbolKind.Namespace: \"namespace\", SymbolKind.Package:",
"1 or (len(paths) > 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder",
"self.view.replace(edit, status_region, text) self.view.set_read_only(True) # self.view.show(size) def is_visible(self): return False def is_enabled(self): return",
"created') file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning",
"Created') printer.write('\\nCreating Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Created') def run_command(self): args = ['sfdx',",
"Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False",
"'exit': EventHub.publish('exit', window, *args) elif command_name == 'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command',",
"0: args.push('-u') args.push(self.input) startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the interface') return",
"printer.show() printer.write('\\nPlease select a single folder to save the component') return self.page_name =",
"import sublime_plugin import os import subprocess import threading import sys import json import",
"view, point, hover_zone): EventHub.publish('on_hover', view, point, hover_zone) def on_window_command(self, window, command_name, *args): if",
"False return True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human'] if not",
"= ['sfdx', 'force:apex:test:run', '-r', 'human'] if not self.test_org is None and len(self.test_org) >",
"if p.returncode == 0: printer.write('\\nScratch org created') else: printer.write('\\nError creating scratch org') printer.write('\\n'",
"class created') file = os.path.join(self.class_dir, self.class_name + '.cls') sublime.active_window().open_file(file) else: printer.write('\\nError creating Apex",
"creating Lightning Test:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if",
"'EventName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Event Name', self.event_name, self.create_event, None, None) def is_enabled(self,",
"input): self.project_template = input sublime.active_window().show_input_panel('Project Path', self.project_path, self.create_project_namespace, None, None) def create_project_namespace(self, input):",
"self.view.size() self.view.set_read_only(False) self.view.replace(edit, status_region, text) self.view.set_read_only(True) # self.view.show(size) def is_visible(self): return False def",
"response): self.completions = [] items = response[\"items\"] if isinstance(response, dict) else response for",
"printer.write('\\nCreating Lightning Event') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Event Created') def run_command(self): dx_folder =",
"OrderedDict from .lib.printer import PanelPrinter from .lib.threads import ThreadProgress from .lib.threads import PanelThreadProgress",
"printer.write('\\nProject upgraded') else: printer.write('\\nError upgrading project:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def",
"= util.dxProjectFolder() args = ['sfdx', 'force:lightning:component:create', '-n', self.cmp_name, '-d', self.class_dir] startupinfo = None",
"lsClient.kill() def set_syntax(view): if util.is_apex_file(view): util.debug('setting syntax for file') if \"linux\" in sys.platform",
"Visualforce Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Component Created') def run_command(self): dx_folder = util.dxProjectFolder()",
"and os.path.isfile(paths[0])): return False return True def create_app(self, input): self.app_name = input printer.show()",
"Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:interface:create', '-n', self.event_name, '-d',",
"self.view.size())) self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls') with open(self.file_path, 'w+') as file_obj: file_obj.write(self.selection) printer.show()",
"EventHub.publish('on_activated_async', view) def on_post_save_async(self, view): EventHub.publish('on_post_save_async', view) def on_close(self, view): EventHub.publish('on_close', view) def",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Upgrading Project', 'Project Upgraded') printer.write('\\nUpgrading Project') printer.write('\\nResult: ')",
"window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_modified_async(self, view): active_file_extension = util.file_extension(view)",
"sublime.active_window().active_view().run_command( \"auto_complete\", { 'disable_auto_insert': True, 'api_completions_only': False, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True, }) class",
"sublime.active_window().show_input_panel( 'App Name', self.app_name, self.create_app, None, None) def is_enabled(self, paths=[]): if util.isDXProject() ==",
"False return True def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:project:upgrade', '-f']",
"Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:event:create', '-n', self.event_name, '-d',",
"0: printer.write('\\nLightning Event created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.evt') sublime.active_window().open_file(file) else:",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Auth Page Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:component:create', '-n', self.page_name,'-l', self.page_label,",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Page', 'Visualforce Page Created') printer.write('\\nCreating",
"False: return False return True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human']",
"util.debug(paths) if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])): return False",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Interface', 'Lightning Interface Created') printer.write('\\nCreating Lightning Interface') printer.write('\\nResult:",
"subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate()",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Page Created') def run_command(self): dx_folder = util.dxProjectFolder() args =",
"p.returncode == 0: printer.write('\\nOpening results file') content = str(out,'UTF-8') #try: # parsed =",
"args = ['sfdx', 'force:auth:web:login', '-d', '-s', '-a', 'DevHub'] startupinfo = None if os.name",
"= '' self.template = 'Defaultsfdx-project.json' self.project_path = '' self.namespace = None sublime.active_window().show_input_panel( 'Project",
"self.page_name = 'PageName' self.page_label = 'Page Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Page API",
"from .lib.diagnostic import * import ntpath class SymbolKind(object): File = 1 Module =",
"util.dxProjectFolder() args = ['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None",
"printer.write('\\nApex class created') file = os.path.join(self.class_dir, self.class_name + '.cls') sublime.active_window().open_file(file) else: printer.write('\\nError creating",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running tests', 'Tests",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pulling Source', 'Source Pulled') printer.write('\\nPulling Source') printer.write('\\nResult: ')",
"= out printer.write('\\n' + str(printErr, 'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder =",
"Test') printer.write('\\nCreating Lightning Test') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Test Created') def run_command(self): dx_folder",
"startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err",
"return True def create_app(self, input): self.app_name = input printer.show() t = threading.Thread(target=self.run_command) t.start()",
"str(out, 'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self, edit): self.selection = '' for region in",
"printer.write('\\nLightning App created') file = os.path.join(self.class_dir, self.app_name, self.app_name + '.app') sublime.active_window().open_file(file) else: printer.write('\\nError",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Component',",
"input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d",
"False return True def run_command(self): args = ['sfdx', 'force:source:push'] startupinfo = None if",
"'force:lightning:event:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo",
"False def is_enabled(self): return True def description(self): return class WriteOperationStatus(sublime_plugin.TextCommand): def run(self, edit,",
"printer.write('\\nOpening Auth Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Auth Page Opened') def is_enabled(self, paths=[]): #dx_folder",
"os.path.join(self.class_dir, self.page_name + '.page') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce page:') printer.write('\\n' + str(err,",
"Component', 'Lightning Component Created') printer.write('\\nCreating Lightning Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Component Created')",
"folder save the class') return self.class_name = 'ApexClassName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Class",
"util.dxProjectFolder() self.def_file = os.path.join( self.dx_folder, 'config', 'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class Name', self.def_file, self.create_org, None,",
"running apex') printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if err is",
"server') EventHub.subscribe('on_load_async', set_syntax) active_window_id = sublime.active_window().id() printer = PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin loaded\", erase=True)",
"save the page') return self.page_name = 'PageName' self.page_label = 'Page Label' self.class_dir =",
"class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0",
"'Tuple[str, str]': label = item.get(\"label\") # kind = item.get(\"kind\") detail = item.get(\"kind\") detail",
"Lightning Interface', 'Lightning Interface Created') printer.write('\\nCreating Lightning Interface') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Interface",
"printer.write('\\nError pushing source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder",
"not client: return completionProvider = client.get_capability('completionProvider') if not completionProvider: return autocomplete_triggers = completionProvider.get('triggerCharacters')",
"or a list of string lists. In the latter case, each entry in",
"run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])): printer.show()",
"if not self.refreshing: client = lsClient if not client: return completionProvider = client.get_capability('completionProvider')",
"None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Page Label', self.page_label, self.create_page, None,",
"PanelPrinter from .lib.threads import ThreadProgress from .lib.threads import PanelThreadProgress from .lib.languageServer import *",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nScratch org",
"False return True def create_app(self, input): self.app_name = input printer.show() t = threading.Thread(target=self.run_command)",
"self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"EventHub.publish('on_hover', view, point, hover_zone) def on_window_command(self, window, command_name, *args): if command_name == 'exit':",
"'force:source:push'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"+ '.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class",
"printErr = out else: printer.write('\\nError pulling source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand):",
"is None and not err == '': printErr = out else: printer.write('\\nError pushing",
"self.project_name, self.create_project_name, None, None) def create_project_name(self, input): self.project_name = input sublime.active_window().show_input_panel('Project Template', self.template,",
"from .lib.util import util from .lib.diagnostic import * import ntpath class SymbolKind(object): File",
"startupinfo=startupinfo) p.wait() out,err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nProject",
"'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command)",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Event Created') def run_command(self): dx_folder = util.dxProjectFolder() args =",
"sublime.active_window().show_input_panel( 'Class Name', self.def_file, self.create_org, None, None) def create_org(self, input): printer.show() self.def_file =",
"'-f', self.def_file, '-a', 'ScratchOrg', '-s'] startupinfo = None if os.name == 'nt': startupinfo",
"*args) def on_modified_async(self, view): active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and active_file_extension",
"r = p.returncode if p.returncode == 0: printer.write('\\nApex class created') file = os.path.join(self.class_dir,",
"\"darwin\" in sys.platform: syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content})",
"save the class') return self.app_name = 'AppName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name',",
"time.localtime()) ThreadProgress(t, 'Creating Lightning Event', 'Lightning Event Created') printer.write('\\nCreating Lightning Event') printer.write('\\nResult: ')",
"App') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning App Created') def run_command(self): dx_folder = util.dxProjectFolder() args",
"class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org (leave blank for",
"text) else: self.view.insert(edit, size, text) self.view.set_read_only(True) self.view.show(size) def is_visible(self): return False def is_enabled(self):",
"string lists. In the latter case, each entry in the quick panel will",
"item.get(\"insertText\") if insertText[0] == '$': # sublime needs leading '$' escaped. insertText =",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pushing Source', 'Source Pushed') printer.write('\\nResult:",
"'Running tests', 'Tests run') PanelThreadProgress(t, 'Running Tests') def is_enabled(self): self.dx_folder = util.dxProjectFolder() if(self.dx_folder",
"self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return False",
"') PanelThreadProgress(t, 'Anonymous apex run') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"printer.write('\\nError opening') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder =",
"*args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_text_command(self, window, command_name, *args): if command_name",
"printer.write('\\nPulling Source') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pulled') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"['sfdx', 'force:org:open'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"def on_hover(self, view, point, hover_zone): EventHub.publish('on_hover', view, point, hover_zone) def on_window_command(self, window, command_name,",
"# content = json.dumps(parsed, sort_keys=True,indent=1, separators=(',', ':')) # util.debug(content) #except Exception as e:",
"create_project(self, input): printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"['sfdx', 'force:project:upgrade', '-f'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"= item.get(\"insertText\") if insertText[0] == '$': # sublime needs leading '$' escaped. insertText",
"Lightning Interface') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Interface Created') def run_command(self): dx_folder = util.dxProjectFolder()",
"= 7 Field = 8 Constructor = 9 Enum = 10 Interface =",
"sublime.active_window().show_input_panel( 'Component Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"self.selection = self.view.substr(sublime.Region(0, self.view.size())) self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls') with open(self.file_path, 'w+') as",
"printer.show() printer.write('\\nPlease select a single folder save the interface') return self.event_name = 'InterfaceName'",
"== 0: printer.write('\\nOpening results file') content = str(out,'UTF-8') #try: # parsed = json.loads(content)",
"== 0: printer.write('\\nScratch org created') else: printer.write('\\nError creating scratch org') printer.write('\\n' + str(err,",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Event', 'Lightning Event Created') printer.write('\\nCreating",
"class EventHandlers(sublime_plugin.EventListener): def __init__(self): self.completions = [] # type: List[Tuple[str, str]] self.refreshing =",
"False return True def run_command(self): args = ['sfdx', 'force:org:open'] startupinfo = None if",
"p.returncode if p.returncode == 0: printer.write('\\nLightning App created') file = os.path.join(self.class_dir, self.app_name, self.app_name",
"'-a', 'ScratchOrg', '-s'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"insertText = label if item.get(\"insertTextFormat\") == 2: insertText = item.get(\"insertText\") if insertText[0] ==",
"= util.dxProjectFolder() if(self.dx_folder == ''): return False self.active_file = util.active_file() if not self.active_file.endswith('.cls'):",
"is not None and self.namespace != '': args.push('-s') args.push(self.namespace) startupinfo = None if",
"of strings, or a list of string lists. In the latter case, each",
"is_enabled(self): self.dx_folder = util.dxProjectFolder() if(self.dx_folder == ''): return False self.active_file = util.active_file() if",
"len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True",
"True def create_class(self, input): self.class_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer",
"Variable = 13 Constant = 14 String = 15 Number = 16 Boolean",
"PanelThreadProgress(t, 'Auth Page Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Page Created') def run_command(self): dx_folder = util.dxProjectFolder() args",
"= out else: printer.write('\\nError pulling source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def",
"Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:component:create', '-n', self.cmp_name,",
"authorized') else: printer.write('\\nError authorizing Dev Hub:') printer.write('\\n' + str(err, 'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def",
"of string lists. In the latter case, each entry in the quick panel",
"self.event_name, self.event_name + '.intf') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Interface:') printer.write('\\n' + str(err,",
"may be a list of strings, or a list of string lists. In",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Event', 'Lightning Event Created') printer.write('\\nCreating Lightning",
"PanelThreadProgress(t, 'Visualforce Page Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:page:create',",
"separators=(',', ':')) # util.debug(content) #except Exception as e: # util.debug('could not format query",
"opened') else: printer.write('\\nError opening') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit):",
"opening') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder()",
"False: return False if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])):",
"'Creating Scratch Org', 'Scratch Org Created') printer.write('\\nCreatin Scratch Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Scratch",
"not self.test_org is None and len(self.test_org) > 0: args.push('-u') args.push(self.input) startupinfo = None",
"['sfdx', 'force:lightning:event:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt':",
"os.path.join(self.class_dir, self.class_name + '.cls') sublime.active_window().open_file(file) else: printer.write('\\nError creating Apex Class:') printer.write('\\n' + str(err,",
"ThreadProgress(t, 'Creating Lightning Event', 'Lightning Event Created') printer.write('\\nCreating Lightning Event') printer.write('\\nResult: ') PanelThreadProgress(t,",
"PanelThreadProgress(t, 'Project Upgraded') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"= os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content}) else: printer.write('\\nError running query:')",
"syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content}) else: printer.write('\\nError running query:') printer.write('\\n' + str(err,",
"p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning",
"view): active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and active_file_extension != '.trigger': return",
"= '' self.namespace = None sublime.active_window().show_input_panel( 'Project Name', self.project_name, self.create_project_name, None, None) def",
"project:') printer.write('\\n' + str(out, 'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self, edit): self.selection = ''",
"util.debug('setting syntax for file') if \"linux\" in sys.platform or \"darwin\" in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\"))",
"'Query', '', self.run_query, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"if util.isDXProject() == False: return False return True def run_command(self): args = ['sfdx',",
"['sfdx', 'force:lightning:interface:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt':",
"'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command)",
"1 Module = 2 Namespace = 3 Package = 4 Class = 5",
"Name', self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Page",
"edit): self.dx_folder = util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org (leave blank for default)', '', self.run_tests, None,",
"> 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder to save the",
"== 0: printer.write('\\nApex class created') file = os.path.join(self.class_dir, self.class_name + '.cls') sublime.active_window().open_file(file) else:",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Org Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"self.create_project, None, None) def create_project(self, input): printer.show() self.namespace = input t = threading.Thread(target=self.run_command)",
"self.template = 'Defaultsfdx-project.json' self.project_path = '' self.namespace = None sublime.active_window().show_input_panel( 'Project Name', self.project_name,",
"'$': # sublime needs leading '$' escaped. insertText = '\\$' + insertText[1:] return",
"out,err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nProject created') else:",
"page:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) !=",
"= 10 Interface = 11 Function = 12 Variable = 13 Constant =",
"file = os.path.join(self.class_dir, self.page_name + '.component') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce Component:') printer.write('\\n'",
"Interface Test') printer.write('\\nCreating Lightning Test') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Test Created') def run_command(self):",
"set_syntax) active_window_id = sublime.active_window().id() printer = PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin loaded\", erase=True) def plugin_unloaded():",
"= util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org (leave blank for default)', '', self.run_tests, None, None) def",
"PanelThreadProgress(t, 'Source Pushed') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running anonymous apex', 'Anonymous apex run') printer.write('\\nRunning anonymous apex') printer.write('\\nResult:",
"in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener): def on_window_commad(self, window, command_name, args): if",
"import * import ntpath class SymbolKind(object): File = 1 Module = 2 Namespace",
"'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org (leave blank",
"'Page Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running tests',",
"Class Created') printer.write('\\nCreating Apex Class') printer.write('\\nResult: ') PanelThreadProgress(t, 'Apex Class Created') def run_command(self):",
"str(printErr, 'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() printer.write('\\nPushing Source')",
"'', self.create_project, None, None) def create_project(self, input): printer.show() self.namespace = input t =",
"return False return True def run_command(self): args = ['sfdx', 'force:org:open'] startupinfo = None",
"['sfdx', 'force:source:push'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Scratch Org',",
"0: printer.write('\\nOpening results file') content = str(out,'UTF-8') #try: # parsed = json.loads(content) #",
"1 or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_event(self,",
"== False: return False if len(paths) != 1 or (len(paths) > 0 and",
"create_project_template(self, input): self.project_template = input sublime.active_window().show_input_panel('Project Path', self.project_path, self.create_project_namespace, None, None) def create_project_namespace(self,",
"input): self.cmp_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"self.create_class, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"out printer.write('\\n' + str(printErr, 'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder()",
"with open(self.file_path, 'w+') as file_obj: file_obj.write(self.selection) printer.show() self.namespace = input t = threading.Thread(target=self.run_command)",
"time.localtime()) ThreadProgress(t, 'Creating Visualforce Component', 'Visualforce Component Created') printer.write('\\nCreating Visualforce Component') printer.write('\\nResult: ')",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nScratch org opened') else: printer.write('\\nError",
"p.returncode == 0: printer.write('\\nLightning App created') file = os.path.join(self.class_dir, self.app_name, self.app_name + '.app')",
"def create_project_name(self, input): self.project_name = input sublime.active_window().show_input_panel('Project Template', self.template, self.create_project_template, None, None) def",
"DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self): sublime.active_window().show_input_panel( 'Query', '', self.run_query, None, None) def is_enabled(self, paths=[]): #dx_folder",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:interface:create', '-n', self.event_name, '-d', self.class_dir] startupinfo =",
"file.set_name('SOQL') syntax_path = None if \"linux\" in sys.platform or \"darwin\" in sys.platform: syntax_path",
"ntpath class SymbolKind(object): File = 1 Module = 2 Namespace = 3 Package",
"+= self.view.substr(region) if self.selection == '': self.selection = self.view.substr(sublime.Region(0, self.view.size())) self.file_path = os.path.join(util.dxProjectFolder(),",
"(leave blank for default)', '', self.run_tests, None, None) def run_tests(self, input): self.test_org =",
"= start_client() if lsClient is None: util.debug('Unable start langauge server') EventHub.subscribe('on_load_async', set_syntax) active_window_id",
"self.refreshing = False return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self, item) -> 'Tuple[str,",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nOpening results",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Test',",
"None) def create_project(self, input): printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start() t.printer",
"= 3 Package = 4 Class = 5 Method = 6 Property =",
"active_window_id = sublime.active_window().id() printer = PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin loaded\", erase=True) def plugin_unloaded(): if",
"*args): if command_name == 'exit': EventHub.publish('exit', window, *args) elif command_name == 'close_window': EventHub.publish('close_window',",
"creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if",
"') PanelThreadProgress(t, 'Apex Class Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx',",
"if p.returncode == 0: printer.write('\\nLightning Interface created') file = os.path.join(self.class_dir, self.event_name, self.event_name +",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Org', 'Org Opened') printer.write('\\nOpening Org') printer.write('\\nResult: ') PanelThreadProgress(t,",
"util.debug('Unable start langauge server') EventHub.subscribe('on_load_async', set_syntax) active_window_id = sublime.active_window().id() printer = PanelPrinter.get(active_window_id) printer.write(\"sfdx",
"+ str(err, 'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or",
"not region.empty(): self.selection += self.view.substr(region) if self.selection == '': self.selection = self.view.substr(sublime.Region(0, self.view.size()))",
"client: return completionProvider = client.get_capability('completionProvider') if not completionProvider: return autocomplete_triggers = completionProvider.get('triggerCharacters') if",
"run_command(self): args = ['sfdx', 'force:project:create', '-n', self.project_name, '-t', self.template, '-d', self.project_path] if self.namespace",
"= 'ApexClassName' t = threading.Thread(target=self.run_command) t.start() printer.show() printer.write('\\nRunning Tests') printer.write('\\nResult: ') t.printer =",
"import time from collections import OrderedDict from .lib.printer import PanelPrinter from .lib.threads import",
"'Creating Lightning Event', 'Lightning Event Created') printer.write('\\nCreating Lightning Event') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning",
"printer.write('\\nCreating Lightning Test') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Test Created') def run_command(self): dx_folder =",
"os.path.join(self.class_dir, self.event_name, self.event_name + '.evt') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Event:') printer.write('\\n' +",
"view): EventHub.publish('on_pre_close', view) def on_close(self, view): EventHub.publish('on_close', view) def on_load_async(self, view): EventHub.publish('on_load_async', view)",
"if not self.active_file.endswith('.cls'): return False if not util.file_is_test(self.window.active_view()): return False return True def",
"util.dxProjectFolder() if util.isDXProject() == False: return False if len(paths) != 1 or (len(paths)",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Test', 'Lightning Interface Test') printer.write('\\nCreating Lightning",
"= input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a,",
"= 'ComponentName' self.page_label = 'Component Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Component API Name',",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Test', 'Lightning Interface Test')",
"def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Page Label', self.page_label, self.create_page, None, None)",
"'Query run') printer.write('\\nRunning query') printer.write('\\nResult: ') PanelThreadProgress(t, 'Query run') def run_command(self): dx_folder =",
"== '': printErr = out else: printer.write('\\nError pushing source') printer.write('\\n' + str(printErr, 'utf-8'))",
"(len(paths) > 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder to save",
"return self.cmp_name = 'ComponentName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.cmp_name, self.create_cmp, None,",
"view) def on_post_save_async(self, view): EventHub.publish('on_post_save_async', view) def on_close(self, view): EventHub.publish('on_close', view) def on_hover(self,",
"not err == '': printErr = out else: printer.write('\\nError pulling source') printer.write('\\n' +",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:component:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo",
"'Lightning Interface Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:interface:create', '-n',",
"*args) def on_text_command(self, window, command_name, *args): if command_name == 'exit': EventHub.publish('exit', window, *args)",
"Dev Hub:') printer.write('\\n' + str(err, 'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self): sublime.active_window().show_input_panel( 'Query', '',",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args =",
"startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder) p.wait() out, err",
"util.dxProjectFolder() if(self.dx_folder == ''): return False self.active_file = util.active_file() if not self.active_file.endswith('.cls'): return",
"') PanelThreadProgress(t, 'Visualforce Page Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx',",
"on_modified_async(self, view): active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and active_file_extension != '.trigger':",
"printer.write('\\nError creating Visualforce page:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]):",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nFinished running apex') printer.write('\\n' +",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Component', 'Visualforce Component Created') printer.write('\\nCreating Visualforce Component') printer.write('\\nResult:",
"client.get_capability('completionProvider') if not completionProvider: return autocomplete_triggers = completionProvider.get('triggerCharacters') if locations[0] > 0: self.completions",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Project', 'Project Created') printer.write('\\nCreating Project') printer.write('\\nResult: ') PanelThreadProgress(t,",
"self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Test Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]):",
"self.view.show(size) def is_visible(self): return False def is_enabled(self): return True def description(self): return class",
"= input printer.show() printer.write('\\nRunning Org Tests') printer.write('\\nResult: ') t = threading.Thread(target=self.run_command) t.start() t.printer",
"= 6 Property = 7 Field = 8 Constructor = 9 Enum =",
"== False: return False return True def run_command(self): args = ['sfdx', 'force:source:push'] startupinfo",
"return True def description(self): return # not ready for code completion yet lsClient",
"paths[0] sublime.active_window().show_input_panel( 'Test Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject()",
"0 and os.path.isfile(paths[0])): return False return True def create_class(self, input): self.class_name = input",
"multiple rows \"\"\" # file_path = uri_to_filename(location.get(\"uri\")) # kind = format_symbol_kind(item.get(\"kind\")) # return",
"class') return self.app_name = 'AppName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.app_name, self.create_app,",
"'Visualforce Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:component:create', '-n',",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:data:soql:query', '-q', self.query] startupinfo = None if",
"def run_tests(self, input): self.test_org = input printer.show() printer.write('\\nRunning Org Tests') printer.write('\\nResult: ') t",
"= 15 Number = 16 Boolean = 17 Array = 18 symbol_kind_names =",
"['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if os.name ==",
"= ntpath.split(self.active_file)[ 1].replace('.cls', '') self.class_name = 'ApexClassName' t = threading.Thread(target=self.run_command) t.start() printer.show() printer.write('\\nRunning",
"items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def run_auto_complete(self): self.refreshing = True sublime.active_window().active_view().run_command( \"auto_complete\", { 'disable_auto_insert':",
"class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0",
"window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_text_command(self, window, command_name, *args): if",
"[] purge_did_change(view.buffer_id()) client.send_request( Request.complete( util.get_document_position(view, locations[0])), self.handle_response) self.refreshing = False return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS",
"['sfdx', 'force:apex:class:create', '-n', self.class_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt':",
"= util.dxProjectFolder() if util.isDXProject() == False: return False return True def run_command(self): dx_folder",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1",
"False return True def run_command(self): args = ['sfdx', 'force:source:pull'] startupinfo = None if",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1",
"on_hover(self, view, point, hover_zone): EventHub.publish('on_hover', view, point, hover_zone) def on_window_command(self, window, command_name, *args):",
"Lightning App', 'Lightning App Created') printer.write('\\nCreating Lightning App') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning App",
"and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the class') return self.event_name",
"0: printer.write('\\nProject created') else: printer.write('\\nError creating project:') printer.write('\\n' + str(out, 'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand):",
"Interface', 'Lightning Interface Created') printer.write('\\nCreating Lightning Interface') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Interface Created')",
"sublime.active_window().show_input_panel( 'Event Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject() ==",
"p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\n'",
"= os.path.join(self.class_dir, self.page_name + '.page') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce page:') printer.write('\\n' +",
"def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
".lib.event_hub import EventHub from .lib.util import util from .lib.diagnostic import * import ntpath",
"> 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the class')",
"'': printErr = out else: printer.write('\\nError pulling source') printer.write('\\n' + str(printErr, 'utf-8')) class",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce Component created')",
"'$' escaped. insertText = '\\$' + insertText[1:] return (\"{}\\t{}\".format(label, detail), insertText) def handle_response(self,",
"response[\"items\"] if isinstance(response, dict) else response for item in items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete()",
"import sys import json import mdpopups import time from collections import OrderedDict from",
"Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) !=",
"SymbolKind.Constant: \"constant\" } def format_symbol_kind(kind): return symbol_kind_names.get(kind, str(kind)) def format_symbol(item): \"\"\" items may",
"printer.show() printer.write('\\nPushing Source') t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a,",
"loaded\", erase=True) def plugin_unloaded(): if lsClient: lsClient.kill() def set_syntax(view): if util.is_apex_file(view): util.debug('setting syntax",
"collections import OrderedDict from .lib.printer import PanelPrinter from .lib.threads import ThreadProgress from .lib.threads",
"Lightning Interface:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths)",
"Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Component API Name', self.page_name, self.get_label, None, None) def",
"'Visualforce Page Created') printer.write('\\nCreating Visualforce Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Page Created') def",
"') PanelThreadProgress(t, 'Query run') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:data:soql:query',",
"Lightning Component', 'Lightning Component Created') printer.write('\\nCreating Lightning Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Component",
"'Lightning Event Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:event:create', '-n',",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Test', 'Lightning Interface Test') printer.write('\\nCreating",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pulling Source', 'Source Pulled') printer.write('\\nPulling",
"label = item.get(\"label\") # kind = item.get(\"kind\") detail = item.get(\"kind\") detail = format_symbol_kind(detail)",
"'Auth Page Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"= ['sfdx', 'force:apex:class:create', '-n', self.class_name, '-d', self.class_dir] startupinfo = None if os.name ==",
"False: return False return True def run_command(self): args = ['sfdx', 'force:source:push'] startupinfo =",
"util.dxProjectFolder() if util.isDXProject() == False: return False return True def run_command(self): args =",
"args = ['sfdx', 'force:lightning:interface:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name",
"\"\"\" items may be a list of strings, or a list of string",
"None, None) def create_project_template(self, input): self.project_template = input sublime.active_window().show_input_panel('Project Path', self.project_path, self.create_project_namespace, None,",
"def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Component Label', self.page_label, self.create_page, None, None)",
"insertText[1:] return (\"{}\\t{}\".format(label, detail), insertText) def handle_response(self, response): self.completions = [] items =",
"= True sublime.active_window().active_view().run_command( \"auto_complete\", { 'disable_auto_insert': True, 'api_completions_only': False, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True,",
"a single folder to save the page') return self.page_name = 'PageName' self.page_label =",
"0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder to save the page')",
"or (len(paths) > 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder to",
"command_name, *args): if command_name == 'exit': EventHub.publish('exit', window, *args) elif command_name == 'close_window':",
"'Creating Visualforce Page', 'Visualforce Page Created') printer.write('\\nCreating Visualforce Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce",
"folder save the class') return self.event_name = 'EventName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Event",
"printer.write('\\nRunning query') printer.write('\\nResult: ') PanelThreadProgress(t, 'Query run') def run_command(self): dx_folder = util.dxProjectFolder() args",
"return False return True def run_command(self): args = ['sfdx', 'force:apex:execute', '-f', self.file_path] startupinfo",
"Page Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return",
"False: return False util.debug(paths) if len(paths) != 1 or (len(paths) > 0 and",
"'', self.run_tests, None, None) def run_tests(self, input): self.test_org = input printer.show() printer.write('\\nRunning Org",
"printer.write('\\nScratch org opened') else: printer.write('\\nError opening') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:apex:class:create', '-n', self.class_name, '-d', self.class_dir] startupinfo",
"'Interface Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False:",
"'Defaultsfdx-project.json' self.project_path = '' self.namespace = None sublime.active_window().show_input_panel( 'Project Name', self.project_name, self.create_project_name, None,",
"+ str(err, 'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or",
"'Test Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False:",
"'force:org:open'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"None) def create_project_name(self, input): self.project_name = input sublime.active_window().show_input_panel('Project Template', self.template, self.create_project_template, None, None)",
"'ApexClassName' t = threading.Thread(target=self.run_command) t.start() printer.show() printer.write('\\nRunning Tests') printer.write('\\nResult: ') t.printer = printer",
"util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org (leave blank for default)', '', self.run_tests, None, None) def run_tests(self,",
"import threading import sys import json import mdpopups import time from collections import",
"err is None and not err == '': printErr = out else: printer.write('\\nError",
"erase == True: size = sublime.Region(0, self.view.size()) self.view.replace(edit, size, text) else: self.view.insert(edit, size,",
"is None and not err == '': printErr = out else: printer.write('\\nError pulling",
"0: printer.write('\\nFinished running apex') printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if",
"class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0",
"\"auto_complete\", { 'disable_auto_insert': True, 'api_completions_only': False, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True, }) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand):",
"if p.returncode == 0: printer.write('\\nApex class created') file = os.path.join(self.class_dir, self.class_name + '.cls')",
"!= '.cls' and active_file_extension != '.trigger': return None if not self.refreshing: client =",
"run_command(self): args = ['sfdx', 'force:org:create', '-f', self.def_file, '-a', 'ScratchOrg', '-s'] startupinfo = None",
"format query results\\n', e) file = sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL') syntax_path = None if",
"file.set_scratch(True) file.set_name('SOQL') syntax_path = None if \"linux\" in sys.platform or \"darwin\" in sys.platform:",
"\"\"\" # file_path = uri_to_filename(location.get(\"uri\")) # kind = format_symbol_kind(item.get(\"kind\")) # return [item.get(\"name\"), kind]",
"printer.write('\\nRunning Tests') printer.write('\\nResult: ') t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y",
"'-n', self.project_name, '-t', self.template, '-d', self.project_path] if self.namespace is not None and self.namespace",
"on_text_command(self, window, command_name, *args): if command_name == 'exit': EventHub.publish('exit', window, *args) elif command_name",
"in sys.platform or \"darwin\" in sys.platform: syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\")",
"printer.write('\\nVisaulforce page created') file = os.path.join(self.class_dir, self.page_name + '.page') sublime.active_window().open_file(file) else: printer.write('\\nError creating",
"stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait() out,err = p.communicate() r = p.returncode if p.returncode ==",
"created') file = os.path.join(self.class_dir, self.page_name + '.component') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce Component:')",
"not completionProvider: return autocomplete_triggers = completionProvider.get('triggerCharacters') if locations[0] > 0: self.completions = []",
"import EventHub from .lib.util import util from .lib.diagnostic import * import ntpath class",
"lsClient = start_client() if lsClient is None: util.debug('Unable start langauge server') EventHub.subscribe('on_load_async', set_syntax)",
"'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) >",
"App created') file = os.path.join(self.class_dir, self.app_name, self.app_name + '.app') sublime.active_window().open_file(file) else: printer.write('\\nError creating",
"self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return False if",
"str(out,'UTF-8') #try: # parsed = json.loads(content) # content = json.dumps(parsed, sort_keys=True,indent=1, separators=(',', ':'))",
"False return True def run_command(self): args = ['sfdx', 'force:apex:execute', '-f', self.file_path] startupinfo =",
"Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Auth Page Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Auth Page', 'Auth Page Opened') printer.write('\\nOpening Auth Page') printer.write('\\nResult:",
"util.isDXProject() == False: return False util.debug(paths) if len(paths) != 1 or (len(paths) >",
"str(err, 'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths)",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nApex class created') file =",
"run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human', '-l', 'RunSpecifiedTests', '-n', self.class_name] startupinfo =",
"'': self.selection = self.view.substr(sublime.Region(0, self.view.size())) self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls') with open(self.file_path, 'w+')",
"time.localtime()) ThreadProgress(t, 'Pushing Source', 'Source Pushed') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pushed') def is_enabled(self,",
"'' self.template = 'Defaultsfdx-project.json' self.project_path = '' self.namespace = None sublime.active_window().show_input_panel( 'Project Name',",
"anonymous apex') printer.write('\\nResult: ') PanelThreadProgress(t, 'Anonymous apex run') def is_enabled(self, paths=[]): #dx_folder =",
"printer.write('\\nError creating scratch org') printer.write('\\n' + str(err, 'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self, edit):",
"if util.isDXProject() == False: return False return True def run_query(self, input): self.query =",
"args = ['sfdx', 'force:apex:test:run', '-r', 'human'] if not self.test_org is None and len(self.test_org)",
"run') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:data:soql:query', '-q', self.query] startupinfo",
"self.page_name + '.page') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce page:') printer.write('\\n' + str(err, 'utf-8'))",
"= util.dxProjectFolder() args = ['sfdx', 'force:lightning:test:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None",
"= p.returncode if p.returncode == 0: printer.write('\\nProject created') else: printer.write('\\nError creating project:') printer.write('\\n'",
"Scratch Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Scratch Org Created') def is_enabled(self, paths=[]): #dx_folder =",
"sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL') syntax_path = None if \"linux\" in sys.platform or \"darwin\" in",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Component', 'Lightning",
"self.dx_folder = util.dxProjectFolder() self.def_file = os.path.join( self.dx_folder, 'config', 'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class Name', self.def_file,",
"'.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand):",
"None: util.debug('Unable start langauge server') EventHub.subscribe('on_load_async', set_syntax) active_window_id = sublime.active_window().id() printer = PanelPrinter.get(active_window_id)",
"item in items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def run_auto_complete(self): self.refreshing = True sublime.active_window().active_view().run_command( \"auto_complete\",",
"util.dxProjectFolder() args = ['sfdx', 'force:visualforce:component:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None",
"self.create_app, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return False if",
"folder save the component') return self.cmp_name = 'ComponentName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App",
"point, hover_zone): EventHub.publish('on_hover', view, point, hover_zone) def on_window_command(self, window, command_name, *args): if command_name",
"r = p.returncode if p.returncode == 0: printer.write('\\nDevHub authorized') else: printer.write('\\nError authorizing Dev",
"run_command(self): args = ['sfdx', 'force:apex:execute', '-f', self.file_path] startupinfo = None if os.name ==",
"util.dxProjectFolder() args = ['sfdx', 'force:auth:web:login', '-d', '-s', '-a', 'DevHub'] startupinfo = None if",
"os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the component') return self.cmp_name =",
"EventHub.publish('on_post_save_async', view) def on_close(self, view): EventHub.publish('on_close', view) def on_hover(self, view, point, hover_zone): EventHub.publish('on_hover',",
"else: printer.write('\\nError pulling source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit):",
"'Creating Lightning Test', 'Lightning Interface Test') printer.write('\\nCreating Lightning Test') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning",
"File = 1 Module = 2 Namespace = 3 Package = 4 Class",
"self.test_org = input printer.show() printer.write('\\nRunning Org Tests') printer.write('\\nResult: ') t = threading.Thread(target=self.run_command) t.start()",
"select a single folder to save the component') return self.page_name = 'ComponentName' self.page_label",
"printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d %b",
"def run_command(self): args = ['sfdx', 'force:project:create', '-n', self.project_name, '-t', self.template, '-d', self.project_path] if",
"items = response[\"items\"] if isinstance(response, dict) else response for item in items: self.completions.append(self.format_completion(item))",
"Tests') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False",
"if lsClient is None: util.debug('Unable start langauge server') EventHub.subscribe('on_load_async', set_syntax) active_window_id = sublime.active_window().id()",
"get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Page Label', self.page_label, self.create_page, None, None) def",
"Source') t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d %b",
"self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo =",
"else: printer.write('\\nError creating Lightning Interface:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self,",
"printer.write('\\nCreating Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Created') def run_command(self): args = ['sfdx', 'force:project:create',",
"def is_enabled(self, paths=[]): if util.isDXProject() == False: return False util.debug(paths) if len(paths) !=",
"+ str(printErr, 'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org",
"component') return self.cmp_name = 'ComponentName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.cmp_name, self.create_cmp,",
"3 Package = 4 Class = 5 Method = 6 Property = 7",
"window, command_name, *args) def on_modified_async(self, view): active_file_extension = util.file_extension(view) if active_file_extension != '.cls'",
"EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_modified_async(self, view): active_file_extension =",
"'Org Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return",
"Visualforce Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths)",
"False return True def run_query(self, input): self.query = input printer.show() t = threading.Thread(target=self.run_command)",
"self.dx_folder = util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org (leave blank for default)', '', self.run_tests, None, None)",
"== False: return False return True def run_command(self): args = ['sfdx', 'force:org:create', '-f',",
"'Lightning App Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:app:create', '-n',",
"sublime.active_window().show_input_panel( 'Query', '', self.run_query, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"input sublime.active_window().show_input_panel( 'Component Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder =",
"= ['sfdx', 'force:project:create', '-n', self.project_name, '-t', self.template, '-d', self.project_path] if self.namespace is not",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Component',",
"EventHub.publish('on_close', view) def on_load_async(self, view): EventHub.publish('on_load_async', view) def on_activated_async(self, view): EventHub.publish('on_activated_async', view) def",
"False: return False return True def run_command(self): args = ['sfdx', 'force:source:pull'] startupinfo =",
"a single folder save the component') return self.cmp_name = 'ComponentName' self.class_dir = paths[0]",
"self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Page API Name', self.page_name, self.get_label, None, None) def get_label(self,",
"args = ['sfdx', 'force:org:open'] startupinfo = None if os.name == 'nt': startupinfo =",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Event created')",
"input sublime.active_window().show_input_panel('Project Template', self.template, self.create_project_template, None, None) def create_project_template(self, input): self.project_template = input",
"'Pushing Source', 'Source Pushed') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pushed') def is_enabled(self, paths=[]): #dx_folder",
"e: # util.debug('could not format query results\\n', e) file = sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL')",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pushing Source', 'Source Pushed') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source",
"util.isDXProject() == False: return False return True def run_command(self): args = ['sfdx', 'force:org:open']",
"Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) !=",
"def create_org(self, input): printer.show() self.def_file = input t = threading.Thread(target=self.run_command) t.start() t.printer =",
"run(self, edit): self.dx_folder = util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org (leave blank for default)', '', self.run_tests,",
"= 17 Array = 18 symbol_kind_names = { SymbolKind.File: \"file\", SymbolKind.Module: \"module\", SymbolKind.Namespace:",
"the test') return self.event_name = 'TestName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Test Name', self.event_name,",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Page', 'Visualforce Page Created')",
"= ['sfdx', 'force:apex:execute', '-f', self.file_path] startupinfo = None if os.name == 'nt': startupinfo",
"be a list of strings, or a list of string lists. In the",
"'') self.class_name = 'ApexClassName' t = threading.Thread(target=self.run_command) t.start() printer.show() printer.write('\\nRunning Tests') printer.write('\\nResult: ')",
"= os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Component:') printer.write('\\n'",
"== 0: printer.write('\\nLightning Component created') file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp') sublime.active_window().open_file(file)",
"time.localtime()) ThreadProgress(t, 'Creating Lightning Test', 'Lightning Interface Test') printer.write('\\nCreating Lightning Test') printer.write('\\nResult: ')",
"args = ['sfdx', 'force:source:push'] startupinfo = None if os.name == 'nt': startupinfo =",
"create_page(self, input): self.page_label = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"err == '': printErr = out printer.write('\\nError running apex') printer.write('\\n' + str(printErr, 'utf-8'))",
"input printer.show() printer.write('\\nRunning Org Tests') printer.write('\\nResult: ') t = threading.Thread(target=self.run_command) t.start() t.printer =",
"ThreadProgress(t, 'Opening Org', 'Org Opened') printer.write('\\nOpening Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Org Opened') def",
"os.path.isfile(paths[0])): return False return True def create_event(self, input): self.event_name = input printer.show() t",
"as e: # util.debug('could not format query results\\n', e) file = sublime.active_window().new_file() file.set_scratch(True)",
"'w+') as file_obj: file_obj.write(self.selection) printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start() t.printer",
"printer.show() printer.write('\\nPlease select a single folder save the class') return self.app_name = 'AppName'",
"'-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo =",
"0: printer.write('\\nScratch org created') else: printer.write('\\nError creating scratch org') printer.write('\\n' + str(err, 'utf-8'))",
"= json.loads(content) # content = json.dumps(parsed, sort_keys=True,indent=1, separators=(',', ':')) # util.debug(content) #except Exception",
"\"linux\" in sys.platform or \"darwin\" in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener): def",
"= paths[0] sublime.active_window().show_input_panel( 'Class Name', self.class_name, self.create_class, None, None) def is_enabled(self, paths=[]): #dx_folder",
"Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths)",
"[item.get(\"name\"), kind] return [item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand): def run(self, edit, text, erase=False, *args, **kwargs):",
"= util.dxProjectFolder() args = ['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo =",
"= p.returncode if p.returncode == 0: printer.write('\\nLightning Event created') file = os.path.join(self.class_dir, self.event_name,",
"view) def on_close(self, view): EventHub.publish('on_close', view) def on_load_async(self, view): EventHub.publish('on_load_async', view) def on_activated_async(self,",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Event', 'Lightning",
"from .lib.languageServer import * from .lib.event_hub import EventHub from .lib.util import util from",
"def on_window_commad(self, window, command_name, args): if command_name == 'exit': plugin_unloaded() class EventHandlers(sublime_plugin.EventListener): def",
"Org', 'Org Opened') printer.write('\\nOpening Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Org Opened') def is_enabled(self, paths=[]):",
"> 0 and os.path.isfile(paths[0])): return False return True def create_event(self, input): self.event_name =",
"def on_pre_close(self, view): EventHub.publish('on_pre_close', view) def on_close(self, view): EventHub.publish('on_close', view) def on_load_async(self, view):",
"Name', self.project_name, self.create_project_name, None, None) def create_project_name(self, input): self.project_name = input sublime.active_window().show_input_panel('Project Template',",
"printer.write('\\nProject created') else: printer.write('\\nError creating project:') printer.write('\\n' + str(out, 'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def",
"'force:visualforce:component:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if os.name == 'nt':",
"str(printErr, 'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org (leave",
"= 'AppName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.app_name, self.create_app, None, None) def",
"is None and len(self.test_org) > 0: args.push('-u') args.push(self.input) startupinfo = None if os.name",
"self.page_name = input sublime.active_window().show_input_panel( 'Page Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]):",
"False: return False return True def run_command(self): args = ['sfdx', 'force:apex:execute', '-f', self.file_path]",
"# return [item.get(\"name\"), kind] return [item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand): def run(self, edit, text, erase=False,",
"*args, **kwargs): size = self.view.size() self.view.set_read_only(False) if erase == True: size = sublime.Region(0,",
"') PanelThreadProgress(t, 'Lightning App Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx',",
"the component') return self.cmp_name = 'ComponentName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.cmp_name,",
"p.returncode if p.returncode == 0: printer.write('\\nOpening results file') content = str(out,'UTF-8') #try: #",
"\"module\", SymbolKind.Namespace: \"namespace\", SymbolKind.Package: \"package\", SymbolKind.Class: \"class\", SymbolKind.Method: \"method\", SymbolKind.Function: \"function\", SymbolKind.Field: \"field\",",
"else: printErr = err if err is None or err == '': printErr",
"file = sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL') syntax_path = None if \"linux\" in sys.platform or",
"printer.write('\\nVisaulforce Component created') file = os.path.join(self.class_dir, self.page_name + '.component') sublime.active_window().open_file(file) else: printer.write('\\nError creating",
"'Creating Lightning Interface', 'Lightning Interface Created') printer.write('\\nCreating Lightning Interface') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning",
"save the class') return self.event_name = 'EventName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Event Name',",
"'force:apex:execute', '-f', self.file_path] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"is_enabled(self): return True def description(self): return class WriteOperationStatus(sublime_plugin.TextCommand): def run(self, edit, text, *args,",
"self.active_file.endswith('.cls'): return False if not util.file_is_test(self.window.active_view()): return False return True def run_command(self): args",
"format_symbol(item): \"\"\" items may be a list of strings, or a list of",
"args = ['sfdx', 'force:lightning:event:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name",
"global lsClient global printer if util.dxProjectFolder() != '': lsClient = start_client() if lsClient",
"self.cmp_name, self.create_cmp, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"p.returncode == 0: printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if err",
"return False return True def run_query(self, input): self.query = input printer.show() t =",
"client = lsClient if not client: return completionProvider = client.get_capability('completionProvider') if not completionProvider:",
"DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nDevHub authorized')",
"if util.dxProjectFolder() != '': lsClient = start_client() if lsClient is None: util.debug('Unable start",
"run') printer.write('\\nRunning query') printer.write('\\nResult: ') PanelThreadProgress(t, 'Query run') def run_command(self): dx_folder = util.dxProjectFolder()",
"') t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d %b",
"else: printer.write('\\nError running query:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]):",
"#except Exception as e: # util.debug('could not format query results\\n', e) file =",
"self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Component Label',",
"is_visible(self): return False def is_enabled(self): return True def description(self): return # not ready",
"def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human'] if not self.test_org is None",
"'Lightning Interface Test') printer.write('\\nCreating Lightning Test') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Test Created') def",
"Test Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:test:create', '-n', self.event_name,",
"return False if not util.file_is_test(self.window.active_view()): return False return True def run_command(self): args =",
"run(self): sublime.active_window().show_input_panel( 'Query', '', self.run_query, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"Lightning Test') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Test Created') def run_command(self): dx_folder = util.dxProjectFolder()",
"'tmpFile.cls') with open(self.file_path, 'w+') as file_obj: file_obj.write(self.selection) printer.show() self.namespace = input t =",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1",
"Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) !=",
"self.active_file = util.active_file() self.active_file = ntpath.split(self.active_file)[ 1].replace('.cls', '') self.class_name = 'ApexClassName' t =",
"'Org (leave blank for default)', '', self.run_tests, None, None) def run_tests(self, input): self.test_org",
"else: printErr = err if not err is None and not err ==",
"0]) status_region = sublime.Region(kw_region[0], kw_region[1]) size = self.view.size() self.view.set_read_only(False) self.view.replace(edit, status_region, text) self.view.set_read_only(True)",
"self.dx_folder = util.dxProjectFolder() self.active_file = util.active_file() self.active_file = ntpath.split(self.active_file)[ 1].replace('.cls', '') self.class_name =",
"paths[0] sublime.active_window().show_input_panel( 'Component API Name', self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name",
"self.project_path = input sublime.active_window().show_input_panel( 'Project Namespace', '', self.create_project, None, None) def create_project(self, input):",
"file') if \"linux\" in sys.platform or \"darwin\" in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class",
"= [] items = response[\"items\"] if isinstance(response, dict) else response for item in",
"for file') if \"linux\" in sys.platform or \"darwin\" in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\"))",
"query', 'Query run') printer.write('\\nRunning query') printer.write('\\nResult: ') PanelThreadProgress(t, 'Query run') def run_command(self): dx_folder",
"self.page_label, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"edit, text, *args, **kwargs): kw_region = kwargs.get('region', [0, 0]) status_region = sublime.Region(kw_region[0], kw_region[1])",
"if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select",
"0: printer.write('\\nLightning Test created') file = os.path.join(self.class_dir, self.event_name + '.resource') sublime.active_window().open_file(file) else: printer.write('\\nError",
"Lightning Event', 'Lightning Event Created') printer.write('\\nCreating Lightning Event') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Event",
"self.class_name = 'ApexClassName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Class Name', self.class_name, self.create_class, None, None)",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Event',",
"printErr = err if not err is None and not err == '':",
"self.cmp_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"= os.path.join(self.class_dir, self.event_name + '.resource') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Test:') printer.write('\\n' +",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:test:create', '-n', self.event_name, '-d', self.class_dir]",
"printer.write('\\nRunning Org Tests') printer.write('\\nResult: ') t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW",
"'disable_auto_insert': True, 'api_completions_only': False, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True, }) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self):",
"util.dxProjectFolder() self.active_file = util.active_file() self.active_file = ntpath.split(self.active_file)[ 1].replace('.cls', '') self.class_name = 'ApexClassName' t",
"+ str(out, 'utf-8')) else: printErr = err if not err is None and",
"EventHub.publish('on_window_command', window, command_name, *args) def on_modified_async(self, view): active_file_extension = util.file_extension(view) if active_file_extension !=",
"Class = 5 Method = 6 Property = 7 Field = 8 Constructor",
"#detail = format_symbol(detail) insertText = label if item.get(\"insertTextFormat\") == 2: insertText = item.get(\"insertText\")",
"= p.returncode if p.returncode == 0: printer.write('\\nLightning Test created') file = os.path.join(self.class_dir, self.event_name",
"self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Interface Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]):",
"+ str(err, 'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start()",
"= ['sfdx', 'force:visualforce:component:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if os.name",
"') PanelThreadProgress(t, 'Project Upgraded') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"= format_symbol(detail) insertText = label if item.get(\"insertTextFormat\") == 2: insertText = item.get(\"insertText\") if",
"1 or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_class(self,",
"the quick panel will show multiple rows \"\"\" # file_path = uri_to_filename(location.get(\"uri\")) #",
"str(err, 'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths)",
"'-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"'.evt') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Event:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand):",
"= p.returncode if p.returncode == 0: printer.write('\\nProject upgraded') else: printer.write('\\nError upgrading project:') printer.write('\\n'",
"command_name == 'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_modified_async(self,",
"self.cmp_name + '.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8'))",
"self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Page Label',",
"file_obj: file_obj.write(self.selection) printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"Constant = 14 String = 15 Number = 16 Boolean = 17 Array",
"or err == '': printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand):",
"0: printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if not err is",
"return True def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:auth:web:login', '-d', '-s',",
"hover_zone): EventHub.publish('on_hover', view, point, hover_zone) def on_window_command(self, window, command_name, *args): if command_name ==",
"App:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) !=",
"component') return self.page_name = 'ComponentName' self.page_label = 'Component Label' self.class_dir = paths[0] sublime.active_window().show_input_panel(",
"sublime.active_window().show_input_panel( 'Interface Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject() ==",
"'Component Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0 and",
"self.class_name + '.cls') sublime.active_window().open_file(file) else: printer.write('\\nError creating Apex Class:') printer.write('\\n' + str(err, 'utf-8'))",
"self.project_path = '' self.namespace = None sublime.active_window().show_input_panel( 'Project Name', self.project_name, self.create_project_name, None, None)",
"format_completion(self, item) -> 'Tuple[str, str]': label = item.get(\"label\") # kind = item.get(\"kind\") detail",
"self.namespace is not None and self.namespace != '': args.push('-s') args.push(self.namespace) startupinfo = None",
"'-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo",
"# not ready for code completion yet lsClient = None printer = None",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Project', 'Project Created') printer.write('\\nCreating Project') printer.write('\\nResult:",
"== True: size = sublime.Region(0, self.view.size()) self.view.replace(edit, size, text) else: self.view.insert(edit, size, text)",
"*args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_modified_async(self, view): active_file_extension = util.file_extension(view) if",
"return autocomplete_triggers = completionProvider.get('triggerCharacters') if locations[0] > 0: self.completions = [] purge_did_change(view.buffer_id()) client.send_request(",
"for default)', '', self.run_tests, None, None) def run_tests(self, input): self.test_org = input printer.show()",
"source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder()",
"'ComponentName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.cmp_name, self.create_cmp, None, None) def is_enabled(self,",
"= util.dxProjectFolder() args = ['sfdx', 'force:lightning:interface:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None",
"printer.write('\\nCreating Lightning App') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning App Created') def run_command(self): dx_folder =",
"view): EventHub.publish('on_close', view) def on_load_async(self, view): EventHub.publish('on_load_async', view) def on_activated_async(self, view): EventHub.publish('on_activated_async', view)",
"printer.show() printer.write('\\nPlease select a single folder save the component') return self.cmp_name = 'ComponentName'",
"== 'exit': plugin_unloaded() class EventHandlers(sublime_plugin.EventListener): def __init__(self): self.completions = [] # type: List[Tuple[str,",
"self.app_name + '.app') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning App:') printer.write('\\n' + str(err, 'utf-8'))",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Apex Class', 'Apex Class Created') printer.write('\\nCreating Apex",
"kind = item.get(\"kind\") detail = item.get(\"kind\") detail = format_symbol_kind(detail) #detail = format_symbol(detail) insertText",
"== False: return False return True def run_query(self, input): self.query = input printer.show()",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running query',",
"\"package\", SymbolKind.Class: \"class\", SymbolKind.Method: \"method\", SymbolKind.Function: \"function\", SymbolKind.Field: \"field\", SymbolKind.Variable: \"variable\", SymbolKind.Constant: \"constant\"",
"p.returncode if p.returncode == 0: printer.write('\\nScratch org opened') else: printer.write('\\nError opening') printer.write('\\n' +",
"['sfdx', 'force:project:create', '-n', self.project_name, '-t', self.template, '-d', self.project_path] if self.namespace is not None",
"DxmateOutputText(sublime_plugin.TextCommand): def run(self, edit, text, erase=False, *args, **kwargs): size = self.view.size() self.view.set_read_only(False) if",
"'Component API Name', self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name = input",
"15 Number = 16 Boolean = 17 Array = 18 symbol_kind_names = {",
"window, command_name, args): if command_name == 'exit': plugin_unloaded() class EventHandlers(sublime_plugin.EventListener): def __init__(self): self.completions",
"err == '': printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def",
"'force:lightning:test:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo",
"needs leading '$' escaped. insertText = '\\$' + insertText[1:] return (\"{}\\t{}\".format(label, detail), insertText)",
"os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE,",
"def is_enabled(self, paths=[]): if util.isDXProject() == False: return False if len(paths) != 1",
"'\\$' + insertText[1:] return (\"{}\\t{}\".format(label, detail), insertText) def handle_response(self, response): self.completions = []",
"= json.dumps(parsed, sort_keys=True,indent=1, separators=(',', ':')) # util.debug(content) #except Exception as e: # util.debug('could",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Event', 'Lightning Event Created') printer.write('\\nCreating Lightning Event')",
"edit): self.dx_folder = util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"results file') content = str(out,'UTF-8') #try: # parsed = json.loads(content) # content =",
"def run_command(self): args = ['sfdx', 'force:apex:execute', '-f', self.file_path] startupinfo = None if os.name",
"False, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True, }) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self): self.dx_folder = util.dxProjectFolder()",
"ntpath.split(self.active_file)[ 1].replace('.cls', '') self.class_name = 'ApexClassName' t = threading.Thread(target=self.run_command) t.start() printer.show() printer.write('\\nRunning Tests')",
"str(out, 'utf-8')) else: printErr = err if err is None or err ==",
"DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer",
"Lightning Event:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths)",
"ThreadProgress(t, 'Pushing Source', 'Source Pushed') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pushed') def is_enabled(self, paths=[]):",
"False: return False return True def run_command(self): args = ['sfdx', 'force:org:create', '-f', self.def_file,",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running query', 'Query",
"Component Created') printer.write('\\nCreating Visualforce Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Component Created') def run_command(self):",
"False: return False return True def run_command(self): args = ['sfdx', 'force:org:open'] startupinfo =",
"1 or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_cmp(self,",
"os.path.isfile(paths[0])): return False return True def create_class(self, input): self.class_name = input printer.show() t",
"sublime.active_window().show_input_panel( 'Test Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if util.isDXProject() ==",
"return True def run_command(self): args = ['sfdx', 'force:org:create', '-f', self.def_file, '-a', 'ScratchOrg', '-s']",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Event', 'Lightning Event Created') printer.write('\\nCreating Lightning Event') printer.write('\\nResult:",
"= p.returncode if p.returncode == 0: printer.write('\\nOpening results file') content = str(out,'UTF-8') #try:",
"printer = None def plugin_loaded(): global lsClient global printer if util.dxProjectFolder() != '':",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nDevHub authorized') else:",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running tests', 'Tests run') PanelThreadProgress(t, 'Running",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Auth Page', 'Auth Page",
"printer.write('\\nError creating Lightning Interface:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self, paths=[]):",
"'Lightning Event Created') printer.write('\\nCreating Lightning Event') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Event Created') def",
"= ['sfdx', 'force:lightning:test:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name ==",
"sys import json import mdpopups import time from collections import OrderedDict from .lib.printer",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Interface', 'Lightning",
"= edit self.project_name = '' self.template = 'Defaultsfdx-project.json' self.project_path = '' self.namespace =",
"folder to save the page') return self.page_name = 'PageName' self.page_label = 'Page Label'",
"text, erase=False, *args, **kwargs): size = self.view.size() self.view.set_read_only(False) if erase == True: size",
"view) def on_query_completions(self, view, prefix, locations): active_file_extension = util.file_extension(view) if active_file_extension != '.cls'",
"str(err, 'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths)",
"os.path.isfile(paths[0])): return False return True def create_cmp(self, input): self.cmp_name = input printer.show() t",
"strings, or a list of string lists. In the latter case, each entry",
"SymbolKind.Module: \"module\", SymbolKind.Namespace: \"namespace\", SymbolKind.Package: \"package\", SymbolKind.Class: \"class\", SymbolKind.Method: \"method\", SymbolKind.Function: \"function\", SymbolKind.Field:",
"input sublime.active_window().show_input_panel( 'Page Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder =",
"return True def create_page(self, input): self.page_label = input printer.show() t = threading.Thread(target=self.run_command) t.start()",
"PanelThreadProgress(t, 'Running Tests') def is_enabled(self): self.dx_folder = util.dxProjectFolder() if(self.dx_folder == ''): return False",
"printer.write('\\nOpening results file') content = str(out,'UTF-8') #try: # parsed = json.loads(content) # content",
"return True def create_cmp(self, input): self.cmp_name = input printer.show() t = threading.Thread(target=self.run_command) t.start()",
"paths[0] sublime.active_window().show_input_panel( 'Class Name', self.class_name, self.create_class, None, None) def is_enabled(self, paths=[]): #dx_folder =",
"os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the class') return self.event_name =",
"return False if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])): return",
"os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Component:') printer.write('\\n' +",
"lsClient = None printer = None def plugin_loaded(): global lsClient global printer if",
"args.push('-s') args.push(self.namespace) startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags",
"printer.write('\\nResult: ') t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())",
"def run(self, edit): self.dx_folder = util.dxProjectFolder() sublime.active_window().show_input_panel( 'Org (leave blank for default)', '',",
"the page') return self.page_name = 'PageName' self.page_label = 'Page Label' self.class_dir = paths[0]",
"0: self.completions = [] purge_did_change(view.buffer_id()) client.send_request( Request.complete( util.get_document_position(view, locations[0])), self.handle_response) self.refreshing = False",
"paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False if len(paths) !=",
"sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def",
"False return True def create_cmp(self, input): self.cmp_name = input printer.show() t = threading.Thread(target=self.run_command)",
"sublime needs leading '$' escaped. insertText = '\\$' + insertText[1:] return (\"{}\\t{}\".format(label, detail),",
"upgraded') else: printer.write('\\nError upgrading project:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self,",
"is_enabled(self, paths=[]): if util.isDXProject() == False: return False util.debug(paths) if len(paths) != 1",
"self.def_file, '-a', 'ScratchOrg', '-s'] startupinfo = None if os.name == 'nt': startupinfo =",
"file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Component:')",
"run') PanelThreadProgress(t, 'Running Org Tests') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"'DevHub'] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"= util.dxProjectFolder() if util.isDXProject() == False: return False return True def run_query(self, input):",
"else: printer.write('\\nError creating Lightning Test:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self,",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Auth Page', 'Auth Page Opened')",
"size, text) self.view.set_read_only(True) self.view.show(size) def is_visible(self): return False def is_enabled(self): return True def",
"os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the class') return self.app_name =",
"Name', self.app_name, self.create_app, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return",
"set_syntax(view): if util.is_apex_file(view): util.debug('setting syntax for file') if \"linux\" in sys.platform or \"darwin\"",
"'App Name', self.cmp_name, self.create_cmp, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"Created') printer.write('\\nCreating Lightning Event') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Event Created') def run_command(self): dx_folder",
"sublime.active_window().show_input_panel( 'Project Namespace', '', self.create_project, None, None) def create_project(self, input): printer.show() self.namespace =",
"args.push(self.input) startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"def description(self): return # not ready for code completion yet lsClient = None",
"return symbol_kind_names.get(kind, str(kind)) def format_symbol(item): \"\"\" items may be a list of strings,",
"Apex Class') printer.write('\\nResult: ') PanelThreadProgress(t, 'Apex Class Created') def run_command(self): dx_folder = util.dxProjectFolder()",
"args = ['sfdx', 'force:data:soql:query', '-q', self.query] startupinfo = None if os.name == 'nt':",
"None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return False if len(paths)",
"self.template, self.create_project_template, None, None) def create_project_template(self, input): self.project_template = input sublime.active_window().show_input_panel('Project Path', self.project_path,",
"printer.show() self.def_file = input t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"self.class_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"18 symbol_kind_names = { SymbolKind.File: \"file\", SymbolKind.Module: \"module\", SymbolKind.Namespace: \"namespace\", SymbolKind.Package: \"package\", SymbolKind.Class:",
"p.returncode == 0: printer.write('\\nScratch org opened') else: printer.write('\\nError opening') printer.write('\\n' + str(err, 'utf-8'))",
"and active_file_extension != '.trigger': return None EventHub.publish(\"on_modified_async\", view) def on_query_completions(self, view, prefix, locations):",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pushing Source', 'Source",
"query') printer.write('\\nResult: ') PanelThreadProgress(t, 'Query run') def run_command(self): dx_folder = util.dxProjectFolder() args =",
"entry in the quick panel will show multiple rows \"\"\" # file_path =",
"view): EventHub.publish('on_activated_async', view) def on_post_save_async(self, view): EventHub.publish('on_post_save_async', view) def on_close(self, view): EventHub.publish('on_close', view)",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:event:create', '-n', self.event_name, '-d', self.class_dir]",
"item.get(\"kind\") detail = item.get(\"kind\") detail = format_symbol_kind(detail) #detail = format_symbol(detail) insertText = label",
"Tests', 'Org tests run') PanelThreadProgress(t, 'Running Org Tests') def is_enabled(self, paths=[]): #dx_folder =",
"EventHub.subscribe('on_load_async', set_syntax) active_window_id = sublime.active_window().id() printer = PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin loaded\", erase=True) def",
"insertText = item.get(\"insertText\") if insertText[0] == '$': # sublime needs leading '$' escaped.",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir]",
"= item.get(\"kind\") detail = format_symbol_kind(detail) #detail = format_symbol(detail) insertText = label if item.get(\"insertTextFormat\")",
"apex') printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if err is None",
"= ['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if os.name",
"+ str(err, 'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or",
"on_activated_async(self, view): EventHub.publish('on_activated_async', view) def on_post_save_async(self, view): EventHub.publish('on_post_save_async', view) def on_close(self, view): EventHub.publish('on_close',",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:component:create', '-n', self.cmp_name, '-d', self.class_dir]",
"EventHub from .lib.util import util from .lib.diagnostic import * import ntpath class SymbolKind(object):",
"True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human', '-l', 'RunSpecifiedTests', '-n', self.class_name]",
"False return True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human', '-l', 'RunSpecifiedTests',",
"#dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False if len(paths) != 1",
"def on_close(self, view): EventHub.publish('on_close', view) def on_hover(self, view, point, hover_zone): EventHub.publish('on_hover', view, point,",
"yet lsClient = None printer = None def plugin_loaded(): global lsClient global printer",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nScratch org created')",
"p.returncode if p.returncode == 0: printer.write('\\nScratch org created') else: printer.write('\\nError creating scratch org')",
"PanelThreadProgress(t, 'Query run') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:data:soql:query', '-q',",
"select a single folder save the test') return self.event_name = 'TestName' self.class_dir =",
"panel will show multiple rows \"\"\" # file_path = uri_to_filename(location.get(\"uri\")) # kind =",
"== '$': # sublime needs leading '$' escaped. insertText = '\\$' + insertText[1:]",
"self.cmp_name, self.cmp_name + '.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err,",
"= 'ApexClassName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Class Name', self.class_name, self.create_class, None, None) def",
"create_app(self, input): self.app_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"util.dxProjectFolder() printer.show() printer.write('\\nPushing Source') t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"':')) # util.debug(content) #except Exception as e: # util.debug('could not format query results\\n',",
"tests', 'Tests run') PanelThreadProgress(t, 'Running Tests') def is_enabled(self): self.dx_folder = util.dxProjectFolder() if(self.dx_folder ==",
"p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder) p.wait() out, err = p.communicate() r",
"Package = 4 Class = 5 Method = 6 Property = 7 Field",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning",
"lsClient: lsClient.kill() def set_syntax(view): if util.is_apex_file(view): util.debug('setting syntax for file') if \"linux\" in",
"file.run_command(\"insert\", {\"characters\":content}) else: printer.write('\\nError running query:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def",
"'Running query', 'Query run') printer.write('\\nRunning query') printer.write('\\nResult: ') PanelThreadProgress(t, 'Query run') def run_command(self):",
"err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nLightning Component created')",
"command_name, *args) def on_modified_async(self, view): active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and",
"True def create_cmp(self, input): self.cmp_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer",
"'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) >",
"input): self.page_name = input sublime.active_window().show_input_panel( 'Page Label', self.page_label, self.create_page, None, None) def is_enabled(self,",
"SymbolKind.Variable: \"variable\", SymbolKind.Constant: \"constant\" } def format_symbol_kind(kind): return symbol_kind_names.get(kind, str(kind)) def format_symbol(item): \"\"\"",
"else: printer.write('\\nError creating Lightning Event:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self,",
"['sfdx', 'force:apex:test:run', '-r', 'human'] if not self.test_org is None and len(self.test_org) > 0:",
"printer.write('\\nLightning Interface created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.intf') sublime.active_window().open_file(file) else: printer.write('\\nError",
"p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nOpening",
"\"field\", SymbolKind.Variable: \"variable\", SymbolKind.Constant: \"constant\" } def format_symbol_kind(kind): return symbol_kind_names.get(kind, str(kind)) def format_symbol(item):",
"True def run_query(self, input): self.query = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer",
"Visualforce Component', 'Visualforce Component Created') printer.write('\\nCreating Visualforce Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Component",
"view, point, hover_zone) def on_window_command(self, window, command_name, *args): if command_name == 'exit': EventHub.publish('exit',",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Page', 'Visualforce",
"purge_did_change(view.buffer_id()) client.send_request( Request.complete( util.get_document_position(view, locations[0])), self.handle_response) self.refreshing = False return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS |",
"p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce",
"and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the component') return self.cmp_name",
"= util.file_extension(view) if active_file_extension != '.cls' and active_file_extension != '.trigger': return None EventHub.publish(\"on_modified_async\",",
"') PanelThreadProgress(t, 'Lightning Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx',",
"creating Visualforce page:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if",
"EventHub.publish(\"on_modified_async\", view) def on_query_completions(self, view, prefix, locations): active_file_extension = util.file_extension(view) if active_file_extension !=",
"DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() printer.write('\\nPushing Source') t = threading.Thread(target=self.run_command)",
"printer.write('\\nCreating Apex Class') printer.write('\\nResult: ') PanelThreadProgress(t, 'Apex Class Created') def run_command(self): dx_folder =",
"''): return False self.active_file = util.active_file() if not self.active_file.endswith('.cls'): return False if not",
"= sublime.Region(kw_region[0], kw_region[1]) size = self.view.size() self.view.set_read_only(False) self.view.replace(edit, status_region, text) self.view.set_read_only(True) # self.view.show(size)",
"Org', 'Scratch Org Created') printer.write('\\nCreatin Scratch Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Scratch Org Created')",
"return False return True def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:auth:web:login',",
"save the component') return self.page_name = 'ComponentName' self.page_label = 'Component Label' self.class_dir =",
"'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True, }) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self): self.dx_folder = util.dxProjectFolder() self.active_file",
"select a single folder save the class') return self.event_name = 'EventName' self.class_dir =",
"self.file_path] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"the component') return self.page_name = 'ComponentName' self.page_label = 'Component Label' self.class_dir = paths[0]",
"*args) elif command_name == 'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name, *args)",
"'': args.push('-s') args.push(self.namespace) startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"= 'ComponentName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.cmp_name, self.create_cmp, None, None) def",
"= sublime.active_window().new_file() file.set_scratch(True) file.set_name('SOQL') syntax_path = None if \"linux\" in sys.platform or \"darwin\"",
"> 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the interface')",
"8 Constructor = 9 Enum = 10 Interface = 11 Function = 12",
"None, None) def create_project_name(self, input): self.project_name = input sublime.active_window().show_input_panel('Project Template', self.template, self.create_project_template, None,",
"format_symbol_kind(kind): return symbol_kind_names.get(kind, str(kind)) def format_symbol(item): \"\"\" items may be a list of",
"util.dxProjectFolder() args = ['sfdx', 'force:lightning:interface:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if",
"select a single folder save the class') return self.class_name = 'ApexClassName' self.class_dir =",
"input): self.page_name = input sublime.active_window().show_input_panel( 'Component Label', self.page_label, self.create_page, None, None) def is_enabled(self,",
"and os.path.isfile(paths[0])): return False return True def create_page(self, input): self.page_label = input printer.show()",
"(len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_cmp(self, input): self.cmp_name",
"command_name, *args) def on_text_command(self, window, command_name, *args): if command_name == 'exit': EventHub.publish('exit', window,",
"'Visualforce Component Created') printer.write('\\nCreating Visualforce Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Component Created') def",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:interface:create', '-n', self.event_name, '-d', self.class_dir]",
"p.returncode if p.returncode == 0: printer.write('\\nDevHub authorized') else: printer.write('\\nError authorizing Dev Hub:') printer.write('\\n'",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Interface', 'Lightning Interface Created') printer.write('\\nCreating Lightning",
"class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0",
"> 0: args.push('-u') args.push(self.input) startupinfo = None if os.name == 'nt': startupinfo =",
"input): self.event_name = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"'Running Org Tests', 'Org tests run') PanelThreadProgress(t, 'Running Org Tests') def is_enabled(self, paths=[]):",
"region.empty(): self.selection += self.view.substr(region) if self.selection == '': self.selection = self.view.substr(sublime.Region(0, self.view.size())) self.file_path",
"'utf-8')) class DxmateCreateLightningAppCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) >",
"'-n', self.class_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo =",
"self.namespace = input t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a,",
"\"constant\" } def format_symbol_kind(kind): return symbol_kind_names.get(kind, str(kind)) def format_symbol(item): \"\"\" items may be",
"'Visualforce Page Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:page:create', '-n',",
"== 0: printer.write('\\nLightning Test created') file = os.path.join(self.class_dir, self.event_name + '.resource') sublime.active_window().open_file(file) else:",
"create_project_namespace(self, input): self.project_path = input sublime.active_window().show_input_panel( 'Project Namespace', '', self.create_project, None, None) def",
"import json import mdpopups import time from collections import OrderedDict from .lib.printer import",
"creating project:') printer.write('\\n' + str(out, 'UTF-8')) class DxmateExecuteAnonymousApexCommand(sublime_plugin.TextCommand): def run(self, edit): self.selection =",
"def run(self, edit): self.edit = edit self.project_name = '' self.template = 'Defaultsfdx-project.json' self.project_path",
"size = self.view.size() self.view.set_read_only(False) self.view.replace(edit, status_region, text) self.view.set_read_only(True) # self.view.show(size) def is_visible(self): return",
"from collections import OrderedDict from .lib.printer import PanelPrinter from .lib.threads import ThreadProgress from",
"True def description(self): return class WriteOperationStatus(sublime_plugin.TextCommand): def run(self, edit, text, *args, **kwargs): kw_region",
"from .lib.threads import PanelThreadProgress from .lib.languageServer import * from .lib.event_hub import EventHub from",
"out else: printer.write('\\nError pulling source') printer.write('\\n' + str(printErr, 'utf-8')) class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self,",
"if not self.test_org is None and len(self.test_org) > 0: args.push('-u') args.push(self.input) startupinfo =",
"sublime.active_window().show_input_panel( 'Page Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"creating Lightning App:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if",
"and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder save the class') return self.class_name",
"self.run_tests, None, None) def run_tests(self, input): self.test_org = input printer.show() printer.write('\\nRunning Org Tests')",
"r = p.returncode if p.returncode == 0: printer.write('\\nLightning Test created') file = os.path.join(self.class_dir,",
"self.page_name = 'ComponentName' self.page_label = 'Component Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Component API",
"False: return False return True def run_query(self, input): self.query = input printer.show() t",
"return # not ready for code completion yet lsClient = None printer =",
"self.page_label = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"| sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self, item) -> 'Tuple[str, str]': label = item.get(\"label\") # kind",
"+ str(printErr, 'utf-8')) class DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t",
"'.app') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning App:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand):",
"kw_region = kwargs.get('region', [0, 0]) status_region = sublime.Region(kw_region[0], kw_region[1]) size = self.view.size() self.view.set_read_only(False)",
"[item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand): def run(self, edit, text, erase=False, *args, **kwargs): size = self.view.size()",
"= 1 Module = 2 Namespace = 3 Package = 4 Class =",
"input): printer.show() self.def_file = input t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id",
"'Lightning Component Created') printer.write('\\nCreating Lightning Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Component Created') def",
"type: List[Tuple[str, str]] self.refreshing = False def on_pre_close(self, view): EventHub.publish('on_pre_close', view) def on_close(self,",
"self.view.size() self.view.set_read_only(False) if erase == True: size = sublime.Region(0, self.view.size()) self.view.replace(edit, size, text)",
"return self.event_name = 'InterfaceName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Interface Name', self.event_name, self.create_event, None,",
"item) -> 'Tuple[str, str]': label = item.get(\"label\") # kind = item.get(\"kind\") detail =",
"'Lightning App Created') printer.write('\\nCreating Lightning App') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning App Created') def",
"= 'InterfaceName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Interface Name', self.event_name, self.create_event, None, None) def",
"Page Opened') printer.write('\\nOpening Auth Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Auth Page Opened') def is_enabled(self,",
"self.def_file, self.create_org, None, None) def create_org(self, input): printer.show() self.def_file = input t =",
"= util.dxProjectFolder() if util.isDXProject() == False: return False if len(paths) != 1 or",
"if not err is None and not err == '': printErr = out",
"') t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t,",
"= threading.Thread(target=self.run_command) t.start() printer.show() printer.write('\\nRunning Tests') printer.write('\\nResult: ') t.printer = printer t.process_id =",
"'Scratch Org Created') printer.write('\\nCreatin Scratch Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Scratch Org Created') def",
"self.handle_response) self.refreshing = False return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self, item) ->",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Scratch Org', 'Scratch Org Created')",
"self.event_name + '.intf') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Interface:') printer.write('\\n' + str(err, 'utf-8'))",
"self.selection == '': self.selection = self.view.substr(sublime.Region(0, self.view.size())) self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls') with",
"run') PanelThreadProgress(t, 'Running Tests') def is_enabled(self): self.dx_folder = util.dxProjectFolder() if(self.dx_folder == ''): return",
"text, *args, **kwargs): kw_region = kwargs.get('region', [0, 0]) status_region = sublime.Region(kw_region[0], kw_region[1]) size",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pushing Source',",
"'.component') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand):",
"self.get_label, None, None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Page Label', self.page_label,",
"= None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p",
"sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand): def",
"'force:lightning:component:create', '-n', self.cmp_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo",
"query:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) !=",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:data:soql:query', '-q', self.query] startupinfo = None",
"= 'TestName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Test Name', self.event_name, self.create_event, None, None) def",
"prefix, locations): active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and active_file_extension != '.trigger':",
"p.returncode if p.returncode == 0: printer.write('\\nApex class created') file = os.path.join(self.class_dir, self.class_name +",
"= ['sfdx', 'force:apex:test:run', '-r', 'human', '-l', 'RunSpecifiedTests', '-n', self.class_name] startupinfo = None if",
"Path', self.project_path, self.create_project_namespace, None, None) def create_project_namespace(self, input): self.project_path = input sublime.active_window().show_input_panel( 'Project",
"return class WriteOperationStatus(sublime_plugin.TextCommand): def run(self, edit, text, *args, **kwargs): kw_region = kwargs.get('region', [0,",
"def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False if",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Auth Page',",
"'PageName' self.page_label = 'Page Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Page API Name', self.page_name,",
"time.localtime()) ThreadProgress(t, 'Creating Scratch Org', 'Scratch Org Created') printer.write('\\nCreatin Scratch Org') printer.write('\\nResult: ')",
"ThreadProgress(t, 'Creating Lightning Test', 'Lightning Interface Test') printer.write('\\nCreating Lightning Test') printer.write('\\nResult: ') PanelThreadProgress(t,",
"!= '': args.push('-s') args.push(self.namespace) startupinfo = None if os.name == 'nt': startupinfo =",
"= ['sfdx', 'force:lightning:event:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name ==",
"self.edit = edit self.project_name = '' self.template = 'Defaultsfdx-project.json' self.project_path = '' self.namespace",
"|= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait() out,err = p.communicate() r",
"self.view.set_read_only(False) self.view.replace(edit, status_region, text) self.view.set_read_only(True) # self.view.show(size) def is_visible(self): return False def is_enabled(self):",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Page', 'Visualforce Page Created') printer.write('\\nCreating Visualforce Page')",
"printer = PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin loaded\", erase=True) def plugin_unloaded(): if lsClient: lsClient.kill() def",
"!= '': lsClient = start_client() if lsClient is None: util.debug('Unable start langauge server')",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running tests', 'Tests run') PanelThreadProgress(t,",
"= subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait()",
"False def is_enabled(self): return True def description(self): return # not ready for code",
"DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() self.def_file = os.path.join( self.dx_folder, 'config', 'project-scratch-def.json')",
"dict) else response for item in items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def run_auto_complete(self): self.refreshing",
"self.view.replace(edit, size, text) else: self.view.insert(edit, size, text) self.view.set_read_only(True) self.view.show(size) def is_visible(self): return False",
"err == '': printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand): def",
"paths=[]): if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease",
"class') return self.class_name = 'ApexClassName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Class Name', self.class_name, self.create_class,",
"False return True def run_command(self): args = ['sfdx', 'force:org:create', '-f', self.def_file, '-a', 'ScratchOrg',",
"printer.write('\\nDevHub authorized') else: printer.write('\\nError authorizing Dev Hub:') printer.write('\\n' + str(err, 'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand):",
"PanelThreadProgress(t, 'Anonymous apex run') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"PanelThreadProgress(t, 'Lightning Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:component:create',",
"def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False return",
"printer.write(\"sfdx plugin loaded\", erase=True) def plugin_unloaded(): if lsClient: lsClient.kill() def set_syntax(view): if util.is_apex_file(view):",
"class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"= util.active_file() if not self.active_file.endswith('.cls'): return False if not util.file_is_test(self.window.active_view()): return False return",
"#dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False return True def run_query(self,",
"def set_syntax(view): if util.is_apex_file(view): util.debug('setting syntax for file') if \"linux\" in sys.platform or",
"= util.dxProjectFolder() args = ['sfdx', 'force:visualforce:component:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo =",
"printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running Org Tests',",
"None and self.namespace != '': args.push('-s') args.push(self.namespace) startupinfo = None if os.name ==",
"= 11 Function = 12 Variable = 13 Constant = 14 String =",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Component', 'Lightning Component",
"str(err, 'utf-8')) class DxmateCreateLightningEventCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths)",
"None) def create_project_template(self, input): self.project_template = input sublime.active_window().show_input_panel('Project Path', self.project_path, self.create_project_namespace, None, None)",
"'.cmp') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Component:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningTestCommand(sublime_plugin.WindowCommand):",
"created') file = os.path.join(self.class_dir, self.page_name + '.page') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce page:')",
"kind] return [item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand): def run(self, edit, text, erase=False, *args, **kwargs): size",
"text) self.view.set_read_only(True) # self.view.show(size) def is_visible(self): return False def is_enabled(self): return True def",
"import sublime import sublime_plugin import os import subprocess import threading import sys import",
"* import ntpath class SymbolKind(object): File = 1 Module = 2 Namespace =",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Project', 'Project Created') printer.write('\\nCreating Project')",
"ThreadProgress(t, 'Creating Lightning Interface', 'Lightning Interface Created') printer.write('\\nCreating Lightning Interface') printer.write('\\nResult: ') PanelThreadProgress(t,",
"paths[0] sublime.active_window().show_input_panel( 'App Name', self.app_name, self.create_app, None, None) def is_enabled(self, paths=[]): if util.isDXProject()",
"= [] # type: List[Tuple[str, str]] self.refreshing = False def on_pre_close(self, view): EventHub.publish('on_pre_close',",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command)",
"= printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce",
"args = ['sfdx', 'force:visualforce:component:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if",
"os.path.join(self.class_dir, self.page_name + '.component') sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce Component:') printer.write('\\n' + str(err,",
"sublime.active_window().open_file(file) else: printer.write('\\nError creating Apex Class:') printer.write('\\n' + str(err, 'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def",
"created') file = os.path.join(self.class_dir, self.class_name + '.cls') sublime.active_window().open_file(file) else: printer.write('\\nError creating Apex Class:')",
"None, None) def get_label(self, input): self.page_name = input sublime.active_window().show_input_panel( 'Component Label', self.page_label, self.create_page,",
"printer.show() printer.write('\\nRunning Org Tests') printer.write('\\nResult: ') t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nScratch org created') else:",
"'config', 'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class Name', self.def_file, self.create_org, None, None) def create_org(self, input): printer.show()",
"printer.write('\\nResult: ') t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d",
"in the quick panel will show multiple rows \"\"\" # file_path = uri_to_filename(location.get(\"uri\"))",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Org', 'Org Opened') printer.write('\\nOpening Org') printer.write('\\nResult:",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nScratch org opened') else:",
"'Lightning Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:component:create', '-n',",
"|= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err =",
"leading '$' escaped. insertText = '\\$' + insertText[1:] return (\"{}\\t{}\".format(label, detail), insertText) def",
"single folder save the class') return self.event_name = 'EventName' self.class_dir = paths[0] sublime.active_window().show_input_panel(",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Project', 'Project Created') printer.write('\\nCreating Project') printer.write('\\nResult: ')",
"out printer.write('\\n' + str(printErr, 'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder()",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:app:create', '-n', self.app_name, '-d', self.class_dir] startupinfo =",
"'utf-8')) class DxmateAuthDevHubCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer =",
"None if \"linux\" in sys.platform or \"darwin\" in sys.platform: syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else:",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce Component",
"Lightning Test:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths)",
"the interface') return self.event_name = 'InterfaceName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Interface Name', self.event_name,",
"['sfdx', 'force:auth:web:login', '-d', '-s', '-a', 'DevHub'] startupinfo = None if os.name == 'nt':",
"creating Apex Class:') printer.write('\\n' + str(err, 'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show()",
"self.create_cmp, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"class DxmatePullSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command) t.start()",
"and os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder to save the page') return",
".lib.threads import PanelThreadProgress from .lib.languageServer import * from .lib.event_hub import EventHub from .lib.util",
"p.returncode == 0: printer.write('\\nProject upgraded') else: printer.write('\\nError upgrading project:') printer.write('\\n' + str(err, 'utf-8'))",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:event:create', '-n', self.event_name, '-d', self.class_dir] startupinfo",
"printErr = err if err is None or err == '': printErr =",
"subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) p.wait() out,err =",
"class DxmateOpenScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command) t.start()",
"self.query] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"= p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nFinished running apex') printer.write('\\n'",
"= 'PageName' self.page_label = 'Page Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Page API Name',",
"if command_name == 'exit': plugin_unloaded() class EventHandlers(sublime_plugin.EventListener): def __init__(self): self.completions = [] #",
"p.returncode == 0: printer.write('\\nLightning Test created') file = os.path.join(self.class_dir, self.event_name + '.resource') sublime.active_window().open_file(file)",
"PanelThreadProgress(t, 'Org Opened') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"str]': label = item.get(\"label\") # kind = item.get(\"kind\") detail = item.get(\"kind\") detail =",
"or err == '': printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand):",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Interface', 'Lightning Interface Created') printer.write('\\nCreating Lightning Interface')",
"0: printer.write('\\nApex class created') file = os.path.join(self.class_dir, self.class_name + '.cls') sublime.active_window().open_file(file) else: printer.write('\\nError",
"self.app_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"Visualforce Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Page Created') def run_command(self): dx_folder = util.dxProjectFolder()",
"list of strings, or a list of string lists. In the latter case,",
"return self.page_name = 'ComponentName' self.page_label = 'Component Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Component",
"') PanelThreadProgress(t, 'Source Pushed') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() ==",
"== 0: printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if err is",
"'api_completions_only': False, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True, }) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self): self.dx_folder =",
"args = ['sfdx', 'force:lightning:app:create', '-n', self.app_name, '-d', self.class_dir] startupinfo = None if os.name",
"return False return True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human'] if",
"return True def run_query(self, input): self.query = input printer.show() t = threading.Thread(target=self.run_command) t.start()",
"return False util.debug(paths) if len(paths) != 1 or (len(paths) > 0 and os.path.isfile(paths[0])):",
"p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nFinished",
"Number = 16 Boolean = 17 Array = 18 symbol_kind_names = { SymbolKind.File:",
"detail = item.get(\"kind\") detail = format_symbol_kind(detail) #detail = format_symbol(detail) insertText = label if",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Component', 'Visualforce Component Created')",
"r = p.returncode if p.returncode == 0: printer.write('\\nLightning Interface created') file = os.path.join(self.class_dir,",
"ThreadProgress from .lib.threads import PanelThreadProgress from .lib.languageServer import * from .lib.event_hub import EventHub",
"os.path.isfile(paths[0])): return False return True def create_page(self, input): self.page_label = input printer.show() t",
"printer.write('\\nPlease select a single folder to save the component') return self.page_name = 'ComponentName'",
"(len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_app(self, input): self.app_name",
"'Creating Lightning App', 'Lightning App Created') printer.write('\\nCreating Lightning App') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning",
"if not util.file_is_test(self.window.active_view()): return False return True def run_command(self): args = ['sfdx', 'force:apex:test:run',",
"'.cls') sublime.active_window().open_file(file) else: printer.write('\\nError creating Apex Class:') printer.write('\\n' + str(err, 'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand):",
"self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"printer.show() printer.write('\\nPlease select a single folder to save the page') return self.page_name =",
"r = p.returncode if p.returncode == 0: printer.write('\\nLightning Event created') file = os.path.join(self.class_dir,",
"str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths)",
"return True def run_command(self): args = ['sfdx', 'force:source:push'] startupinfo = None if os.name",
"Page Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l',",
"printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if err is None or",
"DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0 and",
"time.localtime()) ThreadProgress(t, 'Upgrading Project', 'Project Upgraded') printer.write('\\nUpgrading Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Upgraded')",
"def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() printer.write('\\nPushing Source') t = threading.Thread(target=self.run_command) t.start()",
"Method = 6 Property = 7 Field = 8 Constructor = 9 Enum",
"0 and os.path.isfile(paths[0])): return False return True def create_cmp(self, input): self.cmp_name = input",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:auth:web:login', '-d', '-s', '-a', 'DevHub'] startupinfo",
"None) def run_tests(self, input): self.test_org = input printer.show() printer.write('\\nRunning Org Tests') printer.write('\\nResult: ')",
"'Page Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Page API Name', self.page_name, self.get_label, None, None)",
"class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) > 0",
"4 Class = 5 Method = 6 Property = 7 Field = 8",
"'AppName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.app_name, self.create_app, None, None) def is_enabled(self,",
"p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r",
"format_symbol_kind(detail) #detail = format_symbol(detail) insertText = label if item.get(\"insertTextFormat\") == 2: insertText =",
"ThreadProgress(t, 'Pulling Source', 'Source Pulled') printer.write('\\nPulling Source') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pulled') def",
"= [] purge_did_change(view.buffer_id()) client.send_request( Request.complete( util.get_document_position(view, locations[0])), self.handle_response) self.refreshing = False return self.completions,",
"sublime.active_window().show_input_panel('Project Template', self.template, self.create_project_template, None, None) def create_project_template(self, input): self.project_template = input sublime.active_window().show_input_panel('Project",
"self.event_name = 'TestName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Test Name', self.event_name, self.create_event, None, None)",
"0: printer.write('\\nLightning Interface created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.intf') sublime.active_window().open_file(file) else:",
"def plugin_unloaded(): if lsClient: lsClient.kill() def set_syntax(view): if util.is_apex_file(view): util.debug('setting syntax for file')",
"format_symbol_kind(item.get(\"kind\")) # return [item.get(\"name\"), kind] return [item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand): def run(self, edit, text,",
"sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener): def on_window_commad(self, window, command_name, args): if command_name",
"list of string lists. In the latter case, each entry in the quick",
"self.event_name, self.event_name + '.evt') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Event:') printer.write('\\n' + str(err,",
"tests run') PanelThreadProgress(t, 'Running Org Tests') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"False return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self, item) -> 'Tuple[str, str]': label",
"Project', 'Project Created') printer.write('\\nCreating Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Created') def run_command(self): args",
"import util from .lib.diagnostic import * import ntpath class SymbolKind(object): File = 1",
"= p.returncode if p.returncode == 0: printer.write('\\nLightning App created') file = os.path.join(self.class_dir, self.app_name,",
"'human'] if not self.test_org is None and len(self.test_org) > 0: args.push('-u') args.push(self.input) startupinfo",
"None printer = None def plugin_loaded(): global lsClient global printer if util.dxProjectFolder() !=",
"= util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a,",
"'auto_complete_commit_on_tab': True, }) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self): self.dx_folder = util.dxProjectFolder() self.active_file = util.active_file()",
"or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_cmp(self, input):",
"def is_enabled(self): return True def description(self): return # not ready for code completion",
"not ready for code completion yet lsClient = None printer = None def",
"printer.write('\\nError creating Apex Class:') printer.write('\\n' + str(err, 'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self, edit):",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Pulling Source', 'Source Pulled') printer.write('\\nPulling Source') printer.write('\\nResult:",
"= subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder) p.wait() out, err = p.communicate() r =",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Component', 'Lightning Component Created') printer.write('\\nCreating",
"def run(self, edit): self.dx_folder = util.dxProjectFolder() self.def_file = os.path.join( self.dx_folder, 'config', 'project-scratch-def.json') sublime.active_window().show_input_panel(",
"printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Upgrading Project', 'Project Upgraded')",
"!= 1 or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def",
"Pushed') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return False",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running anonymous apex', 'Anonymous apex run') printer.write('\\nRunning anonymous apex')",
"= 'Page Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Page API Name', self.page_name, self.get_label, None,",
"Created') printer.write('\\nCreatin Scratch Org') printer.write('\\nResult: ') PanelThreadProgress(t, 'Scratch Org Created') def is_enabled(self, paths=[]):",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Event', 'Lightning Event",
"Module = 2 Namespace = 3 Package = 4 Class = 5 Method",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nProject upgraded')",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running anonymous apex', 'Anonymous",
"self.class_name] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |=",
"if p.returncode == 0: printer.write('\\nProject upgraded') else: printer.write('\\nError upgrading project:') printer.write('\\n' + str(err,",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder) p.wait() out, err = p.communicate() r = p.returncode if",
"= 14 String = 15 Number = 16 Boolean = 17 Array =",
"+ str(printErr, 'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() printer.write('\\nPushing",
"item.get(\"kind\") detail = format_symbol_kind(detail) #detail = format_symbol(detail) insertText = label if item.get(\"insertTextFormat\") ==",
"'Project Upgraded') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False: return",
"p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\n' + str(out, 'utf-8')) else:",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning App', 'Lightning App Created')",
"printer.write('\\nPlease select a single folder save the class') return self.app_name = 'AppName' self.class_dir",
"printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Interface Created') def run_command(self): dx_folder = util.dxProjectFolder() args =",
"%H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Scratch Org', 'Scratch Org Created') printer.write('\\nCreatin Scratch Org') printer.write('\\nResult:",
"import ntpath class SymbolKind(object): File = 1 Module = 2 Namespace = 3",
"return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self, item) -> 'Tuple[str, str]': label =",
"None and not err == '': printErr = out else: printer.write('\\nError pulling source')",
"Interface Created') printer.write('\\nCreating Lightning Interface') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Interface Created') def run_command(self):",
"def run(self, edit, text, *args, **kwargs): kw_region = kwargs.get('region', [0, 0]) status_region =",
"= p.returncode if p.returncode == 0: printer.write('\\nScratch org created') else: printer.write('\\nError creating scratch",
"* from .lib.event_hub import EventHub from .lib.util import util from .lib.diagnostic import *",
"util.file_is_test(self.window.active_view()): return False return True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human',",
"not err == '': printErr = out else: printer.write('\\nError pushing source') printer.write('\\n' +",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Visualforce Component', 'Visualforce Component Created') printer.write('\\nCreating Visualforce",
"'Anonymous apex run') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"edit): self.edit = edit self.project_name = '' self.template = 'Defaultsfdx-project.json' self.project_path = ''",
"return self.page_name = 'PageName' self.page_label = 'Page Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Page",
"syntax_path = None if \"linux\" in sys.platform or \"darwin\" in sys.platform: syntax_path =",
"# parsed = json.loads(content) # content = json.dumps(parsed, sort_keys=True,indent=1, separators=(',', ':')) # util.debug(content)",
"== 'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_modified_async(self, view):",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:project:upgrade', '-f'] startupinfo = None if os.name",
"self.project_name = '' self.template = 'Defaultsfdx-project.json' self.project_path = '' self.namespace = None sublime.active_window().show_input_panel(",
"printer.write('\\nPlease select a single folder save the test') return self.event_name = 'TestName' self.class_dir",
"= response[\"items\"] if isinstance(response, dict) else response for item in items: self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete')",
"sublime.active_window().open_file(file) else: printer.write('\\nError creating Visualforce page:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def",
"class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() self.def_file = os.path.join( self.dx_folder, 'config',",
"None or err == '': printErr = out printer.write('\\nError running apex') printer.write('\\n' +",
"self.project_path, self.create_project_namespace, None, None) def create_project_namespace(self, input): self.project_path = input sublime.active_window().show_input_panel( 'Project Namespace',",
"subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder) p.wait() out, err = p.communicate()",
"quick panel will show multiple rows \"\"\" # file_path = uri_to_filename(location.get(\"uri\")) # kind",
"paths=[]): if util.isDXProject() == False: return False util.debug(paths) if len(paths) != 1 or",
"= None sublime.active_window().show_input_panel( 'Project Name', self.project_name, self.create_project_name, None, None) def create_project_name(self, input): self.project_name",
"def run_command(self): args = ['sfdx', 'force:org:open'] startupinfo = None if os.name == 'nt':",
"'utf-8')) class DxmatePushSourceCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder = util.dxProjectFolder() printer.show() printer.write('\\nPushing Source') t",
"None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return False util.debug(paths) if len(paths)",
"'Source Pushed') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pushed') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"folder save the test') return self.event_name = 'TestName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Test",
"running query:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateVisualforceComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths)",
"= paths[0] sublime.active_window().show_input_panel( 'Interface Name', self.event_name, self.create_event, None, None) def is_enabled(self, paths=[]): if",
"on_close(self, view): EventHub.publish('on_close', view) def on_hover(self, view, point, hover_zone): EventHub.publish('on_hover', view, point, hover_zone)",
"self.completions.append(self.format_completion(item)) sublime.active_window().active_view().run_command('hide_auto_complete') self.run_auto_complete() def run_auto_complete(self): self.refreshing = True sublime.active_window().active_view().run_command( \"auto_complete\", { 'disable_auto_insert': True,",
"or (len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_event(self, input):",
"class SymbolKind(object): File = 1 Module = 2 Namespace = 3 Package =",
"args = ['sfdx', 'force:project:create', '-n', self.project_name, '-t', self.template, '-d', self.project_path] if self.namespace is",
"self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.cmp_name, self.create_cmp, None, None) def is_enabled(self, paths=[]):",
"else: printer.write('\\nError upgrading project:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self, edit):",
"t.printer = printer t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running",
"p.returncode if p.returncode == 0: printer.write('\\n' + str(out, 'utf-8')) else: printErr = err",
"= time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Org', 'Org Opened') printer.write('\\nOpening",
"if util.isDXProject() == False: return False return True def run_command(self): dx_folder = util.dxProjectFolder()",
"+ str(err, 'utf-8')) class DxmateUpgradeProjectCommand(sublime_plugin.TextCommand): def run(self, edit): printer.show() t = threading.Thread(target=self.run_command) t.start()",
"= os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls') with open(self.file_path, 'w+') as file_obj: file_obj.write(self.selection) printer.show() self.namespace =",
"os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder to save the component') return self.page_name",
"> 0 and os.path.isfile(paths[0])): return False return True def create_cmp(self, input): self.cmp_name =",
"= completionProvider.get('triggerCharacters') if locations[0] > 0: self.completions = [] purge_did_change(view.buffer_id()) client.send_request( Request.complete( util.get_document_position(view,",
"return False return True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human', '-l',",
"out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nVisaulforce page",
"return self.event_name = 'EventName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Event Name', self.event_name, self.create_event, None,",
"[] items = response[\"items\"] if isinstance(response, dict) else response for item in items:",
"self.cmp_name = 'ComponentName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name', self.cmp_name, self.create_cmp, None, None)",
"17 Array = 18 symbol_kind_names = { SymbolKind.File: \"file\", SymbolKind.Module: \"module\", SymbolKind.Namespace: \"namespace\",",
"on_window_commad(self, window, command_name, args): if command_name == 'exit': plugin_unloaded() class EventHandlers(sublime_plugin.EventListener): def __init__(self):",
"['sfdx', 'force:apex:test:run', '-r', 'human', '-l', 'RunSpecifiedTests', '-n', self.class_name] startupinfo = None if os.name",
"self.app_name, self.create_app, None, None) def is_enabled(self, paths=[]): if util.isDXProject() == False: return False",
"Project', 'Project Upgraded') printer.write('\\nUpgrading Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Upgraded') def is_enabled(self, paths=[]):",
"App Created') printer.write('\\nCreating Lightning App') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning App Created') def run_command(self):",
"\"method\", SymbolKind.Function: \"function\", SymbolKind.Field: \"field\", SymbolKind.Variable: \"variable\", SymbolKind.Constant: \"constant\" } def format_symbol_kind(kind): return",
"+ str(err, 'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self, edit): self.edit = edit self.project_name =",
"p.returncode if p.returncode == 0: printer.write('\\nLightning Interface created') file = os.path.join(self.class_dir, self.event_name, self.event_name",
"Event', 'Lightning Event Created') printer.write('\\nCreating Lightning Event') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Event Created')",
"on_query_completions(self, view, prefix, locations): active_file_extension = util.file_extension(view) if active_file_extension != '.cls' and active_file_extension",
"\"function\", SymbolKind.Field: \"field\", SymbolKind.Variable: \"variable\", SymbolKind.Constant: \"constant\" } def format_symbol_kind(kind): return symbol_kind_names.get(kind, str(kind))",
"[0, 0]) status_region = sublime.Region(kw_region[0], kw_region[1]) size = self.view.size() self.view.set_read_only(False) self.view.replace(edit, status_region, text)",
"WriteOperationStatus(sublime_plugin.TextCommand): def run(self, edit, text, *args, **kwargs): kw_region = kwargs.get('region', [0, 0]) status_region",
"os.path.isfile(paths[0])): printer.show() printer.write('\\nPlease select a single folder to save the page') return self.page_name",
"False return True def create_class(self, input): self.class_name = input printer.show() t = threading.Thread(target=self.run_command)",
"insertText = '\\$' + insertText[1:] return (\"{}\\t{}\".format(label, detail), insertText) def handle_response(self, response): self.completions",
"run_query(self, input): self.query = input printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer",
"printer.write('\\nPlease select a single folder save the interface') return self.event_name = 'InterfaceName' self.class_dir",
"= 13 Constant = 14 String = 15 Number = 16 Boolean =",
"and not err == '': printErr = out else: printer.write('\\nError pulling source') printer.write('\\n'",
"'Query run') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:data:soql:query', '-q', self.query]",
"== '': self.selection = self.view.substr(sublime.Region(0, self.view.size())) self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls') with open(self.file_path,",
"if util.is_apex_file(view): util.debug('setting syntax for file') if \"linux\" in sys.platform or \"darwin\" in",
"printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self, edit): self.edit = edit self.project_name",
"printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if not err is None",
"util.file_extension(view) if active_file_extension != '.cls' and active_file_extension != '.trigger': return None if not",
"None if not self.refreshing: client = lsClient if not client: return completionProvider =",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running query', 'Query run') printer.write('\\nRunning query') printer.write('\\nResult: ')",
"util.dxProjectFolder() args = ['sfdx', 'force:lightning:app:create', '-n', self.app_name, '-d', self.class_dir] startupinfo = None if",
"def description(self): return class WriteOperationStatus(sublime_plugin.TextCommand): def run(self, edit, text, *args, **kwargs): kw_region =",
"else: self.view.insert(edit, size, text) self.view.set_read_only(True) self.view.show(size) def is_visible(self): return False def is_enabled(self): return",
"'.resource') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Test:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateLightningInterfaceCommand(sublime_plugin.WindowCommand):",
"run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:test:create', '-n', self.event_name, '-d', self.class_dir] startupinfo",
"\"namespace\", SymbolKind.Package: \"package\", SymbolKind.Class: \"class\", SymbolKind.Method: \"method\", SymbolKind.Function: \"function\", SymbolKind.Field: \"field\", SymbolKind.Variable: \"variable\",",
"'RunSpecifiedTests', '-n', self.class_name] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO()",
"Source', 'Source Pulled') printer.write('\\nPulling Source') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pulled') def is_enabled(self, paths=[]):",
"return True def run_command(self): args = ['sfdx', 'force:apex:execute', '-f', self.file_path] startupinfo = None",
"'Lightning Interface Created') printer.write('\\nCreating Lightning Interface') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Interface Created') def",
"(\"{}\\t{}\".format(label, detail), insertText) def handle_response(self, response): self.completions = [] items = response[\"items\"] if",
"os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls') with open(self.file_path, 'w+') as file_obj: file_obj.write(self.selection) printer.show() self.namespace = input",
"to save the component') return self.page_name = 'ComponentName' self.page_label = 'Component Label' self.class_dir",
"Pushed') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pushed') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if",
"# type: List[Tuple[str, str]] self.refreshing = False def on_pre_close(self, view): EventHub.publish('on_pre_close', view) def",
"self.dx_folder = util.dxProjectFolder() printer.show() t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id =",
"util.dxProjectFolder() if util.isDXProject() == False: return False return True def run_query(self, input): self.query",
"from .lib.printer import PanelPrinter from .lib.threads import ThreadProgress from .lib.threads import PanelThreadProgress from",
"else: printer.write('\\nError opening') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateScratchOrgCommand(sublime_plugin.TextCommand): def run(self, edit): self.dx_folder",
"client.send_request( Request.complete( util.get_document_position(view, locations[0])), self.handle_response) self.refreshing = False return self.completions, (sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)",
"str(err, 'utf-8')) class DxmateCreateProjectCommand(sublime_plugin.TextCommand): def run(self, edit): self.edit = edit self.project_name = ''",
"['sfdx', 'force:lightning:test:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt':",
"time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning Interface', 'Lightning Interface Created')",
"== '': printErr = out printer.write('\\n' + str(printErr, 'utf-8')) class DxmateRunOrgTestsCommand(sublime_plugin.TextCommand): def run(self,",
"+ str(err, 'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or",
"p.returncode == 0: printer.write('\\nLightning Component created') file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp')",
"False return True def create_event(self, input): self.event_name = input printer.show() t = threading.Thread(target=self.run_command)",
"'force:project:create', '-n', self.project_name, '-t', self.template, '-d', self.project_path] if self.namespace is not None and",
"paths[0] sublime.active_window().show_input_panel( 'Page API Name', self.page_name, self.get_label, None, None) def get_label(self, input): self.page_name",
"class WriteOperationStatus(sublime_plugin.TextCommand): def run(self, edit, text, *args, **kwargs): kw_region = kwargs.get('region', [0, 0])",
"True, }) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self): self.dx_folder = util.dxProjectFolder() self.active_file = util.active_file() self.active_file",
"if p.returncode == 0: printer.write('\\nLightning Test created') file = os.path.join(self.class_dir, self.event_name + '.resource')",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning App', 'Lightning App Created') printer.write('\\nCreating Lightning",
"== False: return False return True def run_command(self): dx_folder = util.dxProjectFolder() args =",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label, '-d',",
"dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:component:create', '-n', self.cmp_name, '-d', self.class_dir] startupinfo =",
"PanelPrinter.get(active_window_id) printer.write(\"sfdx plugin loaded\", erase=True) def plugin_unloaded(): if lsClient: lsClient.kill() def set_syntax(view): if",
"def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:project:upgrade', '-f'] startupinfo = None",
"(sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) def format_completion(self, item) -> 'Tuple[str, str]': label = item.get(\"label\") #",
"file = os.path.join(self.class_dir, self.event_name, self.event_name + '.evt') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Event:')",
"'Anonymous apex run') printer.write('\\nRunning anonymous apex') printer.write('\\nResult: ') PanelThreadProgress(t, 'Anonymous apex run') def",
"'force:apex:class:create', '-n', self.class_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo",
"= False def on_pre_close(self, view): EventHub.publish('on_pre_close', view) def on_close(self, view): EventHub.publish('on_close', view) def",
"== 2: insertText = item.get(\"insertText\") if insertText[0] == '$': # sublime needs leading",
"edit): self.dx_folder = util.dxProjectFolder() self.def_file = os.path.join( self.dx_folder, 'config', 'project-scratch-def.json') sublime.active_window().show_input_panel( 'Class Name',",
"['sfdx', 'force:data:soql:query', '-q', self.query] startupinfo = None if os.name == 'nt': startupinfo =",
"return False return True def run_command(self): args = ['sfdx', 'force:org:create', '-f', self.def_file, '-a',",
"Component Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:component:create', '-n', self.page_name,'-l',",
"PanelThreadProgress(t, 'Source Pulled') def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject() == False:",
"p.returncode if p.returncode == 0: printer.write('\\nVisaulforce Component created') file = os.path.join(self.class_dir, self.page_name +",
"Pulled') printer.write('\\nPulling Source') printer.write('\\nResult: ') PanelThreadProgress(t, 'Source Pulled') def is_enabled(self, paths=[]): #dx_folder =",
"= subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r =",
"folder save the interface') return self.event_name = 'InterfaceName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Interface",
"created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.evt') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning",
"p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\\nProject",
"str(err, 'utf-8')) class DxmateCreateVisualforcePageCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths)",
"= uri_to_filename(location.get(\"uri\")) # kind = format_symbol_kind(item.get(\"kind\")) # return [item.get(\"name\"), kind] return [item.get(\"name\")] class",
"Org Tests', 'Org tests run') PanelThreadProgress(t, 'Running Org Tests') def is_enabled(self, paths=[]): #dx_folder",
"['sfdx', 'force:apex:execute', '-f', self.file_path] startupinfo = None if os.name == 'nt': startupinfo =",
"Name', self.cmp_name, self.create_cmp, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
"r = p.returncode if p.returncode == 0: printer.write('\\nScratch org opened') else: printer.write('\\nError opening')",
"Created') printer.write('\\nCreating Visualforce Page') printer.write('\\nResult: ') PanelThreadProgress(t, 'Visualforce Page Created') def run_command(self): dx_folder",
"== '': printErr = out else: printer.write('\\nError pulling source') printer.write('\\n' + str(printErr, 'utf-8'))",
"sublime.active_window().show_input_panel( 'Class Name', self.class_name, self.create_class, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder()",
"args = ['sfdx', 'force:project:upgrade', '-f'] startupinfo = None if os.name == 'nt': startupinfo",
"else: EventHub.publish('on_window_command', window, command_name, *args) def on_modified_async(self, view): active_file_extension = util.file_extension(view) if active_file_extension",
"EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_text_command(self, window, command_name, *args):",
"if \"linux\" in sys.platform or \"darwin\" in sys.platform: view.set_syntax_file(os.path.join(\"Packages\",util.plugin_name(),\"sublime\",\"lang\",\"Apex.sublime-syntax\")) else: view.set_syntax_file(os.path.join(\"Packages/\"+util.plugin_name()+\"/sublime/lang/Apex.sublime-syntax\")) class ExitHandler(sublime_plugin.EventListener):",
"False, 'auto_complete_commit_on_tab': True, }) class DxmateRunFileTestsCommand(sublime_plugin.WindowCommand): def run(self): self.dx_folder = util.dxProjectFolder() self.active_file =",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning App', 'Lightning App Created') printer.write('\\nCreating Lightning App')",
"single folder save the class') return self.class_name = 'ApexClassName' self.class_dir = paths[0] sublime.active_window().show_input_panel(",
"if p.returncode == 0: printer.write('\\nScratch org opened') else: printer.write('\\nError opening') printer.write('\\n' + str(err,",
"Test', 'Lightning Interface Test') printer.write('\\nCreating Lightning Test') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Test Created')",
"printer.write('\\nCreating Lightning Component') printer.write('\\nResult: ') PanelThreadProgress(t, 'Lightning Component Created') def run_command(self): dx_folder =",
"True def run_command(self): args = ['sfdx', 'force:org:create', '-f', self.def_file, '-a', 'ScratchOrg', '-s'] startupinfo",
"%b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Opening Org', 'Org Opened') printer.write('\\nOpening Org') printer.write('\\nResult: ')",
"else: printer.write('\\nError creating Lightning App:') printer.write('\\n' + str(err, 'utf-8')) class DxmateCreateApexClassCommand(sublime_plugin.WindowCommand): def run(self,",
"syntax_path = os.path.join(\"Packages\",plugin_name(),\"sublime\",\"lang\",\"JSON.tmLanguage\") else: syntax_path = os.path.join(\"Packages/\"+plugin_name()+\"/sublime/lang/JSON.tmLanguage\") #file.set_syntax_file(syntax_path) file.run_command(\"insert\", {\"characters\":content}) else: printer.write('\\nError running",
"run_command(self): args = ['sfdx', 'force:org:open'] startupinfo = None if os.name == 'nt': startupinfo",
"Label', self.page_label, self.create_page, None, None) def is_enabled(self, paths=[]): #dx_folder = util.dxProjectFolder() if util.isDXProject()",
".lib.printer import PanelPrinter from .lib.threads import ThreadProgress from .lib.threads import PanelThreadProgress from .lib.languageServer",
"stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode",
"if p.returncode == 0: printer.write('\\nVisaulforce page created') file = os.path.join(self.class_dir, self.page_name + '.page')",
"r = p.returncode if p.returncode == 0: printer.write('\\nOpening results file') content = str(out,'UTF-8')",
"%Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Scratch Org', 'Scratch Org Created') printer.write('\\nCreatin Scratch Org')",
"p.returncode == 0: printer.write('\\nVisaulforce page created') file = os.path.join(self.class_dir, self.page_name + '.page') sublime.active_window().open_file(file)",
"run(self, edit, text, erase=False, *args, **kwargs): size = self.view.size() self.view.set_read_only(False) if erase ==",
"t.process_id = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Running tests', 'Tests run')",
"= 'Component Label' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Component API Name', self.page_name, self.get_label, None,",
"None, None) def create_project(self, input): printer.show() self.namespace = input t = threading.Thread(target=self.run_command) t.start()",
"return True def run_command(self): args = ['sfdx', 'force:apex:test:run', '-r', 'human', '-l', 'RunSpecifiedTests', '-n',",
"subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out,",
"False return True def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:auth:web:login', '-d',",
"def run_command(self): args = ['sfdx', 'force:source:push'] startupinfo = None if os.name == 'nt':",
"return [item.get(\"name\")] class DxmateOutputText(sublime_plugin.TextCommand): def run(self, edit, text, erase=False, *args, **kwargs): size =",
"2: insertText = item.get(\"insertText\") if insertText[0] == '$': # sublime needs leading '$'",
"(len(paths) > 0 and os.path.isfile(paths[0])): return False return True def create_class(self, input): self.class_name",
"'ApexClassName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'Class Name', self.class_name, self.create_class, None, None) def is_enabled(self,",
"save the component') return self.cmp_name = 'ComponentName' self.class_dir = paths[0] sublime.active_window().show_input_panel( 'App Name',",
"None, None) def create_project_namespace(self, input): self.project_path = input sublime.active_window().show_input_panel( 'Project Namespace', '', self.create_project,",
"0: printer.write('\\n' + str(out, 'utf-8')) else: printErr = err if err is None",
"Hub:') printer.write('\\n' + str(err, 'utf-8')) class DxmateRunSoqlCommand(sublime_plugin.WindowCommand): def run(self): sublime.active_window().show_input_panel( 'Query', '', self.run_query,",
"util.file_extension(view) if active_file_extension != '.cls' and active_file_extension != '.trigger': return None EventHub.publish(\"on_modified_async\", view)",
"input sublime.active_window().show_input_panel('Project Path', self.project_path, self.create_project_namespace, None, None) def create_project_namespace(self, input): self.project_path = input",
"'Project Upgraded') printer.write('\\nUpgrading Project') printer.write('\\nResult: ') PanelThreadProgress(t, 'Project Upgraded') def is_enabled(self, paths=[]): #dx_folder",
"p.returncode == 0: printer.write('\\nScratch org created') else: printer.write('\\nError creating scratch org') printer.write('\\n' +",
"command_name == 'exit': plugin_unloaded() class EventHandlers(sublime_plugin.EventListener): def __init__(self): self.completions = [] # type:",
"time.localtime()) ThreadProgress(t, 'Creating Lightning App', 'Lightning App Created') printer.write('\\nCreating Lightning App') printer.write('\\nResult: ')",
"'utf-8')) class DxmateCreateLightningComponentCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) != 1 or (len(paths) >",
"on_post_save_async(self, view): EventHub.publish('on_post_save_async', view) def on_close(self, view): EventHub.publish('on_close', view) def on_hover(self, view, point,",
"self.project_name, '-t', self.template, '-d', self.project_path] if self.namespace is not None and self.namespace !=",
"time.localtime()) ThreadProgress(t, 'Creating Apex Class', 'Apex Class Created') printer.write('\\nCreating Apex Class') printer.write('\\nResult: ')",
"= util.dxProjectFolder() args = ['sfdx', 'force:auth:web:login', '-d', '-s', '-a', 'DevHub'] startupinfo = None",
"%d %b %Y %H:%M:%S\", time.localtime()) ThreadProgress(t, 'Creating Lightning App', 'Lightning App Created') printer.write('\\nCreating",
"file = os.path.join(self.class_dir, self.event_name + '.resource') sublime.active_window().open_file(file) else: printer.write('\\nError creating Lightning Test:') printer.write('\\n'",
"view) def on_load_async(self, view): EventHub.publish('on_load_async', view) def on_activated_async(self, view): EventHub.publish('on_activated_async', view) def on_post_save_async(self,",
"ThreadProgress(t, 'Running anonymous apex', 'Anonymous apex run') printer.write('\\nRunning anonymous apex') printer.write('\\nResult: ') PanelThreadProgress(t,",
"printer.write('\\nScratch org created') else: printer.write('\\nError creating scratch org') printer.write('\\n' + str(err, 'utf-8')) class",
"printer.write('\\nPlease select a single folder save the component') return self.cmp_name = 'ComponentName' self.class_dir",
"True def run_command(self): args = ['sfdx', 'force:apex:execute', '-f', self.file_path] startupinfo = None if",
"return False return True def create_event(self, input): self.event_name = input printer.show() t =",
"t.start() printer.show() printer.write('\\nRunning Tests') printer.write('\\nResult: ') t.printer = printer t.process_id = time.strftime(\"%a, %d",
"is_visible(self): return False def is_enabled(self): return True def description(self): return class WriteOperationStatus(sublime_plugin.TextCommand): def",
"') PanelThreadProgress(t, 'Lightning Interface Created') def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx',",
"= input t = threading.Thread(target=self.run_command) t.start() t.printer = printer t.process_id = time.strftime(\"%a, %d",
"== 'close_window': EventHub.publish('close_window', window, *args) else: EventHub.publish('on_window_command', window, command_name, *args) def on_text_command(self, window,",
"= input sublime.active_window().show_input_panel( 'Project Namespace', '', self.create_project, None, None) def create_project(self, input): printer.show()",
"not self.active_file.endswith('.cls'): return False if not util.file_is_test(self.window.active_view()): return False return True def run_command(self):",
"'-r', 'human'] if not self.test_org is None and len(self.test_org) > 0: args.push('-u') args.push(self.input)",
"|= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=self.dx_folder) p.wait() out, err ="
] |
[] |
[
"np.array(row_vals), delimiter=\",\") np.savetxt(colpath, np.array(col_vals), delimiter=\",\", fmt=\"%s\") return datapath, rowpath, colpath def state_read(datapath, rowpath,",
"labels (ie. name for ith element of state vector) datapath = output_dir +",
"timestamped run directory: data_folder = os.path.join(current_run_folder, \"data\") plot_lattice_folder = os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder =",
"+ sep + dataname + '_' + colname + \".txt\" np.savetxt(datapath, np.array(state), delimiter=\",\",",
"from noneq_settings import RUNS_FOLDER def run_subdir_setup(run_subfolder=None): current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder = current_time",
"sep from noneq_settings import RUNS_FOLDER def run_subdir_setup(run_subfolder=None): current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder =",
"colpath def state_read(datapath, rowpath, colpath): # here row refers to time array and",
"\".txt\" np.savetxt(datapath, np.array(state), delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals), delimiter=\",\") np.savetxt(colpath, np.array(col_vals), delimiter=\",\", fmt=\"%s\") return",
"colpath = output_dir + sep + dataname + '_' + colname + \".txt\"",
"+ sep + dataname + '_' + rowname + \".txt\" colpath = output_dir",
"+ '_' + colname + \".txt\" np.savetxt(datapath, np.array(state), delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals), delimiter=\",\")",
"np import os from os import sep from noneq_settings import RUNS_FOLDER def run_subdir_setup(run_subfolder=None):",
"np.array(col_vals), delimiter=\",\", fmt=\"%s\") return datapath, rowpath, colpath def state_read(datapath, rowpath, colpath): # here",
"= current_time + os.sep if run_subfolder is None: current_run_folder = RUNS_FOLDER + time_folder",
"output_dir + sep + dataname + \".txt\" rowpath = output_dir + sep +",
"RUNS_FOLDER def run_subdir_setup(run_subfolder=None): current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder = current_time + os.sep if",
"refers to gene labels (ie. name for ith element of state vector) state",
"= np.loadtxt(datapath, delimiter=\",\") row = np.loadtxt(rowpath, delimiter=\",\", dtype=float) col = np.loadtxt(colpath, delimiter=\",\", dtype=str)",
"fmt=\"%s\") return datapath, rowpath, colpath def state_read(datapath, rowpath, colpath): # here row refers",
"col refers to gene labels (ie. name for ith element of state vector)",
"'_' + rowname + \".txt\" colpath = output_dir + sep + dataname +",
"delimiter=\",\", fmt=\"%s\") return datapath, rowpath, colpath def state_read(datapath, rowpath, colpath): # here row",
"in dir_list: if not os.path.exists(dirs): os.makedirs(dirs) return current_run_folder, data_folder, plot_lattice_folder, plot_data_folder def state_write(state,",
"labels (ie. name for ith element of state vector) state = np.loadtxt(datapath, delimiter=\",\")",
"ith element of state vector) state = np.loadtxt(datapath, delimiter=\",\") row = np.loadtxt(rowpath, delimiter=\",\",",
"col_vals, dataname, rowname, colname, output_dir): # here row refers to time array and",
"colname, output_dir): # here row refers to time array and col refers to",
"row refers to time array and col refers to gene labels (ie. name",
"= RUNS_FOLDER + run_subfolder + os.sep + time_folder # subfolders in the timestamped",
"vector) datapath = output_dir + sep + dataname + \".txt\" rowpath = output_dir",
"delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals), delimiter=\",\") np.savetxt(colpath, np.array(col_vals), delimiter=\",\", fmt=\"%s\") return datapath, rowpath, colpath",
"current_run_folder = RUNS_FOLDER + run_subfolder + os.sep + time_folder # subfolders in the",
"[RUNS_FOLDER, current_run_folder, data_folder, plot_lattice_folder, plot_data_folder] for dirs in dir_list: if not os.path.exists(dirs): os.makedirs(dirs)",
"run_subfolder + os.sep + time_folder # subfolders in the timestamped run directory: data_folder",
"np.savetxt(rowpath, np.array(row_vals), delimiter=\",\") np.savetxt(colpath, np.array(col_vals), delimiter=\",\", fmt=\"%s\") return datapath, rowpath, colpath def state_read(datapath,",
"is None: current_run_folder = RUNS_FOLDER + time_folder else: current_run_folder = RUNS_FOLDER + run_subfolder",
"if not os.path.exists(dirs): os.makedirs(dirs) return current_run_folder, data_folder, plot_lattice_folder, plot_data_folder def state_write(state, row_vals, col_vals,",
"state_read(datapath, rowpath, colpath): # here row refers to time array and col refers",
"rowpath, colpath def state_read(datapath, rowpath, colpath): # here row refers to time array",
"gene labels (ie. name for ith element of state vector) state = np.loadtxt(datapath,",
"output_dir + sep + dataname + '_' + rowname + \".txt\" colpath =",
"sep + dataname + \".txt\" rowpath = output_dir + sep + dataname +",
"os.path.join(current_run_folder, \"plot_data\") dir_list = [RUNS_FOLDER, current_run_folder, data_folder, plot_lattice_folder, plot_data_folder] for dirs in dir_list:",
"else: current_run_folder = RUNS_FOLDER + run_subfolder + os.sep + time_folder # subfolders in",
"= [RUNS_FOLDER, current_run_folder, data_folder, plot_lattice_folder, plot_data_folder] for dirs in dir_list: if not os.path.exists(dirs):",
"plot_data_folder] for dirs in dir_list: if not os.path.exists(dirs): os.makedirs(dirs) return current_run_folder, data_folder, plot_lattice_folder,",
"current_run_folder, data_folder, plot_lattice_folder, plot_data_folder def state_write(state, row_vals, col_vals, dataname, rowname, colname, output_dir): #",
"row_vals, col_vals, dataname, rowname, colname, output_dir): # here row refers to time array",
"+ \".txt\" np.savetxt(datapath, np.array(state), delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals), delimiter=\",\") np.savetxt(colpath, np.array(col_vals), delimiter=\",\", fmt=\"%s\")",
"import numpy as np import os from os import sep from noneq_settings import",
"'_' + colname + \".txt\" np.savetxt(datapath, np.array(state), delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals), delimiter=\",\") np.savetxt(colpath,",
"rowpath = output_dir + sep + dataname + '_' + rowname + \".txt\"",
"rowname, colname, output_dir): # here row refers to time array and col refers",
"gene labels (ie. name for ith element of state vector) datapath = output_dir",
"current_run_folder, data_folder, plot_lattice_folder, plot_data_folder] for dirs in dir_list: if not os.path.exists(dirs): os.makedirs(dirs) return",
"def run_subdir_setup(run_subfolder=None): current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder = current_time + os.sep if run_subfolder",
"import datetime import numpy as np import os from os import sep from",
"+ \".txt\" rowpath = output_dir + sep + dataname + '_' + rowname",
"+ colname + \".txt\" np.savetxt(datapath, np.array(state), delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals), delimiter=\",\") np.savetxt(colpath, np.array(col_vals),",
"ith element of state vector) datapath = output_dir + sep + dataname +",
"dataname + '_' + colname + \".txt\" np.savetxt(datapath, np.array(state), delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals),",
"+ sep + dataname + \".txt\" rowpath = output_dir + sep + dataname",
"time_folder # subfolders in the timestamped run directory: data_folder = os.path.join(current_run_folder, \"data\") plot_lattice_folder",
"np.array(state), delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals), delimiter=\",\") np.savetxt(colpath, np.array(col_vals), delimiter=\",\", fmt=\"%s\") return datapath, rowpath,",
"of state vector) state = np.loadtxt(datapath, delimiter=\",\") row = np.loadtxt(rowpath, delimiter=\",\", dtype=float) col",
"+ dataname + \".txt\" rowpath = output_dir + sep + dataname + '_'",
"refers to time array and col refers to gene labels (ie. name for",
"to time array and col refers to gene labels (ie. name for ith",
"= datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder = current_time + os.sep if run_subfolder is None: current_run_folder",
"# subfolders in the timestamped run directory: data_folder = os.path.join(current_run_folder, \"data\") plot_lattice_folder =",
"+ run_subfolder + os.sep + time_folder # subfolders in the timestamped run directory:",
"import os from os import sep from noneq_settings import RUNS_FOLDER def run_subdir_setup(run_subfolder=None): current_time",
"+ os.sep + time_folder # subfolders in the timestamped run directory: data_folder =",
"datapath, rowpath, colpath def state_read(datapath, rowpath, colpath): # here row refers to time",
"from os import sep from noneq_settings import RUNS_FOLDER def run_subdir_setup(run_subfolder=None): current_time = datetime.datetime.now().strftime(\"%Y-%m-%d",
"return current_run_folder, data_folder, plot_lattice_folder, plot_data_folder def state_write(state, row_vals, col_vals, dataname, rowname, colname, output_dir):",
"def state_write(state, row_vals, col_vals, dataname, rowname, colname, output_dir): # here row refers to",
"\"plot_lattice\") plot_data_folder = os.path.join(current_run_folder, \"plot_data\") dir_list = [RUNS_FOLDER, current_run_folder, data_folder, plot_lattice_folder, plot_data_folder] for",
"\"plot_data\") dir_list = [RUNS_FOLDER, current_run_folder, data_folder, plot_lattice_folder, plot_data_folder] for dirs in dir_list: if",
"fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals), delimiter=\",\") np.savetxt(colpath, np.array(col_vals), delimiter=\",\", fmt=\"%s\") return datapath, rowpath, colpath def",
"for dirs in dir_list: if not os.path.exists(dirs): os.makedirs(dirs) return current_run_folder, data_folder, plot_lattice_folder, plot_data_folder",
"os from os import sep from noneq_settings import RUNS_FOLDER def run_subdir_setup(run_subfolder=None): current_time =",
"+ time_folder else: current_run_folder = RUNS_FOLDER + run_subfolder + os.sep + time_folder #",
"array and col refers to gene labels (ie. name for ith element of",
"= output_dir + sep + dataname + '_' + rowname + \".txt\" colpath",
"dir_list = [RUNS_FOLDER, current_run_folder, data_folder, plot_lattice_folder, plot_data_folder] for dirs in dir_list: if not",
"current_time + os.sep if run_subfolder is None: current_run_folder = RUNS_FOLDER + time_folder else:",
"to gene labels (ie. name for ith element of state vector) datapath =",
"= os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder = os.path.join(current_run_folder, \"plot_data\") dir_list = [RUNS_FOLDER, current_run_folder, data_folder, plot_lattice_folder,",
"def state_read(datapath, rowpath, colpath): # here row refers to time array and col",
"plot_lattice_folder, plot_data_folder def state_write(state, row_vals, col_vals, dataname, rowname, colname, output_dir): # here row",
"of state vector) datapath = output_dir + sep + dataname + \".txt\" rowpath",
"# here row refers to time array and col refers to gene labels",
"plot_data_folder def state_write(state, row_vals, col_vals, dataname, rowname, colname, output_dir): # here row refers",
"+ time_folder # subfolders in the timestamped run directory: data_folder = os.path.join(current_run_folder, \"data\")",
"dataname + '_' + rowname + \".txt\" colpath = output_dir + sep +",
"= RUNS_FOLDER + time_folder else: current_run_folder = RUNS_FOLDER + run_subfolder + os.sep +",
"not os.path.exists(dirs): os.makedirs(dirs) return current_run_folder, data_folder, plot_lattice_folder, plot_data_folder def state_write(state, row_vals, col_vals, dataname,",
"as np import os from os import sep from noneq_settings import RUNS_FOLDER def",
"output_dir): # here row refers to time array and col refers to gene",
"the timestamped run directory: data_folder = os.path.join(current_run_folder, \"data\") plot_lattice_folder = os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder",
"if run_subfolder is None: current_run_folder = RUNS_FOLDER + time_folder else: current_run_folder = RUNS_FOLDER",
"subfolders in the timestamped run directory: data_folder = os.path.join(current_run_folder, \"data\") plot_lattice_folder = os.path.join(current_run_folder,",
"+ dataname + '_' + colname + \".txt\" np.savetxt(datapath, np.array(state), delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath,",
"\".txt\" rowpath = output_dir + sep + dataname + '_' + rowname +",
"sep + dataname + '_' + colname + \".txt\" np.savetxt(datapath, np.array(state), delimiter=\",\", fmt=\"%d\")",
"import sep from noneq_settings import RUNS_FOLDER def run_subdir_setup(run_subfolder=None): current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder",
"here row refers to time array and col refers to gene labels (ie.",
"run directory: data_folder = os.path.join(current_run_folder, \"data\") plot_lattice_folder = os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder = os.path.join(current_run_folder,",
"import RUNS_FOLDER def run_subdir_setup(run_subfolder=None): current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder = current_time + os.sep",
"os.path.exists(dirs): os.makedirs(dirs) return current_run_folder, data_folder, plot_lattice_folder, plot_data_folder def state_write(state, row_vals, col_vals, dataname, rowname,",
"= output_dir + sep + dataname + '_' + colname + \".txt\" np.savetxt(datapath,",
"colname + \".txt\" np.savetxt(datapath, np.array(state), delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals), delimiter=\",\") np.savetxt(colpath, np.array(col_vals), delimiter=\",\",",
"state vector) datapath = output_dir + sep + dataname + \".txt\" rowpath =",
"dirs in dir_list: if not os.path.exists(dirs): os.makedirs(dirs) return current_run_folder, data_folder, plot_lattice_folder, plot_data_folder def",
"+ '_' + rowname + \".txt\" colpath = output_dir + sep + dataname",
"os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder = os.path.join(current_run_folder, \"plot_data\") dir_list = [RUNS_FOLDER, current_run_folder, data_folder, plot_lattice_folder, plot_data_folder]",
"dataname, rowname, colname, output_dir): # here row refers to time array and col",
"plot_lattice_folder = os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder = os.path.join(current_run_folder, \"plot_data\") dir_list = [RUNS_FOLDER, current_run_folder, data_folder,",
"and col refers to gene labels (ie. name for ith element of state",
"datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder = current_time + os.sep if run_subfolder is None: current_run_folder =",
"for ith element of state vector) datapath = output_dir + sep + dataname",
"to gene labels (ie. name for ith element of state vector) state =",
"data_folder = os.path.join(current_run_folder, \"data\") plot_lattice_folder = os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder = os.path.join(current_run_folder, \"plot_data\") dir_list",
"plot_data_folder = os.path.join(current_run_folder, \"plot_data\") dir_list = [RUNS_FOLDER, current_run_folder, data_folder, plot_lattice_folder, plot_data_folder] for dirs",
"delimiter=\",\") row = np.loadtxt(rowpath, delimiter=\",\", dtype=float) col = np.loadtxt(colpath, delimiter=\",\", dtype=str) return state,",
"output_dir + sep + dataname + '_' + colname + \".txt\" np.savetxt(datapath, np.array(state),",
"name for ith element of state vector) state = np.loadtxt(datapath, delimiter=\",\") row =",
"os.path.join(current_run_folder, \"data\") plot_lattice_folder = os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder = os.path.join(current_run_folder, \"plot_data\") dir_list = [RUNS_FOLDER,",
"\"data\") plot_lattice_folder = os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder = os.path.join(current_run_folder, \"plot_data\") dir_list = [RUNS_FOLDER, current_run_folder,",
"(ie. name for ith element of state vector) state = np.loadtxt(datapath, delimiter=\",\") row",
"refers to gene labels (ie. name for ith element of state vector) datapath",
"<gh_stars>0 import datetime import numpy as np import os from os import sep",
"rowname + \".txt\" colpath = output_dir + sep + dataname + '_' +",
"= np.loadtxt(rowpath, delimiter=\",\", dtype=float) col = np.loadtxt(colpath, delimiter=\",\", dtype=str) return state, row, col",
"datetime import numpy as np import os from os import sep from noneq_settings",
"numpy as np import os from os import sep from noneq_settings import RUNS_FOLDER",
"%I.%M.%S%p\") time_folder = current_time + os.sep if run_subfolder is None: current_run_folder = RUNS_FOLDER",
"time array and col refers to gene labels (ie. name for ith element",
"element of state vector) datapath = output_dir + sep + dataname + \".txt\"",
"current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder = current_time + os.sep if run_subfolder is None:",
"time_folder else: current_run_folder = RUNS_FOLDER + run_subfolder + os.sep + time_folder # subfolders",
"state vector) state = np.loadtxt(datapath, delimiter=\",\") row = np.loadtxt(rowpath, delimiter=\",\", dtype=float) col =",
"dir_list: if not os.path.exists(dirs): os.makedirs(dirs) return current_run_folder, data_folder, plot_lattice_folder, plot_data_folder def state_write(state, row_vals,",
"name for ith element of state vector) datapath = output_dir + sep +",
"np.loadtxt(datapath, delimiter=\",\") row = np.loadtxt(rowpath, delimiter=\",\", dtype=float) col = np.loadtxt(colpath, delimiter=\",\", dtype=str) return",
"dataname + \".txt\" rowpath = output_dir + sep + dataname + '_' +",
"element of state vector) state = np.loadtxt(datapath, delimiter=\",\") row = np.loadtxt(rowpath, delimiter=\",\", dtype=float)",
"os.makedirs(dirs) return current_run_folder, data_folder, plot_lattice_folder, plot_data_folder def state_write(state, row_vals, col_vals, dataname, rowname, colname,",
"colpath): # here row refers to time array and col refers to gene",
"os.sep + time_folder # subfolders in the timestamped run directory: data_folder = os.path.join(current_run_folder,",
"vector) state = np.loadtxt(datapath, delimiter=\",\") row = np.loadtxt(rowpath, delimiter=\",\", dtype=float) col = np.loadtxt(colpath,",
"run_subdir_setup(run_subfolder=None): current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder = current_time + os.sep if run_subfolder is",
"+ \".txt\" colpath = output_dir + sep + dataname + '_' + colname",
"+ rowname + \".txt\" colpath = output_dir + sep + dataname + '_'",
"return datapath, rowpath, colpath def state_read(datapath, rowpath, colpath): # here row refers to",
"+ dataname + '_' + rowname + \".txt\" colpath = output_dir + sep",
"data_folder, plot_lattice_folder, plot_data_folder def state_write(state, row_vals, col_vals, dataname, rowname, colname, output_dir): # here",
"None: current_run_folder = RUNS_FOLDER + time_folder else: current_run_folder = RUNS_FOLDER + run_subfolder +",
"current_run_folder = RUNS_FOLDER + time_folder else: current_run_folder = RUNS_FOLDER + run_subfolder + os.sep",
"run_subfolder is None: current_run_folder = RUNS_FOLDER + time_folder else: current_run_folder = RUNS_FOLDER +",
"= output_dir + sep + dataname + \".txt\" rowpath = output_dir + sep",
"plot_lattice_folder, plot_data_folder] for dirs in dir_list: if not os.path.exists(dirs): os.makedirs(dirs) return current_run_folder, data_folder,",
"row = np.loadtxt(rowpath, delimiter=\",\", dtype=float) col = np.loadtxt(colpath, delimiter=\",\", dtype=str) return state, row,",
"noneq_settings import RUNS_FOLDER def run_subdir_setup(run_subfolder=None): current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\") time_folder = current_time +",
"= os.path.join(current_run_folder, \"data\") plot_lattice_folder = os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder = os.path.join(current_run_folder, \"plot_data\") dir_list =",
"+ os.sep if run_subfolder is None: current_run_folder = RUNS_FOLDER + time_folder else: current_run_folder",
"datapath = output_dir + sep + dataname + \".txt\" rowpath = output_dir +",
"np.savetxt(colpath, np.array(col_vals), delimiter=\",\", fmt=\"%s\") return datapath, rowpath, colpath def state_read(datapath, rowpath, colpath): #",
"directory: data_folder = os.path.join(current_run_folder, \"data\") plot_lattice_folder = os.path.join(current_run_folder, \"plot_lattice\") plot_data_folder = os.path.join(current_run_folder, \"plot_data\")",
"(ie. name for ith element of state vector) datapath = output_dir + sep",
"sep + dataname + '_' + rowname + \".txt\" colpath = output_dir +",
"os import sep from noneq_settings import RUNS_FOLDER def run_subdir_setup(run_subfolder=None): current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %I.%M.%S%p\")",
"\".txt\" colpath = output_dir + sep + dataname + '_' + colname +",
"os.sep if run_subfolder is None: current_run_folder = RUNS_FOLDER + time_folder else: current_run_folder =",
"state_write(state, row_vals, col_vals, dataname, rowname, colname, output_dir): # here row refers to time",
"rowpath, colpath): # here row refers to time array and col refers to",
"data_folder, plot_lattice_folder, plot_data_folder] for dirs in dir_list: if not os.path.exists(dirs): os.makedirs(dirs) return current_run_folder,",
"for ith element of state vector) state = np.loadtxt(datapath, delimiter=\",\") row = np.loadtxt(rowpath,",
"np.savetxt(datapath, np.array(state), delimiter=\",\", fmt=\"%d\") np.savetxt(rowpath, np.array(row_vals), delimiter=\",\") np.savetxt(colpath, np.array(col_vals), delimiter=\",\", fmt=\"%s\") return datapath,",
"state = np.loadtxt(datapath, delimiter=\",\") row = np.loadtxt(rowpath, delimiter=\",\", dtype=float) col = np.loadtxt(colpath, delimiter=\",\",",
"RUNS_FOLDER + run_subfolder + os.sep + time_folder # subfolders in the timestamped run",
"in the timestamped run directory: data_folder = os.path.join(current_run_folder, \"data\") plot_lattice_folder = os.path.join(current_run_folder, \"plot_lattice\")",
"delimiter=\",\") np.savetxt(colpath, np.array(col_vals), delimiter=\",\", fmt=\"%s\") return datapath, rowpath, colpath def state_read(datapath, rowpath, colpath):",
"= os.path.join(current_run_folder, \"plot_data\") dir_list = [RUNS_FOLDER, current_run_folder, data_folder, plot_lattice_folder, plot_data_folder] for dirs in",
"time_folder = current_time + os.sep if run_subfolder is None: current_run_folder = RUNS_FOLDER +",
"RUNS_FOLDER + time_folder else: current_run_folder = RUNS_FOLDER + run_subfolder + os.sep + time_folder"
] |
[
"..users.models import User @admin.register(User) class UserAdmin(UserAdmin): model = User list_display = ('cid', 'email',",
"from django.contrib import admin from django.contrib.auth.admin import UserAdmin from ..users.models import User @admin.register(User)",
"'last_name') search_fields = list_display list_filter = list_display ordering = ('cid',) fieldsets = (",
"= ('cid',) fieldsets = ( ('Personal Information', {'fields': ('cid', 'first_name', 'last_name', 'email', 'password')}),",
"Information', {'fields': ('cid', 'first_name', 'last_name', 'email', 'password')}), ('Facilities', {'fields': ('facilities',)}), ('Permissions', {'fields': ('is_superuser',",
"( ('Personal Information', {'fields': ('cid', 'first_name', 'last_name', 'email', 'password')}), ('Facilities', {'fields': ('facilities',)}), ('Permissions',",
"('cid', 'email', 'first_name', 'last_name') search_fields = list_display list_filter = list_display ordering = ('cid',)",
"from django.contrib.auth.admin import UserAdmin from ..users.models import User @admin.register(User) class UserAdmin(UserAdmin): model =",
"list_filter = list_display ordering = ('cid',) fieldsets = ( ('Personal Information', {'fields': ('cid',",
"'first_name', 'last_name') search_fields = list_display list_filter = list_display ordering = ('cid',) fieldsets =",
"list_display list_filter = list_display ordering = ('cid',) fieldsets = ( ('Personal Information', {'fields':",
"admin from django.contrib.auth.admin import UserAdmin from ..users.models import User @admin.register(User) class UserAdmin(UserAdmin): model",
"model = User list_display = ('cid', 'email', 'first_name', 'last_name') search_fields = list_display list_filter",
"{'fields': ('cid', 'first_name', 'last_name', 'email', 'password')}), ('Facilities', {'fields': ('facilities',)}), ('Permissions', {'fields': ('is_superuser', 'user_permissions')}),",
"list_display ordering = ('cid',) fieldsets = ( ('Personal Information', {'fields': ('cid', 'first_name', 'last_name',",
"import User @admin.register(User) class UserAdmin(UserAdmin): model = User list_display = ('cid', 'email', 'first_name',",
"'email', 'first_name', 'last_name') search_fields = list_display list_filter = list_display ordering = ('cid',) fieldsets",
"('cid', 'first_name', 'last_name', 'email', 'password')}), ('Facilities', {'fields': ('facilities',)}), ('Permissions', {'fields': ('is_superuser', 'user_permissions')}), )",
"= User list_display = ('cid', 'email', 'first_name', 'last_name') search_fields = list_display list_filter =",
"list_display = ('cid', 'email', 'first_name', 'last_name') search_fields = list_display list_filter = list_display ordering",
"<filename>apps/users/admin.py<gh_stars>1-10 from django.contrib import admin from django.contrib.auth.admin import UserAdmin from ..users.models import User",
"UserAdmin(UserAdmin): model = User list_display = ('cid', 'email', 'first_name', 'last_name') search_fields = list_display",
"from ..users.models import User @admin.register(User) class UserAdmin(UserAdmin): model = User list_display = ('cid',",
"('cid',) fieldsets = ( ('Personal Information', {'fields': ('cid', 'first_name', 'last_name', 'email', 'password')}), ('Facilities',",
"django.contrib.auth.admin import UserAdmin from ..users.models import User @admin.register(User) class UserAdmin(UserAdmin): model = User",
"('Personal Information', {'fields': ('cid', 'first_name', 'last_name', 'email', 'password')}), ('Facilities', {'fields': ('facilities',)}), ('Permissions', {'fields':",
"search_fields = list_display list_filter = list_display ordering = ('cid',) fieldsets = ( ('Personal",
"= ( ('Personal Information', {'fields': ('cid', 'first_name', 'last_name', 'email', 'password')}), ('Facilities', {'fields': ('facilities',)}),",
"UserAdmin from ..users.models import User @admin.register(User) class UserAdmin(UserAdmin): model = User list_display =",
"django.contrib import admin from django.contrib.auth.admin import UserAdmin from ..users.models import User @admin.register(User) class",
"User list_display = ('cid', 'email', 'first_name', 'last_name') search_fields = list_display list_filter = list_display",
"import UserAdmin from ..users.models import User @admin.register(User) class UserAdmin(UserAdmin): model = User list_display",
"= ('cid', 'email', 'first_name', 'last_name') search_fields = list_display list_filter = list_display ordering =",
"= list_display ordering = ('cid',) fieldsets = ( ('Personal Information', {'fields': ('cid', 'first_name',",
"class UserAdmin(UserAdmin): model = User list_display = ('cid', 'email', 'first_name', 'last_name') search_fields =",
"import admin from django.contrib.auth.admin import UserAdmin from ..users.models import User @admin.register(User) class UserAdmin(UserAdmin):",
"@admin.register(User) class UserAdmin(UserAdmin): model = User list_display = ('cid', 'email', 'first_name', 'last_name') search_fields",
"User @admin.register(User) class UserAdmin(UserAdmin): model = User list_display = ('cid', 'email', 'first_name', 'last_name')",
"fieldsets = ( ('Personal Information', {'fields': ('cid', 'first_name', 'last_name', 'email', 'password')}), ('Facilities', {'fields':",
"= list_display list_filter = list_display ordering = ('cid',) fieldsets = ( ('Personal Information',",
"ordering = ('cid',) fieldsets = ( ('Personal Information', {'fields': ('cid', 'first_name', 'last_name', 'email',"
] |
[
"# pygame init pygame.init() window_surface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS Driver Station') background =",
"clock.tick(60)/1000.0 for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True manager.process_events(event)",
"= pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100, 50)), text='Say Hello', manager=manager) exit = False while not",
"manager = pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100, 50)), text='Say Hello', manager=manager)",
"window_surface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS Driver Station') background = pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000')) clock",
"1600 HEIGHT = 1200 # pygame init pygame.init() window_surface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS",
"Driver Station') background = pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000')) clock = pygame.time.Clock() # pygame_gui init",
"# pygame_gui init manager = pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100, 50)),",
"pygame import pygame_gui WIDTH = 1600 HEIGHT = 1200 # pygame init pygame.init()",
"pygame_gui init manager = pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100, 50)), text='Say",
"Station') background = pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000')) clock = pygame.time.Clock() # pygame_gui init manager",
"manager=manager) exit = False while not exit: delta_t = clock.tick(60)/1000.0 for event in",
"False while not exit: delta_t = clock.tick(60)/1000.0 for event in pygame.event.get(): if event.type",
"hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100, 50)), text='Say Hello', manager=manager) exit = False while",
"= clock.tick(60)/1000.0 for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True",
"event.type == pygame.QUIT: exit = True manager.process_events(event) window_surface.blit(background, (0, 0)) manager.update(delta_t) manager.draw_ui(window_surface) pygame.display.update()",
"275), (100, 50)), text='Say Hello', manager=manager) exit = False while not exit: delta_t",
"= pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100, 50)), text='Say Hello', manager=manager) exit",
"import pygame_gui WIDTH = 1600 HEIGHT = 1200 # pygame init pygame.init() window_surface",
"= pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS Driver Station') background = pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000')) clock =",
"WIDTH = 1600 HEIGHT = 1200 # pygame init pygame.init() window_surface = pygame.display.set_mode((WIDTH,",
"HEIGHT = 1200 # pygame init pygame.init() window_surface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS Driver",
"= 1600 HEIGHT = 1200 # pygame init pygame.init() window_surface = pygame.display.set_mode((WIDTH, HEIGHT))",
"clock = pygame.time.Clock() # pygame_gui init manager = pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350,",
"background.fill(pygame.Color('#000000')) clock = pygame.time.Clock() # pygame_gui init manager = pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button =",
"pygame.event.get(): if event.type == pygame.QUIT: exit = True manager.process_events(event) window_surface.blit(background, (0, 0)) manager.update(delta_t)",
"= False while not exit: delta_t = clock.tick(60)/1000.0 for event in pygame.event.get(): if",
"pygame.init() window_surface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS Driver Station') background = pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000'))",
"pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS Driver Station') background = pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000')) clock = pygame.time.Clock()",
"= pygame.time.Clock() # pygame_gui init manager = pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275),",
"pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100, 50)), text='Say Hello', manager=manager) exit =",
"HEIGHT)) hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100, 50)), text='Say Hello', manager=manager) exit = False",
"pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100, 50)), text='Say Hello', manager=manager) exit = False while not exit:",
"text='Say Hello', manager=manager) exit = False while not exit: delta_t = clock.tick(60)/1000.0 for",
"pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000')) clock = pygame.time.Clock() # pygame_gui init manager = pygame_gui.UIManager((WIDTH, HEIGHT))",
"(100, 50)), text='Say Hello', manager=manager) exit = False while not exit: delta_t =",
"event in pygame.event.get(): if event.type == pygame.QUIT: exit = True manager.process_events(event) window_surface.blit(background, (0,",
"if event.type == pygame.QUIT: exit = True manager.process_events(event) window_surface.blit(background, (0, 0)) manager.update(delta_t) manager.draw_ui(window_surface)",
"pygame.display.set_caption('MGS Driver Station') background = pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000')) clock = pygame.time.Clock() # pygame_gui",
"1200 # pygame init pygame.init() window_surface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS Driver Station') background",
"import pygame import pygame_gui WIDTH = 1600 HEIGHT = 1200 # pygame init",
"for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True manager.process_events(event) window_surface.blit(background,",
"pygame init pygame.init() window_surface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS Driver Station') background = pygame.Surface((WIDTH,",
"50)), text='Say Hello', manager=manager) exit = False while not exit: delta_t = clock.tick(60)/1000.0",
"exit = False while not exit: delta_t = clock.tick(60)/1000.0 for event in pygame.event.get():",
"HEIGHT)) background.fill(pygame.Color('#000000')) clock = pygame.time.Clock() # pygame_gui init manager = pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button",
"<reponame>metal-gear-solidworks/mgs-ds import pygame import pygame_gui WIDTH = 1600 HEIGHT = 1200 # pygame",
"= pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000')) clock = pygame.time.Clock() # pygame_gui init manager = pygame_gui.UIManager((WIDTH,",
"pygame_gui WIDTH = 1600 HEIGHT = 1200 # pygame init pygame.init() window_surface =",
"background = pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000')) clock = pygame.time.Clock() # pygame_gui init manager =",
"pygame.time.Clock() # pygame_gui init manager = pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100,",
"init manager = pygame_gui.UIManager((WIDTH, HEIGHT)) hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((350, 275), (100, 50)), text='Say Hello',",
"in pygame.event.get(): if event.type == pygame.QUIT: exit = True manager.process_events(event) window_surface.blit(background, (0, 0))",
"Hello', manager=manager) exit = False while not exit: delta_t = clock.tick(60)/1000.0 for event",
"not exit: delta_t = clock.tick(60)/1000.0 for event in pygame.event.get(): if event.type == pygame.QUIT:",
"= 1200 # pygame init pygame.init() window_surface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS Driver Station')",
"exit: delta_t = clock.tick(60)/1000.0 for event in pygame.event.get(): if event.type == pygame.QUIT: exit",
"delta_t = clock.tick(60)/1000.0 for event in pygame.event.get(): if event.type == pygame.QUIT: exit =",
"HEIGHT)) pygame.display.set_caption('MGS Driver Station') background = pygame.Surface((WIDTH, HEIGHT)) background.fill(pygame.Color('#000000')) clock = pygame.time.Clock() #",
"while not exit: delta_t = clock.tick(60)/1000.0 for event in pygame.event.get(): if event.type ==",
"init pygame.init() window_surface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('MGS Driver Station') background = pygame.Surface((WIDTH, HEIGHT))"
] |
[
"_format_ips(request, i) server_pool_members[\"ip\"] = v4 server_pool_members[\"ipv6\"] = v6 pool_members.append(server_pool_members) return pool_members def _format_equipments(request,",
"KIND, either express or implied. # See the License for the specific language",
"= request.POST.get('healthcheck_destination') healthcheck[\"destination\"] = (\"*:%s\" % healthcheck_destination) \\ if healthcheck_destination else '*:*' return",
"Unless required by applicable law or agreed to in writing, software # distributed",
"enviroments_choices.append((obj['id'], \"%s - %s - %s\" % (obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name']))) return enviroments_choices def",
"The ASF licenses this file to You under the Apache License, Version 2.0",
"environment): optionspool_choices = [('', '-')] optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment) is not int",
"server_pool_members = dict() server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i]) \\ if request.POST.getlist('id_pool_member')[i] else None server_pool_members[\"identifier\"] =",
"healthcheck[\"identifier\"] = \"\" healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect') healthcheck_destination",
"i): equipments = dict() equipments[\"id\"] = int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] = str(request.POST.getlist('equip')[i]) return equipments def",
"if \":\" in ips['ip_formated'] else None return v4, v6 def format_name_ip_search(name): try: ip",
"% healthcheck_destination) \\ if healthcheck_destination else '*:*' return healthcheck def format_servicedownaction(client, form): servicedownaction",
"'', 'ip': ip['ip_formated'] if ip else ''}) return pool_members def format_healthcheck(request): healthcheck =",
"request.POST.getlist('id_pool_member')[i] else None server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] = _format_equipments(request, i)",
"'1%s%s' % ( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"] = int(member_status, 2) except: #When copying",
"populate_healthcheck_choices(client): optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices = [('', '-')] for obj in optionspool: healthcheck_choices.append((obj['name'],",
"(obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name']))) return enviroments_choices def populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips = client.create_option_vip().get_all() optionsvips_choices =",
"obj in server_pool_members: mbs = bin(int(obj.get('member_status')))[2:5].zfill(3) ip = obj['ip'] if obj['ip'] else obj['ipv6']",
"the NOTICE file distributed with # this work for additional information regarding copyright",
"in optionspool: if obj['name'] == option_name: return obj['id'] def find_servicedownaction_object(client, option_name=None, id=None): optionspool",
"id=servicedownaction['id'])) return servicedownaction def format_server_pool_members(request, limit=0): pool_members = [] equips = request.POST.getlist('id_equip') for",
"server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] = limit server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i]) try: member_status = '1%s%s'",
"%s\" % (obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name']))) return enviroments_choices def populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips = client.create_option_vip().get_all()",
"obj['port_real'], 'weight': obj['weight'], 'id_ip': ip['id'] if ip else '', 'ip': ip['ip_formated'] if ip",
"name} else: if ip.version == 6: ip = ip.compressed.split(':') search = { 'ipv6equipament__ip__oct1':",
"in server_pool_members: mbs = bin(int(obj.get('member_status')))[2:5].zfill(3) ip = obj['ip'] if obj['ip'] else obj['ipv6'] pool_members.append(",
"request.POST.getlist('id_equip') for i in range(0, len(equips)): server_pool_members = dict() server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i]) \\",
"= int(request.POST.getlist('id_pool_member')[i]) \\ if request.POST.getlist('id_pool_member')[i] else None server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i])",
"= int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] = str(find_servicedownaction_object(client, id=servicedownaction['id'])) return servicedownaction def format_server_pool_members(request, limit=0): pool_members =",
"request # and there is no separation of hab and updown server_pool_members[\"member_status\"] =",
"equipments[\"id\"] = int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] = str(request.POST.getlist('equip')[i]) return equipments def _format_ips(request, i): ips =",
"len(members.get(\"ports_reals\"))): pool_members.append({ 'id': members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i], 'weight':",
"obj in optionspool: if obj['id'] == id: return obj['name'] for obj in optionspool:",
"# Format enviroments for obj in enviroments: enviroments_choices.append((obj['id'], \"%s - %s - %s\"",
"healthcheck = dict() healthcheck[\"identifier\"] = \"\" healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"]",
"else '*:*' return healthcheck def format_servicedownaction(client, form): servicedownaction = dict() servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction'])",
"return optionspool_choices def populate_pool_members_by_lists(client, members): pool_members = [] ip_list_full = [] if len(members.get(\"ports_reals\"))",
"ANY KIND, either express or implied. # See the License for the specific",
"updown server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i]) v4, v6 = _format_ips(request, i) server_pool_members[\"ip\"] = v4 server_pool_members[\"ipv6\"]",
"governing permissions and # limitations under the License. import ipaddress def populate_expectstring_choices(client): expectstring_choices",
"= { 'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6':",
"optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id: for obj in optionspool: if obj['id'] == id:",
"tips='ServiceDownAction'): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices = [('', '-')] for obj in optionspool: servicedownaction_choices.append((obj['id'],",
"optionsvips = client.create_option_vip().get_all() optionsvips_choices = [('', '-')] for obj in optionsvips['option_vip']: if obj['tipo_opcao']",
"members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i] }) ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]}) return pool_members, ip_list_full",
"{'id': obj['id'], 'id_equip': obj['equipment']['id'], 'member_status_hab': mbs[1], 'member_status_updown': mbs[2], 'member_status': obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'], 'priority':",
"if len(members.get(\"ports_reals\")) > 0 and len(members.get(\"ips\")) > 0: for i in range(0, len(members.get(\"ports_reals\"))):",
"ip = ipaddress.ip_address(name) except: search = {'nome': name} else: if ip.version == 6:",
"\".\" in ips['ip_formated'] else None v6 = ips if \":\" in ips['ip_formated'] else",
"obj['ip'] else obj['ipv6'] pool_members.append( {'id': obj['id'], 'id_equip': obj['equipment']['id'], 'member_status_hab': mbs[1], 'member_status_updown': mbs[2], 'member_status':",
"ip[5], 'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8': ip[7] } if ip.version == 4: ip = ip.compressed.split('.')",
"obj['name'] for obj in optionspool: if obj['name'] == option_name: return obj def populate_optionspool_choices(client,",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"= [] if len(members.get(\"ports_reals\")) > 0 and len(members.get(\"ips\")) > 0: for i in",
"work for additional information regarding copyright ownership. # The ASF licenses this file",
"= client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices = [('', '-')] for obj in optionspool: healthcheck_choices.append((obj['name'], obj['name'])) return",
"''}) return pool_members def format_healthcheck(request): healthcheck = dict() healthcheck[\"identifier\"] = \"\" healthcheck[\"healthcheck_type\"] =",
"ip[4], 'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8': ip[7] } if ip.version == 4: ip",
"populate_pool_members_by_lists(client, members): pool_members = [] ip_list_full = [] if len(members.get(\"ports_reals\")) > 0 and",
"= [] for obj in server_pool_members: mbs = bin(int(obj.get('member_status')))[2:5].zfill(3) ip = obj['ip'] if",
"else '', 'ip': ip['ip_formated'] if ip else ''}) return pool_members def format_healthcheck(request): healthcheck",
"else obj['ipv6'] pool_members.append( {'id': obj['id'], 'id_equip': obj['equipment']['id'], 'member_status_hab': mbs[1], 'member_status_updown': mbs[2], 'member_status': obj[\"member_status\"],",
"= request.POST.get('healthcheck_expect') healthcheck_destination = request.POST.get('healthcheck_destination') healthcheck[\"destination\"] = (\"*:%s\" % healthcheck_destination) \\ if healthcheck_destination",
"i): ips = dict() ips[\"id\"] = int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i]) v4 = ips",
"ip[7] } if ip.version == 4: ip = ip.compressed.split('.') search = { 'ipequipamento__ip__oct1':",
"format_healthcheck(request): healthcheck = dict() healthcheck[\"identifier\"] = \"\" healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request')",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"healthcheck def format_servicedownaction(client, form): servicedownaction = dict() servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] = str(find_servicedownaction_object(client,",
"{ 'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6': ip[5],",
"ip[6], 'ipv6equipament__ip__oct8': ip[7] } if ip.version == 4: ip = ip.compressed.split('.') search =",
"v6 = _format_ips(request, i) server_pool_members[\"ip\"] = v4 server_pool_members[\"ipv6\"] = v6 pool_members.append(server_pool_members) return pool_members",
"OF ANY KIND, either express or implied. # See the License for the",
"obj['name'])) return servicedownaction_choices def populate_healthcheck_choices(client): optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices = [('', '-')] for",
"servicedownaction def format_server_pool_members(request, limit=0): pool_members = [] equips = request.POST.getlist('id_equip') for i in",
"ip else ''}) return pool_members def format_healthcheck(request): healthcheck = dict() healthcheck[\"identifier\"] = \"\"",
"optionspool_choices def populate_pool_members_by_lists(client, members): pool_members = [] ip_list_full = [] if len(members.get(\"ports_reals\")) >",
"ipaddress.ip_address(name) except: search = {'nome': name} else: if ip.version == 6: ip =",
"in ips['ip_formated'] else None return v4, v6 def format_name_ip_search(name): try: ip = ipaddress.ip_address(name)",
"optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj in optionspool: if obj['name'] == option_name: return obj['id']",
"ownership. # The ASF licenses this file to You under the Apache License,",
"server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i]) try: member_status = '1%s%s' % ( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"]",
"regarding copyright ownership. # The ASF licenses this file to You under the",
"ip.compressed.split(':') search = { 'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5':",
"server_pool_members[\"limit\"] = limit server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i]) try: member_status = '1%s%s' % ( request.POST.getlist('member_status_hab')[i],",
"obj['id'] == id: return obj['name'] for obj in optionspool: if obj['name'] == option_name:",
"dict() servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] = str(find_servicedownaction_object(client, id=servicedownaction['id'])) return servicedownaction def format_server_pool_members(request, limit=0):",
"else: if ip.version == 6: ip = ip.compressed.split(':') search = { 'ipv6equipament__ip__oct1': ip[0],",
"enviroments = client.create_pool().list_all_environment_related_environment_vip() enviroments_choices = [('', '-')] # Format enviroments for obj in",
"request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"] = int(member_status, 2) except: #When copying a pool, information",
"'nome_equipamento': obj['equipment']['name'], 'priority': obj['priority'], 'port_real': obj['port_real'], 'weight': obj['weight'], 'id_ip': ip['id'] if ip else",
"int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] = _format_equipments(request, i) server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] = limit server_pool_members[\"port_real\"] =",
"copyright ownership. # The ASF licenses this file to You under the Apache",
"[('', '-')] optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment) is not int else \\ client.create_pool().get_opcoes_pool_by_environment(environment)",
"obj in optionspool: if obj['name'] == option_name: return obj['id'] def find_servicedownaction_object(client, option_name=None, id=None):",
"server_pool_members[\"ip\"] = v4 server_pool_members[\"ipv6\"] = v6 pool_members.append(server_pool_members) return pool_members def _format_equipments(request, i): equipments",
"for obj in optionspool: if obj['id'] == id: return obj['name'] for obj in",
"len(members.get(\"ips\")) > 0: for i in range(0, len(members.get(\"ports_reals\"))): pool_members.append({ 'id': members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i],",
"= (\"*:%s\" % healthcheck_destination) \\ if healthcheck_destination else '*:*' return healthcheck def format_servicedownaction(client,",
"in optionspool: servicedownaction_choices.append((obj['id'], obj['name'])) return servicedownaction_choices def populate_healthcheck_choices(client): optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices =",
"# this work for additional information regarding copyright ownership. # The ASF licenses",
"servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] = str(find_servicedownaction_object(client, id=servicedownaction['id'])) return servicedownaction def format_server_pool_members(request, limit=0): pool_members",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"return servicedownaction def format_server_pool_members(request, limit=0): pool_members = [] equips = request.POST.getlist('id_equip') for i",
"enviroments: enviroments_choices.append((obj['id'], \"%s - %s - %s\" % (obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name']))) return enviroments_choices",
"client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices = [('', '-')] for obj in optionspool: servicedownaction_choices.append((obj['id'], obj['name'])) return servicedownaction_choices",
"= [('', '-')] for obj in optionspool: healthcheck_choices.append((obj['name'], obj['name'])) return healthcheck_choices def find_servicedownaction_id(client,",
"= obj['ip'] if obj['ip'] else obj['ipv6'] pool_members.append( {'id': obj['id'], 'id_equip': obj['equipment']['id'], 'member_status_hab': mbs[1],",
"members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]}) return pool_members, ip_list_full def populate_pool_members_by_obj(server_pool_members): pool_members = [] for obj",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"def format_servicedownaction(client, form): servicedownaction = dict() servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] = str(find_servicedownaction_object(client, id=servicedownaction['id']))",
"str(request.POST.getlist('equip')[i]) return equipments def _format_ips(request, i): ips = dict() ips[\"id\"] = int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"]",
"for obj in optionspool: if obj['name'] == option_name: return obj def populate_optionspool_choices(client, environment):",
"in ips['ip_formated'] else None v6 = ips if \":\" in ips['ip_formated'] else None",
"# -*- coding:utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under",
"if obj['id'] == id: return obj['name'] for obj in optionspool: if obj['name'] ==",
"optionsvips['option_vip']: if obj['tipo_opcao'] == tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return optionsvips_choices def populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool",
"specific language governing permissions and # limitations under the License. import ipaddress def",
"ips if \".\" in ips['ip_formated'] else None v6 = ips if \":\" in",
"client.create_option_vip().get_all() optionsvips_choices = [('', '-')] for obj in optionsvips['option_vip']: if obj['tipo_opcao'] == tips:",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"> 0 and len(members.get(\"ips\")) > 0: for i in range(0, len(members.get(\"ports_reals\"))): pool_members.append({ 'id':",
"in optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name'])) return optionspool_choices def populate_pool_members_by_lists(client, members): pool_members = [] ip_list_full",
"License, Version 2.0 # (the \"License\"); you may not use this file except",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8': ip[7] } if ip.version == 4:",
"0 and len(members.get(\"ips\")) > 0: for i in range(0, len(members.get(\"ports_reals\"))): pool_members.append({ 'id': members.get(\"id_pool_member\")[i],",
"limit=0): pool_members = [] equips = request.POST.getlist('id_equip') for i in range(0, len(equips)): server_pool_members",
"ips['ip_formated'] else None v6 = ips if \":\" in ips['ip_formated'] else None return",
"required by applicable law or agreed to in writing, software # distributed under",
"in optionsvips['option_vip']: if obj['tipo_opcao'] == tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return optionsvips_choices def populate_servicedownaction_choices(client, tips='ServiceDownAction'):",
"ips[\"id\"] = int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i]) v4 = ips if \".\" in ips['ip_formated']",
"this file except in compliance with # the License. You may obtain a",
"2) except: #When copying a pool, information required was already sent in request",
"applicable law or agreed to in writing, software # distributed under the License",
"{'nome': name} else: if ip.version == 6: ip = ip.compressed.split(':') search = {",
"healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect') healthcheck_destination = request.POST.get('healthcheck_destination') healthcheck[\"destination\"] = (\"*:%s\" %",
"int(member_status, 2) except: #When copying a pool, information required was already sent in",
"> 0: for i in range(0, len(members.get(\"ports_reals\"))): pool_members.append({ 'id': members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento':",
"members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i] }) ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip':",
"ip[2], 'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8': ip[7] } if",
"or agreed to in writing, software # distributed under the License is distributed",
"ips['ip_formated'] else None return v4, v6 def format_name_ip_search(name): try: ip = ipaddress.ip_address(name) except:",
"enviroments for obj in enviroments: enviroments_choices.append((obj['id'], \"%s - %s - %s\" % (obj['divisao_dc_name'],",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"\\ if healthcheck_destination else '*:*' return healthcheck def format_servicedownaction(client, form): servicedownaction = dict()",
"client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('', '-')) return expectstring_choices def populate_enviroments_choices(client): enviroments = client.create_pool().list_all_environment_related_environment_vip() enviroments_choices =",
"required was already sent in request # and there is no separation of",
"expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('', '-')) return expectstring_choices def populate_enviroments_choices(client): enviroments = client.create_pool().list_all_environment_related_environment_vip()",
"def format_healthcheck(request): healthcheck = dict() healthcheck[\"identifier\"] = \"\" healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] =",
"return v4, v6 def format_name_ip_search(name): try: ip = ipaddress.ip_address(name) except: search = {'nome':",
"not int else \\ client.create_pool().get_opcoes_pool_by_environment(environment) for obj in optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name'])) return optionspool_choices",
"dict() healthcheck[\"identifier\"] = \"\" healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect')",
"[('', '-')] for obj in optionsvips['option_vip']: if obj['tipo_opcao'] == tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return",
"_format_equipments(request, i) server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] = limit server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i]) try: member_status",
"client.create_pool().get_opcoes_pool_by_environment(environment) for obj in optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name'])) return optionspool_choices def populate_pool_members_by_lists(client, members): pool_members",
"for i in range(0, len(equips)): server_pool_members = dict() server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i]) \\ if",
"ips = dict() ips[\"id\"] = int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i]) v4 = ips if",
"obj['priority'], 'port_real': obj['port_real'], 'weight': obj['weight'], 'id_ip': ip['id'] if ip else '', 'ip': ip['ip_formated']",
"in request # and there is no separation of hab and updown server_pool_members[\"member_status\"]",
"= request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect') healthcheck_destination = request.POST.get('healthcheck_destination') healthcheck[\"destination\"] = (\"*:%s\" % healthcheck_destination)",
"i in range(0, len(equips)): server_pool_members = dict() server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i]) \\ if request.POST.getlist('id_pool_member')[i]",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"\"%s - %s - %s\" % (obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name']))) return enviroments_choices def populate_optionsvips_choices(client,",
"id: for obj in optionspool: if obj['id'] == id: return obj['name'] for obj",
"mbs[1], 'member_status_updown': mbs[2], 'member_status': obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'], 'priority': obj['priority'], 'port_real': obj['port_real'], 'weight': obj['weight'],",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"ip[3], 'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8': ip[7] } if ip.version ==",
"tips='Balanceamento'): optionsvips = client.create_option_vip().get_all() optionsvips_choices = [('', '-')] for obj in optionsvips['option_vip']: if",
"client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices = [('', '-')] for obj in optionspool: healthcheck_choices.append((obj['name'], obj['name'])) return healthcheck_choices",
"= [] equips = request.POST.getlist('id_equip') for i in range(0, len(equips)): server_pool_members = dict()",
"None return v4, v6 def format_name_ip_search(name): try: ip = ipaddress.ip_address(name) except: search =",
"find_servicedownaction_object(client, option_name=None, id=None): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id: for obj in optionspool: if",
"server_pool_members: mbs = bin(int(obj.get('member_status')))[2:5].zfill(3) ip = obj['ip'] if obj['ip'] else obj['ipv6'] pool_members.append( {'id':",
"compliance with # the License. You may obtain a copy of the License",
"mbs = bin(int(obj.get('member_status')))[2:5].zfill(3) ip = obj['ip'] if obj['ip'] else obj['ipv6'] pool_members.append( {'id': obj['id'],",
"NOTICE file distributed with # this work for additional information regarding copyright ownership.",
"in enviroments: enviroments_choices.append((obj['id'], \"%s - %s - %s\" % (obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name']))) return",
"'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8': ip[7] } if ip.version",
"obj in optionsvips['option_vip']: if obj['tipo_opcao'] == tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return optionsvips_choices def populate_servicedownaction_choices(client,",
"'ipv6equipament__ip__oct8': ip[7] } if ip.version == 4: ip = ip.compressed.split('.') search = {",
"distributed with # this work for additional information regarding copyright ownership. # The",
"if ip else ''}) return pool_members def format_healthcheck(request): healthcheck = dict() healthcheck[\"identifier\"] =",
"'port_real': obj['port_real'], 'weight': obj['weight'], 'id_ip': ip['id'] if ip else '', 'ip': ip['ip_formated'] if",
"server_pool_members[\"ipv6\"] = v6 pool_members.append(server_pool_members) return pool_members def _format_equipments(request, i): equipments = dict() equipments[\"id\"]",
"dict() equipments[\"id\"] = int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] = str(request.POST.getlist('equip')[i]) return equipments def _format_ips(request, i): ips",
"for the specific language governing permissions and # limitations under the License. import",
"'member_status': obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'], 'priority': obj['priority'], 'port_real': obj['port_real'], 'weight': obj['weight'], 'id_ip': ip['id'] if",
"= limit server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i]) try: member_status = '1%s%s' % ( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i]",
"4: ip = ip.compressed.split('.') search = { 'ipequipamento__ip__oct1': ip[0], 'ipequipamento__ip__oct2': ip[1], 'ipequipamento__ip__oct3': ip[2],",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"'ip': members.get(\"ips\")[i] }) ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]}) return pool_members, ip_list_full def populate_pool_members_by_obj(server_pool_members): pool_members",
"% ( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"] = int(member_status, 2) except: #When copying a",
"healthcheck_choices = [('', '-')] for obj in optionspool: healthcheck_choices.append((obj['name'], obj['name'])) return healthcheck_choices def",
"License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"[('', '-')] # Format enviroments for obj in enviroments: enviroments_choices.append((obj['id'], \"%s - %s",
"members.get(\"ips\")[i] }) ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]}) return pool_members, ip_list_full def populate_pool_members_by_obj(server_pool_members): pool_members =",
"= str(request.POST.getlist('equip')[i]) return equipments def _format_ips(request, i): ips = dict() ips[\"id\"] = int(request.POST.getlist('id_ip')[i])",
"except: #When copying a pool, information required was already sent in request #",
"agreements. See the NOTICE file distributed with # this work for additional information",
"ip.compressed.split('.') search = { 'ipequipamento__ip__oct1': ip[0], 'ipequipamento__ip__oct2': ip[1], 'ipequipamento__ip__oct3': ip[2], 'ipequipamento__ip__oct4': ip[3] }",
"pool_members = [] for obj in server_pool_members: mbs = bin(int(obj.get('member_status')))[2:5].zfill(3) ip = obj['ip']",
"type(environment) is not int else \\ client.create_pool().get_opcoes_pool_by_environment(environment) for obj in optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name']))",
"ASF licenses this file to You under the Apache License, Version 2.0 #",
"= v4 server_pool_members[\"ipv6\"] = v6 pool_members.append(server_pool_members) return pool_members def _format_equipments(request, i): equipments =",
"servicedownaction_choices.append((obj['id'], obj['name'])) return servicedownaction_choices def populate_healthcheck_choices(client): optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices = [('', '-')]",
"client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id: for obj in optionspool: if obj['id'] == id: return obj['name']",
"for obj in server_pool_members: mbs = bin(int(obj.get('member_status')))[2:5].zfill(3) ip = obj['ip'] if obj['ip'] else",
"servicedownaction_choices def populate_healthcheck_choices(client): optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices = [('', '-')] for obj in",
"'priority': members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i] }) ip_list_full.append({'id': members.get(\"id_ips\")[i],",
"== 6: ip = ip.compressed.split(':') search = { 'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3':",
"= ips if \":\" in ips['ip_formated'] else None return v4, v6 def format_name_ip_search(name):",
"'ip': members.get(\"ips\")[i]}) return pool_members, ip_list_full def populate_pool_members_by_obj(server_pool_members): pool_members = [] for obj in",
"2.0 # (the \"License\"); you may not use this file except in compliance",
"import ipaddress def populate_expectstring_choices(client): expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('', '-')) return expectstring_choices def",
"int(request.POST.getlist('ports_real_reals')[i]) try: member_status = '1%s%s' % ( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"] = int(member_status,",
"the specific language governing permissions and # limitations under the License. import ipaddress",
"def populate_pool_members_by_lists(client, members): pool_members = [] ip_list_full = [] if len(members.get(\"ports_reals\")) > 0",
"'ip': ip['ip_formated'] if ip else ''}) return pool_members def format_healthcheck(request): healthcheck = dict()",
"Apache License, Version 2.0 # (the \"License\"); you may not use this file",
"pool_members = [] ip_list_full = [] if len(members.get(\"ports_reals\")) > 0 and len(members.get(\"ips\")) >",
"v6 = ips if \":\" in ips['ip_formated'] else None return v4, v6 def",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8': ip[7] }",
"members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i] }) ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]}) return pool_members, ip_list_full def populate_pool_members_by_obj(server_pool_members):",
"if ip else '', 'ip': ip['ip_formated'] if ip else ''}) return pool_members def",
"in compliance with # the License. You may obtain a copy of the",
"obj['name'])) return healthcheck_choices def find_servicedownaction_id(client, option_name): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj in optionspool:",
"= str(find_servicedownaction_object(client, id=servicedownaction['id'])) return servicedownaction def format_server_pool_members(request, limit=0): pool_members = [] equips =",
"coding:utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or",
"ip = obj['ip'] if obj['ip'] else obj['ipv6'] pool_members.append( {'id': obj['id'], 'id_equip': obj['equipment']['id'], 'member_status_hab':",
"= _format_equipments(request, i) server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] = limit server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i]) try:",
"agreed to in writing, software # distributed under the License is distributed on",
"pool_members = [] equips = request.POST.getlist('id_equip') for i in range(0, len(equips)): server_pool_members =",
"\":\" in ips['ip_formated'] else None return v4, v6 def format_name_ip_search(name): try: ip =",
"Foundation (ASF) under one or more # contributor license agreements. See the NOTICE",
"return obj['id'] def find_servicedownaction_object(client, option_name=None, id=None): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id: for obj",
"def populate_enviroments_choices(client): enviroments = client.create_pool().list_all_environment_related_environment_vip() enviroments_choices = [('', '-')] # Format enviroments for",
"servicedownaction[\"name\"] = str(find_servicedownaction_object(client, id=servicedownaction['id'])) return servicedownaction def format_server_pool_members(request, limit=0): pool_members = [] equips",
"healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect') healthcheck_destination = request.POST.get('healthcheck_destination') healthcheck[\"destination\"]",
"file to You under the Apache License, Version 2.0 # (the \"License\"); you",
"member_status = '1%s%s' % ( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"] = int(member_status, 2) except:",
"members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i],",
"str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] = _format_equipments(request, i) server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] =",
"ips if \":\" in ips['ip_formated'] else None return v4, v6 def format_name_ip_search(name): try:",
"except: search = {'nome': name} else: if ip.version == 6: ip = ip.compressed.split(':')",
"def _format_equipments(request, i): equipments = dict() equipments[\"id\"] = int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] = str(request.POST.getlist('equip')[i]) return",
"optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name'])) return optionspool_choices def populate_pool_members_by_lists(client, members): pool_members = [] ip_list_full =",
"= v6 pool_members.append(server_pool_members) return pool_members def _format_equipments(request, i): equipments = dict() equipments[\"id\"] =",
"# Unless required by applicable law or agreed to in writing, software #",
"= client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices = [('', '-')] for obj in optionspool: servicedownaction_choices.append((obj['id'], obj['name'])) return",
"may not use this file except in compliance with # the License. You",
"by applicable law or agreed to in writing, software # distributed under the",
"pool_members def format_healthcheck(request): healthcheck = dict() healthcheck[\"identifier\"] = \"\" healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"]",
"populate_optionspool_choices(client, environment): optionspool_choices = [('', '-')] optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment) is not",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"return obj def populate_optionspool_choices(client, environment): optionspool_choices = [('', '-')] optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if",
"bin(int(obj.get('member_status')))[2:5].zfill(3) ip = obj['ip'] if obj['ip'] else obj['ipv6'] pool_members.append( {'id': obj['id'], 'id_equip': obj['equipment']['id'],",
"search = {'nome': name} else: if ip.version == 6: ip = ip.compressed.split(':') search",
"== option_name: return obj def populate_optionspool_choices(client, environment): optionspool_choices = [('', '-')] optionspools =",
"id=None): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id: for obj in optionspool: if obj['id'] ==",
"== option_name: return obj['id'] def find_servicedownaction_object(client, option_name=None, id=None): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id:",
"option_name: return obj def populate_optionspool_choices(client, environment): optionspool_choices = [('', '-')] optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"])",
"members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i] }) ip_list_full.append({'id':",
"'member_status_updown': mbs[2], 'member_status': obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'], 'priority': obj['priority'], 'port_real': obj['port_real'], 'weight': obj['weight'], 'id_ip':",
"healthcheck_destination = request.POST.get('healthcheck_destination') healthcheck[\"destination\"] = (\"*:%s\" % healthcheck_destination) \\ if healthcheck_destination else '*:*'",
"[] equips = request.POST.getlist('id_equip') for i in range(0, len(equips)): server_pool_members = dict() server_pool_members[\"id\"]",
"healthcheck_choices def find_servicedownaction_id(client, option_name): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj in optionspool: if obj['name']",
"equipments[\"nome\"] = str(request.POST.getlist('equip')[i]) return equipments def _format_ips(request, i): ips = dict() ips[\"id\"] =",
"# Licensed to the Apache Software Foundation (ASF) under one or more #",
"optionspool_choices = [('', '-')] optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment) is not int else",
"if ip.version == 6: ip = ip.compressed.split(':') search = { 'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2':",
"more # contributor license agreements. See the NOTICE file distributed with # this",
"obj['weight'], 'id_ip': ip['id'] if ip else '', 'ip': ip['ip_formated'] if ip else ''})",
"int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] = str(find_servicedownaction_object(client, id=servicedownaction['id'])) return servicedownaction def format_server_pool_members(request, limit=0): pool_members = []",
"\\ if request.POST.getlist('id_pool_member')[i] else None server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] =",
"License for the specific language governing permissions and # limitations under the License.",
"ip_list_full def populate_pool_members_by_obj(server_pool_members): pool_members = [] for obj in server_pool_members: mbs = bin(int(obj.get('member_status')))[2:5].zfill(3)",
"Apache Software Foundation (ASF) under one or more # contributor license agreements. See",
"to in writing, software # distributed under the License is distributed on an",
"to You under the Apache License, Version 2.0 # (the \"License\"); you may",
"implied. # See the License for the specific language governing permissions and #",
"expectstring_choices def populate_enviroments_choices(client): enviroments = client.create_pool().list_all_environment_related_environment_vip() enviroments_choices = [('', '-')] # Format enviroments",
"limit server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i]) try: member_status = '1%s%s' % ( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] )",
"permissions and # limitations under the License. import ipaddress def populate_expectstring_choices(client): expectstring_choices =",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"- %s - %s\" % (obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name']))) return enviroments_choices def populate_optionsvips_choices(client, tips='Balanceamento'):",
"the Apache License, Version 2.0 # (the \"License\"); you may not use this",
"[] for obj in server_pool_members: mbs = bin(int(obj.get('member_status')))[2:5].zfill(3) ip = obj['ip'] if obj['ip']",
"\"License\"); you may not use this file except in compliance with # the",
"and there is no separation of hab and updown server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i]) v4,",
"members): pool_members = [] ip_list_full = [] if len(members.get(\"ports_reals\")) > 0 and len(members.get(\"ips\"))",
"= ips if \".\" in ips['ip_formated'] else None v6 = ips if \":\"",
"Format enviroments for obj in enviroments: enviroments_choices.append((obj['id'], \"%s - %s - %s\" %",
"for obj in optionsvips['option_vip']: if obj['tipo_opcao'] == tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return optionsvips_choices def",
"% (obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name']))) return enviroments_choices def populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips = client.create_option_vip().get_all() optionsvips_choices",
"'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7':",
"'weight': members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i] }) ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]}) return pool_members,",
"= dict() servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] = str(find_servicedownaction_object(client, id=servicedownaction['id'])) return servicedownaction def format_server_pool_members(request,",
"obj in optionspool: if obj['name'] == option_name: return obj def populate_optionspool_choices(client, environment): optionspool_choices",
"return pool_members def format_healthcheck(request): healthcheck = dict() healthcheck[\"identifier\"] = \"\" healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck'))",
"or implied. # See the License for the specific language governing permissions and",
"try: ip = ipaddress.ip_address(name) except: search = {'nome': name} else: if ip.version ==",
"ip = ip.compressed.split('.') search = { 'ipequipamento__ip__oct1': ip[0], 'ipequipamento__ip__oct2': ip[1], 'ipequipamento__ip__oct3': ip[2], 'ipequipamento__ip__oct4':",
"return servicedownaction_choices def populate_healthcheck_choices(client): optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices = [('', '-')] for obj",
"equipments = dict() equipments[\"id\"] = int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] = str(request.POST.getlist('equip')[i]) return equipments def _format_ips(request,",
"= ip.compressed.split(':') search = { 'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4': ip[3],",
"'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i], 'ip':",
"= int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] = _format_equipments(request, i) server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] = limit server_pool_members[\"port_real\"]",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"= dict() ips[\"id\"] = int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i]) v4 = ips if \".\"",
"ip_list_full = [] if len(members.get(\"ports_reals\")) > 0 and len(members.get(\"ips\")) > 0: for i",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"pool_members def _format_equipments(request, i): equipments = dict() equipments[\"id\"] = int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] = str(request.POST.getlist('equip')[i])",
"in writing, software # distributed under the License is distributed on an \"AS",
"the Apache Software Foundation (ASF) under one or more # contributor license agreements.",
"#When copying a pool, information required was already sent in request # and",
"[] ip_list_full = [] if len(members.get(\"ports_reals\")) > 0 and len(members.get(\"ips\")) > 0: for",
"members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i] }) ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]}) return",
"i in range(0, len(members.get(\"ports_reals\"))): pool_members.append({ 'id': members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i],",
"if ip.version == 4: ip = ip.compressed.split('.') search = { 'ipequipamento__ip__oct1': ip[0], 'ipequipamento__ip__oct2':",
"6: ip = ip.compressed.split(':') search = { 'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3': ip[2],",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'], 'priority': obj['priority'], 'port_real': obj['port_real'], 'weight': obj['weight'], 'id_ip': ip['id'] if ip",
"obj in optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name'])) return optionspool_choices def populate_pool_members_by_lists(client, members): pool_members = []",
"id: return obj['name'] for obj in optionspool: if obj['name'] == option_name: return obj",
"'-')) return expectstring_choices def populate_enviroments_choices(client): enviroments = client.create_pool().list_all_environment_related_environment_vip() enviroments_choices = [('', '-')] #",
"'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8': ip[7] } if ip.version == 4: ip =",
"def format_name_ip_search(name): try: ip = ipaddress.ip_address(name) except: search = {'nome': name} else: if",
"populate_enviroments_choices(client): enviroments = client.create_pool().list_all_environment_related_environment_vip() enviroments_choices = [('', '-')] # Format enviroments for obj",
"v4 = ips if \".\" in ips['ip_formated'] else None v6 = ips if",
"for obj in optionspool: healthcheck_choices.append((obj['name'], obj['name'])) return healthcheck_choices def find_servicedownaction_id(client, option_name): optionspool =",
"= request.POST.getlist('id_equip') for i in range(0, len(equips)): server_pool_members = dict() server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i])",
"i) server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] = limit server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i]) try: member_status =",
"under the License. import ipaddress def populate_expectstring_choices(client): expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('', '-'))",
"}) ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]}) return pool_members, ip_list_full def populate_pool_members_by_obj(server_pool_members): pool_members = []",
"obj['id'], 'id_equip': obj['equipment']['id'], 'member_status_hab': mbs[1], 'member_status_updown': mbs[2], 'member_status': obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'], 'priority': obj['priority'],",
"for obj in optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name'])) return optionspool_choices def populate_pool_members_by_lists(client, members): pool_members =",
"len(equips)): server_pool_members = dict() server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i]) \\ if request.POST.getlist('id_pool_member')[i] else None server_pool_members[\"identifier\"]",
"is not int else \\ client.create_pool().get_opcoes_pool_by_environment(environment) for obj in optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name'])) return",
"healthcheck[\"destination\"] = (\"*:%s\" % healthcheck_destination) \\ if healthcheck_destination else '*:*' return healthcheck def",
"you may not use this file except in compliance with # the License.",
"in optionspool: if obj['name'] == option_name: return obj def populate_optionspool_choices(client, environment): optionspool_choices =",
"request.POST.get('healthcheck_expect') healthcheck_destination = request.POST.get('healthcheck_destination') healthcheck[\"destination\"] = (\"*:%s\" % healthcheck_destination) \\ if healthcheck_destination else",
"[('', '-')] for obj in optionspool: healthcheck_choices.append((obj['name'], obj['name'])) return healthcheck_choices def find_servicedownaction_id(client, option_name):",
"obj['tipo_opcao'] == tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return optionsvips_choices def populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction')",
"'priority': obj['priority'], 'port_real': obj['port_real'], 'weight': obj['weight'], 'id_ip': ip['id'] if ip else '', 'ip':",
"= [('', '-')] for obj in optionspool: servicedownaction_choices.append((obj['id'], obj['name'])) return servicedownaction_choices def populate_healthcheck_choices(client):",
"server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i]) v4, v6 = _format_ips(request, i) server_pool_members[\"ip\"] = v4 server_pool_members[\"ipv6\"] =",
"v6 def format_name_ip_search(name): try: ip = ipaddress.ip_address(name) except: search = {'nome': name} else:",
"use this file except in compliance with # the License. You may obtain",
"language governing permissions and # limitations under the License. import ipaddress def populate_expectstring_choices(client):",
"def _format_ips(request, i): ips = dict() ips[\"id\"] = int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i]) v4",
"obj['nome_opcao_txt'])) return optionsvips_choices def populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices = [('', '-')]",
"for i in range(0, len(members.get(\"ports_reals\"))): pool_members.append({ 'id': members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i], 'priority':",
"def populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices = [('', '-')] for obj in",
"obj['ipv6'] pool_members.append( {'id': obj['id'], 'id_equip': obj['equipment']['id'], 'member_status_hab': mbs[1], 'member_status_updown': mbs[2], 'member_status': obj[\"member_status\"], 'nome_equipamento':",
"Software Foundation (ASF) under one or more # contributor license agreements. See the",
"optionsvips_choices def populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices = [('', '-')] for obj",
"'nome_equipamento': members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i] })",
"len(members.get(\"ports_reals\")) > 0 and len(members.get(\"ips\")) > 0: for i in range(0, len(members.get(\"ports_reals\"))): pool_members.append({",
"== 4: ip = ip.compressed.split('.') search = { 'ipequipamento__ip__oct1': ip[0], 'ipequipamento__ip__oct2': ip[1], 'ipequipamento__ip__oct3':",
"} if ip.version == 4: ip = ip.compressed.split('.') search = { 'ipequipamento__ip__oct1': ip[0],",
"'port_real': members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i] }) ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]})",
"copying a pool, information required was already sent in request # and there",
"is no separation of hab and updown server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i]) v4, v6 =",
"a pool, information required was already sent in request # and there is",
"in range(0, len(members.get(\"ports_reals\"))): pool_members.append({ 'id': members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i], 'port_real':",
"_format_ips(request, i): ips = dict() ips[\"id\"] = int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i]) v4 =",
"int else \\ client.create_pool().get_opcoes_pool_by_environment(environment) for obj in optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name'])) return optionspool_choices def",
"= [('', '-')] for obj in optionsvips['option_vip']: if obj['tipo_opcao'] == tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt']))",
"search = { 'ipequipamento__ip__oct1': ip[0], 'ipequipamento__ip__oct2': ip[1], 'ipequipamento__ip__oct3': ip[2], 'ipequipamento__ip__oct4': ip[3] } return",
"v4 server_pool_members[\"ipv6\"] = v6 pool_members.append(server_pool_members) return pool_members def _format_equipments(request, i): equipments = dict()",
"= str(request.POST.getlist('ip')[i]) v4 = ips if \".\" in ips['ip_formated'] else None v6 =",
"obj['ambiente_logico_name'], obj['grupo_l3_name']))) return enviroments_choices def populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips = client.create_option_vip().get_all() optionsvips_choices = [('',",
"None server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] = _format_equipments(request, i) server_pool_members[\"weight\"] =",
"pool, information required was already sent in request # and there is no",
"0: for i in range(0, len(members.get(\"ports_reals\"))): pool_members.append({ 'id': members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i],",
"enviroments_choices def populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips = client.create_option_vip().get_all() optionsvips_choices = [('', '-')] for obj",
"int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i]) v4 = ips if \".\" in ips['ip_formated'] else None",
"ip.version == 6: ip = ip.compressed.split(':') search = { 'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2': ip[1],",
"option_name=None, id=None): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id: for obj in optionspool: if obj['id']",
"information required was already sent in request # and there is no separation",
"pool_members, ip_list_full def populate_pool_members_by_obj(server_pool_members): pool_members = [] for obj in server_pool_members: mbs =",
"= client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('', '-')) return expectstring_choices def populate_enviroments_choices(client): enviroments = client.create_pool().list_all_environment_related_environment_vip() enviroments_choices",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"obj['grupo_l3_name']))) return enviroments_choices def populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips = client.create_option_vip().get_all() optionsvips_choices = [('', '-')]",
"range(0, len(members.get(\"ports_reals\"))): pool_members.append({ 'id': members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i],",
"'-')] optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment) is not int else \\ client.create_pool().get_opcoes_pool_by_environment(environment) for",
"# (the \"License\"); you may not use this file except in compliance with",
"option_name: return obj['id'] def find_servicedownaction_object(client, option_name=None, id=None): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id: for",
"already sent in request # and there is no separation of hab and",
"[] if len(members.get(\"ports_reals\")) > 0 and len(members.get(\"ips\")) > 0: for i in range(0,",
"if obj['ip'] else obj['ipv6'] pool_members.append( {'id': obj['id'], 'id_equip': obj['equipment']['id'], 'member_status_hab': mbs[1], 'member_status_updown': mbs[2],",
") server_pool_members[\"member_status\"] = int(member_status, 2) except: #When copying a pool, information required was",
"= client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj in optionspool: if obj['name'] == option_name: return obj['id'] def",
"# # Unless required by applicable law or agreed to in writing, software",
"express or implied. # See the License for the specific language governing permissions",
"except in compliance with # the License. You may obtain a copy of",
"for obj in enviroments: enviroments_choices.append((obj['id'], \"%s - %s - %s\" % (obj['divisao_dc_name'], obj['ambiente_logico_name'],",
"file distributed with # this work for additional information regarding copyright ownership. #",
"else None v6 = ips if \":\" in ips['ip_formated'] else None return v4,",
"= str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] = _format_equipments(request, i) server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"]",
"(ASF) under one or more # contributor license agreements. See the NOTICE file",
"= int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i]) v4 = ips if \".\" in ips['ip_formated'] else",
"= [('', '-')] # Format enviroments for obj in enviroments: enviroments_choices.append((obj['id'], \"%s -",
"the License. You may obtain a copy of the License at # #",
"ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]}) return pool_members, ip_list_full def populate_pool_members_by_obj(server_pool_members): pool_members = [] for",
"return pool_members, ip_list_full def populate_pool_members_by_obj(server_pool_members): pool_members = [] for obj in server_pool_members: mbs",
"either express or implied. # See the License for the specific language governing",
"License. import ipaddress def populate_expectstring_choices(client): expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('', '-')) return expectstring_choices",
"= {'nome': name} else: if ip.version == 6: ip = ip.compressed.split(':') search =",
"dict() ips[\"id\"] = int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i]) v4 = ips if \".\" in",
"or more # contributor license agreements. See the NOTICE file distributed with #",
"int(request.POST.getlist('id_pool_member')[i]) \\ if request.POST.getlist('id_pool_member')[i] else None server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"]",
"server_pool_members[\"equipment\"] = _format_equipments(request, i) server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] = limit server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i])",
"expectstring_choices['healthcheck_expect'].insert(0, ('', '-')) return expectstring_choices def populate_enviroments_choices(client): enviroments = client.create_pool().list_all_environment_related_environment_vip() enviroments_choices = [('',",
"ip.version == 4: ip = ip.compressed.split('.') search = { 'ipequipamento__ip__oct1': ip[0], 'ipequipamento__ip__oct2': ip[1],",
"return obj['name'] for obj in optionspool: if obj['name'] == option_name: return obj def",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"enviroments_choices = [('', '-')] # Format enviroments for obj in enviroments: enviroments_choices.append((obj['id'], \"%s",
"option_name): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj in optionspool: if obj['name'] == option_name: return",
"= client.create_option_vip().get_all() optionsvips_choices = [('', '-')] for obj in optionsvips['option_vip']: if obj['tipo_opcao'] ==",
"i) server_pool_members[\"ip\"] = v4 server_pool_members[\"ipv6\"] = v6 pool_members.append(server_pool_members) return pool_members def _format_equipments(request, i):",
"optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return optionsvips_choices def populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices = [('',",
"= int(request.POST.getlist('ports_real_reals')[i]) try: member_status = '1%s%s' % ( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"] =",
"( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"] = int(member_status, 2) except: #When copying a pool,",
"= client.create_pool().list_all_environment_related_environment_vip() enviroments_choices = [('', '-')] # Format enviroments for obj in enviroments:",
"license agreements. See the NOTICE file distributed with # this work for additional",
"in optionspool: healthcheck_choices.append((obj['name'], obj['name'])) return healthcheck_choices def find_servicedownaction_id(client, option_name): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for",
"ip else '', 'ip': ip['ip_formated'] if ip else ''}) return pool_members def format_healthcheck(request):",
"= dict() healthcheck[\"identifier\"] = \"\" healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] =",
"if obj['name'] == option_name: return obj['id'] def find_servicedownaction_object(client, option_name=None, id=None): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction')",
"licenses this file to You under the Apache License, Version 2.0 # (the",
"'id_equip': obj['equipment']['id'], 'member_status_hab': mbs[1], 'member_status_updown': mbs[2], 'member_status': obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'], 'priority': obj['priority'], 'port_real':",
"if request.POST.getlist('id_pool_member')[i] else None server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] = _format_equipments(request,",
"under the Apache License, Version 2.0 # (the \"License\"); you may not use",
"= dict() server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i]) \\ if request.POST.getlist('id_pool_member')[i] else None server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i])",
"else None server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] = _format_equipments(request, i) server_pool_members[\"weight\"]",
"# limitations under the License. import ipaddress def populate_expectstring_choices(client): expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0,",
"else None return v4, v6 def format_name_ip_search(name): try: ip = ipaddress.ip_address(name) except: search",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"healthcheck_choices.append((obj['name'], obj['name'])) return healthcheck_choices def find_servicedownaction_id(client, option_name): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj in",
"'id_ip': ip['id'] if ip else '', 'ip': ip['ip_formated'] if ip else ''}) return",
"Version 2.0 # (the \"License\"); you may not use this file except in",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"optionspool: if obj['name'] == option_name: return obj def populate_optionspool_choices(client, environment): optionspool_choices = [('',",
"= [('', '-')] optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment) is not int else \\",
"mbs[2], 'member_status': obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'], 'priority': obj['priority'], 'port_real': obj['port_real'], 'weight': obj['weight'], 'id_ip': ip['id']",
"and updown server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i]) v4, v6 = _format_ips(request, i) server_pool_members[\"ip\"] = v4",
"optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment) is not int else \\ client.create_pool().get_opcoes_pool_by_environment(environment) for obj",
"(\"*:%s\" % healthcheck_destination) \\ if healthcheck_destination else '*:*' return healthcheck def format_servicedownaction(client, form):",
"-*- coding:utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one",
"servicedownaction = dict() servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] = str(find_servicedownaction_object(client, id=servicedownaction['id'])) return servicedownaction def",
"return expectstring_choices def populate_enviroments_choices(client): enviroments = client.create_pool().list_all_environment_related_environment_vip() enviroments_choices = [('', '-')] # Format",
"populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices = [('', '-')] for obj in optionspool:",
"= \"\" healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect') healthcheck_destination =",
"client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj in optionspool: if obj['name'] == option_name: return obj['id'] def find_servicedownaction_object(client,",
"# contributor license agreements. See the NOTICE file distributed with # this work",
"sent in request # and there is no separation of hab and updown",
"optionspool: servicedownaction_choices.append((obj['id'], obj['name'])) return servicedownaction_choices def populate_healthcheck_choices(client): optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices = [('',",
"format_servicedownaction(client, form): servicedownaction = dict() servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] = str(find_servicedownaction_object(client, id=servicedownaction['id'])) return",
"str(find_servicedownaction_object(client, id=servicedownaction['id'])) return servicedownaction def format_server_pool_members(request, limit=0): pool_members = [] equips = request.POST.getlist('id_equip')",
"See the NOTICE file distributed with # this work for additional information regarding",
"\\ client.create_pool().get_opcoes_pool_by_environment(environment) for obj in optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name'])) return optionspool_choices def populate_pool_members_by_lists(client, members):",
"def populate_optionspool_choices(client, environment): optionspool_choices = [('', '-')] optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment) is",
"members.get(\"ips\")[i]}) return pool_members, ip_list_full def populate_pool_members_by_obj(server_pool_members): pool_members = [] for obj in server_pool_members:",
"obj['name'] == option_name: return obj def populate_optionspool_choices(client, environment): optionspool_choices = [('', '-')] optionspools",
"= ipaddress.ip_address(name) except: search = {'nome': name} else: if ip.version == 6: ip",
"search = { 'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5': ip[4],",
"populate_expectstring_choices(client): expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('', '-')) return expectstring_choices def populate_enviroments_choices(client): enviroments =",
"request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect') healthcheck_destination = request.POST.get('healthcheck_destination') healthcheck[\"destination\"] = (\"*:%s\" % healthcheck_destination) \\",
"find_servicedownaction_id(client, option_name): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj in optionspool: if obj['name'] == option_name:",
"with # the License. You may obtain a copy of the License at",
"obj['name'] == option_name: return obj['id'] def find_servicedownaction_object(client, option_name=None, id=None): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if",
"= str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect') healthcheck_destination = request.POST.get('healthcheck_destination') healthcheck[\"destination\"] =",
"def format_server_pool_members(request, limit=0): pool_members = [] equips = request.POST.getlist('id_equip') for i in range(0,",
"equipments def _format_ips(request, i): ips = dict() ips[\"id\"] = int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i])",
"'weight': obj['weight'], 'id_ip': ip['id'] if ip else '', 'ip': ip['ip_formated'] if ip else",
"v6 pool_members.append(server_pool_members) return pool_members def _format_equipments(request, i): equipments = dict() equipments[\"id\"] = int(request.POST.getlist('id_equip')[i])",
"under one or more # contributor license agreements. See the NOTICE file distributed",
"'-')] # Format enviroments for obj in enviroments: enviroments_choices.append((obj['id'], \"%s - %s -",
"ipaddress def populate_expectstring_choices(client): expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('', '-')) return expectstring_choices def populate_enviroments_choices(client):",
"form): servicedownaction = dict() servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] = str(find_servicedownaction_object(client, id=servicedownaction['id'])) return servicedownaction",
"= dict() equipments[\"id\"] = int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] = str(request.POST.getlist('equip')[i]) return equipments def _format_ips(request, i):",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"# the License. You may obtain a copy of the License at #",
"int(request.POST.getlist('member_status')[i]) v4, v6 = _format_ips(request, i) server_pool_members[\"ip\"] = v4 server_pool_members[\"ipv6\"] = v6 pool_members.append(server_pool_members)",
"= client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment) is not int else \\ client.create_pool().get_opcoes_pool_by_environment(environment) for obj in",
"the License. import ipaddress def populate_expectstring_choices(client): expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('', '-')) return",
"this file to You under the Apache License, Version 2.0 # (the \"License\");",
"not use this file except in compliance with # the License. You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"request.POST.get('healthcheck_destination') healthcheck[\"destination\"] = (\"*:%s\" % healthcheck_destination) \\ if healthcheck_destination else '*:*' return healthcheck",
"server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] = _format_equipments(request, i) server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] = limit",
"You under the Apache License, Version 2.0 # (the \"License\"); you may not",
"no separation of hab and updown server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i]) v4, v6 = _format_ips(request,",
"obj['equipment']['id'], 'member_status_hab': mbs[1], 'member_status_updown': mbs[2], 'member_status': obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'], 'priority': obj['priority'], 'port_real': obj['port_real'],",
"healthcheck_destination else '*:*' return healthcheck def format_servicedownaction(client, form): servicedownaction = dict() servicedownaction[\"id\"] =",
"None v6 = ips if \":\" in ips['ip_formated'] else None return v4, v6",
"'-')] for obj in optionspool: servicedownaction_choices.append((obj['id'], obj['name'])) return servicedownaction_choices def populate_healthcheck_choices(client): optionspool =",
"one or more # contributor license agreements. See the NOTICE file distributed with",
"ip[1], 'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8': ip[7]",
"format_name_ip_search(name): try: ip = ipaddress.ip_address(name) except: search = {'nome': name} else: if ip.version",
"populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips = client.create_option_vip().get_all() optionsvips_choices = [('', '-')] for obj in optionsvips['option_vip']:",
"and len(members.get(\"ips\")) > 0: for i in range(0, len(members.get(\"ports_reals\"))): pool_members.append({ 'id': members.get(\"id_pool_member\")[i], 'id_equip':",
"return healthcheck def format_servicedownaction(client, form): servicedownaction = dict() servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"] =",
"ips[\"ip_formated\"] = str(request.POST.getlist('ip')[i]) v4 = ips if \".\" in ips['ip_formated'] else None v6",
"for obj in optionspool: if obj['name'] == option_name: return obj['id'] def find_servicedownaction_object(client, option_name=None,",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"[('', '-')] for obj in optionspool: servicedownaction_choices.append((obj['id'], obj['name'])) return servicedownaction_choices def populate_healthcheck_choices(client): optionspool",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"= ip.compressed.split('.') search = { 'ipequipamento__ip__oct1': ip[0], 'ipequipamento__ip__oct2': ip[1], 'ipequipamento__ip__oct3': ip[2], 'ipequipamento__ip__oct4': ip[3]",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices = [('', '-')] for obj in optionspool: servicedownaction_choices.append((obj['id'], obj['name']))",
"Licensed to the Apache Software Foundation (ASF) under one or more # contributor",
"obj['equipment']['name'], 'priority': obj['priority'], 'port_real': obj['port_real'], 'weight': obj['weight'], 'id_ip': ip['id'] if ip else '',",
"format_server_pool_members(request, limit=0): pool_members = [] equips = request.POST.getlist('id_equip') for i in range(0, len(equips)):",
"v4, v6 = _format_ips(request, i) server_pool_members[\"ip\"] = v4 server_pool_members[\"ipv6\"] = v6 pool_members.append(server_pool_members) return",
"def find_servicedownaction_id(client, option_name): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj in optionspool: if obj['name'] ==",
"v4, v6 def format_name_ip_search(name): try: ip = ipaddress.ip_address(name) except: search = {'nome': name}",
"pool_members.append( {'id': obj['id'], 'id_equip': obj['equipment']['id'], 'member_status_hab': mbs[1], 'member_status_updown': mbs[2], 'member_status': obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'],",
"request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"] = int(member_status, 2) except: #When copying a pool, information required",
"and # limitations under the License. import ipaddress def populate_expectstring_choices(client): expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct()",
"limitations under the License. import ipaddress def populate_expectstring_choices(client): expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('',",
"See the License for the specific language governing permissions and # limitations under",
"for obj in optionspool: servicedownaction_choices.append((obj['id'], obj['name'])) return servicedownaction_choices def populate_healthcheck_choices(client): optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck')",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8':",
"servicedownaction_choices = [('', '-')] for obj in optionspool: servicedownaction_choices.append((obj['id'], obj['name'])) return servicedownaction_choices def",
"optionspool_choices.append((obj['id'], obj['name'])) return optionspool_choices def populate_pool_members_by_lists(client, members): pool_members = [] ip_list_full = []",
"str(request.POST.getlist('ip')[i]) v4 = ips if \".\" in ips['ip_formated'] else None v6 = ips",
"optionspool: healthcheck_choices.append((obj['name'], obj['name'])) return healthcheck_choices def find_servicedownaction_id(client, option_name): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj",
"client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment) is not int else \\ client.create_pool().get_opcoes_pool_by_environment(environment) for obj in optionspools['options_pool']:",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"= bin(int(obj.get('member_status')))[2:5].zfill(3) ip = obj['ip'] if obj['ip'] else obj['ipv6'] pool_members.append( {'id': obj['id'], 'id_equip':",
"in optionspool: if obj['id'] == id: return obj['name'] for obj in optionspool: if",
"populate_pool_members_by_obj(server_pool_members): pool_members = [] for obj in server_pool_members: mbs = bin(int(obj.get('member_status')))[2:5].zfill(3) ip =",
"= int(request.POST.getlist('member_status')[i]) v4, v6 = _format_ips(request, i) server_pool_members[\"ip\"] = v4 server_pool_members[\"ipv6\"] = v6",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"(the \"License\"); you may not use this file except in compliance with #",
"else ''}) return pool_members def format_healthcheck(request): healthcheck = dict() healthcheck[\"identifier\"] = \"\" healthcheck[\"healthcheck_type\"]",
"else \\ client.create_pool().get_opcoes_pool_by_environment(environment) for obj in optionspools['options_pool']: optionspool_choices.append((obj['id'], obj['name'])) return optionspool_choices def populate_pool_members_by_lists(client,",
"def populate_pool_members_by_obj(server_pool_members): pool_members = [] for obj in server_pool_members: mbs = bin(int(obj.get('member_status')))[2:5].zfill(3) ip",
"try: member_status = '1%s%s' % ( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"] = int(member_status, 2)",
"for additional information regarding copyright ownership. # The ASF licenses this file to",
"def find_servicedownaction_object(client, option_name=None, id=None): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id: for obj in optionspool:",
"'ipv6equipament__ip__oct7': ip[6], 'ipv6equipament__ip__oct8': ip[7] } if ip.version == 4: ip = ip.compressed.split('.') search",
"obj in optionspool: healthcheck_choices.append((obj['name'], obj['name'])) return healthcheck_choices def find_servicedownaction_id(client, option_name): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction')",
"optionspool: if obj['id'] == id: return obj['name'] for obj in optionspool: if obj['name']",
"members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i], 'id_ip': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]",
"# and there is no separation of hab and updown server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i])",
"= '1%s%s' % ( request.POST.getlist('member_status_hab')[i], request.POST.getlist('member_status_updown')[i] ) server_pool_members[\"member_status\"] = int(member_status, 2) except: #When",
"range(0, len(equips)): server_pool_members = dict() server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i]) \\ if request.POST.getlist('id_pool_member')[i] else None",
"client.create_pool().list_all_environment_related_environment_vip() enviroments_choices = [('', '-')] # Format enviroments for obj in enviroments: enviroments_choices.append((obj['id'],",
"obj['ip'] if obj['ip'] else obj['ipv6'] pool_members.append( {'id': obj['id'], 'id_equip': obj['equipment']['id'], 'member_status_hab': mbs[1], 'member_status_updown':",
"'id_ip': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i] }) ip_list_full.append({'id': members.get(\"id_ips\")[i], 'ip': members.get(\"ips\")[i]}) return pool_members, ip_list_full def",
"str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect') healthcheck_destination = request.POST.get('healthcheck_destination') healthcheck[\"destination\"] = (\"*:%s\"",
"('', '-')) return expectstring_choices def populate_enviroments_choices(client): enviroments = client.create_pool().list_all_environment_related_environment_vip() enviroments_choices = [('', '-')]",
"additional information regarding copyright ownership. # The ASF licenses this file to You",
"contributor license agreements. See the NOTICE file distributed with # this work for",
"pool_members.append(server_pool_members) return pool_members def _format_equipments(request, i): equipments = dict() equipments[\"id\"] = int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"]",
"obj['id'] def find_servicedownaction_object(client, option_name=None, id=None): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id: for obj in",
"there is no separation of hab and updown server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i]) v4, v6",
"of hab and updown server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i]) v4, v6 = _format_ips(request, i) server_pool_members[\"ip\"]",
"return equipments def _format_ips(request, i): ips = dict() ips[\"id\"] = int(request.POST.getlist('id_ip')[i]) ips[\"ip_formated\"] =",
"int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] = str(request.POST.getlist('equip')[i]) return equipments def _format_ips(request, i): ips = dict() ips[\"id\"]",
"pool_members.append({ 'id': members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i],",
"def populate_healthcheck_choices(client): optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices = [('', '-')] for obj in optionspool:",
"equips = request.POST.getlist('id_equip') for i in range(0, len(equips)): server_pool_members = dict() server_pool_members[\"id\"] =",
"\"\" healthcheck[\"healthcheck_type\"] = str(request.POST.get('healthcheck')) healthcheck[\"healthcheck_request\"] = request.POST.get('healthcheck_request') healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect') healthcheck_destination = request.POST.get('healthcheck_destination')",
"'id': members.get(\"id_pool_member\")[i], 'id_equip': members.get(\"id_equips\")[i], 'nome_equipamento': members.get(\"name_equips\")[i], 'priority': members.get(\"priorities\")[i], 'port_real': members.get(\"ports_reals\")[i], 'weight': members.get(\"weight\")[i], 'id_ip':",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"optionspool: if obj['name'] == option_name: return obj['id'] def find_servicedownaction_object(client, option_name=None, id=None): optionspool =",
"obj in optionspool: servicedownaction_choices.append((obj['id'], obj['name'])) return servicedownaction_choices def populate_healthcheck_choices(client): optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices",
"in range(0, len(equips)): server_pool_members = dict() server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i]) \\ if request.POST.getlist('id_pool_member')[i] else",
"return optionsvips_choices def populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices = [('', '-')] for",
"'member_status_hab': mbs[1], 'member_status_updown': mbs[2], 'member_status': obj[\"member_status\"], 'nome_equipamento': obj['equipment']['name'], 'priority': obj['priority'], 'port_real': obj['port_real'], 'weight':",
"= _format_ips(request, i) server_pool_members[\"ip\"] = v4 server_pool_members[\"ipv6\"] = v6 pool_members.append(server_pool_members) return pool_members def",
"'*:*' return healthcheck def format_servicedownaction(client, form): servicedownaction = dict() servicedownaction[\"id\"] = int(form.cleaned_data['servicedownaction']) servicedownaction[\"name\"]",
"%s - %s\" % (obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name']))) return enviroments_choices def populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips",
"server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] = int(request.POST.getlist('priority')[i]) server_pool_members[\"equipment\"] = _format_equipments(request, i) server_pool_members[\"weight\"] = int(request.POST.getlist('weight')[i])",
"if healthcheck_destination else '*:*' return healthcheck def format_servicedownaction(client, form): servicedownaction = dict() servicedownaction[\"id\"]",
"this work for additional information regarding copyright ownership. # The ASF licenses this",
"separation of hab and updown server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i]) v4, v6 = _format_ips(request, i)",
"tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return optionsvips_choices def populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices =",
"if obj['tipo_opcao'] == tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return optionsvips_choices def populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool =",
"optionspool = client.create_option_pool().get_all_option_pool(option_type='HealthCheck') healthcheck_choices = [('', '-')] for obj in optionspool: healthcheck_choices.append((obj['name'], obj['name']))",
"_format_equipments(request, i): equipments = dict() equipments[\"id\"] = int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] = str(request.POST.getlist('equip')[i]) return equipments",
"to the Apache Software Foundation (ASF) under one or more # contributor license",
"healthcheck_destination) \\ if healthcheck_destination else '*:*' return healthcheck def format_servicedownaction(client, form): servicedownaction =",
"ip['id'] if ip else '', 'ip': ip['ip_formated'] if ip else ''}) return pool_members",
"ip['ip_formated'] if ip else ''}) return pool_members def format_healthcheck(request): healthcheck = dict() healthcheck[\"identifier\"]",
"int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] = limit server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i]) try: member_status = '1%s%s' % (",
"with # this work for additional information regarding copyright ownership. # The ASF",
"return healthcheck_choices def find_servicedownaction_id(client, option_name): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') for obj in optionspool: if",
"file except in compliance with # the License. You may obtain a copy",
"information regarding copyright ownership. # The ASF licenses this file to You under",
"def populate_expectstring_choices(client): expectstring_choices = client.create_ambiente().listar_healtchcheck_expect_distinct() expectstring_choices['healthcheck_expect'].insert(0, ('', '-')) return expectstring_choices def populate_enviroments_choices(client): enviroments",
"= int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] = str(request.POST.getlist('equip')[i]) return equipments def _format_ips(request, i): ips = dict()",
"if \".\" in ips['ip_formated'] else None v6 = ips if \":\" in ips['ip_formated']",
"obj def populate_optionspool_choices(client, environment): optionspool_choices = [('', '-')] optionspools = client.create_pool().get_opcoes_pool_by_environment(environment[\"id\"]) if type(environment)",
"def populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips = client.create_option_vip().get_all() optionsvips_choices = [('', '-')] for obj in",
"dict() server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i]) \\ if request.POST.getlist('id_pool_member')[i] else None server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"]",
"return pool_members def _format_equipments(request, i): equipments = dict() equipments[\"id\"] = int(request.POST.getlist('id_equip')[i]) equipments[\"nome\"] =",
"= { 'ipequipamento__ip__oct1': ip[0], 'ipequipamento__ip__oct2': ip[1], 'ipequipamento__ip__oct3': ip[2], 'ipequipamento__ip__oct4': ip[3] } return search",
"return enviroments_choices def populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips = client.create_option_vip().get_all() optionsvips_choices = [('', '-')] for",
"'-')] for obj in optionsvips['option_vip']: if obj['tipo_opcao'] == tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return optionsvips_choices",
"if type(environment) is not int else \\ client.create_pool().get_opcoes_pool_by_environment(environment) for obj in optionspools['options_pool']: optionspool_choices.append((obj['id'],",
"= int(member_status, 2) except: #When copying a pool, information required was already sent",
"hab and updown server_pool_members[\"member_status\"] = int(request.POST.getlist('member_status')[i]) v4, v6 = _format_ips(request, i) server_pool_members[\"ip\"] =",
"-*- # Licensed to the Apache Software Foundation (ASF) under one or more",
"- %s\" % (obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name']))) return enviroments_choices def populate_optionsvips_choices(client, tips='Balanceamento'): optionsvips =",
"healthcheck[\"healthcheck_expect\"] = request.POST.get('healthcheck_expect') healthcheck_destination = request.POST.get('healthcheck_destination') healthcheck[\"destination\"] = (\"*:%s\" % healthcheck_destination) \\ if",
"optionsvips_choices = [('', '-')] for obj in optionsvips['option_vip']: if obj['tipo_opcao'] == tips: optionsvips_choices.append((obj['nome_opcao_txt'],",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"== id: return obj['name'] for obj in optionspool: if obj['name'] == option_name: return",
"= client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') if id: for obj in optionspool: if obj['id'] == id: return",
"ip[0], 'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4': ip[3], 'ipv6equipament__ip__oct5': ip[4], 'ipv6equipament__ip__oct6': ip[5], 'ipv6equipament__ip__oct7': ip[6],",
"server_pool_members[\"id\"] = int(request.POST.getlist('id_pool_member')[i]) \\ if request.POST.getlist('id_pool_member')[i] else None server_pool_members[\"identifier\"] = str(request.POST.getlist('equip')[i]) server_pool_members[\"priority\"] =",
"was already sent in request # and there is no separation of hab",
"ip = ip.compressed.split(':') search = { 'ipv6equipament__ip__oct1': ip[0], 'ipv6equipament__ip__oct2': ip[1], 'ipv6equipament__ip__oct3': ip[2], 'ipv6equipament__ip__oct4':",
"obj['name'])) return optionspool_choices def populate_pool_members_by_lists(client, members): pool_members = [] ip_list_full = [] if",
"if id: for obj in optionspool: if obj['id'] == id: return obj['name'] for",
"= [] ip_list_full = [] if len(members.get(\"ports_reals\")) > 0 and len(members.get(\"ips\")) > 0:",
"obj in enviroments: enviroments_choices.append((obj['id'], \"%s - %s - %s\" % (obj['divisao_dc_name'], obj['ambiente_logico_name'], obj['grupo_l3_name'])))",
"'-')] for obj in optionspool: healthcheck_choices.append((obj['name'], obj['name'])) return healthcheck_choices def find_servicedownaction_id(client, option_name): optionspool",
"= int(request.POST.getlist('weight')[i]) server_pool_members[\"limit\"] = limit server_pool_members[\"port_real\"] = int(request.POST.getlist('ports_real_reals')[i]) try: member_status = '1%s%s' %",
"server_pool_members[\"member_status\"] = int(member_status, 2) except: #When copying a pool, information required was already",
"== tips: optionsvips_choices.append((obj['nome_opcao_txt'], obj['nome_opcao_txt'])) return optionsvips_choices def populate_servicedownaction_choices(client, tips='ServiceDownAction'): optionspool = client.create_option_pool().get_all_option_pool(option_type='ServiceDownAction') servicedownaction_choices",
"if obj['name'] == option_name: return obj def populate_optionspool_choices(client, environment): optionspool_choices = [('', '-')]",
"# The ASF licenses this file to You under the Apache License, Version"
] |
[
"= f(.5) if norm <= .67 else f(1) else: idx = f(0) else:",
"turn = get_agent_turn(x=x, byr=False) # index of action f = wrapper(turn) if turn",
"turn == 6: if self.patient: days4 = get_days(x=x, turn=4) if days4 <= 2.01:",
"else f(1) elif turn == 4: if self.patient: days = get_days(x=x, turn=turn) idx",
"get_agent_turn(x=x, byr=False) # index of action f = wrapper(turn) if turn == 2:",
"numpy as np import torch from agent.heuristics.util import get_agent_turn, wrapper, get_days, \\ get_recent_byr_offers,",
"4: if self.patient: days = get_days(x=x, turn=turn) idx = f(0) if days <=",
"get_days, \\ get_recent_byr_offers, get_last_norm from agent.const import DELTA_SLR, NUM_COMMON_CONS class HeuristicSlr: def __init__(self,",
"# deterministic categorical action distribution pdf = torch.zeros(NUM_COMMON_CONS + 3, dtype=torch.float) pdf[idx] =",
"if days4 <= 2.01: days6 = get_days(x=x, turn=6) idx = f(0) if days6",
"f(1) if num_offers <= .5 else f(0) elif turn == 6: if self.patient:",
"num_offers <= .5 else f(0) elif turn == 6: if self.patient: days4 =",
"self.patient: days4 = get_days(x=x, turn=4) if days4 <= 2.01: days6 = get_days(x=x, turn=6)",
"import numpy as np import torch from agent.heuristics.util import get_agent_turn, wrapper, get_days, \\",
"idx = f(1) if num_offers <= .5 else f(0) elif turn == 6:",
"days = get_days(x=x, turn=turn) tau = 5.05 if self.patient else 3.03 idx =",
"DELTA_SLR, NUM_COMMON_CONS class HeuristicSlr: def __init__(self, delta=None): self.patient = np.isclose(delta, DELTA_SLR[-1]) def __call__(self,",
"f(.5) else: num_offers = get_recent_byr_offers(x=x, turn=turn) idx = f(1) if num_offers <= .5",
"get_days(x=x, turn=turn) idx = f(0) if days <= 2.01 else f(.5) else: num_offers",
"else: raise ValueError('Invalid turn: {}'.format(turn)) # deterministic categorical action distribution pdf = torch.zeros(NUM_COMMON_CONS",
"idx = f(0) if days <= tau else f(1) elif turn == 4:",
".5 else f(0) elif turn == 6: if self.patient: days4 = get_days(x=x, turn=4)",
"days4 = get_days(x=x, turn=4) if days4 <= 2.01: days6 = get_days(x=x, turn=6) idx",
"turn: {}'.format(turn)) # deterministic categorical action distribution pdf = torch.zeros(NUM_COMMON_CONS + 3, dtype=torch.float)",
"get_days(x=x, turn=4) if days4 <= 2.01: days6 = get_days(x=x, turn=6) idx = f(0)",
"= get_days(x=x, turn=6) idx = f(0) if days6 <= 2.04 else f(1) else:",
"= wrapper(turn) if turn == 2: days = get_days(x=x, turn=turn) tau = 5.05",
"HeuristicSlr: def __init__(self, delta=None): self.patient = np.isclose(delta, DELTA_SLR[-1]) def __call__(self, observation=None): # noinspection",
"= f(0) if days <= tau else f(1) elif turn == 4: if",
"f = wrapper(turn) if turn == 2: days = get_days(x=x, turn=turn) tau =",
"2.01 else f(.5) else: num_offers = get_recent_byr_offers(x=x, turn=turn) idx = f(1) if num_offers",
"NUM_COMMON_CONS class HeuristicSlr: def __init__(self, delta=None): self.patient = np.isclose(delta, DELTA_SLR[-1]) def __call__(self, observation=None):",
"delta=None): self.patient = np.isclose(delta, DELTA_SLR[-1]) def __call__(self, observation=None): # noinspection PyProtectedMember x =",
"turn=turn) idx = f(1) if num_offers <= .5 else f(0) elif turn ==",
"2.04 else f(1) else: norm = get_last_norm(x=x, turn=turn) idx = f(.5) if norm",
"# turn number turn = get_agent_turn(x=x, byr=False) # index of action f =",
"days = get_days(x=x, turn=turn) idx = f(0) if days <= 2.01 else f(.5)",
"if self.patient: days = get_days(x=x, turn=turn) idx = f(0) if days <= 2.01",
"# noinspection PyProtectedMember x = observation._asdict() # turn number turn = get_agent_turn(x=x, byr=False)",
"get_last_norm(x=x, turn=turn) idx = f(.5) if norm <= .67 else f(1) else: idx",
"elif turn == 4: if self.patient: days = get_days(x=x, turn=turn) idx = f(0)",
"x = observation._asdict() # turn number turn = get_agent_turn(x=x, byr=False) # index of",
"observation._asdict() # turn number turn = get_agent_turn(x=x, byr=False) # index of action f",
"6: if self.patient: days4 = get_days(x=x, turn=4) if days4 <= 2.01: days6 =",
"else f(1) else: norm = get_last_norm(x=x, turn=turn) idx = f(.5) if norm <=",
"days4 <= 2.01: days6 = get_days(x=x, turn=6) idx = f(0) if days6 <=",
"<= .5 else f(0) elif turn == 6: if self.patient: days4 = get_days(x=x,",
"= np.isclose(delta, DELTA_SLR[-1]) def __call__(self, observation=None): # noinspection PyProtectedMember x = observation._asdict() #",
"f(1) elif turn == 4: if self.patient: days = get_days(x=x, turn=turn) idx =",
"__init__(self, delta=None): self.patient = np.isclose(delta, DELTA_SLR[-1]) def __call__(self, observation=None): # noinspection PyProtectedMember x",
"np import torch from agent.heuristics.util import get_agent_turn, wrapper, get_days, \\ get_recent_byr_offers, get_last_norm from",
"turn=turn) idx = f(.5) if norm <= .67 else f(1) else: idx =",
"if days <= 2.01 else f(.5) else: num_offers = get_recent_byr_offers(x=x, turn=turn) idx =",
"if num_offers <= .5 else f(0) elif turn == 6: if self.patient: days4",
"torch from agent.heuristics.util import get_agent_turn, wrapper, get_days, \\ get_recent_byr_offers, get_last_norm from agent.const import",
"turn number turn = get_agent_turn(x=x, byr=False) # index of action f = wrapper(turn)",
"3.03 idx = f(0) if days <= tau else f(1) elif turn ==",
"f(1) else: norm = get_last_norm(x=x, turn=turn) idx = f(.5) if norm <= .67",
"else f(1) else: idx = f(0) else: raise ValueError('Invalid turn: {}'.format(turn)) # deterministic",
"== 4: if self.patient: days = get_days(x=x, turn=turn) idx = f(0) if days",
"else: num_offers = get_recent_byr_offers(x=x, turn=turn) idx = f(1) if num_offers <= .5 else",
"<= 2.04 else f(1) else: norm = get_last_norm(x=x, turn=turn) idx = f(.5) if",
"idx = f(.5) if norm <= .67 else f(1) else: idx = f(0)",
".67 else f(1) else: idx = f(0) else: raise ValueError('Invalid turn: {}'.format(turn)) #",
"idx = f(0) if days6 <= 2.04 else f(1) else: norm = get_last_norm(x=x,",
"f(1) else: idx = f(0) else: raise ValueError('Invalid turn: {}'.format(turn)) # deterministic categorical",
"ValueError('Invalid turn: {}'.format(turn)) # deterministic categorical action distribution pdf = torch.zeros(NUM_COMMON_CONS + 3,",
"wrapper(turn) if turn == 2: days = get_days(x=x, turn=turn) tau = 5.05 if",
"get_recent_byr_offers(x=x, turn=turn) idx = f(1) if num_offers <= .5 else f(0) elif turn",
"turn == 2: days = get_days(x=x, turn=turn) tau = 5.05 if self.patient else",
"idx = f(0) if days <= 2.01 else f(.5) else: num_offers = get_recent_byr_offers(x=x,",
"f(0) if days <= 2.01 else f(.5) else: num_offers = get_recent_byr_offers(x=x, turn=turn) idx",
"if days <= tau else f(1) elif turn == 4: if self.patient: days",
"{}'.format(turn)) # deterministic categorical action distribution pdf = torch.zeros(NUM_COMMON_CONS + 3, dtype=torch.float) pdf[idx]",
"idx = f(0) else: raise ValueError('Invalid turn: {}'.format(turn)) # deterministic categorical action distribution",
"PyProtectedMember x = observation._asdict() # turn number turn = get_agent_turn(x=x, byr=False) # index",
"turn=4) if days4 <= 2.01: days6 = get_days(x=x, turn=6) idx = f(0) if",
"days6 = get_days(x=x, turn=6) idx = f(0) if days6 <= 2.04 else f(1)",
"days <= 2.01 else f(.5) else: num_offers = get_recent_byr_offers(x=x, turn=turn) idx = f(1)",
"= observation._asdict() # turn number turn = get_agent_turn(x=x, byr=False) # index of action",
"<= 2.01 else f(.5) else: num_offers = get_recent_byr_offers(x=x, turn=turn) idx = f(1) if",
"<= 2.01: days6 = get_days(x=x, turn=6) idx = f(0) if days6 <= 2.04",
"= get_last_norm(x=x, turn=turn) idx = f(.5) if norm <= .67 else f(1) else:",
"wrapper, get_days, \\ get_recent_byr_offers, get_last_norm from agent.const import DELTA_SLR, NUM_COMMON_CONS class HeuristicSlr: def",
"def __call__(self, observation=None): # noinspection PyProtectedMember x = observation._asdict() # turn number turn",
"else 3.03 idx = f(0) if days <= tau else f(1) elif turn",
"else f(0) elif turn == 6: if self.patient: days4 = get_days(x=x, turn=4) if",
"2.01: days6 = get_days(x=x, turn=6) idx = f(0) if days6 <= 2.04 else",
"deterministic categorical action distribution pdf = torch.zeros(NUM_COMMON_CONS + 3, dtype=torch.float) pdf[idx] = 1.",
"class HeuristicSlr: def __init__(self, delta=None): self.patient = np.isclose(delta, DELTA_SLR[-1]) def __call__(self, observation=None): #",
"agent.heuristics.util import get_agent_turn, wrapper, get_days, \\ get_recent_byr_offers, get_last_norm from agent.const import DELTA_SLR, NUM_COMMON_CONS",
"== 6: if self.patient: days4 = get_days(x=x, turn=4) if days4 <= 2.01: days6",
"<= .67 else f(1) else: idx = f(0) else: raise ValueError('Invalid turn: {}'.format(turn))",
"5.05 if self.patient else 3.03 idx = f(0) if days <= tau else",
"get_last_norm from agent.const import DELTA_SLR, NUM_COMMON_CONS class HeuristicSlr: def __init__(self, delta=None): self.patient =",
"get_agent_turn, wrapper, get_days, \\ get_recent_byr_offers, get_last_norm from agent.const import DELTA_SLR, NUM_COMMON_CONS class HeuristicSlr:",
"from agent.const import DELTA_SLR, NUM_COMMON_CONS class HeuristicSlr: def __init__(self, delta=None): self.patient = np.isclose(delta,",
"from agent.heuristics.util import get_agent_turn, wrapper, get_days, \\ get_recent_byr_offers, get_last_norm from agent.const import DELTA_SLR,",
"f(0) elif turn == 6: if self.patient: days4 = get_days(x=x, turn=4) if days4",
"num_offers = get_recent_byr_offers(x=x, turn=turn) idx = f(1) if num_offers <= .5 else f(0)",
"import DELTA_SLR, NUM_COMMON_CONS class HeuristicSlr: def __init__(self, delta=None): self.patient = np.isclose(delta, DELTA_SLR[-1]) def",
"import torch from agent.heuristics.util import get_agent_turn, wrapper, get_days, \\ get_recent_byr_offers, get_last_norm from agent.const",
"DELTA_SLR[-1]) def __call__(self, observation=None): # noinspection PyProtectedMember x = observation._asdict() # turn number",
"raise ValueError('Invalid turn: {}'.format(turn)) # deterministic categorical action distribution pdf = torch.zeros(NUM_COMMON_CONS +",
"= f(0) if days6 <= 2.04 else f(1) else: norm = get_last_norm(x=x, turn=turn)",
"import get_agent_turn, wrapper, get_days, \\ get_recent_byr_offers, get_last_norm from agent.const import DELTA_SLR, NUM_COMMON_CONS class",
"self.patient else 3.03 idx = f(0) if days <= tau else f(1) elif",
"elif turn == 6: if self.patient: days4 = get_days(x=x, turn=4) if days4 <=",
"get_recent_byr_offers, get_last_norm from agent.const import DELTA_SLR, NUM_COMMON_CONS class HeuristicSlr: def __init__(self, delta=None): self.patient",
"if norm <= .67 else f(1) else: idx = f(0) else: raise ValueError('Invalid",
"index of action f = wrapper(turn) if turn == 2: days = get_days(x=x,",
"turn=turn) idx = f(0) if days <= 2.01 else f(.5) else: num_offers =",
"get_days(x=x, turn=turn) tau = 5.05 if self.patient else 3.03 idx = f(0) if",
"= f(1) if num_offers <= .5 else f(0) elif turn == 6: if",
"turn=6) idx = f(0) if days6 <= 2.04 else f(1) else: norm =",
"== 2: days = get_days(x=x, turn=turn) tau = 5.05 if self.patient else 3.03",
"norm <= .67 else f(1) else: idx = f(0) else: raise ValueError('Invalid turn:",
"agent.const import DELTA_SLR, NUM_COMMON_CONS class HeuristicSlr: def __init__(self, delta=None): self.patient = np.isclose(delta, DELTA_SLR[-1])",
"\\ get_recent_byr_offers, get_last_norm from agent.const import DELTA_SLR, NUM_COMMON_CONS class HeuristicSlr: def __init__(self, delta=None):",
"as np import torch from agent.heuristics.util import get_agent_turn, wrapper, get_days, \\ get_recent_byr_offers, get_last_norm",
"= get_days(x=x, turn=turn) idx = f(0) if days <= 2.01 else f(.5) else:",
"= f(0) else: raise ValueError('Invalid turn: {}'.format(turn)) # deterministic categorical action distribution pdf",
"else: idx = f(0) else: raise ValueError('Invalid turn: {}'.format(turn)) # deterministic categorical action",
"number turn = get_agent_turn(x=x, byr=False) # index of action f = wrapper(turn) if",
"= get_days(x=x, turn=4) if days4 <= 2.01: days6 = get_days(x=x, turn=6) idx =",
"else: norm = get_last_norm(x=x, turn=turn) idx = f(.5) if norm <= .67 else",
"action distribution pdf = torch.zeros(NUM_COMMON_CONS + 3, dtype=torch.float) pdf[idx] = 1. return pdf",
"= f(0) if days <= 2.01 else f(.5) else: num_offers = get_recent_byr_offers(x=x, turn=turn)",
"self.patient: days = get_days(x=x, turn=turn) idx = f(0) if days <= 2.01 else",
"if days6 <= 2.04 else f(1) else: norm = get_last_norm(x=x, turn=turn) idx =",
"of action f = wrapper(turn) if turn == 2: days = get_days(x=x, turn=turn)",
"else f(.5) else: num_offers = get_recent_byr_offers(x=x, turn=turn) idx = f(1) if num_offers <=",
"action f = wrapper(turn) if turn == 2: days = get_days(x=x, turn=turn) tau",
"noinspection PyProtectedMember x = observation._asdict() # turn number turn = get_agent_turn(x=x, byr=False) #",
"f(0) if days6 <= 2.04 else f(1) else: norm = get_last_norm(x=x, turn=turn) idx",
"f(0) else: raise ValueError('Invalid turn: {}'.format(turn)) # deterministic categorical action distribution pdf =",
"f(.5) if norm <= .67 else f(1) else: idx = f(0) else: raise",
"observation=None): # noinspection PyProtectedMember x = observation._asdict() # turn number turn = get_agent_turn(x=x,",
"self.patient = np.isclose(delta, DELTA_SLR[-1]) def __call__(self, observation=None): # noinspection PyProtectedMember x = observation._asdict()",
"turn == 4: if self.patient: days = get_days(x=x, turn=turn) idx = f(0) if",
"if self.patient else 3.03 idx = f(0) if days <= tau else f(1)",
"np.isclose(delta, DELTA_SLR[-1]) def __call__(self, observation=None): # noinspection PyProtectedMember x = observation._asdict() # turn",
"if turn == 2: days = get_days(x=x, turn=turn) tau = 5.05 if self.patient",
"<= tau else f(1) elif turn == 4: if self.patient: days = get_days(x=x,",
"norm = get_last_norm(x=x, turn=turn) idx = f(.5) if norm <= .67 else f(1)",
"= 5.05 if self.patient else 3.03 idx = f(0) if days <= tau",
"tau else f(1) elif turn == 4: if self.patient: days = get_days(x=x, turn=turn)",
"= get_recent_byr_offers(x=x, turn=turn) idx = f(1) if num_offers <= .5 else f(0) elif",
"f(0) if days <= tau else f(1) elif turn == 4: if self.patient:",
"days6 <= 2.04 else f(1) else: norm = get_last_norm(x=x, turn=turn) idx = f(.5)",
"byr=False) # index of action f = wrapper(turn) if turn == 2: days",
"turn=turn) tau = 5.05 if self.patient else 3.03 idx = f(0) if days",
"def __init__(self, delta=None): self.patient = np.isclose(delta, DELTA_SLR[-1]) def __call__(self, observation=None): # noinspection PyProtectedMember",
"= get_agent_turn(x=x, byr=False) # index of action f = wrapper(turn) if turn ==",
"if self.patient: days4 = get_days(x=x, turn=4) if days4 <= 2.01: days6 = get_days(x=x,",
"__call__(self, observation=None): # noinspection PyProtectedMember x = observation._asdict() # turn number turn =",
"# index of action f = wrapper(turn) if turn == 2: days =",
"= get_days(x=x, turn=turn) tau = 5.05 if self.patient else 3.03 idx = f(0)",
"tau = 5.05 if self.patient else 3.03 idx = f(0) if days <=",
"get_days(x=x, turn=6) idx = f(0) if days6 <= 2.04 else f(1) else: norm",
"categorical action distribution pdf = torch.zeros(NUM_COMMON_CONS + 3, dtype=torch.float) pdf[idx] = 1. return",
"2: days = get_days(x=x, turn=turn) tau = 5.05 if self.patient else 3.03 idx",
"days <= tau else f(1) elif turn == 4: if self.patient: days ="
] |
[
"useful values theta = 0 # ====================== YOUR CODE HERE ====================== # Instructions:",
"====================== YOUR CODE HERE ====================== # Instructions: Complete the code to compute the",
"regression using the normal equations. \"\"\" # Initialize some useful values theta =",
"compute the closed form solution # to linear regression and put the result",
"import numpy as np def normalEqn(X, y): \"\"\" Computes the closed-form solution to",
"<reponame>piwithy/ENSTA_MACHINE_LEARNING<gh_stars>0 import numpy as np def normalEqn(X, y): \"\"\" Computes the closed-form solution",
"as np def normalEqn(X, y): \"\"\" Computes the closed-form solution to linear regression",
"closed-form solution to linear regression normalEqn(X,y) computes the closed-form solution to linear regression",
"def normalEqn(X, y): \"\"\" Computes the closed-form solution to linear regression normalEqn(X,y) computes",
"the normal equations. \"\"\" # Initialize some useful values theta = 0 #",
"Complete the code to compute the closed form solution # to linear regression",
"y): \"\"\" Computes the closed-form solution to linear regression normalEqn(X,y) computes the closed-form",
"code to compute the closed form solution # to linear regression and put",
"normalEqn(X, y): \"\"\" Computes the closed-form solution to linear regression normalEqn(X,y) computes the",
"CODE HERE ====================== # Instructions: Complete the code to compute the closed form",
"HERE ====================== # Instructions: Complete the code to compute the closed form solution",
"solution to linear regression normalEqn(X,y) computes the closed-form solution to linear regression using",
"\"\"\" Computes the closed-form solution to linear regression normalEqn(X,y) computes the closed-form solution",
"# Instructions: Complete the code to compute the closed form solution # to",
"to linear regression and put the result in theta. # theta = np.dot(np.dot(np.linalg.inv(np.dot(X.T,",
"computes the closed-form solution to linear regression using the normal equations. \"\"\" #",
"using the normal equations. \"\"\" # Initialize some useful values theta = 0",
"solution to linear regression using the normal equations. \"\"\" # Initialize some useful",
"the result in theta. # theta = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y) # ==============================================================",
"Instructions: Complete the code to compute the closed form solution # to linear",
"Computes the closed-form solution to linear regression normalEqn(X,y) computes the closed-form solution to",
"closed-form solution to linear regression using the normal equations. \"\"\" # Initialize some",
"solution # to linear regression and put the result in theta. # theta",
"# ====================== YOUR CODE HERE ====================== # Instructions: Complete the code to compute",
"some useful values theta = 0 # ====================== YOUR CODE HERE ====================== #",
"closed form solution # to linear regression and put the result in theta.",
"values theta = 0 # ====================== YOUR CODE HERE ====================== # Instructions: Complete",
"the closed form solution # to linear regression and put the result in",
"# to linear regression and put the result in theta. # theta =",
"the closed-form solution to linear regression normalEqn(X,y) computes the closed-form solution to linear",
"linear regression and put the result in theta. # theta = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)),",
"in theta. # theta = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y) # ============================================================== return theta",
"the closed-form solution to linear regression using the normal equations. \"\"\" # Initialize",
"YOUR CODE HERE ====================== # Instructions: Complete the code to compute the closed",
"np def normalEqn(X, y): \"\"\" Computes the closed-form solution to linear regression normalEqn(X,y)",
"numpy as np def normalEqn(X, y): \"\"\" Computes the closed-form solution to linear",
"the code to compute the closed form solution # to linear regression and",
"and put the result in theta. # theta = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y)",
"put the result in theta. # theta = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y) #",
"\"\"\" # Initialize some useful values theta = 0 # ====================== YOUR CODE",
"to linear regression using the normal equations. \"\"\" # Initialize some useful values",
"to linear regression normalEqn(X,y) computes the closed-form solution to linear regression using the",
"regression normalEqn(X,y) computes the closed-form solution to linear regression using the normal equations.",
"linear regression using the normal equations. \"\"\" # Initialize some useful values theta",
"normal equations. \"\"\" # Initialize some useful values theta = 0 # ======================",
"result in theta. # theta = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y) # ============================================================== return",
"= 0 # ====================== YOUR CODE HERE ====================== # Instructions: Complete the code",
"theta = 0 # ====================== YOUR CODE HERE ====================== # Instructions: Complete the",
"====================== # Instructions: Complete the code to compute the closed form solution #",
"equations. \"\"\" # Initialize some useful values theta = 0 # ====================== YOUR",
"normalEqn(X,y) computes the closed-form solution to linear regression using the normal equations. \"\"\"",
"0 # ====================== YOUR CODE HERE ====================== # Instructions: Complete the code to",
"form solution # to linear regression and put the result in theta. #",
"to compute the closed form solution # to linear regression and put the",
"Initialize some useful values theta = 0 # ====================== YOUR CODE HERE ======================",
"# Initialize some useful values theta = 0 # ====================== YOUR CODE HERE",
"linear regression normalEqn(X,y) computes the closed-form solution to linear regression using the normal",
"regression and put the result in theta. # theta = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T),"
] |
[
"migrations.AlterField( model_name='group', name='postal_code', field=models.CharField(max_length=12, null=True, verbose_name='Postal Code'), ), migrations.AlterField( model_name='group', name='rep_email', field=models.EmailField(max_length=254, null=True,",
"field=models.CharField(max_length=12, null=True, verbose_name='Postal Code'), ), migrations.AlterField( model_name='group', name='rep_email', field=models.EmailField(max_length=254, null=True, verbose_name='Contact Email'), ),",
"[ ('local_groups', '0027_auto_20170308_1801'), ] operations = [ migrations.AlterField( model_name='group', name='description', field=models.TextField(max_length=250, null=True, verbose_name='Description",
"by Django 1.10.2 on 2017-03-08 18:12 from __future__ import unicode_literals from django.db import",
"(250 characters or less)'), ), migrations.AlterField( model_name='group', name='postal_code', field=models.CharField(max_length=12, null=True, verbose_name='Postal Code'), ),",
"or less)'), ), migrations.AlterField( model_name='group', name='postal_code', field=models.CharField(max_length=12, null=True, verbose_name='Postal Code'), ), migrations.AlterField( model_name='group',",
"Email'), ), migrations.AlterField( model_name='group', name='rep_first_name', field=models.CharField(blank=True, default='John', max_length=9, verbose_name='First Name'), preserve_default=False, ), migrations.AlterField(",
"field=models.CharField(blank=True, default='Doe', max_length=12, verbose_name='Last Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='slug', field=models.SlugField(null=True, unique=True), ),",
"model_name='group', name='rep_email', field=models.EmailField(max_length=254, null=True, verbose_name='Contact Email'), ), migrations.AlterField( model_name='group', name='rep_first_name', field=models.CharField(blank=True, default='John', max_length=9,",
"coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-03-08 18:12 from __future__",
"# Generated by Django 1.10.2 on 2017-03-08 18:12 from __future__ import unicode_literals from",
"1.10.2 on 2017-03-08 18:12 from __future__ import unicode_literals from django.db import migrations, models",
"field=models.TextField(max_length=250, null=True, verbose_name='Description (250 characters or less)'), ), migrations.AlterField( model_name='group', name='postal_code', field=models.CharField(max_length=12, null=True,",
"-*- # Generated by Django 1.10.2 on 2017-03-08 18:12 from __future__ import unicode_literals",
"field=models.EmailField(max_length=254, null=True, verbose_name='Contact Email'), ), migrations.AlterField( model_name='group', name='rep_first_name', field=models.CharField(blank=True, default='John', max_length=9, verbose_name='First Name'),",
"migrations.AlterField( model_name='group', name='rep_email', field=models.EmailField(max_length=254, null=True, verbose_name='Contact Email'), ), migrations.AlterField( model_name='group', name='rep_first_name', field=models.CharField(blank=True, default='John',",
"'0027_auto_20170308_1801'), ] operations = [ migrations.AlterField( model_name='group', name='description', field=models.TextField(max_length=250, null=True, verbose_name='Description (250 characters",
"models class Migration(migrations.Migration): dependencies = [ ('local_groups', '0027_auto_20170308_1801'), ] operations = [ migrations.AlterField(",
"), migrations.AlterField( model_name='group', name='postal_code', field=models.CharField(max_length=12, null=True, verbose_name='Postal Code'), ), migrations.AlterField( model_name='group', name='rep_email', field=models.EmailField(max_length=254,",
"dependencies = [ ('local_groups', '0027_auto_20170308_1801'), ] operations = [ migrations.AlterField( model_name='group', name='description', field=models.TextField(max_length=250,",
"null=True, verbose_name='Postal Code'), ), migrations.AlterField( model_name='group', name='rep_email', field=models.EmailField(max_length=254, null=True, verbose_name='Contact Email'), ), migrations.AlterField(",
"Django 1.10.2 on 2017-03-08 18:12 from __future__ import unicode_literals from django.db import migrations,",
"migrations.AlterField( model_name='group', name='rep_last_name', field=models.CharField(blank=True, default='Doe', max_length=12, verbose_name='Last Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='slug',",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('local_groups', '0027_auto_20170308_1801'), ]",
"Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='rep_last_name', field=models.CharField(blank=True, default='Doe', max_length=12, verbose_name='Last Name'), preserve_default=False, ),",
"on 2017-03-08 18:12 from __future__ import unicode_literals from django.db import migrations, models class",
"verbose_name='First Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='rep_last_name', field=models.CharField(blank=True, default='Doe', max_length=12, verbose_name='Last Name'), preserve_default=False,",
"unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('local_groups', '0027_auto_20170308_1801'),",
"default='Doe', max_length=12, verbose_name='Last Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='slug', field=models.SlugField(null=True, unique=True), ), ]",
"model_name='group', name='rep_last_name', field=models.CharField(blank=True, default='Doe', max_length=12, verbose_name='Last Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='slug', field=models.SlugField(null=True,",
"migrations.AlterField( model_name='group', name='description', field=models.TextField(max_length=250, null=True, verbose_name='Description (250 characters or less)'), ), migrations.AlterField( model_name='group',",
"), migrations.AlterField( model_name='group', name='rep_email', field=models.EmailField(max_length=254, null=True, verbose_name='Contact Email'), ), migrations.AlterField( model_name='group', name='rep_first_name', field=models.CharField(blank=True,",
"operations = [ migrations.AlterField( model_name='group', name='description', field=models.TextField(max_length=250, null=True, verbose_name='Description (250 characters or less)'),",
"class Migration(migrations.Migration): dependencies = [ ('local_groups', '0027_auto_20170308_1801'), ] operations = [ migrations.AlterField( model_name='group',",
"= [ ('local_groups', '0027_auto_20170308_1801'), ] operations = [ migrations.AlterField( model_name='group', name='description', field=models.TextField(max_length=250, null=True,",
"] operations = [ migrations.AlterField( model_name='group', name='description', field=models.TextField(max_length=250, null=True, verbose_name='Description (250 characters or",
"[ migrations.AlterField( model_name='group', name='description', field=models.TextField(max_length=250, null=True, verbose_name='Description (250 characters or less)'), ), migrations.AlterField(",
"null=True, verbose_name='Description (250 characters or less)'), ), migrations.AlterField( model_name='group', name='postal_code', field=models.CharField(max_length=12, null=True, verbose_name='Postal",
"verbose_name='Postal Code'), ), migrations.AlterField( model_name='group', name='rep_email', field=models.EmailField(max_length=254, null=True, verbose_name='Contact Email'), ), migrations.AlterField( model_name='group',",
"name='rep_email', field=models.EmailField(max_length=254, null=True, verbose_name='Contact Email'), ), migrations.AlterField( model_name='group', name='rep_first_name', field=models.CharField(blank=True, default='John', max_length=9, verbose_name='First",
"less)'), ), migrations.AlterField( model_name='group', name='postal_code', field=models.CharField(max_length=12, null=True, verbose_name='Postal Code'), ), migrations.AlterField( model_name='group', name='rep_email',",
"), migrations.AlterField( model_name='group', name='rep_last_name', field=models.CharField(blank=True, default='Doe', max_length=12, verbose_name='Last Name'), preserve_default=False, ), migrations.AlterField( model_name='group',",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('local_groups', '0027_auto_20170308_1801'), ] operations",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('local_groups', '0027_auto_20170308_1801'), ] operations = [",
"Code'), ), migrations.AlterField( model_name='group', name='rep_email', field=models.EmailField(max_length=254, null=True, verbose_name='Contact Email'), ), migrations.AlterField( model_name='group', name='rep_first_name',",
"), migrations.AlterField( model_name='group', name='rep_first_name', field=models.CharField(blank=True, default='John', max_length=9, verbose_name='First Name'), preserve_default=False, ), migrations.AlterField( model_name='group',",
"preserve_default=False, ), migrations.AlterField( model_name='group', name='rep_last_name', field=models.CharField(blank=True, default='Doe', max_length=12, verbose_name='Last Name'), preserve_default=False, ), migrations.AlterField(",
"2017-03-08 18:12 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):",
"null=True, verbose_name='Contact Email'), ), migrations.AlterField( model_name='group', name='rep_first_name', field=models.CharField(blank=True, default='John', max_length=9, verbose_name='First Name'), preserve_default=False,",
"18:12 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"Migration(migrations.Migration): dependencies = [ ('local_groups', '0027_auto_20170308_1801'), ] operations = [ migrations.AlterField( model_name='group', name='description',",
"characters or less)'), ), migrations.AlterField( model_name='group', name='postal_code', field=models.CharField(max_length=12, null=True, verbose_name='Postal Code'), ), migrations.AlterField(",
"verbose_name='Contact Email'), ), migrations.AlterField( model_name='group', name='rep_first_name', field=models.CharField(blank=True, default='John', max_length=9, verbose_name='First Name'), preserve_default=False, ),",
"name='rep_last_name', field=models.CharField(blank=True, default='Doe', max_length=12, verbose_name='Last Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='slug', field=models.SlugField(null=True, unique=True),",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('local_groups', '0027_auto_20170308_1801'), ] operations =",
"-*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-03-08 18:12 from",
"<reponame>JoshZero87/site<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-03-08",
"from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"name='postal_code', field=models.CharField(max_length=12, null=True, verbose_name='Postal Code'), ), migrations.AlterField( model_name='group', name='rep_email', field=models.EmailField(max_length=254, null=True, verbose_name='Contact Email'),",
"name='rep_first_name', field=models.CharField(blank=True, default='John', max_length=9, verbose_name='First Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='rep_last_name', field=models.CharField(blank=True, default='Doe',",
"= [ migrations.AlterField( model_name='group', name='description', field=models.TextField(max_length=250, null=True, verbose_name='Description (250 characters or less)'), ),",
"# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-03-08 18:12",
"verbose_name='Description (250 characters or less)'), ), migrations.AlterField( model_name='group', name='postal_code', field=models.CharField(max_length=12, null=True, verbose_name='Postal Code'),",
"__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"utf-8 -*- # Generated by Django 1.10.2 on 2017-03-08 18:12 from __future__ import",
"model_name='group', name='postal_code', field=models.CharField(max_length=12, null=True, verbose_name='Postal Code'), ), migrations.AlterField( model_name='group', name='rep_email', field=models.EmailField(max_length=254, null=True, verbose_name='Contact",
"model_name='group', name='rep_first_name', field=models.CharField(blank=True, default='John', max_length=9, verbose_name='First Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='rep_last_name', field=models.CharField(blank=True,",
"name='description', field=models.TextField(max_length=250, null=True, verbose_name='Description (250 characters or less)'), ), migrations.AlterField( model_name='group', name='postal_code', field=models.CharField(max_length=12,",
"('local_groups', '0027_auto_20170308_1801'), ] operations = [ migrations.AlterField( model_name='group', name='description', field=models.TextField(max_length=250, null=True, verbose_name='Description (250",
"max_length=9, verbose_name='First Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='rep_last_name', field=models.CharField(blank=True, default='Doe', max_length=12, verbose_name='Last Name'),",
"migrations.AlterField( model_name='group', name='rep_first_name', field=models.CharField(blank=True, default='John', max_length=9, verbose_name='First Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='rep_last_name',",
"model_name='group', name='description', field=models.TextField(max_length=250, null=True, verbose_name='Description (250 characters or less)'), ), migrations.AlterField( model_name='group', name='postal_code',",
"import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('local_groups',",
"default='John', max_length=9, verbose_name='First Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='rep_last_name', field=models.CharField(blank=True, default='Doe', max_length=12, verbose_name='Last",
"field=models.CharField(blank=True, default='John', max_length=9, verbose_name='First Name'), preserve_default=False, ), migrations.AlterField( model_name='group', name='rep_last_name', field=models.CharField(blank=True, default='Doe', max_length=12,",
"Generated by Django 1.10.2 on 2017-03-08 18:12 from __future__ import unicode_literals from django.db"
] |
[
"None) -> dict: with h5py.File(h5_file_loc, 'a') as h5_file: output_images = h5_file[h5_dataset_key] all_targets_shape =",
"College Dublin, 2017. Contact sbruton[á]tcd.ie. \"\"\" import json import os from typing import",
"view_idx in range(num_views): target_reshape = np.moveaxis( target_lf[view_idx], -3, -1 ) output_reshape = np.moveaxis(",
"np.array, n_values: int = \"auto\"): if n_values == 'auto': n_values = np.max(y) num_samples",
"in custom.bar(range(num_images)): target_lf = test_set.get_only_y(image_idx) for view_idx in range(num_views): target_reshape = np.moveaxis( target_lf[view_idx],",
"output_reshape ) # Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics = { 'ssim_avg': float(np.mean(ssim_results)), 'ssim_std':",
"Type[LightFieldDataset], output_path: os.path, h5_file_loc: os.path = None, h5_dataset_key: str = None) -> dict:",
"as nrmse from skimage.measure import compare_psnr as psnr import numpy as np import",
"mse_results) output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg'])",
"nn import h5py from .meters import CustomProgressBar, AverageMeter from ..datasets import LightFieldDataset def",
"{ 'ssim_avg': float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)),",
"image metrics.\") for image_idx in custom.bar(range(num_images)): target_lf = test_set.get_only_y(image_idx) for view_idx in range(num_views):",
"encoder = OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False) y_encoded = encoder.fit_transform(y_to_encode) return y_encoded def save_model(model: nn.Module,",
"= os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(), model_output_path) def save_evaluation(model, output_path: os.path, time_per_image: float, final_loss): print(\"Saving",
"save_history(train_loss_history, valid_loss_history, output_path: os.path): print(\"Saving history to pickle file.\") with open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb')",
"If the images are in an array we need to reshape them #",
"as plt import pickle from sklearn.preprocessing import OneHotEncoder from skimage.measure import compare_ssim as",
"skimage.measure import compare_nrmse as nrmse from skimage.measure import compare_psnr as psnr import numpy",
"reshape them # TODO: And again when saving. num_images = all_targets_shape[0] num_views =",
"h5_file[h5_dataset_key] all_targets_shape = ( len(test_set), test_set.num_views_y, test_set.num_channels, test_set.height_y, test_set.width_y ) assert output_images.shape ==",
"are in an array we need to reshape them # TODO: And again",
"LightFieldDataset def one_hot_to_dense(y: np.array) -> np.ndarray: return np.fromiter((np.argmax(row) for row in y), dtype=np.int)",
"save_model(model: nn.Module, output_path: os.path): print(\"Saving \" + str(output_path) + \" model definition...\") model_output_path",
"from ..datasets import LightFieldDataset def one_hot_to_dense(y: np.array) -> np.ndarray: return np.fromiter((np.argmax(row) for row",
"-> np.ndarray: return np.fromiter((np.argmax(row) for row in y), dtype=np.int) def dense_to_one_hot(y: np.array, n_values:",
"from skimage.measure import compare_psnr as psnr import numpy as np import torch from",
"= AverageMeter(name='SSIM', cum=False) custom = CustomProgressBar(label='SSIM') print(\"Calculating image metrics.\") for image_idx in custom.bar(range(num_images)):",
"2017. Contact sbruton[á]tcd.ie. \"\"\" import json import os from typing import Type #",
"import Type # Need to ensure can run on server, i.e. no X",
"float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results)) } # Also save to a json for easy viewing.",
"output_path: os.path, time_per_image: float, final_loss): print(\"Saving the evaluation of model.\") save_model(model=model, output_path=output_path) results",
"output_path: os.path): print(\"Saving \" + str(output_path) + \" model definition...\") model_output_path = os.path.join(output_path,",
"return y_encoded def save_model(model: nn.Module, output_path: os.path): print(\"Saving \" + str(output_path) + \"",
") nrmse_results[image_idx, view_idx] = nrmse( target_reshape, output_reshape ) # Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value())",
"'auto': n_values = np.max(y) num_samples = y.shape[-1] y_to_encode = y if len(y.shape) ==",
"os.path): print(\"Saving \" + str(output_path) + \" model definition...\") model_output_path = os.path.join(output_path, \"model.pkl\")",
"def dense_to_one_hot(y: np.array, n_values: int = \"auto\"): if n_values == 'auto': n_values =",
"server, i.e. no X session import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt import",
"custom = CustomProgressBar(label='SSIM') print(\"Calculating image metrics.\") for image_idx in custom.bar(range(num_images)): target_lf = test_set.get_only_y(image_idx)",
"# TODO: And again when saving. num_images = all_targets_shape[0] num_views = all_targets_shape[1] ssim_results",
"print(\"Calculating image metrics.\") for image_idx in custom.bar(range(num_images)): target_lf = test_set.get_only_y(image_idx) for view_idx in",
"be adapted for pytorch print(\"Saving training config.\") json_filename = 'train_config.json' with open(os.path.join(output_path, json_filename),",
"Also save to a json for easy viewing. with open(os.path.join(output_path, \"metrics.json\"), 'w') as",
"metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def save_history_plots(train_loss_history, valid_loss_history, output_path:",
"'w') as fp: json.dump(train_config, fp, indent=4, sort_keys=True) def save_history(train_loss_history, valid_loss_history, output_path: os.path): print(\"Saving",
"output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std',",
"loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'], loc='upper left') loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig) def model_dump(full_model, train_config,",
"from skimage.measure import compare_mse as mse from skimage.measure import compare_nrmse as nrmse from",
"if n_values == 'auto': n_values = np.max(y) num_samples = y.shape[-1] y_to_encode = y",
"target_reshape, output_reshape ) nrmse_results[image_idx, view_idx] = nrmse( target_reshape, output_reshape ) # Log errors",
"save to a json for easy viewing. with open(os.path.join(output_path, \"metrics.json\"), 'w') as fp:",
") mse_results[image_idx, view_idx] = mse( target_reshape, output_reshape ) nrmse_results[image_idx, view_idx] = nrmse( target_reshape,",
"Type # Need to ensure can run on server, i.e. no X session",
"metrics.\") for image_idx in custom.bar(range(num_images)): target_lf = test_set.get_only_y(image_idx) for view_idx in range(num_views): target_reshape",
"} # Also save to a json for easy viewing. with open(os.path.join(output_path, \"metrics.json\"),",
"all_targets_shape # TODO: If the images are in an array we need to",
"TODO: This needs to be adapted for pytorch if not os.path.isdir(output_path): os.mkdir(output_path) save_model(full_model,",
"test_set.num_views_y, test_set.num_channels, test_set.height_y, test_set.width_y ) assert output_images.shape == all_targets_shape # TODO: If the",
"time_per_image} print(results) with open(os.path.join(output_path, \"results.json\"), 'w') as fp: json.dump(results, fp, indent=4, sort_keys=True) def",
"\"\"\" Copyright <NAME>, Trinity College Dublin, 2017. Contact sbruton[á]tcd.ie. \"\"\" import json import",
"def one_hot_to_dense(y: np.array) -> np.ndarray: return np.fromiter((np.argmax(row) for row in y), dtype=np.int) def",
"output_images.shape == all_targets_shape # TODO: If the images are in an array we",
"h5py.File(h5_file_loc, 'a') as h5_file: output_images = h5_file[h5_dataset_key] all_targets_shape = ( len(test_set), test_set.num_views_y, test_set.num_channels,",
"target_reshape, output_reshape ) mse_results[image_idx, view_idx] = mse( target_reshape, output_reshape ) nrmse_results[image_idx, view_idx] =",
"custom.bar(range(num_images)): target_lf = test_set.get_only_y(image_idx) for view_idx in range(num_views): target_reshape = np.moveaxis( target_lf[view_idx], -3,",
"np.zeros((num_images, num_views), dtype=np.float32) psnr_results = np.zeros((num_images, num_views), dtype=np.float32) mse_results = np.zeros((num_images, num_views), dtype=np.float32)",
"open(os.path.join(output_path, json_filename), 'w') as fp: json.dump(train_config, fp, indent=4, sort_keys=True) def save_history(train_loss_history, valid_loss_history, output_path:",
"ensure can run on server, i.e. no X session import matplotlib; matplotlib.use('Agg') import",
"metrics = { 'ssim_avg': float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)),",
"os.path): # TODO: This needs to be adapted for pytorch if not os.path.isdir(output_path):",
"output_path: os.path): # TODO: This needs to be adapted for pytorch print(\"Saving training",
"output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg',",
"as np import torch from torch import nn import h5py from .meters import",
"ssim_results[image_idx, view_idx] = ssim( target_reshape, output_reshape, multichannel=True ) psnr_results[image_idx, view_idx] = psnr( target_reshape,",
"skimage.measure import compare_psnr as psnr import numpy as np import torch from torch",
"open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb') as fp: pickle.dump(train_loss_history, fp) with open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb') as fp:",
"'mse_avg': float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results)) } # Also save to",
"= y if len(y.shape) == 1: y_to_encode = np.reshape(y, (-1, 1)) encoder =",
"dtype=np.float32) ssim_meter = AverageMeter(name='SSIM', cum=False) custom = CustomProgressBar(label='SSIM') print(\"Calculating image metrics.\") for image_idx",
"to reshape them # TODO: And again when saving. num_images = all_targets_shape[0] num_views",
"TODO: If the images are in an array we need to reshape them",
"import pickle from sklearn.preprocessing import OneHotEncoder from skimage.measure import compare_ssim as ssim from",
"import LightFieldDataset def one_hot_to_dense(y: np.array) -> np.ndarray: return np.fromiter((np.argmax(row) for row in y),",
"-> dict: with h5py.File(h5_file_loc, 'a') as h5_file: output_images = h5_file[h5_dataset_key] all_targets_shape = (",
"the images are in an array we need to reshape them # TODO:",
"def save_evaluation(model, output_path: os.path, time_per_image: float, final_loss): print(\"Saving the evaluation of model.\") save_model(model=model,",
"import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt import pickle from sklearn.preprocessing import OneHotEncoder",
"can run on server, i.e. no X session import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot",
"print(\"Saving history to pickle file.\") with open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb') as fp: pickle.dump(train_loss_history, fp)",
"left') loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig) def model_dump(full_model, train_config, output_path: os.path): # TODO: This needs",
"plt.figure() loss_plot = loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'], loc='upper left')",
"'psnr_std': float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results)) } # Also",
"AverageMeter from ..datasets import LightFieldDataset def one_hot_to_dense(y: np.array) -> np.ndarray: return np.fromiter((np.argmax(row) for",
"json_filename = 'train_config.json' with open(os.path.join(output_path, json_filename), 'w') as fp: json.dump(train_config, fp, indent=4, sort_keys=True)",
"print(\"Saving \" + str(output_path) + \" model definition...\") model_output_path = os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(),",
"torch.save(model.state_dict(), model_output_path) def save_evaluation(model, output_path: os.path, time_per_image: float, final_loss): print(\"Saving the evaluation of",
"to be adapted for pytorch if not os.path.isdir(output_path): os.mkdir(output_path) save_model(full_model, output_path) save_training_config(train_config, output_path)",
"= mse( target_reshape, output_reshape ) nrmse_results[image_idx, view_idx] = nrmse( target_reshape, output_reshape ) #",
"def save_model(model: nn.Module, output_path: os.path): print(\"Saving \" + str(output_path) + \" model definition...\")",
"skimage.measure import compare_mse as mse from skimage.measure import compare_nrmse as nrmse from skimage.measure",
"# Need to ensure can run on server, i.e. no X session import",
"np.fromiter((np.argmax(row) for row in y), dtype=np.int) def dense_to_one_hot(y: np.array, n_values: int = \"auto\"):",
"metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std'])",
"np.array) -> np.ndarray: return np.fromiter((np.argmax(row) for row in y), dtype=np.int) def dense_to_one_hot(y: np.array,",
"ssim_meter = AverageMeter(name='SSIM', cum=False) custom = CustomProgressBar(label='SSIM') print(\"Calculating image metrics.\") for image_idx in",
"'nrmse_std': float(np.std(nrmse_results)) } # Also save to a json for easy viewing. with",
"np.reshape(y, (-1, 1)) encoder = OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False) y_encoded = encoder.fit_transform(y_to_encode) return y_encoded",
"'mse_std': float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results)) } # Also save to a json",
"'loss.png')) plt.close(loss_fig) def model_dump(full_model, train_config, output_path: os.path): # TODO: This needs to be",
"And again when saving. num_images = all_targets_shape[0] num_views = all_targets_shape[1] ssim_results = np.zeros((num_images,",
"ssim_results) output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg'])",
"cum=False) custom = CustomProgressBar(label='SSIM') print(\"Calculating image metrics.\") for image_idx in custom.bar(range(num_images)): target_lf =",
"def save_history_plots(train_loss_history, valid_loss_history, output_path: os.path): loss_fig = plt.figure() loss_plot = loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history)",
"adapted for pytorch print(\"Saving training config.\") json_filename = 'train_config.json' with open(os.path.join(output_path, json_filename), 'w')",
"import os from typing import Type # Need to ensure can run on",
"with open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb') as fp: pickle.dump(train_loss_history, fp) with open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb') as",
"fp) with open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb') as fp: pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path) def",
"AverageMeter(name='SSIM', cum=False) custom = CustomProgressBar(label='SSIM') print(\"Calculating image metrics.\") for image_idx in custom.bar(range(num_images)): target_lf",
"..datasets import LightFieldDataset def one_hot_to_dense(y: np.array) -> np.ndarray: return np.fromiter((np.argmax(row) for row in",
"y_encoded def save_model(model: nn.Module, output_path: os.path): print(\"Saving \" + str(output_path) + \" model",
"save_history_plots(train_loss_history, valid_loss_history, output_path: os.path): loss_fig = plt.figure() loss_plot = loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model",
"(-1, 1)) encoder = OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False) y_encoded = encoder.fit_transform(y_to_encode) return y_encoded def",
"= { 'ssim_avg': float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)), 'mse_std':",
"h5py from .meters import CustomProgressBar, AverageMeter from ..datasets import LightFieldDataset def one_hot_to_dense(y: np.array)",
"'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results)) } # Also save to a json for easy",
"( len(test_set), test_set.num_views_y, test_set.num_channels, test_set.height_y, test_set.width_y ) assert output_images.shape == all_targets_shape # TODO:",
"float, final_loss): print(\"Saving the evaluation of model.\") save_model(model=model, output_path=output_path) results = {'loss': float(final_loss),",
"def model_dump(full_model, train_config, output_path: os.path): # TODO: This needs to be adapted for",
"in range(num_views): target_reshape = np.moveaxis( target_lf[view_idx], -3, -1 ) output_reshape = np.moveaxis( output_images[image_idx,",
"= psnr( target_reshape, output_reshape ) mse_results[image_idx, view_idx] = mse( target_reshape, output_reshape ) nrmse_results[image_idx,",
"output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std',",
"np.moveaxis( output_images[image_idx, view_idx], -3, -1 ) ssim_results[image_idx, view_idx] = ssim( target_reshape, output_reshape, multichannel=True",
"fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path) def calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path: os.path, h5_file_loc: os.path = None,",
"sklearn.preprocessing import OneHotEncoder from skimage.measure import compare_ssim as ssim from skimage.measure import compare_mse",
"no X session import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt import pickle from",
"pytorch print(\"Saving training config.\") json_filename = 'train_config.json' with open(os.path.join(output_path, json_filename), 'w') as fp:",
"np.zeros((num_images, num_views), dtype=np.float32) ssim_meter = AverageMeter(name='SSIM', cum=False) custom = CustomProgressBar(label='SSIM') print(\"Calculating image metrics.\")",
"num_samples = y.shape[-1] y_to_encode = y if len(y.shape) == 1: y_to_encode = np.reshape(y,",
"model_output_path) def save_evaluation(model, output_path: os.path, time_per_image: float, final_loss): print(\"Saving the evaluation of model.\")",
"output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def save_history_plots(train_loss_history, valid_loss_history, output_path: os.path): loss_fig = plt.figure() loss_plot",
"1: y_to_encode = np.reshape(y, (-1, 1)) encoder = OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False) y_encoded =",
"open(os.path.join(output_path, \"metrics.json\"), 'w') as fp: json.dump(metrics, fp, indent=4, sort_keys=True) output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr', psnr_results)",
"mse_results = np.zeros((num_images, num_views), dtype=np.float32) nrmse_results = np.zeros((num_images, num_views), dtype=np.float32) ssim_meter = AverageMeter(name='SSIM',",
"output_images = h5_file[h5_dataset_key] all_targets_shape = ( len(test_set), test_set.num_views_y, test_set.num_channels, test_set.height_y, test_set.width_y ) assert",
"as psnr import numpy as np import torch from torch import nn import",
"= OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False) y_encoded = encoder.fit_transform(y_to_encode) return y_encoded def save_model(model: nn.Module, output_path:",
"print(\"Saving the evaluation of model.\") save_model(model=model, output_path=output_path) results = {'loss': float(final_loss), 'time_per_image': time_per_image}",
"y if len(y.shape) == 1: y_to_encode = np.reshape(y, (-1, 1)) encoder = OneHotEncoder(n_values=n_values,",
"dict: with h5py.File(h5_file_loc, 'a') as h5_file: output_images = h5_file[h5_dataset_key] all_targets_shape = ( len(test_set),",
"with open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb') as fp: pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path) def calc_and_save_all_metrics(test_set:",
"images are in an array we need to reshape them # TODO: And",
"json import os from typing import Type # Need to ensure can run",
"'wb') as fp: pickle.dump(train_loss_history, fp) with open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb') as fp: pickle.dump(valid_loss_history, fp)",
"CustomProgressBar(label='SSIM') print(\"Calculating image metrics.\") for image_idx in custom.bar(range(num_images)): target_lf = test_set.get_only_y(image_idx) for view_idx",
"them # TODO: And again when saving. num_images = all_targets_shape[0] num_views = all_targets_shape[1]",
"as ssim from skimage.measure import compare_mse as mse from skimage.measure import compare_nrmse as",
"target_reshape, output_reshape, multichannel=True ) psnr_results[image_idx, view_idx] = psnr( target_reshape, output_reshape ) mse_results[image_idx, view_idx]",
"output_path: os.path): # TODO: This needs to be adapted for pytorch if not",
"loss_plot = loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'], loc='upper left') loss_fig.savefig(os.path.join(output_path,",
"fp: json.dump(train_config, fp, indent=4, sort_keys=True) def save_history(train_loss_history, valid_loss_history, output_path: os.path): print(\"Saving history to",
"metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def save_history_plots(train_loss_history, valid_loss_history, output_path: os.path): loss_fig = plt.figure() loss_plot =",
"psnr import numpy as np import torch from torch import nn import h5py",
"h5_file_loc: os.path = None, h5_dataset_key: str = None) -> dict: with h5py.File(h5_file_loc, 'a')",
"dtype=np.float32) nrmse_results = np.zeros((num_images, num_views), dtype=np.float32) ssim_meter = AverageMeter(name='SSIM', cum=False) custom = CustomProgressBar(label='SSIM')",
"in y), dtype=np.int) def dense_to_one_hot(y: np.array, n_values: int = \"auto\"): if n_values ==",
"evaluation of model.\") save_model(model=model, output_path=output_path) results = {'loss': float(final_loss), 'time_per_image': time_per_image} print(results) with",
"output_reshape ) nrmse_results[image_idx, view_idx] = nrmse( target_reshape, output_reshape ) # Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx])))",
"torch from torch import nn import h5py from .meters import CustomProgressBar, AverageMeter from",
"output_images[image_idx, view_idx], -3, -1 ) ssim_results[image_idx, view_idx] = ssim( target_reshape, output_reshape, multichannel=True )",
"valid_loss_history=valid_loss_history, output_path=output_path) def calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path: os.path, h5_file_loc: os.path = None, h5_dataset_key: str",
"os.path): # TODO: This needs to be adapted for pytorch print(\"Saving training config.\")",
"TODO: This needs to be adapted for pytorch print(\"Saving training config.\") json_filename =",
"nn.Module, output_path: os.path): print(\"Saving \" + str(output_path) + \" model definition...\") model_output_path =",
"= np.max(y) num_samples = y.shape[-1] y_to_encode = y if len(y.shape) == 1: y_to_encode",
"psnr_results) output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std'])",
"as fp: pickle.dump(train_loss_history, fp) with open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb') as fp: pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history,",
"= ( len(test_set), test_set.num_views_y, test_set.num_channels, test_set.height_y, test_set.width_y ) assert output_images.shape == all_targets_shape #",
"float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)),",
"def save_history(train_loss_history, valid_loss_history, output_path: os.path): print(\"Saving history to pickle file.\") with open(os.path.join(output_path, 'train_loss_history.pkl'),",
") psnr_results[image_idx, view_idx] = psnr( target_reshape, output_reshape ) mse_results[image_idx, view_idx] = mse( target_reshape,",
"'train_loss_history.pkl'), 'wb') as fp: pickle.dump(train_loss_history, fp) with open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb') as fp: pickle.dump(valid_loss_history,",
"len(test_set), test_set.num_views_y, test_set.num_channels, test_set.height_y, test_set.width_y ) assert output_images.shape == all_targets_shape # TODO: If",
"def calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path: os.path, h5_file_loc: os.path = None, h5_dataset_key: str = None)",
"saving. num_images = all_targets_shape[0] num_views = all_targets_shape[1] ssim_results = np.zeros((num_images, num_views), dtype=np.float32) psnr_results",
"import OneHotEncoder from skimage.measure import compare_ssim as ssim from skimage.measure import compare_mse as",
"indent=4, sort_keys=True) def save_history(train_loss_history, valid_loss_history, output_path: os.path): print(\"Saving history to pickle file.\") with",
"matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt import pickle from sklearn.preprocessing import OneHotEncoder from",
"loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'], loc='upper left') loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig)",
"fp: pickle.dump(train_loss_history, fp) with open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb') as fp: pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history,",
"output_path: os.path): loss_fig = plt.figure() loss_plot = loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates')",
"target_lf[view_idx], -3, -1 ) output_reshape = np.moveaxis( output_images[image_idx, view_idx], -3, -1 ) ssim_results[image_idx,",
"= encoder.fit_transform(y_to_encode) return y_encoded def save_model(model: nn.Module, output_path: os.path): print(\"Saving \" + str(output_path)",
"model_dump(full_model, train_config, output_path: os.path): # TODO: This needs to be adapted for pytorch",
"viewing. with open(os.path.join(output_path, \"metrics.json\"), 'w') as fp: json.dump(metrics, fp, indent=4, sort_keys=True) output_images.attrs.create('ssim', ssim_results)",
"return np.fromiter((np.argmax(row) for row in y), dtype=np.int) def dense_to_one_hot(y: np.array, n_values: int =",
"dtype=np.int) def dense_to_one_hot(y: np.array, n_values: int = \"auto\"): if n_values == 'auto': n_values",
"'valid_loss_history.pkl'), 'wb') as fp: pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path) def calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path:",
"with open(os.path.join(output_path, \"metrics.json\"), 'w') as fp: json.dump(metrics, fp, indent=4, sort_keys=True) output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr',",
"import CustomProgressBar, AverageMeter from ..datasets import LightFieldDataset def one_hot_to_dense(y: np.array) -> np.ndarray: return",
"nrmse( target_reshape, output_reshape ) # Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics = { 'ssim_avg':",
"python3 \"\"\" Copyright <NAME>, Trinity College Dublin, 2017. Contact sbruton[á]tcd.ie. \"\"\" import json",
"'time_per_image': time_per_image} print(results) with open(os.path.join(output_path, \"results.json\"), 'w') as fp: json.dump(results, fp, indent=4, sort_keys=True)",
"dtype=np.float32, sparse=False) y_encoded = encoder.fit_transform(y_to_encode) return y_encoded def save_model(model: nn.Module, output_path: os.path): print(\"Saving",
"# TODO: If the images are in an array we need to reshape",
"-3, -1 ) output_reshape = np.moveaxis( output_images[image_idx, view_idx], -3, -1 ) ssim_results[image_idx, view_idx]",
"y_encoded = encoder.fit_transform(y_to_encode) return y_encoded def save_model(model: nn.Module, output_path: os.path): print(\"Saving \" +",
"view_idx] = nrmse( target_reshape, output_reshape ) # Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics =",
"needs to be adapted for pytorch if not os.path.isdir(output_path): os.mkdir(output_path) save_model(full_model, output_path) save_training_config(train_config,",
"import compare_mse as mse from skimage.measure import compare_nrmse as nrmse from skimage.measure import",
"loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig) def model_dump(full_model, train_config, output_path: os.path): # TODO: This needs to",
"<reponame>leaveitout/deep_light_field_interp #!/usr/bin/env python3 \"\"\" Copyright <NAME>, Trinity College Dublin, 2017. Contact sbruton[á]tcd.ie. \"\"\"",
"test_set.height_y, test_set.width_y ) assert output_images.shape == all_targets_shape # TODO: If the images are",
"\"auto\"): if n_values == 'auto': n_values = np.max(y) num_samples = y.shape[-1] y_to_encode =",
"output_path=output_path) results = {'loss': float(final_loss), 'time_per_image': time_per_image} print(results) with open(os.path.join(output_path, \"results.json\"), 'w') as",
"def save_training_config(train_config: dict, output_path: os.path): # TODO: This needs to be adapted for",
"test_set.num_channels, test_set.height_y, test_set.width_y ) assert output_images.shape == all_targets_shape # TODO: If the images",
"Dublin, 2017. Contact sbruton[á]tcd.ie. \"\"\" import json import os from typing import Type",
"config.\") json_filename = 'train_config.json' with open(os.path.join(output_path, json_filename), 'w') as fp: json.dump(train_config, fp, indent=4,",
"= all_targets_shape[0] num_views = all_targets_shape[1] ssim_results = np.zeros((num_images, num_views), dtype=np.float32) psnr_results = np.zeros((num_images,",
"# TODO: This needs to be adapted for pytorch if not os.path.isdir(output_path): os.mkdir(output_path)",
"array we need to reshape them # TODO: And again when saving. num_images",
"loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'], loc='upper left') loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig) def model_dump(full_model, train_config, output_path: os.path):",
") # Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics = { 'ssim_avg': float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)),",
"final_loss): print(\"Saving the evaluation of model.\") save_model(model=model, output_path=output_path) results = {'loss': float(final_loss), 'time_per_image':",
"numpy as np import torch from torch import nn import h5py from .meters",
"fp, indent=4, sort_keys=True) def save_training_config(train_config: dict, output_path: os.path): # TODO: This needs to",
"need to reshape them # TODO: And again when saving. num_images = all_targets_shape[0]",
"output_reshape ) mse_results[image_idx, view_idx] = mse( target_reshape, output_reshape ) nrmse_results[image_idx, view_idx] = nrmse(",
"output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def save_history_plots(train_loss_history, valid_loss_history, output_path: os.path): loss_fig = plt.figure() loss_plot = loss_fig.add_subplot(111)",
"compare_psnr as psnr import numpy as np import torch from torch import nn",
"Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'], loc='upper left') loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig) def model_dump(full_model, train_config, output_path:",
"Contact sbruton[á]tcd.ie. \"\"\" import json import os from typing import Type # Need",
"train_config, output_path: os.path): # TODO: This needs to be adapted for pytorch if",
"skimage.measure import compare_ssim as ssim from skimage.measure import compare_mse as mse from skimage.measure",
"= np.moveaxis( output_images[image_idx, view_idx], -3, -1 ) ssim_results[image_idx, view_idx] = ssim( target_reshape, output_reshape,",
"float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results)) } # Also save to a",
"target_reshape = np.moveaxis( target_lf[view_idx], -3, -1 ) output_reshape = np.moveaxis( output_images[image_idx, view_idx], -3,",
"plt.close(loss_fig) def model_dump(full_model, train_config, output_path: os.path): # TODO: This needs to be adapted",
"target_reshape, output_reshape ) # Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics = { 'ssim_avg': float(np.mean(ssim_results)),",
"save_model(model=model, output_path=output_path) results = {'loss': float(final_loss), 'time_per_image': time_per_image} print(results) with open(os.path.join(output_path, \"results.json\"), 'w')",
"for image_idx in custom.bar(range(num_images)): target_lf = test_set.get_only_y(image_idx) for view_idx in range(num_views): target_reshape =",
"import json import os from typing import Type # Need to ensure can",
"plt import pickle from sklearn.preprocessing import OneHotEncoder from skimage.measure import compare_ssim as ssim",
"= np.zeros((num_images, num_views), dtype=np.float32) psnr_results = np.zeros((num_images, num_views), dtype=np.float32) mse_results = np.zeros((num_images, num_views),",
"view_idx] = psnr( target_reshape, output_reshape ) mse_results[image_idx, view_idx] = mse( target_reshape, output_reshape )",
"CustomProgressBar, AverageMeter from ..datasets import LightFieldDataset def one_hot_to_dense(y: np.array) -> np.ndarray: return np.fromiter((np.argmax(row)",
"Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics = { 'ssim_avg': float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)),",
"target_lf = test_set.get_only_y(image_idx) for view_idx in range(num_views): target_reshape = np.moveaxis( target_lf[view_idx], -3, -1",
"calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path: os.path, h5_file_loc: os.path = None, h5_dataset_key: str = None) ->",
"compare_ssim as ssim from skimage.measure import compare_mse as mse from skimage.measure import compare_nrmse",
"easy viewing. with open(os.path.join(output_path, \"metrics.json\"), 'w') as fp: json.dump(metrics, fp, indent=4, sort_keys=True) output_images.attrs.create('ssim',",
"y_to_encode = y if len(y.shape) == 1: y_to_encode = np.reshape(y, (-1, 1)) encoder",
"= y.shape[-1] y_to_encode = y if len(y.shape) == 1: y_to_encode = np.reshape(y, (-1,",
"float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results)) } #",
"'w') as fp: json.dump(results, fp, indent=4, sort_keys=True) def save_training_config(train_config: dict, output_path: os.path): #",
"-3, -1 ) ssim_results[image_idx, view_idx] = ssim( target_reshape, output_reshape, multichannel=True ) psnr_results[image_idx, view_idx]",
"output_path: os.path): print(\"Saving history to pickle file.\") with open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb') as fp:",
"y.shape[-1] y_to_encode = y if len(y.shape) == 1: y_to_encode = np.reshape(y, (-1, 1))",
"with open(os.path.join(output_path, \"results.json\"), 'w') as fp: json.dump(results, fp, indent=4, sort_keys=True) def save_training_config(train_config: dict,",
"session import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt import pickle from sklearn.preprocessing import",
"nrmse_results = np.zeros((num_images, num_views), dtype=np.float32) ssim_meter = AverageMeter(name='SSIM', cum=False) custom = CustomProgressBar(label='SSIM') print(\"Calculating",
"n_values: int = \"auto\"): if n_values == 'auto': n_values = np.max(y) num_samples =",
"nrmse_results[image_idx, view_idx] = nrmse( target_reshape, output_reshape ) # Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics",
"as fp: pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path) def calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path: os.path, h5_file_loc:",
"from skimage.measure import compare_nrmse as nrmse from skimage.measure import compare_psnr as psnr import",
"output_path: os.path, h5_file_loc: os.path = None, h5_dataset_key: str = None) -> dict: with",
"fp: json.dump(results, fp, indent=4, sort_keys=True) def save_training_config(train_config: dict, output_path: os.path): # TODO: This",
"matplotlib.pyplot as plt import pickle from sklearn.preprocessing import OneHotEncoder from skimage.measure import compare_ssim",
"float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results)) } # Also save",
"ssim_results = np.zeros((num_images, num_views), dtype=np.float32) psnr_results = np.zeros((num_images, num_views), dtype=np.float32) mse_results = np.zeros((num_images,",
"dense_to_one_hot(y: np.array, n_values: int = \"auto\"): if n_values == 'auto': n_values = np.max(y)",
"= h5_file[h5_dataset_key] all_targets_shape = ( len(test_set), test_set.num_views_y, test_set.num_channels, test_set.height_y, test_set.width_y ) assert output_images.shape",
"nrmse from skimage.measure import compare_psnr as psnr import numpy as np import torch",
"valid_loss_history, output_path: os.path): loss_fig = plt.figure() loss_plot = loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss')",
"metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def save_history_plots(train_loss_history, valid_loss_history, output_path: os.path): loss_fig",
"view_idx], -3, -1 ) ssim_results[image_idx, view_idx] = ssim( target_reshape, output_reshape, multichannel=True ) psnr_results[image_idx,",
"for pytorch print(\"Saving training config.\") json_filename = 'train_config.json' with open(os.path.join(output_path, json_filename), 'w') as",
"= \"auto\"): if n_values == 'auto': n_values = np.max(y) num_samples = y.shape[-1] y_to_encode",
"== 'auto': n_values = np.max(y) num_samples = y.shape[-1] y_to_encode = y if len(y.shape)",
"open(os.path.join(output_path, \"results.json\"), 'w') as fp: json.dump(results, fp, indent=4, sort_keys=True) def save_training_config(train_config: dict, output_path:",
"an array we need to reshape them # TODO: And again when saving.",
"model_output_path = os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(), model_output_path) def save_evaluation(model, output_path: os.path, time_per_image: float, final_loss):",
"test_set.get_only_y(image_idx) for view_idx in range(num_views): target_reshape = np.moveaxis( target_lf[view_idx], -3, -1 ) output_reshape",
"ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics = { 'ssim_avg': float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)),",
"time_per_image: float, final_loss): print(\"Saving the evaluation of model.\") save_model(model=model, output_path=output_path) results = {'loss':",
"output_reshape, multichannel=True ) psnr_results[image_idx, view_idx] = psnr( target_reshape, output_reshape ) mse_results[image_idx, view_idx] =",
"num_views), dtype=np.float32) psnr_results = np.zeros((num_images, num_views), dtype=np.float32) mse_results = np.zeros((num_images, num_views), dtype=np.float32) nrmse_results",
"needs to be adapted for pytorch print(\"Saving training config.\") json_filename = 'train_config.json' with",
"typing import Type # Need to ensure can run on server, i.e. no",
"matplotlib.use('Agg') import matplotlib.pyplot as plt import pickle from sklearn.preprocessing import OneHotEncoder from skimage.measure",
"image_idx in custom.bar(range(num_images)): target_lf = test_set.get_only_y(image_idx) for view_idx in range(num_views): target_reshape = np.moveaxis(",
"to be adapted for pytorch print(\"Saving training config.\") json_filename = 'train_config.json' with open(os.path.join(output_path,",
"json.dump(metrics, fp, indent=4, sort_keys=True) output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg',",
"fp, indent=4, sort_keys=True) def save_history(train_loss_history, valid_loss_history, output_path: os.path): print(\"Saving history to pickle file.\")",
"again when saving. num_images = all_targets_shape[0] num_views = all_targets_shape[1] ssim_results = np.zeros((num_images, num_views),",
"os.path, h5_file_loc: os.path = None, h5_dataset_key: str = None) -> dict: with h5py.File(h5_file_loc,",
"num_views), dtype=np.float32) ssim_meter = AverageMeter(name='SSIM', cum=False) custom = CustomProgressBar(label='SSIM') print(\"Calculating image metrics.\") for",
"= test_set.get_only_y(image_idx) for view_idx in range(num_views): target_reshape = np.moveaxis( target_lf[view_idx], -3, -1 )",
"OneHotEncoder from skimage.measure import compare_ssim as ssim from skimage.measure import compare_mse as mse",
"'ssim_avg': float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)), 'nrmse_avg':",
"training config.\") json_filename = 'train_config.json' with open(os.path.join(output_path, json_filename), 'w') as fp: json.dump(train_config, fp,",
"save_training_config(train_config: dict, output_path: os.path): # TODO: This needs to be adapted for pytorch",
"metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def save_history_plots(train_loss_history,",
"None, h5_dataset_key: str = None) -> dict: with h5py.File(h5_file_loc, 'a') as h5_file: output_images",
"output_reshape = np.moveaxis( output_images[image_idx, view_idx], -3, -1 ) ssim_results[image_idx, view_idx] = ssim( target_reshape,",
"= np.zeros((num_images, num_views), dtype=np.float32) ssim_meter = AverageMeter(name='SSIM', cum=False) custom = CustomProgressBar(label='SSIM') print(\"Calculating image",
"psnr( target_reshape, output_reshape ) mse_results[image_idx, view_idx] = mse( target_reshape, output_reshape ) nrmse_results[image_idx, view_idx]",
"indent=4, sort_keys=True) output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std',",
") ssim_results[image_idx, view_idx] = ssim( target_reshape, output_reshape, multichannel=True ) psnr_results[image_idx, view_idx] = psnr(",
"== all_targets_shape # TODO: If the images are in an array we need",
"#!/usr/bin/env python3 \"\"\" Copyright <NAME>, Trinity College Dublin, 2017. Contact sbruton[á]tcd.ie. \"\"\" import",
"encoder.fit_transform(y_to_encode) return y_encoded def save_model(model: nn.Module, output_path: os.path): print(\"Saving \" + str(output_path) +",
"'a') as h5_file: output_images = h5_file[h5_dataset_key] all_targets_shape = ( len(test_set), test_set.num_views_y, test_set.num_channels, test_set.height_y,",
"1)) encoder = OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False) y_encoded = encoder.fit_transform(y_to_encode) return y_encoded def save_model(model:",
"import compare_ssim as ssim from skimage.measure import compare_mse as mse from skimage.measure import",
"a json for easy viewing. with open(os.path.join(output_path, \"metrics.json\"), 'w') as fp: json.dump(metrics, fp,",
"custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics = { 'ssim_avg': float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)), 'mse_avg':",
"to ensure can run on server, i.e. no X session import matplotlib; matplotlib.use('Agg')",
"h5_file: output_images = h5_file[h5_dataset_key] all_targets_shape = ( len(test_set), test_set.num_views_y, test_set.num_channels, test_set.height_y, test_set.width_y )",
"int = \"auto\"): if n_values == 'auto': n_values = np.max(y) num_samples = y.shape[-1]",
"assert output_images.shape == all_targets_shape # TODO: If the images are in an array",
"indent=4, sort_keys=True) def save_training_config(train_config: dict, output_path: os.path): # TODO: This needs to be",
"metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg'])",
"model.\") save_model(model=model, output_path=output_path) results = {'loss': float(final_loss), 'time_per_image': time_per_image} print(results) with open(os.path.join(output_path, \"results.json\"),",
"import h5py from .meters import CustomProgressBar, AverageMeter from ..datasets import LightFieldDataset def one_hot_to_dense(y:",
"if len(y.shape) == 1: y_to_encode = np.reshape(y, (-1, 1)) encoder = OneHotEncoder(n_values=n_values, dtype=np.float32,",
"import torch from torch import nn import h5py from .meters import CustomProgressBar, AverageMeter",
"output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg',",
"results = {'loss': float(final_loss), 'time_per_image': time_per_image} print(results) with open(os.path.join(output_path, \"results.json\"), 'w') as fp:",
"<NAME>, Trinity College Dublin, 2017. Contact sbruton[á]tcd.ie. \"\"\" import json import os from",
"np.moveaxis( target_lf[view_idx], -3, -1 ) output_reshape = np.moveaxis( output_images[image_idx, view_idx], -3, -1 )",
"num_views), dtype=np.float32) mse_results = np.zeros((num_images, num_views), dtype=np.float32) nrmse_results = np.zeros((num_images, num_views), dtype=np.float32) ssim_meter",
"= np.moveaxis( target_lf[view_idx], -3, -1 ) output_reshape = np.moveaxis( output_images[image_idx, view_idx], -3, -1",
"= 'train_config.json' with open(os.path.join(output_path, json_filename), 'w') as fp: json.dump(train_config, fp, indent=4, sort_keys=True) def",
"sbruton[á]tcd.ie. \"\"\" import json import os from typing import Type # Need to",
"float(np.std(nrmse_results)) } # Also save to a json for easy viewing. with open(os.path.join(output_path,",
") assert output_images.shape == all_targets_shape # TODO: If the images are in an",
"os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(), model_output_path) def save_evaluation(model, output_path: os.path, time_per_image: float, final_loss): print(\"Saving the",
"np.max(y) num_samples = y.shape[-1] y_to_encode = y if len(y.shape) == 1: y_to_encode =",
"os.path): print(\"Saving history to pickle file.\") with open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb') as fp: pickle.dump(train_loss_history,",
"# TODO: This needs to be adapted for pytorch print(\"Saving training config.\") json_filename",
"This needs to be adapted for pytorch if not os.path.isdir(output_path): os.mkdir(output_path) save_model(full_model, output_path)",
"n_values = np.max(y) num_samples = y.shape[-1] y_to_encode = y if len(y.shape) == 1:",
"'wb') as fp: pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path) def calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path: os.path,",
"'psnr_avg': float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results)) }",
"errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics = { 'ssim_avg': float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)), 'psnr_std':",
"from torch import nn import h5py from .meters import CustomProgressBar, AverageMeter from ..datasets",
"num_views = all_targets_shape[1] ssim_results = np.zeros((num_images, num_views), dtype=np.float32) psnr_results = np.zeros((num_images, num_views), dtype=np.float32)",
"\"model.pkl\") torch.save(model.state_dict(), model_output_path) def save_evaluation(model, output_path: os.path, time_per_image: float, final_loss): print(\"Saving the evaluation",
"mse_results[image_idx, view_idx] = mse( target_reshape, output_reshape ) nrmse_results[image_idx, view_idx] = nrmse( target_reshape, output_reshape",
"= {'loss': float(final_loss), 'time_per_image': time_per_image} print(results) with open(os.path.join(output_path, \"results.json\"), 'w') as fp: json.dump(results,",
"view_idx] = mse( target_reshape, output_reshape ) nrmse_results[image_idx, view_idx] = nrmse( target_reshape, output_reshape )",
"os.path = None, h5_dataset_key: str = None) -> dict: with h5py.File(h5_file_loc, 'a') as",
"json for easy viewing. with open(os.path.join(output_path, \"metrics.json\"), 'w') as fp: json.dump(metrics, fp, indent=4,",
"i.e. no X session import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt import pickle",
"Copyright <NAME>, Trinity College Dublin, 2017. Contact sbruton[á]tcd.ie. \"\"\" import json import os",
"mse( target_reshape, output_reshape ) nrmse_results[image_idx, view_idx] = nrmse( target_reshape, output_reshape ) # Log",
"loss_fig = plt.figure() loss_plot = loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'],",
"output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def",
"= all_targets_shape[1] ssim_results = np.zeros((num_images, num_views), dtype=np.float32) psnr_results = np.zeros((num_images, num_views), dtype=np.float32) mse_results",
"sort_keys=True) def save_training_config(train_config: dict, output_path: os.path): # TODO: This needs to be adapted",
"float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results)) } # Also save to a json for",
"X session import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt import pickle from sklearn.preprocessing",
"output_path=output_path) def calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path: os.path, h5_file_loc: os.path = None, h5_dataset_key: str =",
"on server, i.e. no X session import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as plt",
"output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def save_history_plots(train_loss_history, valid_loss_history, output_path: os.path): loss_fig =",
"'Test'], loc='upper left') loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig) def model_dump(full_model, train_config, output_path: os.path): # TODO:",
"torch import nn import h5py from .meters import CustomProgressBar, AverageMeter from ..datasets import",
"{'loss': float(final_loss), 'time_per_image': time_per_image} print(results) with open(os.path.join(output_path, \"results.json\"), 'w') as fp: json.dump(results, fp,",
"output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std',",
"== 1: y_to_encode = np.reshape(y, (-1, 1)) encoder = OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False) y_encoded",
"dtype=np.float32) psnr_results = np.zeros((num_images, num_views), dtype=np.float32) mse_results = np.zeros((num_images, num_views), dtype=np.float32) nrmse_results =",
"os from typing import Type # Need to ensure can run on server,",
"valid_loss_history, output_path: os.path): print(\"Saving history to pickle file.\") with open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb') as",
"of model.\") save_model(model=model, output_path=output_path) results = {'loss': float(final_loss), 'time_per_image': time_per_image} print(results) with open(os.path.join(output_path,",
"as fp: json.dump(metrics, fp, indent=4, sort_keys=True) output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse',",
"nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg', metrics['psnr_avg']) output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std'])",
"= np.zeros((num_images, num_views), dtype=np.float32) mse_results = np.zeros((num_images, num_views), dtype=np.float32) nrmse_results = np.zeros((num_images, num_views),",
"os.path): loss_fig = plt.figure() loss_plot = loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train',",
"to pickle file.\") with open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb') as fp: pickle.dump(train_loss_history, fp) with open(os.path.join(output_path,",
"for row in y), dtype=np.int) def dense_to_one_hot(y: np.array, n_values: int = \"auto\"): if",
"with open(os.path.join(output_path, json_filename), 'w') as fp: json.dump(train_config, fp, indent=4, sort_keys=True) def save_history(train_loss_history, valid_loss_history,",
"metrics['nrmse_std']) def save_history_plots(train_loss_history, valid_loss_history, output_path: os.path): loss_fig = plt.figure() loss_plot = loss_fig.add_subplot(111) loss_plot.plot(train_loss_history)",
"= CustomProgressBar(label='SSIM') print(\"Calculating image metrics.\") for image_idx in custom.bar(range(num_images)): target_lf = test_set.get_only_y(image_idx) for",
"= np.zeros((num_images, num_views), dtype=np.float32) nrmse_results = np.zeros((num_images, num_views), dtype=np.float32) ssim_meter = AverageMeter(name='SSIM', cum=False)",
"range(num_views): target_reshape = np.moveaxis( target_lf[view_idx], -3, -1 ) output_reshape = np.moveaxis( output_images[image_idx, view_idx],",
") output_reshape = np.moveaxis( output_images[image_idx, view_idx], -3, -1 ) ssim_results[image_idx, view_idx] = ssim(",
"n_values == 'auto': n_values = np.max(y) num_samples = y.shape[-1] y_to_encode = y if",
"h5_dataset_key: str = None) -> dict: with h5py.File(h5_file_loc, 'a') as h5_file: output_images =",
"OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False) y_encoded = encoder.fit_transform(y_to_encode) return y_encoded def save_model(model: nn.Module, output_path: os.path):",
"one_hot_to_dense(y: np.array) -> np.ndarray: return np.fromiter((np.argmax(row) for row in y), dtype=np.int) def dense_to_one_hot(y:",
"Trinity College Dublin, 2017. Contact sbruton[á]tcd.ie. \"\"\" import json import os from typing",
"psnr_results[image_idx, view_idx] = psnr( target_reshape, output_reshape ) mse_results[image_idx, view_idx] = mse( target_reshape, output_reshape",
"= np.reshape(y, (-1, 1)) encoder = OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False) y_encoded = encoder.fit_transform(y_to_encode) return",
"'ssim_std': float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std':",
"for easy viewing. with open(os.path.join(output_path, \"metrics.json\"), 'w') as fp: json.dump(metrics, fp, indent=4, sort_keys=True)",
"fp, indent=4, sort_keys=True) output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg'])",
"output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std']) output_images.attrs.create('psnr_avg',",
"= loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'], loc='upper left') loss_fig.savefig(os.path.join(output_path, 'loss.png'))",
"from sklearn.preprocessing import OneHotEncoder from skimage.measure import compare_ssim as ssim from skimage.measure import",
"os.path, time_per_image: float, final_loss): print(\"Saving the evaluation of model.\") save_model(model=model, output_path=output_path) results =",
"print(results) with open(os.path.join(output_path, \"results.json\"), 'w') as fp: json.dump(results, fp, indent=4, sort_keys=True) def save_training_config(train_config:",
"output_images.attrs.create('psnr_std', metrics['psnr_std']) output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def save_history_plots(train_loss_history, valid_loss_history,",
"# Also save to a json for easy viewing. with open(os.path.join(output_path, \"metrics.json\"), 'w')",
"'w') as fp: json.dump(metrics, fp, indent=4, sort_keys=True) output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse', mse_results)",
"np.ndarray: return np.fromiter((np.argmax(row) for row in y), dtype=np.int) def dense_to_one_hot(y: np.array, n_values: int",
"sort_keys=True) output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse', nrmse_results) output_images.attrs.create('ssim_avg', metrics['ssim_avg']) output_images.attrs.create('ssim_std', metrics['ssim_std'])",
"psnr_results = np.zeros((num_images, num_views), dtype=np.float32) mse_results = np.zeros((num_images, num_views), dtype=np.float32) nrmse_results = np.zeros((num_images,",
"all_targets_shape[0] num_views = all_targets_shape[1] ssim_results = np.zeros((num_images, num_views), dtype=np.float32) psnr_results = np.zeros((num_images, num_views),",
"pickle file.\") with open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb') as fp: pickle.dump(train_loss_history, fp) with open(os.path.join(output_path, 'valid_loss_history.pkl'),",
"multichannel=True ) psnr_results[image_idx, view_idx] = psnr( target_reshape, output_reshape ) mse_results[image_idx, view_idx] = mse(",
"the evaluation of model.\") save_model(model=model, output_path=output_path) results = {'loss': float(final_loss), 'time_per_image': time_per_image} print(results)",
"np import torch from torch import nn import h5py from .meters import CustomProgressBar,",
"import numpy as np import torch from torch import nn import h5py from",
"from .meters import CustomProgressBar, AverageMeter from ..datasets import LightFieldDataset def one_hot_to_dense(y: np.array) ->",
"from typing import Type # Need to ensure can run on server, i.e.",
"when saving. num_images = all_targets_shape[0] num_views = all_targets_shape[1] ssim_results = np.zeros((num_images, num_views), dtype=np.float32)",
"as h5_file: output_images = h5_file[h5_dataset_key] all_targets_shape = ( len(test_set), test_set.num_views_y, test_set.num_channels, test_set.height_y, test_set.width_y",
"for view_idx in range(num_views): target_reshape = np.moveaxis( target_lf[view_idx], -3, -1 ) output_reshape =",
"import compare_psnr as psnr import numpy as np import torch from torch import",
"str = None) -> dict: with h5py.File(h5_file_loc, 'a') as h5_file: output_images = h5_file[h5_dataset_key]",
"dtype=np.float32) mse_results = np.zeros((num_images, num_views), dtype=np.float32) nrmse_results = np.zeros((num_images, num_views), dtype=np.float32) ssim_meter =",
"\"\"\" import json import os from typing import Type # Need to ensure",
"as mse from skimage.measure import compare_nrmse as nrmse from skimage.measure import compare_psnr as",
"y_to_encode = np.reshape(y, (-1, 1)) encoder = OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False) y_encoded = encoder.fit_transform(y_to_encode)",
"fp: pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path) def calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path: os.path, h5_file_loc: os.path",
"compare_mse as mse from skimage.measure import compare_nrmse as nrmse from skimage.measure import compare_psnr",
"pickle from sklearn.preprocessing import OneHotEncoder from skimage.measure import compare_ssim as ssim from skimage.measure",
"all_targets_shape[1] ssim_results = np.zeros((num_images, num_views), dtype=np.float32) psnr_results = np.zeros((num_images, num_views), dtype=np.float32) mse_results =",
"float(final_loss), 'time_per_image': time_per_image} print(results) with open(os.path.join(output_path, \"results.json\"), 'w') as fp: json.dump(results, fp, indent=4,",
"\" model definition...\") model_output_path = os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(), model_output_path) def save_evaluation(model, output_path: os.path,",
"-1 ) output_reshape = np.moveaxis( output_images[image_idx, view_idx], -3, -1 ) ssim_results[image_idx, view_idx] =",
"as fp: json.dump(results, fp, indent=4, sort_keys=True) def save_training_config(train_config: dict, output_path: os.path): # TODO:",
"# Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics = { 'ssim_avg': float(np.mean(ssim_results)), 'ssim_std': float(np.std(ssim_results)), 'psnr_avg':",
"loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'], loc='upper left') loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig) def model_dump(full_model,",
"json_filename), 'w') as fp: json.dump(train_config, fp, indent=4, sort_keys=True) def save_history(train_loss_history, valid_loss_history, output_path: os.path):",
"history to pickle file.\") with open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb') as fp: pickle.dump(train_loss_history, fp) with",
"loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'], loc='upper left') loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig) def",
"fp: json.dump(metrics, fp, indent=4, sort_keys=True) output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse', mse_results) output_images.attrs.create('nrmse', nrmse_results)",
"\"metrics.json\"), 'w') as fp: json.dump(metrics, fp, indent=4, sort_keys=True) output_images.attrs.create('ssim', ssim_results) output_images.attrs.create('psnr', psnr_results) output_images.attrs.create('mse',",
"test_set.width_y ) assert output_images.shape == all_targets_shape # TODO: If the images are in",
"num_images = all_targets_shape[0] num_views = all_targets_shape[1] ssim_results = np.zeros((num_images, num_views), dtype=np.float32) psnr_results =",
"\" + str(output_path) + \" model definition...\") model_output_path = os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(), model_output_path)",
"'train_config.json' with open(os.path.join(output_path, json_filename), 'w') as fp: json.dump(train_config, fp, indent=4, sort_keys=True) def save_history(train_loss_history,",
"np.zeros((num_images, num_views), dtype=np.float32) nrmse_results = np.zeros((num_images, num_views), dtype=np.float32) ssim_meter = AverageMeter(name='SSIM', cum=False) custom",
"= plt.figure() loss_plot = loss_fig.add_subplot(111) loss_plot.plot(train_loss_history) loss_plot.plot(valid_loss_history) loss_plot.set_title('Model Loss') loss_plot.set_xlabel('Updates') loss_plot.legend(['Train', 'Test'], loc='upper",
"json.dump(train_config, fp, indent=4, sort_keys=True) def save_history(train_loss_history, valid_loss_history, output_path: os.path): print(\"Saving history to pickle",
"to a json for easy viewing. with open(os.path.join(output_path, \"metrics.json\"), 'w') as fp: json.dump(metrics,",
"run on server, i.e. no X session import matplotlib; matplotlib.use('Agg') import matplotlib.pyplot as",
"save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path) def calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path: os.path, h5_file_loc: os.path = None, h5_dataset_key:",
"compare_nrmse as nrmse from skimage.measure import compare_psnr as psnr import numpy as np",
"dict, output_path: os.path): # TODO: This needs to be adapted for pytorch print(\"Saving",
"num_views), dtype=np.float32) nrmse_results = np.zeros((num_images, num_views), dtype=np.float32) ssim_meter = AverageMeter(name='SSIM', cum=False) custom =",
"row in y), dtype=np.int) def dense_to_one_hot(y: np.array, n_values: int = \"auto\"): if n_values",
"file.\") with open(os.path.join(output_path, 'train_loss_history.pkl'), 'wb') as fp: pickle.dump(train_loss_history, fp) with open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb')",
"sparse=False) y_encoded = encoder.fit_transform(y_to_encode) return y_encoded def save_model(model: nn.Module, output_path: os.path): print(\"Saving \"",
"+ \" model definition...\") model_output_path = os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(), model_output_path) def save_evaluation(model, output_path:",
"Need to ensure can run on server, i.e. no X session import matplotlib;",
"= None, h5_dataset_key: str = None) -> dict: with h5py.File(h5_file_loc, 'a') as h5_file:",
"import nn import h5py from .meters import CustomProgressBar, AverageMeter from ..datasets import LightFieldDataset",
"definition...\") model_output_path = os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(), model_output_path) def save_evaluation(model, output_path: os.path, time_per_image: float,",
"\"results.json\"), 'w') as fp: json.dump(results, fp, indent=4, sort_keys=True) def save_training_config(train_config: dict, output_path: os.path):",
"This needs to be adapted for pytorch print(\"Saving training config.\") json_filename = 'train_config.json'",
"open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb') as fp: pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path) def calc_and_save_all_metrics(test_set: Type[LightFieldDataset],",
"save_evaluation(model, output_path: os.path, time_per_image: float, final_loss): print(\"Saving the evaluation of model.\") save_model(model=model, output_path=output_path)",
"np.zeros((num_images, num_views), dtype=np.float32) mse_results = np.zeros((num_images, num_views), dtype=np.float32) nrmse_results = np.zeros((num_images, num_views), dtype=np.float32)",
"output_images.attrs.create('mse_avg', metrics['mse_avg']) output_images.attrs.create('mse_std', metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def save_history_plots(train_loss_history, valid_loss_history, output_path: os.path):",
"mse from skimage.measure import compare_nrmse as nrmse from skimage.measure import compare_psnr as psnr",
"loc='upper left') loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig) def model_dump(full_model, train_config, output_path: os.path): # TODO: This",
"in an array we need to reshape them # TODO: And again when",
"with h5py.File(h5_file_loc, 'a') as h5_file: output_images = h5_file[h5_dataset_key] all_targets_shape = ( len(test_set), test_set.num_views_y,",
"import matplotlib.pyplot as plt import pickle from sklearn.preprocessing import OneHotEncoder from skimage.measure import",
"metrics['mse_std']) output_images.attrs.create('nrmse_avg', metrics['nrmse_avg']) output_images.attrs.create('nrmse_std', metrics['nrmse_std']) def save_history_plots(train_loss_history, valid_loss_history, output_path: os.path): loss_fig = plt.figure()",
"sort_keys=True) def save_history(train_loss_history, valid_loss_history, output_path: os.path): print(\"Saving history to pickle file.\") with open(os.path.join(output_path,",
"float(np.std(ssim_results)), 'psnr_avg': float(np.mean(psnr_results)), 'psnr_std': float(np.std(psnr_results)), 'mse_avg': float(np.mean(mse_results)), 'mse_std': float(np.std(mse_results)), 'nrmse_avg': float(np.mean(nrmse_results)), 'nrmse_std': float(np.std(nrmse_results))",
"-1 ) ssim_results[image_idx, view_idx] = ssim( target_reshape, output_reshape, multichannel=True ) psnr_results[image_idx, view_idx] =",
".meters import CustomProgressBar, AverageMeter from ..datasets import LightFieldDataset def one_hot_to_dense(y: np.array) -> np.ndarray:",
"+ str(output_path) + \" model definition...\") model_output_path = os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(), model_output_path) def",
"model definition...\") model_output_path = os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(), model_output_path) def save_evaluation(model, output_path: os.path, time_per_image:",
"view_idx] = ssim( target_reshape, output_reshape, multichannel=True ) psnr_results[image_idx, view_idx] = psnr( target_reshape, output_reshape",
"as fp: json.dump(train_config, fp, indent=4, sort_keys=True) def save_history(train_loss_history, valid_loss_history, output_path: os.path): print(\"Saving history",
"pickle.dump(train_loss_history, fp) with open(os.path.join(output_path, 'valid_loss_history.pkl'), 'wb') as fp: pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path)",
"all_targets_shape = ( len(test_set), test_set.num_views_y, test_set.num_channels, test_set.height_y, test_set.width_y ) assert output_images.shape == all_targets_shape",
"= ssim( target_reshape, output_reshape, multichannel=True ) psnr_results[image_idx, view_idx] = psnr( target_reshape, output_reshape )",
"TODO: And again when saving. num_images = all_targets_shape[0] num_views = all_targets_shape[1] ssim_results =",
"from skimage.measure import compare_ssim as ssim from skimage.measure import compare_mse as mse from",
"pickle.dump(valid_loss_history, fp) save_history_plots(train_loss_history=train_loss_history, valid_loss_history=valid_loss_history, output_path=output_path) def calc_and_save_all_metrics(test_set: Type[LightFieldDataset], output_path: os.path, h5_file_loc: os.path =",
"print(\"Saving training config.\") json_filename = 'train_config.json' with open(os.path.join(output_path, json_filename), 'w') as fp: json.dump(train_config,",
"ssim from skimage.measure import compare_mse as mse from skimage.measure import compare_nrmse as nrmse",
"str(output_path) + \" model definition...\") model_output_path = os.path.join(output_path, \"model.pkl\") torch.save(model.state_dict(), model_output_path) def save_evaluation(model,",
"ssim( target_reshape, output_reshape, multichannel=True ) psnr_results[image_idx, view_idx] = psnr( target_reshape, output_reshape ) mse_results[image_idx,",
"y), dtype=np.int) def dense_to_one_hot(y: np.array, n_values: int = \"auto\"): if n_values == 'auto':",
"import compare_nrmse as nrmse from skimage.measure import compare_psnr as psnr import numpy as",
"loss_plot.legend(['Train', 'Test'], loc='upper left') loss_fig.savefig(os.path.join(output_path, 'loss.png')) plt.close(loss_fig) def model_dump(full_model, train_config, output_path: os.path): #",
"= nrmse( target_reshape, output_reshape ) # Log errors ssim_meter.update(float(np.mean(ssim_results[image_idx]))) custom.format_custom_text.update_mapping(value=ssim_meter.value()) metrics = {",
"= None) -> dict: with h5py.File(h5_file_loc, 'a') as h5_file: output_images = h5_file[h5_dataset_key] all_targets_shape",
"we need to reshape them # TODO: And again when saving. num_images =",
"len(y.shape) == 1: y_to_encode = np.reshape(y, (-1, 1)) encoder = OneHotEncoder(n_values=n_values, dtype=np.float32, sparse=False)",
"json.dump(results, fp, indent=4, sort_keys=True) def save_training_config(train_config: dict, output_path: os.path): # TODO: This needs"
] |
[
"is a simple SOCKS5 server implementation based on AsyncIO library Currently easysocks5 only",
"__name__ = \"easysocks5\" __version__ = \"0.0.5\" __author__ = \"<NAME>\" __author_email__ = \"<EMAIL>\" __license__",
"on AsyncIO library Currently easysocks5 only support unauthenticated socks5 and CONNECT command. \"\"\"",
"command. \"\"\" __name__ = \"easysocks5\" __version__ = \"0.0.5\" __author__ = \"<NAME>\" __author_email__ =",
"easysocks5 is a simple SOCKS5 server implementation based on AsyncIO library Currently easysocks5",
"\"\"\" easysocks5 is a simple SOCKS5 server implementation based on AsyncIO library Currently",
"a simple SOCKS5 server implementation based on AsyncIO library Currently easysocks5 only support",
"Currently easysocks5 only support unauthenticated socks5 and CONNECT command. \"\"\" __name__ = \"easysocks5\"",
"and CONNECT command. \"\"\" __name__ = \"easysocks5\" __version__ = \"0.0.5\" __author__ = \"<NAME>\"",
"based on AsyncIO library Currently easysocks5 only support unauthenticated socks5 and CONNECT command.",
"support unauthenticated socks5 and CONNECT command. \"\"\" __name__ = \"easysocks5\" __version__ = \"0.0.5\"",
"AsyncIO library Currently easysocks5 only support unauthenticated socks5 and CONNECT command. \"\"\" __name__",
"implementation based on AsyncIO library Currently easysocks5 only support unauthenticated socks5 and CONNECT",
"simple SOCKS5 server implementation based on AsyncIO library Currently easysocks5 only support unauthenticated",
"socks5 and CONNECT command. \"\"\" __name__ = \"easysocks5\" __version__ = \"0.0.5\" __author__ =",
"CONNECT command. \"\"\" __name__ = \"easysocks5\" __version__ = \"0.0.5\" __author__ = \"<NAME>\" __author_email__",
"\"easysocks5\" __version__ = \"0.0.5\" __author__ = \"<NAME>\" __author_email__ = \"<EMAIL>\" __license__ = \"MIT\"",
"SOCKS5 server implementation based on AsyncIO library Currently easysocks5 only support unauthenticated socks5",
"server implementation based on AsyncIO library Currently easysocks5 only support unauthenticated socks5 and",
"only support unauthenticated socks5 and CONNECT command. \"\"\" __name__ = \"easysocks5\" __version__ =",
"<reponame>keenser/easysocks5 \"\"\" easysocks5 is a simple SOCKS5 server implementation based on AsyncIO library",
"library Currently easysocks5 only support unauthenticated socks5 and CONNECT command. \"\"\" __name__ =",
"= \"easysocks5\" __version__ = \"0.0.5\" __author__ = \"<NAME>\" __author_email__ = \"<EMAIL>\" __license__ =",
"unauthenticated socks5 and CONNECT command. \"\"\" __name__ = \"easysocks5\" __version__ = \"0.0.5\" __author__",
"\"\"\" __name__ = \"easysocks5\" __version__ = \"0.0.5\" __author__ = \"<NAME>\" __author_email__ = \"<EMAIL>\"",
"easysocks5 only support unauthenticated socks5 and CONNECT command. \"\"\" __name__ = \"easysocks5\" __version__"
] |
[] |
[
"this is a vtkRenderWindowInteractor instance in the main program UI (user interface) -",
"if debug: print(rotations) targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing camera = targetVTKWindow.ren.GetActiveCamera() if",
"processes access the inherited renderwindowinteractor (?) # so lets put all the above",
"newActor = VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor = newActor #lets keep",
"numpy array colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a VTK unsigned char",
"#place holder for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPoints =",
"put some of the data objects in the scope of the # main",
"camera = targetVTKWindow.ren.GetActiveCamera() if debug: print(camera) for i in range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render() targetVTKWindow.iren.Render()",
"print(commandArgs) if len(commandArgs) != 0 : #new data has come from MATLAB so",
"'iterations,200,relaxationfactor,1.2' # sanity check if ('iterations' in commandArgs[0]) and ('relaxationfactor' in commandArgs[0]): smoothingArgs",
"the_TCPserver) a_vec = array(a_vec,'uint8') if debug: print(len(r_vec)) print(len(g_vec)) print(len(b_vec)) print(len(a_vec)) #combine into numpy",
"hav the data, lets turn it into vtk stuff # Process vertices points",
"reset the color map (smoothing \"messes\" this up) updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver) def",
"# 4) color data g (rgba) for each vertex # 5) color data",
"mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep copied # and so we can access ui controls",
"= commandArgs[0].strip().split(',') vertices = unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver) vertices = array(vertices,'f') vertices = vertices.reshape((len(vertices)/3,3))",
"* def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #first get all the data we are",
"# current View settings in from the vista session WITH THE COLOR VALUES",
"g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[2].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec =",
"triangles = array(triangles,'f') if debug: print(triangles) triangles = triangles.reshape((len(triangles)/3,3)) if debug: print(triangles) #",
"unpackData from mp_VTKProcessing import * from mp_VTKDrawing import * def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI,",
"debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a string that reads something like 'iterations,200,relaxationfactor,1.2' # sanity check",
"int(smoothingArgs[1]) relaxationfactor = float(smoothingArgs[3]) else: return \"error - expecting vertices, then curvature, then",
"so that they can be manipulated later. mainWindowUI.vtkInstances[-1].curr_actor = actor mainWindowUI.vtkInstances[-1].curr_smoother = smooth",
"('relaxationfactor' in commandArgs[0]): smoothingArgs = commandArgs[0].strip().split(',') iterations = int(smoothingArgs[1]) relaxationfactor = float(smoothingArgs[3]) else:",
"get the original data the_polyData = targetVTKWindow.curr_polydata the_mapper = targetVTKWindow.curr_mapper #first get all",
"debug: print('received request for new mesh with Args:') print(commandArgs) # sanity check if",
"have the content of the main window in scope. <NAME> 2017 ''' import",
"colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a VTK unsigned char array vtkColorArray",
"for each vertex # 4) color data g (rgba) for each vertex #",
"triangles.shape[0] for i in range(nTriangles): polys.InsertNextCell(3) for j in range(3): polys.InsertCellPoint(int(triangles[i][j])) # check",
"window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing # lets show the correct tab",
"mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0) ren = mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren = ren ren.AddActor(actor)",
"= polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep copied # and so we can access",
"debug: print(rotations) targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing camera = targetVTKWindow.ren.GetActiveCamera() if debug:",
"numpy_support.numpy_to_vtk(colorDat,0) curr_scalars = vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ## ---- ok, we hav the data, lets",
"from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)] while others just referene the most recently added instance",
"call # after something like smoothing - just grab the current deep #",
"first load? smooth = vtk.vtkSmoothPolyDataFilter() smooth = vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm",
"a new mesh) --- mainWindowUI.vtkInstances[-1] Note that it is the mainWindowUI that is",
"allow vtk to do this but then overwrite the recomptued color # map",
"the surface picker = vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place holder for",
"= targetVTKWindow.curr_smoother the_mapper = targetVTKWindow.curr_mapper if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a",
"presses per instance esp for the draw routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index",
"mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)] while others just referene the most recently added instance (e.g.",
"= array(b_vec,'uint8') aVecArgs = commandArgs[5].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8')",
"polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ## TODO ? smoothing on first load? smooth = vtk.vtkSmoothPolyDataFilter()",
"expecting vertices, then curvature, then triangles!\" newActor = VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor)",
"polys mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep copied # turns out that later processes access",
"print('received request for new mesh with Args:') print(commandArgs) # sanity check if ('vertices'",
"mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren = ren ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render() # lets put some",
"targetVTKWindow.curr_polydata the_mapper = targetVTKWindow.curr_mapper #first get all the data we are expecting from",
"0 : #new data has come from MATLAB so recompute # load the",
"can track mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place holder for picked vtk",
"that reads something like 'iterations,200,relaxationfactor,1.2' # sanity check if ('iterations' in commandArgs[0]) and",
"this is to workaround some artifacts generated # by vtk algorithms (e.g. smoothing)",
"for i in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process faces (triangles) polys = vtk.vtkCellArray() nTriangles",
"polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ## TODO ? smoothing on first load?",
"track key presses per instance esp for the draw routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1)",
"IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place holder",
"mesh newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor = newActor #lets keep",
"= triangles.reshape((len(triangles)/3,3)) if debug: print(triangles) # load the surface colour data rVecArgs =",
"of the main window in scope. <NAME> 2017 ''' import vtk from numpy",
"keep a \"deep\" copy - this is to workaround some artifacts generated #",
"is a vtkRenderWindowInteractor instance in the main program UI (user interface) - by",
"# by vtk algorithms (e.g. smoothing) that also smooth the color data #",
"mainWindowUI, the_TCPserver): #rotation args rotations = commandArgs[0].strip().split(',') rotations = unpackData(rotations[1], int(rotations[2]), the_TCPserver) if",
"mainWindowUI, the_TCPserver): # here the base mesh is already loaded and we are",
"settings in from the vista session WITH THE COLOR VALUES FROM # VISTA",
"vertices = array(vertices,'f') vertices = vertices.reshape((len(vertices)/3,3)) trianglesArgs = commandArgs[1].strip().split(',') triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]),",
"this to a VTK unsigned char array scalars = numpy_support.numpy_to_vtk(colorDat,0) curr_scalars = vtk.vtkUnsignedCharArray()",
"pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(pdm) iren = mainWindowUI.vtkInstances[-1] ## ---- engine room",
"if debug: print(len(r_vec)) print(len(g_vec)) print(len(b_vec)) print(len(a_vec)) #combine into numpy array colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose())",
"Args:') print(commandArgs) if len(commandArgs) != 0 : #new data has come from MATLAB",
"picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints =",
"vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0",
"unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[1].strip().split(',') g_vec",
"mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing functions imported from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent',",
"turns out that later processes access the inherited renderwindowinteractor (?) # so lets",
"# convert this to a VTK unsigned char array vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0) #",
"grab the current deep # copy of the required scalars vtkColorArray = targetVTKWindow.curr_scalars",
"commandArgs[4].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[5].strip().split(',') a_vec",
"= vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm = vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor =",
"not go through a lookuptable #lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)]",
"if debug: print(polys) if debug: print(scalars) if debug: print(currVTKInstance) # Assemble as PolyData",
"= deepCopyScalars #TODO - this may have impact on later processing - investigate",
"- just grab the current deep # copy of the required scalars vtkColorArray",
"some hardcore processing is handled in subroutines of other imported modules. A core",
"import time from vtk.util import numpy_support debug = True # local modules from",
"can load multiple meshes. Some functions reference this specifically with a reference index",
"so lets put all the above in the scope of that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor",
"unsigned char array vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0) # keep a \"deep\" copy - this",
"actor.SetMapper(pdm) iren = mainWindowUI.vtkInstances[-1] ## ---- engine room for drawing on the surface",
"2) triangles # 3) color data r (rgba) for each vertex # 4)",
"#lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success with direct mesh update routine') ## --------------------------------------------------------------------------------",
"b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[5].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec =",
"for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints",
"this up) updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver) def updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): # here",
"the_mapper, iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render()",
"as PolyData polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ## TODO ? smoothing on",
"array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[1].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec",
"= commandArgs[0].strip().split(',') iterations = int(smoothingArgs[1]) relaxationfactor = float(smoothingArgs[3]) else: return \"error - expecting",
"in the main program UI (user interface) - by creatoing multiple instances of",
"in range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render() targetVTKWindow.iren.Render() time.sleep(0.02) the_TCPserver.socket.write(str('send useful message back here TODO')) ##",
"have run deepCopyScalars = vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars = deepCopyScalars #TODO - this may",
"from MATLAB, probably just an internal re-draw call # after something like smoothing",
"- blue component # 3) b_vector - green component # 4) a_vector -",
"UPDATE DIRECT mesh with Args:') print(commandArgs) if len(commandArgs) != 0 : #new data",
"j in range(3): polys.InsertCellPoint(int(triangles[i][j])) # check if debug: print(points) if debug: print(polys) if",
"mainWindowUI.vtkInstances[-1] Note that it is the mainWindowUI that is passed to all functions",
"debug: print(polys) if debug: print(scalars) if debug: print(currVTKInstance) # Assemble as PolyData polyData",
"newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor = newActor #lets keep track",
"= mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing functions imported",
"on later processing - investigate else: # no new data from MATLAB, probably",
"#zero index def smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): #lets get the apt window targetVTKWindow",
"main program UI (user interface) - by creatoing multiple instances of vtk windows",
"passed from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)] while others just referene the most recently added",
"Process vertices points = vtk.vtkPoints() for i in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process faces",
"mrMeshPy viewer The main vtk processing is done by functions here - although",
"imported from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0) ren = mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren",
"in commandArgs[1]): pass else: return \"error - expecting vertices, then triangles!\" # load",
"OK - we have the data - let's update the mesh newActor =",
"through a lookuptable #lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero",
"component if debug: print('received request for UPDATE DIRECT mesh with Args:') print(commandArgs) if",
"VALUES FROM # VISTA - i.e. do not go through a lookuptable #lets",
"it is the mainWindowUI that is passed to all functions so that all",
"show the correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original",
"print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a string that reads something like 'iterations,200,relaxationfactor,1.2' #",
"array(b_vec,'uint8') aVecArgs = commandArgs[3].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if",
"= array(vertices,'f') vertices = vertices.reshape((len(vertices)/3,3)) trianglesArgs = commandArgs[1].strip().split(',') triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver)",
"color data # on the surface and then automatically update the inherited color",
"if debug: print(r_vec) gVecArgs = commandArgs[3].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec =",
"= smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points =",
"test example animation def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #rotation args rotations = commandArgs[0].strip().split(',')",
"newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() # run mesh update to reset the",
"(rgba) for each vertex if debug: print('received request for new mesh with Args:')",
"debug: print(r_vec) gVecArgs = commandArgs[3].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8')",
"VISTA - i.e. do not go through a lookuptable #lets get the apt",
"VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render()",
"targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success with direct mesh update",
"vertex # 4) color data g (rgba) for each vertex # 5) color",
"data, lets turn it into vtk stuff # Process vertices points = vtk.vtkPoints()",
"the inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI def KeyPress(obj, evt): key = obj.GetKeySym() if",
"for each vertex if debug: print('received request for new mesh with Args:') print(commandArgs)",
"# convert this to a VTK unsigned char array scalars = numpy_support.numpy_to_vtk(colorDat,0) curr_scalars",
"be manipulated later. mainWindowUI.vtkInstances[-1].curr_actor = actor mainWindowUI.vtkInstances[-1].curr_smoother = smooth mainWindowUI.vtkInstances[-1].curr_polydata = polyData mainWindowUI.vtkInstances[-1].curr_mapper",
"- expecting vertices, then curvature, then triangles!\" newActor = VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor)",
"the surfaces data rVecArgs = commandArgs[0].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec =",
"a \"deep\" copy - this is to workaround some artifacts generated # by",
"surface and then automatically update the inherited color map # - we allow",
"creatoing multiple instances of vtk windows we can load multiple meshes. Some functions",
"and the raw mesh coordinate data.. why not mainWindowUI.vtkInstances[-1].curr_points = points mainWindowUI.vtkInstances[-1].curr_polys =",
"algorithms have run deepCopyScalars = vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars = deepCopyScalars #TODO - this",
"is handled in subroutines of other imported modules. A core concept here is",
"from mp_VTKProcessing import * from mp_VTKDrawing import * def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver):",
"mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep copied # turns out that later processes access the",
"vtk.util import numpy_support debug = True # local modules from mp_unpackIncomingData import unpackData",
"debug: print('received request for UPDATE DIRECT mesh with Args:') print(commandArgs) if len(commandArgs) !=",
"indexing # lets show the correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets",
"rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #rotation args rotations = commandArgs[0].strip().split(',') rotations = unpackData(rotations[1], int(rotations[2]),",
"the mainWindowUI that is passed to all functions so that all funcitons have",
"# 3) b_vector - green component # 4) a_vector - aplha component if",
"data a (rgba) for each vertex if debug: print('received request for new mesh",
"points mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep copied # and so we",
"data from MATLAB, probably just an internal re-draw call # after something like",
"mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing # lets show the correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index",
"4) color data g (rgba) for each vertex # 5) color data b",
"component # 3) b_vector - green component # 4) a_vector - aplha component",
"blue component # 3) b_vector - green component # 4) a_vector - aplha",
"deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars = deepCopyScalars #TODO - this may have impact on later processing",
"added instance (e.g. when adding a new mesh) --- mainWindowUI.vtkInstances[-1] Note that it",
"#place holder for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointIds =",
"track mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place holder for picked vtk point",
"= unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[2].strip().split(',') b_vec = unpackData(bVecArgs[1],",
"point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO",
"= polyData mainWindowUI.vtkInstances[-1].curr_mapper = pdm mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera() # and the raw mesh",
"main window in scope. <NAME> 2017 ''' import vtk from numpy import *",
"copied # and so we can access ui controls (e.g. statusbar) from the",
"= unpackData(rotations[1], int(rotations[2]), the_TCPserver) if debug: print(rotations) targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing",
"- this is a vtkRenderWindowInteractor instance in the main program UI (user interface)",
"UI (user interface) - by creatoing multiple instances of vtk windows we can",
"ok, we hav the data, lets turn it into vtk stuff # Process",
"View settings in from the vista session WITH THE COLOR VALUES FROM #",
"no new data from MATLAB, probably just an internal re-draw call # after",
"convert this to a VTK unsigned char array vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0) # keep",
"= True # local modules from mp_unpackIncomingData import unpackData from mp_VTKProcessing import *",
"r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[3].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]),",
"commandArgs[3].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if debug: print(len(r_vec)) print(len(g_vec))",
"surfaces data verticesArgs = commandArgs[0].strip().split(',') vertices = unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver) vertices = array(vertices,'f')",
"modules. A core concept here is the tracking (kepping in scope) or the",
"in scope. <NAME> 2017 ''' import vtk from numpy import * import time",
"viewer The main vtk processing is done by functions here - although some",
"ren.Render() mainWindowUI.vtkInstances[-1].Render() # lets put some of the data objects in the scope",
"else: # no new data from MATLAB, probably just an internal re-draw call",
"gVecArgs = commandArgs[3].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs =",
"= squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a VTK unsigned char array vtkColorArray =",
"if ('iterations' in commandArgs[0]) and ('relaxationfactor' in commandArgs[0]): smoothingArgs = commandArgs[0].strip().split(',') iterations =",
"- expecting vertices, then triangles!\" # load the surfaces data verticesArgs = commandArgs[0].strip().split(',')",
"the_smoother = targetVTKWindow.curr_smoother the_mapper = targetVTKWindow.curr_mapper if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting",
"#lets get the original data the_smoother = targetVTKWindow.curr_smoother the_mapper = targetVTKWindow.curr_mapper if debug:",
"mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success with",
"may have impact on later processing - investigate else: # no new data",
"adding a new mesh) --- mainWindowUI.vtkInstances[-1] Note that it is the mainWindowUI that",
"done by functions here - although some hardcore processing is handled in subroutines",
"is the mainWindowUI that is passed to all functions so that all funcitons",
"drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0) ren = mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren = ren ren.AddActor(actor) ren.SetBackground(1,1,1)",
"new mesh) --- mainWindowUI.vtkInstances[-1] Note that it is the mainWindowUI that is passed",
"mainWindowUI.vtkInstances[-1].Render() # lets put some of the data objects in the scope of",
"expecting vertices, then triangles!\" # load the surfaces data verticesArgs = commandArgs[0].strip().split(',') vertices",
"i in range(nTriangles): polys.InsertNextCell(3) for j in range(3): polys.InsertCellPoint(int(triangles[i][j])) # check if debug:",
"from mp_unpackIncomingData import unpackData from mp_VTKProcessing import * from mp_VTKDrawing import * def",
"not mainWindowUI.vtkInstances[-1].curr_points = points mainWindowUI.vtkInstances[-1].curr_polys = polys mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep copied #",
"# run mesh update to reset the color map (smoothing \"messes\" this up)",
"run mesh update to reset the color map (smoothing \"messes\" this up) updateMeshData(theMeshInstance,",
"mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place holder for picked vtk point IDs so we can",
"mesh is already loaded and we are simply updating with the # current",
"- we allow vtk to do this but then overwrite the recomptued color",
"smooth mainWindowUI.vtkInstances[-1].curr_polydata = polyData mainWindowUI.vtkInstances[-1].curr_mapper = pdm mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera() # and the",
"on the surface # add a picker that allows is top pick points",
"= targetVTKWindow.curr_polydata the_mapper = targetVTKWindow.curr_mapper #first get all the data we are expecting",
"if len(commandArgs) != 0 : #new data has come from MATLAB so recompute",
"3) color data r (rgba) for each vertex # 4) color data g",
"the inherited renderwindowinteractor (?) # so lets put all the above in the",
"then overwrite the recomptued color # map AFTER the algorithms have run deepCopyScalars",
"others just referene the most recently added instance (e.g. when adding a new",
"mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place holder for picked vtk point IDs so we",
"color data b (rgba) for each vertex # 6) color data a (rgba)",
"index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_smoother = targetVTKWindow.curr_smoother the_mapper =",
"so that all funcitons have the content of the main window in scope.",
"modules from mp_unpackIncomingData import unpackData from mp_VTKProcessing import * from mp_VTKDrawing import *",
"pass else: return \"error - expecting vertices, then triangles!\" # load the surfaces",
"in subroutines of other imported modules. A core concept here is the tracking",
"int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if debug: print(len(r_vec)) print(len(g_vec)) print(len(b_vec)) print(len(a_vec)) #combine into",
"into numpy array colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a VTK unsigned",
"session WITH THE COLOR VALUES FROM # VISTA - i.e. do not go",
"all functions so that all funcitons have the content of the main window",
"a lookuptable #lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing",
"(e.g. smoothing) that also smooth the color data # on the surface and",
"points = vtk.vtkPoints() for i in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process faces (triangles) polys",
"we can track mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place holder for picked",
"= vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place holder for picked vtk point",
"bVecArgs = commandArgs[4].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs =",
"the data objects in the scope of the # main window so that",
"mp_VTKProcessing import * from mp_VTKDrawing import * def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #first",
"'l': currVTKinstance = len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also track key presses per instance",
"array(vertices,'f') vertices = vertices.reshape((len(vertices)/3,3)) trianglesArgs = commandArgs[1].strip().split(',') triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver) triangles",
"the color data # on the surface and then automatically update the inherited",
"def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #rotation args rotations = commandArgs[0].strip().split(',') rotations = unpackData(rotations[1],",
"if ('vertices' in commandArgs[0]) and ('triangles' in commandArgs[1]): pass else: return \"error -",
"# and the raw mesh coordinate data.. why not mainWindowUI.vtkInstances[-1].curr_points = points mainWindowUI.vtkInstances[-1].curr_polys",
"the_mapper = targetVTKWindow.curr_mapper if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a string that",
"update the inherited color map # - we allow vtk to do this",
"## -------------------------------------------------------------------------------- # test example animation def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #rotation args",
"(e.g. statusbar) from the inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI def KeyPress(obj, evt): key",
"= array(g_vec,'uint8') bVecArgs = commandArgs[2].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8')",
"apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing # lets show the correct",
"for i in range(nTriangles): polys.InsertNextCell(3) for j in range(3): polys.InsertCellPoint(int(triangles[i][j])) # check if",
"# OK - we have the data - let's update the mesh newActor",
"funcitons have the content of the main window in scope. <NAME> 2017 '''",
"of sending by the server is # 1) vertices # 2) triangles #",
"# check if debug: print(points) if debug: print(polys) if debug: print(scalars) if debug:",
"main window so that they can be manipulated later. mainWindowUI.vtkInstances[-1].curr_actor = actor mainWindowUI.vtkInstances[-1].curr_smoother",
"unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[5].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]),",
"the recomptued color # map AFTER the algorithms have run deepCopyScalars = vtk.vtkUnsignedCharArray()",
"# 2) triangles # 3) color data r (rgba) for each vertex #",
"NB this assumes that the order of sending by the server is #",
"room for drawing on the surface # add a picker that allows is",
"for j in range(3): polys.InsertCellPoint(int(triangles[i][j])) # check if debug: print(points) if debug: print(polys)",
"data the_smoother = targetVTKWindow.curr_smoother the_mapper = targetVTKWindow.curr_mapper if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000))",
"= vtk.vtkCellArray() nTriangles = triangles.shape[0] for i in range(nTriangles): polys.InsertNextCell(3) for j in",
"index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_polyData = targetVTKWindow.curr_polydata the_mapper =",
"polyData mainWindowUI.vtkInstances[-1].curr_mapper = pdm mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera() # and the raw mesh coordinate",
"int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[1].strip().split(',') g_vec =",
"with the # current View settings in from the vista session WITH THE",
"VTK engine room for mrMeshPy viewer The main vtk processing is done by",
"mainWindowUI.tabWidget.update() #lets get the original data the_polyData = targetVTKWindow.curr_polydata the_mapper = targetVTKWindow.curr_mapper #first",
"curr_scalars.DeepCopy(scalars) ## ---- ok, we hav the data, lets turn it into vtk",
"map AFTER the algorithms have run deepCopyScalars = vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars = deepCopyScalars",
"if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a string that reads something like",
"TODO ? smoothing on first load? smooth = vtk.vtkSmoothPolyDataFilter() smooth = vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0)",
"the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[2].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec",
"int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[5].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver)",
"mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place holder for picked vtk point IDs",
"updating with the # current View settings in from the vista session WITH",
"= VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor = newActor #lets keep track",
"unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[4].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]),",
"we can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place holder for picked",
"smoothing on first load? smooth = vtk.vtkSmoothPolyDataFilter() smooth = vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff()",
"they can be manipulated later. mainWindowUI.vtkInstances[-1].curr_actor = actor mainWindowUI.vtkInstances[-1].curr_smoother = smooth mainWindowUI.vtkInstances[-1].curr_polydata =",
"with Args:') print(commandArgs) if len(commandArgs) != 0 : #new data has come from",
"from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0) ren = mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren =",
"b (rgba) for each vertex # 6) color data a (rgba) for each",
"the_TCPserver): #first get all the data we are expecting from the server ##",
"so recompute # load the surfaces data rVecArgs = commandArgs[0].strip().split(',') r_vec = unpackData(rVecArgs[1],",
"surface # add a picker that allows is top pick points on the",
"and then automatically update the inherited color map # - we allow vtk",
"# 3) color data r (rgba) for each vertex # 4) color data",
"from MATLAB so recompute # load the surfaces data rVecArgs = commandArgs[0].strip().split(',') r_vec",
"this assumes that the order of sending by the server is # 1)",
"check if ('vertices' in commandArgs[0]) and ('triangles' in commandArgs[1]): pass else: return \"error",
"polys = vtk.vtkCellArray() nTriangles = triangles.shape[0] for i in range(nTriangles): polys.InsertNextCell(3) for j",
"smooth the color data # on the surface and then automatically update the",
"can track mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode #",
"this specifically with a reference index passed from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)] while others",
"= commandArgs[3].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if debug: print(len(r_vec))",
"= vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ## TODO ? smoothing on first load? smooth",
"## ---- engine room for drawing on the surface # add a picker",
"triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver) triangles = array(triangles,'f') if debug: print(triangles) triangles =",
"lets show the correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the",
"something like 'iterations,200,relaxationfactor,1.2' # sanity check if ('iterations' in commandArgs[0]) and ('relaxationfactor' in",
"the required scalars vtkColorArray = targetVTKWindow.curr_scalars # OK - we have the data",
"vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm = vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor = vtk.vtkActor()",
"color data a (rgba) for each vertex if debug: print('received request for new",
"triangles!\" newActor = VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor = newActor #lets",
"# 2) g_vector - blue component # 3) b_vector - green component #",
"and so we can access ui controls (e.g. statusbar) from the inherited window",
"mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index def smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): #lets get the apt",
"points on the surface picker = vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place",
"ui controls (e.g. statusbar) from the inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI def KeyPress(obj,",
"is done by functions here - although some hardcore processing is handled in",
"print(polys) if debug: print(scalars) if debug: print(currVTKInstance) # Assemble as PolyData polyData =",
"animation def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #rotation args rotations = commandArgs[0].strip().split(',') rotations =",
"most recently added instance (e.g. when adding a new mesh) --- mainWindowUI.vtkInstances[-1] Note",
"#mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_smoother = targetVTKWindow.curr_smoother the_mapper = targetVTKWindow.curr_mapper",
"#NB zero indexing camera = targetVTKWindow.ren.GetActiveCamera() if debug: print(camera) for i in range(len(rotations)):",
"= numpy_support.numpy_to_vtk(colorDat,0) curr_scalars = vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ## ---- ok, we hav the data,",
"- we have the data - let's update the mesh newActor = VTK_updateMesh(targetVTKWindow,",
"# local modules from mp_unpackIncomingData import unpackData from mp_VTKProcessing import * from mp_VTKDrawing",
"mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing functions imported from",
"access the inherited renderwindowinteractor (?) # so lets put all the above in",
"('vertices' in commandArgs[0]) and ('triangles' in commandArgs[1]): pass else: return \"error - expecting",
"def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #first get all the data we are expecting",
"points mainWindowUI.vtkInstances[-1].curr_polys = polys mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep copied # turns out that",
"debug: print(camera) for i in range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render() targetVTKWindow.iren.Render() time.sleep(0.02) the_TCPserver.socket.write(str('send useful message",
"#let's also track key presses per instance esp for the draw routine :)",
"that allows is top pick points on the surface picker = vtk.vtkCellPicker() picker.SetTolerance(0.0001)",
"3) b_vector - green component # 4) a_vector - aplha component if debug:",
"- this is to workaround some artifacts generated # by vtk algorithms (e.g.",
"smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points = points",
"copy of the required scalars vtkColorArray = targetVTKWindow.curr_scalars # OK - we have",
"then triangles!\" newActor = VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor = newActor",
"just referene the most recently added instance (e.g. when adding a new mesh)",
"b_vector - green component # 4) a_vector - aplha component if debug: print('received",
"green component # 4) a_vector - aplha component if debug: print('received request for",
"picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues =",
"if debug: print(r_vec) gVecArgs = commandArgs[1].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec =",
"lets put all the above in the scope of that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor =",
"the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing # lets show the",
"vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars = deepCopyScalars #TODO - this may have impact on later",
"mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing functions",
"= vtk.vtkPoints() for i in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process faces (triangles) polys =",
"# 4) a_vector - aplha component if debug: print('received request for UPDATE DIRECT",
"else: return \"error - expecting vertices, then curvature, then triangles!\" newActor = VTK_smoothing(the_smoother,",
"in commandArgs[0]) and ('triangles' in commandArgs[1]): pass else: return \"error - expecting vertices,",
"('triangles' in commandArgs[1]): pass else: return \"error - expecting vertices, then triangles!\" #",
"pdm = vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(pdm) iren = mainWindowUI.vtkInstances[-1] ##",
"= mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing camera = targetVTKWindow.ren.GetActiveCamera() if debug: print(camera) for i",
"in commandArgs[0]): smoothingArgs = commandArgs[0].strip().split(',') iterations = int(smoothingArgs[1]) relaxationfactor = float(smoothingArgs[3]) else: return",
"drawing functions imported from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0) ren =",
"print(len(b_vec)) print(len(a_vec)) #combine into numpy array colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to",
"mainWindowUI.vtkInstances[-1].curr_polydata = polyData mainWindowUI.vtkInstances[-1].curr_mapper = pdm mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera() # and the raw",
"mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points = points mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars",
"unpackData(rotations[1], int(rotations[2]), the_TCPserver) if debug: print(rotations) targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing camera",
"triangles.reshape((len(triangles)/3,3)) if debug: print(triangles) # load the surface colour data rVecArgs = commandArgs[2].strip().split(',')",
"mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0) ren = mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren = ren ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render()",
"unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[3].strip().split(',') g_vec",
"#NB zero indexing # lets show the correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint()",
"THE COLOR VALUES FROM # VISTA - i.e. do not go through a",
"order of sending by the server is # 1) vertices # 2) triangles",
"engine room for mrMeshPy viewer The main vtk processing is done by functions",
"point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place",
"= unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[3].strip().split(',') a_vec = unpackData(aVecArgs[1],",
"b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[3].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec =",
"load the surfaces data verticesArgs = commandArgs[0].strip().split(',') vertices = unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver) vertices",
"iterations = int(smoothingArgs[1]) relaxationfactor = float(smoothingArgs[3]) else: return \"error - expecting vertices, then",
"recomptued color # map AFTER the algorithms have run deepCopyScalars = vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray)",
"zero indexing camera = targetVTKWindow.ren.GetActiveCamera() if debug: print(camera) for i in range(len(rotations)): camera.Azimuth(rotations[i])",
"a picker that allows is top pick points on the surface picker =",
"update the mesh newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor = newActor",
"the data - let's update the mesh newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor)",
"instance in the main program UI (user interface) - by creatoing multiple instances",
"args rotations = commandArgs[0].strip().split(',') rotations = unpackData(rotations[1], int(rotations[2]), the_TCPserver) if debug: print(rotations) targetVTKWindow",
"# drawing functions imported from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0) ren",
"the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[4].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec",
"== 'l': currVTKinstance = len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also track key presses per",
"# 1) r_vector - red component # 2) g_vector - blue component #",
"- this may have impact on later processing - investigate else: # no",
"debug: print(currVTKInstance) # Assemble as PolyData polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ##",
"unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if debug: print(len(r_vec)) print(len(g_vec)) print(len(b_vec)) print(len(a_vec)) #combine",
"scalars = numpy_support.numpy_to_vtk(colorDat,0) curr_scalars = vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ## ---- ok, we hav the",
"# Assemble as PolyData polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ## TODO ?",
"triangles = triangles.reshape((len(triangles)/3,3)) if debug: print(triangles) # load the surface colour data rVecArgs",
"[] #place holder for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointIds",
"loaded and we are simply updating with the # current View settings in",
"the # current View settings in from the vista session WITH THE COLOR",
"vtk windows we can load multiple meshes. Some functions reference this specifically with",
"curvature, then triangles!\" newActor = VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor =",
"targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success with direct",
"relaxationfactor = float(smoothingArgs[3]) else: return \"error - expecting vertices, then curvature, then triangles!\"",
"mainWindowUI.vtkInstances[int(theMeshInstance)] while others just referene the most recently added instance (e.g. when adding",
"obj.GetKeySym() if key == 'l': currVTKinstance = len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also track",
"for new mesh with Args:') print(commandArgs) # sanity check if ('vertices' in commandArgs[0])",
"triangles!\" # load the surfaces data verticesArgs = commandArgs[0].strip().split(',') vertices = unpackData(verticesArgs[1], int(verticesArgs[2]),",
"controls (e.g. statusbar) from the inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI def KeyPress(obj, evt):",
"iren = mainWindowUI.vtkInstances[-1] ## ---- engine room for drawing on the surface #",
"processing is handled in subroutines of other imported modules. A core concept here",
"= vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ## ---- ok, we hav the data, lets turn it",
"surface picker = vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place holder for picked",
"1) r_vector - red component # 2) g_vector - blue component # 3)",
"server is # 1) vertices # 2) triangles # 3) color data r",
"range(3): polys.InsertCellPoint(int(triangles[i][j])) # check if debug: print(points) if debug: print(polys) if debug: print(scalars)",
"program UI (user interface) - by creatoing multiple instances of vtk windows we",
"vtk.vtkPoints() #place holder for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPoints",
"mesh) --- mainWindowUI.vtkInstances[-1] Note that it is the mainWindowUI that is passed to",
"of the data objects in the scope of the # main window so",
"already loaded and we are simply updating with the # current View settings",
"the vista session WITH THE COLOR VALUES FROM # VISTA - i.e. do",
"we hav the data, lets turn it into vtk stuff # Process vertices",
"- by creatoing multiple instances of vtk windows we can load multiple meshes.",
"smoothingArgs = commandArgs[0].strip().split(',') iterations = int(smoothingArgs[1]) relaxationfactor = float(smoothingArgs[3]) else: return \"error -",
"algorithms (e.g. smoothing) that also smooth the color data # on the surface",
"AFTER the algorithms have run deepCopyScalars = vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars = deepCopyScalars #TODO",
"the draw routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index def smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver):",
"float(smoothingArgs[3]) else: return \"error - expecting vertices, then curvature, then triangles!\" newActor =",
"then automatically update the inherited color map # - we allow vtk to",
"an internal re-draw call # after something like smoothing - just grab the",
"len(commandArgs) != 0 : #new data has come from MATLAB so recompute #",
"deepCopyScalars = vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars = deepCopyScalars #TODO - this may have impact",
"by the server is # 1) vertices # 2) triangles # 3) color",
"and we are simply updating with the # current View settings in from",
"!= 0 : #new data has come from MATLAB so recompute # load",
"curr_scalars #Deep copied # turns out that later processes access the inherited renderwindowinteractor",
"array(b_vec,'uint8') aVecArgs = commandArgs[5].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if",
"load? smooth = vtk.vtkSmoothPolyDataFilter() smooth = vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm =",
"mp_unpackIncomingData import unpackData from mp_VTKProcessing import * from mp_VTKDrawing import * def loadNewMesh(currVTKInstance,",
"load the surface colour data rVecArgs = commandArgs[2].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver)",
"that later processes access the inherited renderwindowinteractor (?) # so lets put all",
"mainWindowUI.vtkInstances[-1]._Iren.curr_points = points mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep copied # and",
"('iterations' in commandArgs[0]) and ('relaxationfactor' in commandArgs[0]): smoothingArgs = commandArgs[0].strip().split(',') iterations = int(smoothingArgs[1])",
"mainWindowUI that is passed to all functions so that all funcitons have the",
"mesh coordinate data.. why not mainWindowUI.vtkInstances[-1].curr_points = points mainWindowUI.vtkInstances[-1].curr_polys = polys mainWindowUI.vtkInstances[-1].curr_scalars =",
"# so lets put all the above in the scope of that too",
"currVTKinstance = len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also track key presses per instance esp",
"the most recently added instance (e.g. when adding a new mesh) --- mainWindowUI.vtkInstances[-1]",
"print(commandArgs) # sanity check if ('vertices' in commandArgs[0]) and ('triangles' in commandArgs[1]): pass",
"(triangles) polys = vtk.vtkCellArray() nTriangles = triangles.shape[0] for i in range(nTriangles): polys.InsertNextCell(3) for",
"print(scalars) if debug: print(currVTKInstance) # Assemble as PolyData polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys)",
"then curvature, then triangles!\" newActor = VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor",
"# test example animation def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #rotation args rotations =",
"the content of the main window in scope. <NAME> 2017 ''' import vtk",
"0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing functions imported from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint,",
"range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process faces (triangles) polys = vtk.vtkCellArray() nTriangles = triangles.shape[0] for",
"mainWindowUI.vtkInstances[-1].curr_points = points mainWindowUI.vtkInstances[-1].curr_polys = polys mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep copied # turns",
"for each vertex # 6) color data a (rgba) for each vertex if",
"for the draw routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index def smoothMesh(theMeshInstance, commandArgs, mainWindowUI,",
"the_TCPserver): #rotation args rotations = commandArgs[0].strip().split(',') rotations = unpackData(rotations[1], int(rotations[2]), the_TCPserver) if debug:",
"The main vtk processing is done by functions here - although some hardcore",
"\"messes\" this up) updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver) def updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): #",
"is # 1) r_vector - red component # 2) g_vector - blue component",
"like 'iterations,200,relaxationfactor,1.2' # sanity check if ('iterations' in commandArgs[0]) and ('relaxationfactor' in commandArgs[0]):",
"commandArgs[0]) and ('relaxationfactor' in commandArgs[0]): smoothingArgs = commandArgs[0].strip().split(',') iterations = int(smoothingArgs[1]) relaxationfactor =",
"def KeyPress(obj, evt): key = obj.GetKeySym() if key == 'l': currVTKinstance = len(mainWindowUI.vtkInstances)",
"mainWindowUI, the_TCPserver): #first get all the data we are expecting from the server",
"commandArgs[0].strip().split(',') rotations = unpackData(rotations[1], int(rotations[2]), the_TCPserver) if debug: print(rotations) targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB",
"simply updating with the # current View settings in from the vista session",
"component # 4) a_vector - aplha component if debug: print('received request for UPDATE",
"is the tracking (kepping in scope) or the \"targetVTKWindow\" - this is a",
"drawing on the surface # add a picker that allows is top pick",
"# on the surface and then automatically update the inherited color map #",
"from mp_VTKDrawing import * def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #first get all the",
"in range(nTriangles): polys.InsertNextCell(3) for j in range(3): polys.InsertCellPoint(int(triangles[i][j])) # check if debug: print(points)",
"#lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing # lets",
"# here the base mesh is already loaded and we are simply updating",
"curr_scalars = vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ## ---- ok, we hav the data, lets turn",
"= points mainWindowUI.vtkInstances[-1].curr_polys = polys mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep copied # turns out",
"targetVTKWindow.curr_smoother the_mapper = targetVTKWindow.curr_mapper if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a string",
"just grab the current deep # copy of the required scalars vtkColorArray =",
"commandArgs[3].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[4].strip().split(',') b_vec",
"print('success with direct mesh update routine') ## -------------------------------------------------------------------------------- # test example animation def",
"inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI def KeyPress(obj, evt): key = obj.GetKeySym() if key",
"## TODO ? smoothing on first load? smooth = vtk.vtkSmoothPolyDataFilter() smooth = vtk.vtkSmoothPolyDataFilter()",
"targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing camera = targetVTKWindow.ren.GetActiveCamera() if debug: print(camera) for",
"\"targetVTKWindow\" - this is a vtkRenderWindowInteractor instance in the main program UI (user",
"have the data - let's update the mesh newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI)",
"Process faces (triangles) polys = vtk.vtkCellArray() nTriangles = triangles.shape[0] for i in range(nTriangles):",
"functions imported from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0) ren = mainWindowUI.vtkInstances[-1].ren",
"hardcore processing is handled in subroutines of other imported modules. A core concept",
"to all functions so that all funcitons have the content of the main",
"the \"targetVTKWindow\" - this is a vtkRenderWindowInteractor instance in the main program UI",
"unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver) vertices = array(vertices,'f') vertices = vertices.reshape((len(vertices)/3,3)) trianglesArgs = commandArgs[1].strip().split(',') triangles",
"aVecArgs = commandArgs[5].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if debug:",
"instances of vtk windows we can load multiple meshes. Some functions reference this",
"vtkRenderWindowInteractor instance in the main program UI (user interface) - by creatoing multiple",
"= vtk.vtkSmoothPolyDataFilter() smooth = vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm = vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData()",
"above in the scope of that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth",
"(smoothing \"messes\" this up) updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver) def updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver):",
"after something like smoothing - just grab the current deep # copy of",
"vertices = vertices.reshape((len(vertices)/3,3)) trianglesArgs = commandArgs[1].strip().split(',') triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver) triangles =",
"= vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(pdm) iren = mainWindowUI.vtkInstances[-1] ## ----",
"---- engine room for drawing on the surface # add a picker that",
"can be manipulated later. mainWindowUI.vtkInstances[-1].curr_actor = actor mainWindowUI.vtkInstances[-1].curr_smoother = smooth mainWindowUI.vtkInstances[-1].curr_polydata = polyData",
"ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points = points mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep copied #",
"= commandArgs[1].strip().split(',') triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver) triangles = array(triangles,'f') if debug: print(triangles)",
"r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[1].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]),",
"coordinate data.. why not mainWindowUI.vtkInstances[-1].curr_points = points mainWindowUI.vtkInstances[-1].curr_polys = polys mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars",
"range(nTriangles): polys.InsertNextCell(3) for j in range(3): polys.InsertCellPoint(int(triangles[i][j])) # check if debug: print(points) if",
"the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[3].strip().split(',') g_vec = unpackData(gVecArgs[1],",
"debug: print(scalars) if debug: print(currVTKInstance) # Assemble as PolyData polyData = vtk.vtkPolyData() polyData.SetPoints(points)",
"actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera()",
"assumes that the order of sending by the server is # 1) vertices",
"# 5) color data b (rgba) for each vertex # 6) color data",
"debug: print(r_vec) gVecArgs = commandArgs[1].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8')",
"the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[3].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec",
"passed to all functions so that all funcitons have the content of the",
"numpy import * import time from vtk.util import numpy_support debug = True #",
"---- ok, we hav the data, lets turn it into vtk stuff #",
"get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing # lets show",
"= float(smoothingArgs[3]) else: return \"error - expecting vertices, then curvature, then triangles!\" newActor",
"#place holder for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues =",
"# copy of the required scalars vtkColorArray = targetVTKWindow.curr_scalars # OK - we",
"window so that they can be manipulated later. mainWindowUI.vtkInstances[-1].curr_actor = actor mainWindowUI.vtkInstances[-1].curr_smoother =",
"reference this specifically with a reference index passed from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)] while",
"debug: print(triangles) triangles = triangles.reshape((len(triangles)/3,3)) if debug: print(triangles) # load the surface colour",
"mesh with Args:') print(commandArgs) # sanity check if ('vertices' in commandArgs[0]) and ('triangles'",
"= array(a_vec,'uint8') if debug: print(len(r_vec)) print(len(g_vec)) print(len(b_vec)) print(len(a_vec)) #combine into numpy array colorDat",
"mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place holder for picked vtk point IDs so we can",
"that they can be manipulated later. mainWindowUI.vtkInstances[-1].curr_actor = actor mainWindowUI.vtkInstances[-1].curr_smoother = smooth mainWindowUI.vtkInstances[-1].curr_polydata",
"pdm mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera() # and the raw mesh coordinate data.. why not",
"loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #first get all the data we are expecting from",
"data g (rgba) for each vertex # 5) color data b (rgba) for",
"int(trianglesArgs[2]), the_TCPserver) triangles = array(triangles,'f') if debug: print(triangles) triangles = triangles.reshape((len(triangles)/3,3)) if debug:",
"into vtk stuff # Process vertices points = vtk.vtkPoints() for i in range(vertices.shape[0]):",
"smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm = vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(pdm)",
"= mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing functions imported from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI,",
"= ren.GetActiveCamera() # and the raw mesh coordinate data.. why not mainWindowUI.vtkInstances[-1].curr_points =",
"= VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render()",
"data - let's update the mesh newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor)",
"= commandArgs[1].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[2].strip().split(',')",
": #new data has come from MATLAB so recompute # load the surfaces",
"# load the surfaces data verticesArgs = commandArgs[0].strip().split(',') vertices = unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver)",
"#zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_smoother = targetVTKWindow.curr_smoother the_mapper",
"to a VTK unsigned char array vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0) # keep a \"deep\"",
"routine') ## -------------------------------------------------------------------------------- # test example animation def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #rotation",
"rotations = commandArgs[0].strip().split(',') rotations = unpackData(rotations[1], int(rotations[2]), the_TCPserver) if debug: print(rotations) targetVTKWindow =",
"debug = True # local modules from mp_unpackIncomingData import unpackData from mp_VTKProcessing import",
"True # local modules from mp_unpackIncomingData import unpackData from mp_VTKProcessing import * from",
"current View settings in from the vista session WITH THE COLOR VALUES FROM",
"the original data the_polyData = targetVTKWindow.curr_polydata the_mapper = targetVTKWindow.curr_mapper #first get all the",
"mainWindowUI.vtkInstances[-1].curr_smoother = smooth mainWindowUI.vtkInstances[-1].curr_polydata = polyData mainWindowUI.vtkInstances[-1].curr_mapper = pdm mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera() #",
"if debug: print(currVTKInstance) # Assemble as PolyData polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars)",
"indexing camera = targetVTKWindow.ren.GetActiveCamera() if debug: print(camera) for i in range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render()",
"targetVTKWindow.ren.GetActiveCamera() if debug: print(camera) for i in range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render() targetVTKWindow.iren.Render() time.sleep(0.02) the_TCPserver.socket.write(str('send",
"- green component # 4) a_vector - aplha component if debug: print('received request",
"vertices points = vtk.vtkPoints() for i in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process faces (triangles)",
"#first get all the data we are expecting from the server ## NB",
"vtkColorArray = targetVTKWindow.curr_scalars # OK - we have the data - let's update",
"windows we can load multiple meshes. Some functions reference this specifically with a",
"so we can track mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place holder for",
"raw mesh coordinate data.. why not mainWindowUI.vtkInstances[-1].curr_points = points mainWindowUI.vtkInstances[-1].curr_polys = polys mainWindowUI.vtkInstances[-1].curr_scalars",
"data objects in the scope of the # main window so that they",
"check if debug: print(points) if debug: print(polys) if debug: print(scalars) if debug: print(currVTKInstance)",
"= mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place holder for picked vtk point IDs so",
"vertices = unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver) vertices = array(vertices,'f') vertices = vertices.reshape((len(vertices)/3,3)) trianglesArgs =",
"mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0) ren = mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren = ren",
"= unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[1].strip().split(',')",
"#lets get the original data the_polyData = targetVTKWindow.curr_polydata the_mapper = targetVTKWindow.curr_mapper #first get",
"multiple meshes. Some functions reference this specifically with a reference index passed from",
"is passed to all functions so that all funcitons have the content of",
"int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[2].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver)",
"tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_smoother =",
"pdm.SetInputConnection(smooth.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(pdm) iren = mainWindowUI.vtkInstances[-1] ## ---- engine room for",
"(rgba) for each vertex # 4) color data g (rgba) for each vertex",
"int(verticesArgs[2]), the_TCPserver) vertices = array(vertices,'f') vertices = vertices.reshape((len(vertices)/3,3)) trianglesArgs = commandArgs[1].strip().split(',') triangles =",
"for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode",
"zero indexing # lets show the correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update()",
"data has come from MATLAB so recompute # load the surfaces data rVecArgs",
"updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver) def updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): # here the base",
"overwrite the recomptued color # map AFTER the algorithms have run deepCopyScalars =",
"here - although some hardcore processing is handled in subroutines of other imported",
"print(rotations) targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing camera = targetVTKWindow.ren.GetActiveCamera() if debug: print(camera)",
"r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs =",
":) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index def smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): #lets get the",
"1.0) ren = mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren = ren ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render() #",
"commandArgs[2].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[3].strip().split(',') a_vec",
"in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process faces (triangles) polys = vtk.vtkCellArray() nTriangles = triangles.shape[0]",
"# lets show the correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get",
"import * def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #first get all the data we",
"array vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0) # keep a \"deep\" copy - this is to",
"targetVTKWindow.curr_scalars = deepCopyScalars #TODO - this may have impact on later processing -",
"deep # copy of the required scalars vtkColorArray = targetVTKWindow.curr_scalars # OK -",
"curr_scalars #Deep copied # and so we can access ui controls (e.g. statusbar)",
"actor mainWindowUI.vtkInstances[-1].curr_smoother = smooth mainWindowUI.vtkInstances[-1].curr_polydata = polyData mainWindowUI.vtkInstances[-1].curr_mapper = pdm mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera()",
"5) color data b (rgba) for each vertex # 6) color data a",
"i in range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render() targetVTKWindow.iren.Render() time.sleep(0.02) the_TCPserver.socket.write(str('send useful message back here TODO'))",
"targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success with direct mesh",
"server ## NB this assumes that the order of sending by the server",
"here the base mesh is already loaded and we are simply updating with",
"= unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver) vertices = array(vertices,'f') vertices = vertices.reshape((len(vertices)/3,3)) trianglesArgs = commandArgs[1].strip().split(',')",
"if debug: print(triangles) triangles = triangles.reshape((len(triangles)/3,3)) if debug: print(triangles) # load the surface",
"with direct mesh update routine') ## -------------------------------------------------------------------------------- # test example animation def rotateMeshAnimation(currVTKInstance,",
"print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a string that reads something like 'iterations,200,relaxationfactor,1.2' # sanity check if",
"add a picker that allows is top pick points on the surface picker",
"mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera",
"unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[3].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]),",
"by the server is # 1) r_vector - red component # 2) g_vector",
"functions so that all funcitons have the content of the main window in",
"the data, lets turn it into vtk stuff # Process vertices points =",
"targetVTKWindow.ren.Render() targetVTKWindow.Render() # run mesh update to reset the color map (smoothing \"messes\"",
"vtk.vtkCellArray() nTriangles = triangles.shape[0] for i in range(nTriangles): polys.InsertNextCell(3) for j in range(3):",
"## NB this assumes that the order of sending by the server is",
"picker = vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place holder for picked vtk",
"vtk.vtkActor() actor.SetMapper(pdm) iren = mainWindowUI.vtkInstances[-1] ## ---- engine room for drawing on the",
"WITH THE COLOR VALUES FROM # VISTA - i.e. do not go through",
"have impact on later processing - investigate else: # no new data from",
"each vertex # 5) color data b (rgba) for each vertex # 6)",
"mainWindowUI.vtkInstances[-1].curr_mapper = pdm mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera() # and the raw mesh coordinate data..",
"targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() # run mesh",
"the server ## NB this assumes that the order of sending by the",
"the main window in scope. <NAME> 2017 ''' import vtk from numpy import",
"with Args:') print(commandArgs) # sanity check if ('vertices' in commandArgs[0]) and ('triangles' in",
"commandArgs, mainWindowUI, the_TCPserver): # here the base mesh is already loaded and we",
"each vertex if debug: print('received request for new mesh with Args:') print(commandArgs) #",
"newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success with direct mesh update routine') ##",
"the order of sending by the server is # 1) r_vector - red",
"= targetVTKWindow.ren.GetActiveCamera() if debug: print(camera) for i in range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render() targetVTKWindow.iren.Render() time.sleep(0.02)",
"imported modules. A core concept here is the tracking (kepping in scope) or",
"= curr_scalars #Deep copied # turns out that later processes access the inherited",
"bVecArgs = commandArgs[2].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs =",
"recently added instance (e.g. when adding a new mesh) --- mainWindowUI.vtkInstances[-1] Note that",
"pick points on the surface picker = vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = []",
"each vertex # 6) color data a (rgba) for each vertex if debug:",
"can access ui controls (e.g. statusbar) from the inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI",
"subroutines of other imported modules. A core concept here is the tracking (kepping",
"data verticesArgs = commandArgs[0].strip().split(',') vertices = unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver) vertices = array(vertices,'f') vertices",
"also track key presses per instance esp for the draw routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress)",
"int(rotations[2]), the_TCPserver) if debug: print(rotations) targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing camera =",
"= commandArgs[2].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[3].strip().split(',')",
"like smoothing - just grab the current deep # copy of the required",
"by creatoing multiple instances of vtk windows we can load multiple meshes. Some",
"MATLAB, probably just an internal re-draw call # after something like smoothing -",
"print(r_vec) gVecArgs = commandArgs[3].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs",
"window in scope. <NAME> 2017 ''' import vtk from numpy import * import",
"trianglesArgs = commandArgs[1].strip().split(',') triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver) triangles = array(triangles,'f') if debug:",
"some of the data objects in the scope of the # main window",
"check if ('iterations' in commandArgs[0]) and ('relaxationfactor' in commandArgs[0]): smoothingArgs = commandArgs[0].strip().split(',') iterations",
"#Deep copied # turns out that later processes access the inherited renderwindowinteractor (?)",
"print(len(a_vec)) #combine into numpy array colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a",
"the surface and then automatically update the inherited color map # - we",
"--- mainWindowUI.vtkInstances[int(theMeshInstance)] while others just referene the most recently added instance (e.g. when",
"also smooth the color data # on the surface and then automatically update",
"VTK unsigned char array vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0) # keep a \"deep\" copy -",
"are simply updating with the # current View settings in from the vista",
"= vtk.vtkActor() actor.SetMapper(pdm) iren = mainWindowUI.vtkInstances[-1] ## ---- engine room for drawing on",
"functions here - although some hardcore processing is handled in subroutines of other",
"objects in the scope of the # main window so that they can",
"a (rgba) for each vertex if debug: print('received request for new mesh with",
"data.. why not mainWindowUI.vtkInstances[-1].curr_points = points mainWindowUI.vtkInstances[-1].curr_polys = polys mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep",
"(rgba) for each vertex # 6) color data a (rgba) for each vertex",
"with a reference index passed from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)] while others just referene",
"polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep copied # and so we can access ui",
"- investigate else: # no new data from MATLAB, probably just an internal",
"for UPDATE DIRECT mesh with Args:') print(commandArgs) if len(commandArgs) != 0 : #new",
"Note that it is the mainWindowUI that is passed to all functions so",
"# Process faces (triangles) polys = vtk.vtkCellArray() nTriangles = triangles.shape[0] for i in",
"commandArgs, mainWindowUI, the_TCPserver): #rotation args rotations = commandArgs[0].strip().split(',') rotations = unpackData(rotations[1], int(rotations[2]), the_TCPserver)",
"we allow vtk to do this but then overwrite the recomptued color #",
"print(triangles) # load the surface colour data rVecArgs = commandArgs[2].strip().split(',') r_vec = unpackData(rVecArgs[1],",
"print(currVTKInstance) # Assemble as PolyData polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ## TODO",
"print(len(g_vec)) print(len(b_vec)) print(len(a_vec)) #combine into numpy array colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this",
"instance esp for the draw routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index def smoothMesh(theMeshInstance,",
"unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver) triangles = array(triangles,'f') if debug: print(triangles) triangles = triangles.reshape((len(triangles)/3,3)) if",
"all the above in the scope of that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother",
"Args:') print(commandArgs) # sanity check if ('vertices' in commandArgs[0]) and ('triangles' in commandArgs[1]):",
"do not go through a lookuptable #lets get the apt window targetVTKWindow =",
"request for UPDATE DIRECT mesh with Args:') print(commandArgs) if len(commandArgs) != 0 :",
"mainWindowUI, the_TCPserver) def updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): # here the base mesh is",
"#TODO mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing functions imported from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0)",
"r_vector - red component # 2) g_vector - blue component # 3) b_vector",
"deepCopyScalars #TODO - this may have impact on later processing - investigate else:",
"the_TCPserver) if debug: print(rotations) targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing camera = targetVTKWindow.ren.GetActiveCamera()",
"the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[1].strip().split(',') g_vec = unpackData(gVecArgs[1],",
"or the \"targetVTKWindow\" - this is a vtkRenderWindowInteractor instance in the main program",
"multiple instances of vtk windows we can load multiple meshes. Some functions reference",
"vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ## ---- ok, we hav the data, lets turn it into",
"= newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() # run mesh update to reset",
"## ---- ok, we hav the data, lets turn it into vtk stuff",
"char array vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0) # keep a \"deep\" copy - this is",
"print(len(r_vec)) print(len(g_vec)) print(len(b_vec)) print(len(a_vec)) #combine into numpy array colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert",
"the scope of the # main window so that they can be manipulated",
"so we can track mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode =",
"# VISTA - i.e. do not go through a lookuptable #lets get the",
"key presses per instance esp for the draw routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero",
"from vtk.util import numpy_support debug = True # local modules from mp_unpackIncomingData import",
"get all the data we are expecting from the server ## NB this",
"then triangles!\" # load the surfaces data verticesArgs = commandArgs[0].strip().split(',') vertices = unpackData(verticesArgs[1],",
"a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if debug: print(len(r_vec)) print(len(g_vec)) print(len(b_vec))",
"debug: print(len(r_vec)) print(len(g_vec)) print(len(b_vec)) print(len(a_vec)) #combine into numpy array colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) #",
"i in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process faces (triangles) polys = vtk.vtkCellArray() nTriangles =",
"- although some hardcore processing is handled in subroutines of other imported modules.",
"if debug: print(points) if debug: print(polys) if debug: print(scalars) if debug: print(currVTKInstance) #",
"print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also track key presses per instance esp for the draw",
"MATLAB so recompute # load the surfaces data rVecArgs = commandArgs[0].strip().split(',') r_vec =",
"the algorithms have run deepCopyScalars = vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars = deepCopyScalars #TODO -",
"vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = []",
"per instance esp for the draw routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index def",
"points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process faces (triangles) polys = vtk.vtkCellArray() nTriangles = triangles.shape[0] for i",
"# no new data from MATLAB, probably just an internal re-draw call #",
"access ui controls (e.g. statusbar) from the inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI def",
"from the vista session WITH THE COLOR VALUES FROM # VISTA - i.e.",
"renderwindowinteractor (?) # so lets put all the above in the scope of",
"array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[3].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec",
"lets put some of the data objects in the scope of the #",
"= squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a VTK unsigned char array scalars =",
"vertex # 5) color data b (rgba) for each vertex # 6) color",
"internal re-draw call # after something like smoothing - just grab the current",
"- i.e. do not go through a lookuptable #lets get the apt window",
"that also smooth the color data # on the surface and then automatically",
"that it is the mainWindowUI that is passed to all functions so that",
"track targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success with direct mesh update routine') ## -------------------------------------------------------------------------------- # test",
"in range(3): polys.InsertCellPoint(int(triangles[i][j])) # check if debug: print(points) if debug: print(polys) if debug:",
"= pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points = points mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars =",
"is # 1) vertices # 2) triangles # 3) color data r (rgba)",
"mainWindowUI.tabWidget.update() #lets get the original data the_smoother = targetVTKWindow.curr_smoother the_mapper = targetVTKWindow.curr_mapper if",
"time from vtk.util import numpy_support debug = True # local modules from mp_unpackIncomingData",
"polys.InsertCellPoint(int(triangles[i][j])) # check if debug: print(points) if debug: print(polys) if debug: print(scalars) if",
"a VTK unsigned char array vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0) # keep a \"deep\" copy",
"smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm = vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(pdm) iren =",
"= [] #place holder for picked vtk point IDs so we can track",
"in the scope of that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata",
"color # map AFTER the algorithms have run deepCopyScalars = vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars",
"sending by the server is # 1) vertices # 2) triangles # 3)",
"some artifacts generated # by vtk algorithms (e.g. smoothing) that also smooth the",
"commandArgs[2].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs",
"- let's update the mesh newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor",
"to workaround some artifacts generated # by vtk algorithms (e.g. smoothing) that also",
"mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place holder for picked vtk point IDs so we",
"* from mp_VTKDrawing import * def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #first get all",
"esp for the draw routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index def smoothMesh(theMeshInstance, commandArgs,",
"gVecArgs = commandArgs[1].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs =",
"if debug: print(scalars) if debug: print(currVTKInstance) # Assemble as PolyData polyData = vtk.vtkPolyData()",
"is to workaround some artifacts generated # by vtk algorithms (e.g. smoothing) that",
"scope. <NAME> 2017 ''' import vtk from numpy import * import time from",
"vertex # 6) color data a (rgba) for each vertex if debug: print('received",
"= unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if debug: print(len(r_vec)) print(len(g_vec)) print(len(b_vec)) print(len(a_vec))",
"vertices # 2) triangles # 3) color data r (rgba) for each vertex",
"commandArgs, mainWindowUI, the_TCPserver): #lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero",
"#TODO - this may have impact on later processing - investigate else: #",
"mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera() # and the raw mesh coordinate data.. why not mainWindowUI.vtkInstances[-1].curr_points",
"the above in the scope of that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother =",
"targetVTKWindow.Render() print('success with direct mesh update routine') ## -------------------------------------------------------------------------------- # test example animation",
"= actor mainWindowUI.vtkInstances[-1].curr_smoother = smooth mainWindowUI.vtkInstances[-1].curr_polydata = polyData mainWindowUI.vtkInstances[-1].curr_mapper = pdm mainWindowUI.vtkInstances[-1].curr_camera =",
"out that later processes access the inherited renderwindowinteractor (?) # so lets put",
"= unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[5].strip().split(',') a_vec = unpackData(aVecArgs[1],",
"vertices, then triangles!\" # load the surfaces data verticesArgs = commandArgs[0].strip().split(',') vertices =",
"the_TCPserver) vertices = array(vertices,'f') vertices = vertices.reshape((len(vertices)/3,3)) trianglesArgs = commandArgs[1].strip().split(',') triangles = unpackData(trianglesArgs[1],",
"smooth.SetInputData(polyData) pdm = vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(pdm) iren = mainWindowUI.vtkInstances[-1]",
"the surface # add a picker that allows is top pick points on",
"picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode =",
"when adding a new mesh) --- mainWindowUI.vtkInstances[-1] Note that it is the mainWindowUI",
"statusbar) from the inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI def KeyPress(obj, evt): key =",
"routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index def smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): #lets get",
"this but then overwrite the recomptued color # map AFTER the algorithms have",
"but then overwrite the recomptued color # map AFTER the algorithms have run",
"# after something like smoothing - just grab the current deep # copy",
"print(camera) for i in range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render() targetVTKWindow.iren.Render() time.sleep(0.02) the_TCPserver.socket.write(str('send useful message back",
"are expecting from the server ## NB this assumes that the order of",
"\"deep\" copy - this is to workaround some artifacts generated # by vtk",
"from the inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI def KeyPress(obj, evt): key = obj.GetKeySym()",
"if debug: print(triangles) # load the surface colour data rVecArgs = commandArgs[2].strip().split(',') r_vec",
"DIRECT mesh with Args:') print(commandArgs) if len(commandArgs) != 0 : #new data has",
"the mesh newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor = newActor #lets",
"for i in range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render() targetVTKWindow.iren.Render() time.sleep(0.02) the_TCPserver.socket.write(str('send useful message back here",
"come from MATLAB so recompute # load the surfaces data rVecArgs = commandArgs[0].strip().split(',')",
"= curr_scalars #Deep copied # and so we can access ui controls (e.g.",
"string that reads something like 'iterations,200,relaxationfactor,1.2' # sanity check if ('iterations' in commandArgs[0])",
"direct mesh update routine') ## -------------------------------------------------------------------------------- # test example animation def rotateMeshAnimation(currVTKInstance, commandArgs,",
"return \"error - expecting vertices, then triangles!\" # load the surfaces data verticesArgs",
"original data the_polyData = targetVTKWindow.curr_polydata the_mapper = targetVTKWindow.curr_mapper #first get all the data",
"we are expecting from the server ## NB this assumes that the order",
"if debug: print(camera) for i in range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render() targetVTKWindow.iren.Render() time.sleep(0.02) the_TCPserver.socket.write(str('send useful",
"smooth = vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm = vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor",
"tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_polyData =",
"= targetVTKWindow.curr_scalars # OK - we have the data - let's update the",
"[] #place holder for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues",
"commandArgs[0].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs",
"= targetVTKWindow.curr_mapper if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a string that reads",
"the raw mesh coordinate data.. why not mainWindowUI.vtkInstances[-1].curr_points = points mainWindowUI.vtkInstances[-1].curr_polys = polys",
"artifacts generated # by vtk algorithms (e.g. smoothing) that also smooth the color",
"the surface colour data rVecArgs = commandArgs[2].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec",
"polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points = points mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys",
"on the surface and then automatically update the inherited color map # -",
"get the original data the_smoother = targetVTKWindow.curr_smoother the_mapper = targetVTKWindow.curr_mapper if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars())",
"vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ## TODO ? smoothing on first load? smooth =",
"# and so we can access ui controls (e.g. statusbar) from the inherited",
"squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a VTK unsigned char array scalars = numpy_support.numpy_to_vtk(colorDat,0)",
"= polys mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep copied # turns out that later processes",
"update to reset the color map (smoothing \"messes\" this up) updateMeshData(theMeshInstance, [], mainWindowUI,",
"= unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver) triangles = array(triangles,'f') if debug: print(triangles) triangles = triangles.reshape((len(triangles)/3,3))",
"ren ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render() # lets put some of the data",
"= commandArgs[0].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec)",
"inherited color map # - we allow vtk to do this but then",
"we have the data - let's update the mesh newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray,",
"data we are expecting from the server ## NB this assumes that the",
"each vertex # 4) color data g (rgba) for each vertex # 5)",
"data rVecArgs = commandArgs[0].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if",
"(rgba) for each vertex # 5) color data b (rgba) for each vertex",
"handled in subroutines of other imported modules. A core concept here is the",
"vtk processing is done by functions here - although some hardcore processing is",
"red component # 2) g_vector - blue component # 3) b_vector - green",
"vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0) # keep a \"deep\" copy - this is to workaround",
"processing - investigate else: # no new data from MATLAB, probably just an",
"smoothing) that also smooth the color data # on the surface and then",
"surface colour data rVecArgs = commandArgs[2].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec =",
"commandArgs[0].strip().split(',') iterations = int(smoothingArgs[1]) relaxationfactor = float(smoothingArgs[3]) else: return \"error - expecting vertices,",
"of the # main window so that they can be manipulated later. mainWindowUI.vtkInstances[-1].curr_actor",
"mainWindowUI.vtkInstances[-1].curr_polys = polys mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep copied # turns out that later",
"load multiple meshes. Some functions reference this specifically with a reference index passed",
"Assemble as PolyData polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ## TODO ? smoothing",
"targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing # lets show the correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance))",
"from the server ## NB this assumes that the order of sending by",
"import vtk from numpy import * import time from vtk.util import numpy_support debug",
"automatically update the inherited color map # - we allow vtk to do",
"= vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars = deepCopyScalars #TODO - this may have impact on",
"up) updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver) def updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): # here the",
"<NAME> 2017 ''' import vtk from numpy import * import time from vtk.util",
"commandArgs[5].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if debug: print(len(r_vec)) print(len(g_vec))",
"= unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[3].strip().split(',')",
"convert this to a VTK unsigned char array scalars = numpy_support.numpy_to_vtk(colorDat,0) curr_scalars =",
"smooth = vtk.vtkSmoothPolyDataFilter() smooth = vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm = vtk.vtkPolyDataMapper()",
"# add a picker that allows is top pick points on the surface",
"just an internal re-draw call # after something like smoothing - just grab",
"data b (rgba) for each vertex # 6) color data a (rgba) for",
"index passed from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)] while others just referene the most recently",
"it into vtk stuff # Process vertices points = vtk.vtkPoints() for i in",
"4) a_vector - aplha component if debug: print('received request for UPDATE DIRECT mesh",
"else: return \"error - expecting vertices, then triangles!\" # load the surfaces data",
"g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[2].strip().split(',') b_vec =",
"vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints()",
"= array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[3].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver)",
"unsigned char array scalars = numpy_support.numpy_to_vtk(colorDat,0) curr_scalars = vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ## ---- ok,",
"= polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points = points mainWindowUI.vtkInstances[-1]._Iren.curr_polys =",
"do this but then overwrite the recomptued color # map AFTER the algorithms",
"import unpackData from mp_VTKProcessing import * from mp_VTKDrawing import * def loadNewMesh(currVTKInstance, commandArgs,",
"data rVecArgs = commandArgs[2].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if",
"we can load multiple meshes. Some functions reference this specifically with a reference",
"holder for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds",
"= vtk.vtkPoints() #place holder for picked vtk point IDs so we can track",
"original data the_smoother = targetVTKWindow.curr_smoother the_mapper = targetVTKWindow.curr_mapper if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug:",
"mesh update to reset the color map (smoothing \"messes\" this up) updateMeshData(theMeshInstance, [],",
"data the_polyData = targetVTKWindow.curr_polydata the_mapper = targetVTKWindow.curr_mapper #first get all the data we",
"assumes that the order of sending by the server is # 1) r_vector",
"a_vector - aplha component if debug: print('received request for UPDATE DIRECT mesh with",
"by vtk algorithms (e.g. smoothing) that also smooth the color data # on",
"something like smoothing - just grab the current deep # copy of the",
"point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place",
"#new data has come from MATLAB so recompute # load the surfaces data",
"required scalars vtkColorArray = targetVTKWindow.curr_scalars # OK - we have the data -",
"vertices.reshape((len(vertices)/3,3)) trianglesArgs = commandArgs[1].strip().split(',') triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver) triangles = array(triangles,'f') if",
"so we can access ui controls (e.g. statusbar) from the inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui",
"return \"error - expecting vertices, then curvature, then triangles!\" newActor = VTK_smoothing(the_smoother, the_mapper,",
"(kepping in scope) or the \"targetVTKWindow\" - this is a vtkRenderWindowInteractor instance in",
"the inherited color map # - we allow vtk to do this but",
"ren = mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren = ren ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render() # lets",
"that the order of sending by the server is # 1) r_vector -",
"r (rgba) for each vertex # 4) color data g (rgba) for each",
"for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues",
"#Deep copied # and so we can access ui controls (e.g. statusbar) from",
"# - we allow vtk to do this but then overwrite the recomptued",
"int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[4].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver)",
"(e.g. when adding a new mesh) --- mainWindowUI.vtkInstances[-1] Note that it is the",
"scope) or the \"targetVTKWindow\" - this is a vtkRenderWindowInteractor instance in the main",
"# load the surface colour data rVecArgs = commandArgs[2].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]),",
"map (smoothing \"messes\" this up) updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver) def updateMeshData(theMeshInstance, commandArgs, mainWindowUI,",
"colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a VTK unsigned char array scalars",
"rVecArgs = commandArgs[0].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug:",
"the server is # 1) vertices # 2) triangles # 3) color data",
"sanity check if ('vertices' in commandArgs[0]) and ('triangles' in commandArgs[1]): pass else: return",
"commandArgs[0].strip().split(',') vertices = unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver) vertices = array(vertices,'f') vertices = vertices.reshape((len(vertices)/3,3)) trianglesArgs",
"mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing functions imported from mp_VTKDrawing",
"1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0) ren = mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren = ren ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera()",
"= actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera =",
"on the surface picker = vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place holder",
"Some functions reference this specifically with a reference index passed from mrVista ---",
"= smooth mainWindowUI.vtkInstances[-1].curr_polydata = polyData mainWindowUI.vtkInstances[-1].curr_mapper = pdm mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera() # and",
"the correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data",
"#expecting a string that reads something like 'iterations,200,relaxationfactor,1.2' # sanity check if ('iterations'",
"base mesh is already loaded and we are simply updating with the #",
"workaround some artifacts generated # by vtk algorithms (e.g. smoothing) that also smooth",
"vtk.vtkSmoothPolyDataFilter() smooth = vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm = vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort())",
"mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_polyData = targetVTKWindow.curr_polydata",
"polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ## TODO ? smoothing on first load? smooth = vtk.vtkSmoothPolyDataFilter() smooth",
"unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[2].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]),",
"sending by the server is # 1) r_vector - red component # 2)",
"a reference index passed from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)] while others just referene the",
"= ren ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render() # lets put some of the",
"# 6) color data a (rgba) for each vertex if debug: print('received request",
"server is # 1) r_vector - red component # 2) g_vector - blue",
"debug: print(triangles) # load the surface colour data rVecArgs = commandArgs[2].strip().split(',') r_vec =",
"although some hardcore processing is handled in subroutines of other imported modules. A",
"a vtkRenderWindowInteractor instance in the main program UI (user interface) - by creatoing",
"--- mainWindowUI.vtkInstances[-1] Note that it is the mainWindowUI that is passed to all",
"targetVTKWindow.curr_scalars # OK - we have the data - let's update the mesh",
"to a VTK unsigned char array scalars = numpy_support.numpy_to_vtk(colorDat,0) curr_scalars = vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars)",
"vtk.vtkPoints() for i in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process faces (triangles) polys = vtk.vtkCellArray()",
"example animation def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #rotation args rotations = commandArgs[0].strip().split(',') rotations",
"main vtk processing is done by functions here - although some hardcore processing",
"commandArgs[1].strip().split(',') triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver) triangles = array(triangles,'f') if debug: print(triangles) triangles",
"correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_polyData",
"= commandArgs[4].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[5].strip().split(',')",
"recompute # load the surfaces data rVecArgs = commandArgs[0].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]),",
"vtk algorithms (e.g. smoothing) that also smooth the color data # on the",
"order of sending by the server is # 1) r_vector - red component",
"manipulated later. mainWindowUI.vtkInstances[-1].curr_actor = actor mainWindowUI.vtkInstances[-1].curr_smoother = smooth mainWindowUI.vtkInstances[-1].curr_polydata = polyData mainWindowUI.vtkInstances[-1].curr_mapper =",
"ren.GetActiveCamera() # and the raw mesh coordinate data.. why not mainWindowUI.vtkInstances[-1].curr_points = points",
"to do this but then overwrite the recomptued color # map AFTER the",
"data # on the surface and then automatically update the inherited color map",
"= vertices.reshape((len(vertices)/3,3)) trianglesArgs = commandArgs[1].strip().split(',') triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver) triangles = array(triangles,'f')",
"scope of that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData",
"vista session WITH THE COLOR VALUES FROM # VISTA - i.e. do not",
"of that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper",
"vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place holder for picked vtk point IDs",
"= ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points = points mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep copied",
"room for mrMeshPy viewer The main vtk processing is done by functions here",
"the base mesh is already loaded and we are simply updating with the",
"mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points = points mainWindowUI.vtkInstances[-1]._Iren.curr_polys",
"the original data the_smoother = targetVTKWindow.curr_smoother the_mapper = targetVTKWindow.curr_mapper if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if",
"print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also track key presses per instance esp for the draw routine",
"let's update the mesh newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor =",
"array colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a VTK unsigned char array",
"# 1) vertices # 2) triangles # 3) color data r (rgba) for",
"= mainWindowUI def KeyPress(obj, evt): key = obj.GetKeySym() if key == 'l': currVTKinstance",
"# sanity check if ('iterations' in commandArgs[0]) and ('relaxationfactor' in commandArgs[0]): smoothingArgs =",
"sanity check if ('iterations' in commandArgs[0]) and ('relaxationfactor' in commandArgs[0]): smoothingArgs = commandArgs[0].strip().split(',')",
"content of the main window in scope. <NAME> 2017 ''' import vtk from",
"so we can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place holder for",
"mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI def KeyPress(obj, evt): key = obj.GetKeySym() if key == 'l':",
"track mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing",
"#zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_polyData = targetVTKWindow.curr_polydata the_mapper",
"numpy_support debug = True # local modules from mp_unpackIncomingData import unpackData from mp_VTKProcessing",
"# sanity check if ('vertices' in commandArgs[0]) and ('triangles' in commandArgs[1]): pass else:",
"the_mapper = targetVTKWindow.curr_mapper #first get all the data we are expecting from the",
"draw routine :) mainWindowUI.vtkInstances[-1].AddObserver(\"KeyPressEvent\",KeyPress) mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index def smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): #lets",
"functions reference this specifically with a reference index passed from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)]",
"copied # turns out that later processes access the inherited renderwindowinteractor (?) #",
"#rotation args rotations = commandArgs[0].strip().split(',') rotations = unpackData(rotations[1], int(rotations[2]), the_TCPserver) if debug: print(rotations)",
"print(triangles) triangles = triangles.reshape((len(triangles)/3,3)) if debug: print(triangles) # load the surface colour data",
"mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place holder for picked vtk point IDs so we can",
"the main program UI (user interface) - by creatoing multiple instances of vtk",
"= commandArgs[2].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec)",
"color map # - we allow vtk to do this but then overwrite",
"1) vertices # 2) triangles # 3) color data r (rgba) for each",
"holder for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues",
"and ('relaxationfactor' in commandArgs[0]): smoothingArgs = commandArgs[0].strip().split(',') iterations = int(smoothingArgs[1]) relaxationfactor = float(smoothingArgs[3])",
"track targetVTKWindow.ren.Render() targetVTKWindow.Render() # run mesh update to reset the color map (smoothing",
"local modules from mp_unpackIncomingData import unpackData from mp_VTKProcessing import * from mp_VTKDrawing import",
"the_TCPserver): #lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing #",
"array(a_vec,'uint8') if debug: print(len(r_vec)) print(len(g_vec)) print(len(b_vec)) print(len(a_vec)) #combine into numpy array colorDat =",
"mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing functions imported from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0) mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0)",
"the_polyData = targetVTKWindow.curr_polydata the_mapper = targetVTKWindow.curr_mapper #first get all the data we are",
"of the required scalars vtkColorArray = targetVTKWindow.curr_scalars # OK - we have the",
"mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index def smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): #lets get the apt window",
"drawingMakeROI, 1.0) ren = mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren = ren ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render()",
"commandArgs, mainWindowUI, the_TCPserver): #first get all the data we are expecting from the",
"''' import vtk from numpy import * import time from vtk.util import numpy_support",
"the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[5].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec",
"actor = vtk.vtkActor() actor.SetMapper(pdm) iren = mainWindowUI.vtkInstances[-1] ## ---- engine room for drawing",
"is top pick points on the surface picker = vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds",
"generated # by vtk algorithms (e.g. smoothing) that also smooth the color data",
"meshes. Some functions reference this specifically with a reference index passed from mrVista",
"to reset the color map (smoothing \"messes\" this up) updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver)",
"data r (rgba) for each vertex # 4) color data g (rgba) for",
"key = obj.GetKeySym() if key == 'l': currVTKinstance = len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's",
"VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render()",
"commandArgs[0]): smoothingArgs = commandArgs[0].strip().split(',') iterations = int(smoothingArgs[1]) relaxationfactor = float(smoothingArgs[3]) else: return \"error",
"picker that allows is top pick points on the surface picker = vtk.vtkCellPicker()",
"- aplha component if debug: print('received request for UPDATE DIRECT mesh with Args:')",
"color data r (rgba) for each vertex # 4) color data g (rgba)",
"has come from MATLAB so recompute # load the surfaces data rVecArgs =",
"# main window so that they can be manipulated later. mainWindowUI.vtkInstances[-1].curr_actor = actor",
"commandArgs[1].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[2].strip().split(',') b_vec",
"for each vertex # 5) color data b (rgba) for each vertex #",
"index def smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): #lets get the apt window targetVTKWindow =",
"request for new mesh with Args:') print(commandArgs) # sanity check if ('vertices' in",
"the_TCPserver) triangles = array(triangles,'f') if debug: print(triangles) triangles = triangles.reshape((len(triangles)/3,3)) if debug: print(triangles)",
"component # 2) g_vector - blue component # 3) b_vector - green component",
"aplha component if debug: print('received request for UPDATE DIRECT mesh with Args:') print(commandArgs)",
"# keep a \"deep\" copy - this is to workaround some artifacts generated",
"\"error - expecting vertices, then curvature, then triangles!\" newActor = VTK_smoothing(the_smoother, the_mapper, iterations,",
"later processing - investigate else: # no new data from MATLAB, probably just",
"relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() # run",
"for mrMeshPy viewer The main vtk processing is done by functions here -",
"mainWindowUI, the_TCPserver): #lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing",
"array(g_vec,'uint8') bVecArgs = commandArgs[2].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs",
"top pick points on the surface picker = vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds =",
"mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_smoother = targetVTKWindow.curr_smoother",
"\"error - expecting vertices, then triangles!\" # load the surfaces data verticesArgs =",
"other imported modules. A core concept here is the tracking (kepping in scope)",
"rVecArgs = commandArgs[2].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug:",
"this may have impact on later processing - investigate else: # no new",
"6) color data a (rgba) for each vertex if debug: print('received request for",
"lets turn it into vtk stuff # Process vertices points = vtk.vtkPoints() for",
"= mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing # lets show the correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero",
"print('received request for UPDATE DIRECT mesh with Args:') print(commandArgs) if len(commandArgs) != 0",
"a string that reads something like 'iterations,200,relaxationfactor,1.2' # sanity check if ('iterations' in",
"= mainWindowUI.vtkInstances[-1].ren mainWindowUI.vtkInstances[-1]._Iren.ren = ren ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render() # lets put",
"mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep copied # and so we can",
"array(triangles,'f') if debug: print(triangles) triangles = triangles.reshape((len(triangles)/3,3)) if debug: print(triangles) # load the",
"COLOR VALUES FROM # VISTA - i.e. do not go through a lookuptable",
"faces (triangles) polys = vtk.vtkCellArray() nTriangles = triangles.shape[0] for i in range(nTriangles): polys.InsertNextCell(3)",
"verticesArgs = commandArgs[0].strip().split(',') vertices = unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver) vertices = array(vertices,'f') vertices =",
"for drawing on the surface # add a picker that allows is top",
"IDs so we can track mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode",
"PolyData polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) polyData.GetPointData().SetScalars(scalars) ## TODO ? smoothing on first",
"track mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place holder for picked vtk point",
"allows is top pick points on the surface picker = vtk.vtkCellPicker() picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker)",
"= commandArgs[5].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if debug: print(len(r_vec))",
"FROM # VISTA - i.e. do not go through a lookuptable #lets get",
"squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a VTK unsigned char array vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0)",
"= triangles.shape[0] for i in range(nTriangles): polys.InsertNextCell(3) for j in range(3): polys.InsertCellPoint(int(triangles[i][j])) #",
"IDs so we can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place holder",
"in commandArgs[0]) and ('relaxationfactor' in commandArgs[0]): smoothingArgs = commandArgs[0].strip().split(',') iterations = int(smoothingArgs[1]) relaxationfactor",
"colour data rVecArgs = commandArgs[2].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8')",
"we can track mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode",
"smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): #lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB",
"= mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place holder for picked vtk point IDs so",
"-------------------------------------------------------------------------------- # test example animation def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #rotation args rotations",
"mesh with Args:') print(commandArgs) if len(commandArgs) != 0 : #new data has come",
"we are simply updating with the # current View settings in from the",
"this to a VTK unsigned char array vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0) # keep a",
"b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[5].strip().split(',') a_vec =",
"correct tab mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index #mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_smoother",
"of other imported modules. A core concept here is the tracking (kepping in",
"the_TCPserver): # here the base mesh is already loaded and we are simply",
"the tracking (kepping in scope) or the \"targetVTKWindow\" - this is a vtkRenderWindowInteractor",
"vertex if debug: print('received request for new mesh with Args:') print(commandArgs) # sanity",
"holder for picked vtk point IDs so we can track mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints",
"mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points = points mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep",
"#mainWindowUI.tabWidget.repaint() mainWindowUI.tabWidget.update() #lets get the original data the_polyData = targetVTKWindow.curr_polydata the_mapper = targetVTKWindow.curr_mapper",
"= array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[1].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver)",
"core concept here is the tracking (kepping in scope) or the \"targetVTKWindow\" -",
"if debug: print('received request for new mesh with Args:') print(commandArgs) # sanity check",
"= array(triangles,'f') if debug: print(triangles) triangles = triangles.reshape((len(triangles)/3,3)) if debug: print(triangles) # load",
"ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render() # lets put some of the data objects in the",
"in the scope of the # main window so that they can be",
"i.e. do not go through a lookuptable #lets get the apt window targetVTKWindow",
"vtk to do this but then overwrite the recomptued color # map AFTER",
"all the data we are expecting from the server ## NB this assumes",
"= unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[4].strip().split(',') b_vec = unpackData(bVecArgs[1],",
"mainWindowUI.vtkInstances[-1] ## ---- engine room for drawing on the surface # add a",
"go through a lookuptable #lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB",
"too mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm",
"triangles # 3) color data r (rgba) for each vertex # 4) color",
"lookuptable #lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing #",
"print(points) if debug: print(polys) if debug: print(scalars) if debug: print(currVTKInstance) # Assemble as",
"= obj.GetKeySym() if key == 'l': currVTKinstance = len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also",
"= targetVTKWindow.curr_mapper #first get all the data we are expecting from the server",
"# lets put some of the data objects in the scope of the",
"specifically with a reference index passed from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)] while others just",
"the data we are expecting from the server ## NB this assumes that",
"# Process vertices points = vtk.vtkPoints() for i in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) # Process",
"surfaces data rVecArgs = commandArgs[0].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8')",
"and ('triangles' in commandArgs[1]): pass else: return \"error - expecting vertices, then triangles!\"",
"mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place holder for picked vtk point IDs",
"interface) - by creatoing multiple instances of vtk windows we can load multiple",
"mainWindowUI.vtkInstances[-1]._Iren.ren = ren ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render() # lets put some of",
"= array(b_vec,'uint8') aVecArgs = commandArgs[3].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8')",
"targetVTKWindow.curr_mapper #first get all the data we are expecting from the server ##",
"= commandArgs[0].strip().split(',') rotations = unpackData(rotations[1], int(rotations[2]), the_TCPserver) if debug: print(rotations) targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)]",
"while others just referene the most recently added instance (e.g. when adding a",
"= array(g_vec,'uint8') bVecArgs = commandArgs[4].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8')",
"expecting from the server ## NB this assumes that the order of sending",
"that is passed to all functions so that all funcitons have the content",
"the surfaces data verticesArgs = commandArgs[0].strip().split(',') vertices = unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver) vertices =",
"scalars vtkColorArray = targetVTKWindow.curr_scalars # OK - we have the data - let's",
"updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): # here the base mesh is already loaded and",
"= points mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep copied # and so",
"reference index passed from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)] while others just referene the most",
"concept here is the tracking (kepping in scope) or the \"targetVTKWindow\" - this",
"vertices, then curvature, then triangles!\" newActor = VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor)",
"iterations, relaxationfactor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() #",
"mesh update routine') ## -------------------------------------------------------------------------------- # test example animation def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI,",
"def updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): # here the base mesh is already loaded",
"map # - we allow vtk to do this but then overwrite the",
"numpy_support.numpy_to_vtk(colorDat,0) # keep a \"deep\" copy - this is to workaround some artifacts",
"commandArgs[0]) and ('triangles' in commandArgs[1]): pass else: return \"error - expecting vertices, then",
"on first load? smooth = vtk.vtkSmoothPolyDataFilter() smooth = vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData)",
"vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(pdm) iren = mainWindowUI.vtkInstances[-1] ## ---- engine",
"of vtk windows we can load multiple meshes. Some functions reference this specifically",
"= numpy_support.numpy_to_vtk(colorDat,0) # keep a \"deep\" copy - this is to workaround some",
"investigate else: # no new data from MATLAB, probably just an internal re-draw",
"later processes access the inherited renderwindowinteractor (?) # so lets put all the",
"reads something like 'iterations,200,relaxationfactor,1.2' # sanity check if ('iterations' in commandArgs[0]) and ('relaxationfactor'",
"new mesh with Args:') print(commandArgs) # sanity check if ('vertices' in commandArgs[0]) and",
"a_vec = array(a_vec,'uint8') if debug: print(len(r_vec)) print(len(g_vec)) print(len(b_vec)) print(len(a_vec)) #combine into numpy array",
"ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render() # lets put some of the data objects in",
"#combine into numpy array colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose()) # convert this to a VTK",
"debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a string that reads something like 'iterations,200,relaxationfactor,1.2'",
"= len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also track key presses per instance esp for",
"= mainWindowUI.vtkInstances[-1] ## ---- engine room for drawing on the surface # add",
"why not mainWindowUI.vtkInstances[-1].curr_points = points mainWindowUI.vtkInstances[-1].curr_polys = polys mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep copied",
"= pdm mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera() # and the raw mesh coordinate data.. why",
"from numpy import * import time from vtk.util import numpy_support debug = True",
"g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[4].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec =",
"stuff # Process vertices points = vtk.vtkPoints() for i in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2]) #",
"# turns out that later processes access the inherited renderwindowinteractor (?) # so",
"mainWindowUI def KeyPress(obj, evt): key = obj.GetKeySym() if key == 'l': currVTKinstance =",
"in from the vista session WITH THE COLOR VALUES FROM # VISTA -",
"- red component # 2) g_vector - blue component # 3) b_vector -",
"aVecArgs = commandArgs[3].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver) a_vec = array(a_vec,'uint8') if debug:",
"? smoothing on first load? smooth = vtk.vtkSmoothPolyDataFilter() smooth = vtk.vtkSmoothPolyDataFilter() smooth.SetNumberOfIterations(0) smooth.SetRelaxationFactor(0.0)",
"targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success with direct mesh update routine') ## -------------------------------------------------------------------------------- # test example",
"def smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): #lets get the apt window targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)]",
"array scalars = numpy_support.numpy_to_vtk(colorDat,0) curr_scalars = vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ## ---- ok, we hav",
"* import time from vtk.util import numpy_support debug = True # local modules",
"''' VTK engine room for mrMeshPy viewer The main vtk processing is done",
"g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[4].strip().split(',') b_vec =",
"the color map (smoothing \"messes\" this up) updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver) def updateMeshData(theMeshInstance,",
"load the surfaces data rVecArgs = commandArgs[0].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver) r_vec",
"targetVTKWindow.Render() # run mesh update to reset the color map (smoothing \"messes\" this",
"array(g_vec,'uint8') bVecArgs = commandArgs[4].strip().split(',') b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs",
"g (rgba) for each vertex # 5) color data b (rgba) for each",
"A core concept here is the tracking (kepping in scope) or the \"targetVTKWindow\"",
"current deep # copy of the required scalars vtkColorArray = targetVTKWindow.curr_scalars # OK",
"mp_VTKDrawing import * def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #first get all the data",
"targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() # run mesh update",
"processing is done by functions here - although some hardcore processing is handled",
"char array scalars = numpy_support.numpy_to_vtk(colorDat,0) curr_scalars = vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ## ---- ok, we",
"that all funcitons have the content of the main window in scope. <NAME>",
"commandArgs[1]): pass else: return \"error - expecting vertices, then triangles!\" # load the",
"KeyPress(obj, evt): key = obj.GetKeySym() if key == 'l': currVTKinstance = len(mainWindowUI.vtkInstances) print(key)",
"evt): key = obj.GetKeySym() if key == 'l': currVTKinstance = len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1])",
"keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() # run mesh update to reset the color map",
"the server is # 1) r_vector - red component # 2) g_vector -",
"if debug: print('received request for UPDATE DIRECT mesh with Args:') print(commandArgs) if len(commandArgs)",
"vtk stuff # Process vertices points = vtk.vtkPoints() for i in range(vertices.shape[0]): points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2])",
"[], mainWindowUI, the_TCPserver) def updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): # here the base mesh",
"that the order of sending by the server is # 1) vertices #",
"inherited renderwindowinteractor (?) # so lets put all the above in the scope",
"the_TCPserver) def updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver): # here the base mesh is already",
"in scope) or the \"targetVTKWindow\" - this is a vtkRenderWindowInteractor instance in the",
"we can access ui controls (e.g. statusbar) from the inherited window mainWindowUI.vtkInstances[-1]._Iren.parent_ui =",
"nTriangles = triangles.shape[0] for i in range(nTriangles): polys.InsertNextCell(3) for j in range(3): polys.InsertCellPoint(int(triangles[i][j]))",
"if key == 'l': currVTKinstance = len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also track key",
"copy - this is to workaround some artifacts generated # by vtk algorithms",
"tracking (kepping in scope) or the \"targetVTKWindow\" - this is a vtkRenderWindowInteractor instance",
"VTK unsigned char array scalars = numpy_support.numpy_to_vtk(colorDat,0) curr_scalars = vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ## ----",
"vtkColorArray, mainWindowUI) targetVTKWindow.ren.AddActor(newActor) targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor) targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success",
"rotations = unpackData(rotations[1], int(rotations[2]), the_TCPserver) if debug: print(rotations) targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero",
"can track mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place holder for picked vtk",
"(?) # so lets put all the above in the scope of that",
"re-draw call # after something like smoothing - just grab the current deep",
"smooth.SetRelaxationFactor(0.0) smooth.FeatureEdgeSmoothingOff() smooth.SetInputData(polyData) pdm = vtk.vtkPolyDataMapper() pdm.SetScalarModeToUsePointData() pdm.SetInputConnection(smooth.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(pdm) iren",
"key == 'l': currVTKinstance = len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also track key presses",
"targetVTKWindow.curr_mapper if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars()) if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a string that reads something",
"new data from MATLAB, probably just an internal re-draw call # after something",
"later. mainWindowUI.vtkInstances[-1].curr_actor = actor mainWindowUI.vtkInstances[-1].curr_smoother = smooth mainWindowUI.vtkInstances[-1].curr_polydata = polyData mainWindowUI.vtkInstances[-1].curr_mapper = pdm",
"smoothing - just grab the current deep # copy of the required scalars",
"= newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success with direct mesh update routine')",
"update routine') ## -------------------------------------------------------------------------------- # test example animation def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver):",
"#!/usr/bin/python ''' VTK engine room for mrMeshPy viewer The main vtk processing is",
"by functions here - although some hardcore processing is handled in subroutines of",
"int(rVecArgs[2]), the_TCPserver) r_vec = array(r_vec,'uint8') if debug: print(r_vec) gVecArgs = commandArgs[3].strip().split(',') g_vec =",
"the # main window so that they can be manipulated later. mainWindowUI.vtkInstances[-1].curr_actor =",
"mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points",
"print(r_vec) gVecArgs = commandArgs[1].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs",
"a VTK unsigned char array scalars = numpy_support.numpy_to_vtk(colorDat,0) curr_scalars = vtk.vtkUnsignedCharArray() curr_scalars.DeepCopy(scalars) ##",
"2) g_vector - blue component # 3) b_vector - green component # 4)",
"len(mainWindowUI.vtkInstances) print(key) print(mainWindowUI.vtkInstances[currVTKinstance-1]) #let's also track key presses per instance esp for the",
"run deepCopyScalars = vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars = deepCopyScalars #TODO - this may have",
"referene the most recently added instance (e.g. when adding a new mesh) ---",
"that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData mainWindowUI.vtkInstances[-1]._Iren.curr_mapper =",
"range(len(rotations)): camera.Azimuth(rotations[i]) #targetVTKWindow.ren.Render() targetVTKWindow.iren.Render() time.sleep(0.02) the_TCPserver.socket.write(str('send useful message back here TODO')) ## --------------------------------------------------------------------------------",
"mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place holder for picked vtk point IDs so we",
"of sending by the server is # 1) r_vector - red component #",
"2017 ''' import vtk from numpy import * import time from vtk.util import",
"polyData.GetPointData().SetScalars(scalars) ## TODO ? smoothing on first load? smooth = vtk.vtkSmoothPolyDataFilter() smooth =",
"probably just an internal re-draw call # after something like smoothing - just",
"if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000)) #expecting a string that reads something like 'iterations,200,relaxationfactor,1.2' # sanity",
"g_vector - blue component # 3) b_vector - green component # 4) a_vector",
"window mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI def KeyPress(obj, evt): key = obj.GetKeySym() if key ==",
"# map AFTER the algorithms have run deepCopyScalars = vtk.vtkUnsignedCharArray() deepCopyScalars.DeepCopy(vtkColorArray) targetVTKWindow.curr_scalars =",
"import numpy_support debug = True # local modules from mp_unpackIncomingData import unpackData from",
"turn it into vtk stuff # Process vertices points = vtk.vtkPoints() for i",
"instance (e.g. when adding a new mesh) --- mainWindowUI.vtkInstances[-1] Note that it is",
"= 0 #TODO mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode # drawing functions imported from mp_VTKDrawing mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent',",
"scope of the # main window so that they can be manipulated later.",
"mainWindowUI.vtkInstances[-1].curr_actor = actor mainWindowUI.vtkInstances[-1].curr_smoother = smooth mainWindowUI.vtkInstances[-1].curr_polydata = polyData mainWindowUI.vtkInstances[-1].curr_mapper = pdm mainWindowUI.vtkInstances[-1].curr_camera",
"impact on later processing - investigate else: # no new data from MATLAB,",
"put all the above in the scope of that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor",
"debug: print(points) if debug: print(polys) if debug: print(scalars) if debug: print(currVTKInstance) # Assemble",
"= int(smoothingArgs[1]) relaxationfactor = float(smoothingArgs[3]) else: return \"error - expecting vertices, then curvature,",
"the order of sending by the server is # 1) vertices # 2)",
"keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() print('success with direct mesh update routine') ## -------------------------------------------------------------------------------- #",
"polys.InsertNextCell(3) for j in range(3): polys.InsertCellPoint(int(triangles[i][j])) # check if debug: print(points) if debug:",
"pdm mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera() mainWindowUI.vtkInstances[-1]._Iren.curr_points = points mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars",
"is already loaded and we are simply updating with the # current View",
"the current deep # copy of the required scalars vtkColorArray = targetVTKWindow.curr_scalars #",
"color map (smoothing \"messes\" this up) updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver) def updateMeshData(theMeshInstance, commandArgs,",
"the scope of that too mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth mainWindowUI.vtkInstances[-1]._Iren.curr_polydata =",
"all funcitons have the content of the main window in scope. <NAME> 2017",
"import * import time from vtk.util import numpy_support debug = True # local",
"targetVTKWindow.curr_actor = newActor #lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() # run mesh update to",
"int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[3].strip().split(',') a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver)",
"mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing camera = targetVTKWindow.ren.GetActiveCamera() if debug: print(camera) for i in",
"#lets keep track targetVTKWindow.ren.Render() targetVTKWindow.Render() # run mesh update to reset the color",
"picker.SetTolerance(0.0001) mainWindowUI.vtkInstances[-1].SetPicker(picker) mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place holder for picked vtk point IDs so",
"(user interface) - by creatoing multiple instances of vtk windows we can load",
"= commandArgs[3].strip().split(',') g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver) g_vec = array(g_vec,'uint8') bVecArgs = commandArgs[4].strip().split(',')",
"engine room for drawing on the surface # add a picker that allows",
"ren.AddActor(actor) ren.SetBackground(1,1,1) ren.ResetCamera() ren.Render() mainWindowUI.vtkInstances[-1].Render() # lets put some of the data objects",
"here is the tracking (kepping in scope) or the \"targetVTKWindow\" - this is",
"import * from mp_VTKDrawing import * def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver): #first get",
"b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver) b_vec = array(b_vec,'uint8') aVecArgs = commandArgs[3].strip().split(',') a_vec =",
"color data g (rgba) for each vertex # 5) color data b (rgba)",
"# load the surfaces data rVecArgs = commandArgs[0].strip().split(',') r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver)",
"vtk from numpy import * import time from vtk.util import numpy_support debug ="
] |
[
"the environment env = gym.make( params[\"env\"][\"name\"], params=params, ) test_env = gym.make( params[\"env\"][\"name\"], params=params",
"import gym import gym_pointrobo from hwr.agents.pointrobo_ddpg import DDPG from hwr.cae.cae import CAE from",
"f.write('batch size: {0: 4}'.format(memory_capacity) + '\\n') # deleting the previous checkpoints: ckp_files =",
"sys import glob import shutil import numpy as np import tensorflow as tf",
"rate: {0: 1.8f} max_grad: {1: 3.2f} Tau_Target_update: {2: 1.3f} memory_capacity: {3: 4}\".format( lr,",
"enumerate([1, 0.5, 0.1]): for tau_i, tau in enumerate([0.005, 0.001, 0.0005]): for memory_capacity_i, memory_capacity",
"PointrobotTrainer from hwr.utils import load_params # loading params: params = load_params('params/hyperparam_tuning_params.json') #Initialize the",
"max_grad_i, max_grad in enumerate([1, 0.5, 0.1]): for tau_i, tau in enumerate([0.005, 0.001, 0.0005]):",
"0.001, 0.0005]): for memory_capacity_i, memory_capacity in enumerate([1e6]): print(\"Learning rate: {0: 1.8f} max_grad: {1:",
"for tau_i, tau in enumerate([0.005, 0.001, 0.0005]): for memory_capacity_i, memory_capacity in enumerate([1e6]): print(\"Learning",
"'\\n') # deleting the previous checkpoints: ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for f in",
"enumerate([0.005, 0.001, 0.0005]): for memory_capacity_i, memory_capacity in enumerate([1e6]): print(\"Learning rate: {0: 1.8f} max_grad:",
"lr, max_grad, tau, memory_capacity)) # the actual parameters: params[\"agent\"][\"lr_actor\"] = lr params[\"agent\"][\"lr_critic\"] =",
"gym.make( params[\"env\"][\"name\"], params=params, ) test_env = gym.make( params[\"env\"][\"name\"], params=params ) # deleting the",
"import tensorflow as tf import gym import gym_pointrobo from hwr.agents.pointrobo_ddpg import DDPG from",
"Tau_Target_update: {2: 1.3f} memory_capacity: {3: 4}\".format( lr, max_grad, tau, memory_capacity)) # the actual",
"'hyperparam_tuning', '*')) for f in logdir_files: if os.path.isdir(f): shutil.rmtree(f) else: os.remove(f) # Hyperparameter",
"open(info_file, 'a') as f: f.write('learning rate: {0: 1.8f}'.format(lr) + '\\n') f.write('max_grad: {0: 3.2f}'.format(max_grad)",
"import sys import glob import shutil import numpy as np import tensorflow as",
"tau in enumerate([0.005, 0.001, 0.0005]): for memory_capacity_i, memory_capacity in enumerate([1e6]): print(\"Learning rate: {0:",
"import PointrobotTrainer from hwr.utils import load_params # loading params: params = load_params('params/hyperparam_tuning_params.json') #Initialize",
"= logdir # writing the hyperparameters into a file: info_file = os.path.join(logdir, 'params.txt')",
"= gym.make( params[\"env\"][\"name\"], params=params ) # deleting the previous runs logs: logdir_files =",
"memory_capacity: {3: 4}\".format( lr, max_grad, tau, memory_capacity)) # the actual parameters: params[\"agent\"][\"lr_actor\"] =",
"params[\"agent\"][\"lr_actor\"] = lr params[\"agent\"][\"lr_critic\"] = lr params[\"agent\"][\"max_grad\"] = max_grad params[\"agent\"][\"tau\"] = tau params[\"agent\"][\"memory_capacity\"]",
"ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for f in ckp_files: os.remove(f) # initialize the agent:",
"= max_grad params[\"agent\"][\"tau\"] = tau params[\"agent\"][\"memory_capacity\"] = memory_capacity # setting up logdir for",
"for f in ckp_files: os.remove(f) # initialize the agent: policy = DDPG( env=env,",
"ckp_files: os.remove(f) # initialize the agent: policy = DDPG( env=env, params=params ) #",
"# the actual parameters: params[\"agent\"][\"lr_actor\"] = lr params[\"agent\"][\"lr_critic\"] = lr params[\"agent\"][\"max_grad\"] = max_grad",
"info_file = os.path.join(logdir, 'params.txt') with open(info_file, 'a') as f: f.write('learning rate: {0: 1.8f}'.format(lr)",
"1.3f}'.format(tau) + '\\n') f.write('batch size: {0: 4}'.format(memory_capacity) + '\\n') # deleting the previous",
"params = load_params('params/hyperparam_tuning_params.json') #Initialize the environment env = gym.make( params[\"env\"][\"name\"], params=params, ) test_env",
"max_grad params[\"agent\"][\"tau\"] = tau params[\"agent\"][\"memory_capacity\"] = memory_capacity # setting up logdir for the",
"lr params[\"agent\"][\"max_grad\"] = max_grad params[\"agent\"][\"tau\"] = tau params[\"agent\"][\"memory_capacity\"] = memory_capacity # setting up",
"environment env = gym.make( params[\"env\"][\"name\"], params=params, ) test_env = gym.make( params[\"env\"][\"name\"], params=params )",
"the current hyperparams: logdir = os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"] = logdir #",
"# Hyperparameter grid search for lr_i, lr in enumerate([5e-4, 1e-4, 5e-5]): for max_grad_i,",
"0.0005]): for memory_capacity_i, memory_capacity in enumerate([1e6]): print(\"Learning rate: {0: 1.8f} max_grad: {1: 3.2f}",
"import gym_pointrobo from hwr.agents.pointrobo_ddpg import DDPG from hwr.cae.cae import CAE from hwr.training.pointrobot_trainer import",
"from hwr.utils import load_params # loading params: params = load_params('params/hyperparam_tuning_params.json') #Initialize the environment",
"the hyperparameters into a file: info_file = os.path.join(logdir, 'params.txt') with open(info_file, 'a') as",
"initialize the agent: policy = DDPG( env=env, params=params ) # initialize the trainer:",
"# initialize the agent: policy = DDPG( env=env, params=params ) # initialize the",
"lr in enumerate([5e-4, 1e-4, 5e-5]): for max_grad_i, max_grad in enumerate([1, 0.5, 0.1]): for",
"memory_capacity)) # the actual parameters: params[\"agent\"][\"lr_actor\"] = lr params[\"agent\"][\"lr_critic\"] = lr params[\"agent\"][\"max_grad\"] =",
"import shutil import numpy as np import tensorflow as tf import gym import",
"3.2f}'.format(max_grad) + '\\n') f.write('tau: {0: 1.3f}'.format(tau) + '\\n') f.write('batch size: {0: 4}'.format(memory_capacity) +",
"glob import shutil import numpy as np import tensorflow as tf import gym",
"DDPG from hwr.cae.cae import CAE from hwr.training.pointrobot_trainer import PointrobotTrainer from hwr.utils import load_params",
"= memory_capacity # setting up logdir for the current hyperparams: logdir = os.path.join('results',",
"1e-4, 5e-5]): for max_grad_i, max_grad in enumerate([1, 0.5, 0.1]): for tau_i, tau in",
"= load_params('params/hyperparam_tuning_params.json') #Initialize the environment env = gym.make( params[\"env\"][\"name\"], params=params, ) test_env =",
"3.2f} Tau_Target_update: {2: 1.3f} memory_capacity: {3: 4}\".format( lr, max_grad, tau, memory_capacity)) # the",
"policy = DDPG( env=env, params=params ) # initialize the trainer: trainer = PointrobotTrainer(",
"'*')) for f in logdir_files: if os.path.isdir(f): shutil.rmtree(f) else: os.remove(f) # Hyperparameter grid",
"as tf import gym import gym_pointrobo from hwr.agents.pointrobo_ddpg import DDPG from hwr.cae.cae import",
"Hyperparameter grid search for lr_i, lr in enumerate([5e-4, 1e-4, 5e-5]): for max_grad_i, max_grad",
"'\\n') f.write('batch size: {0: 4}'.format(memory_capacity) + '\\n') # deleting the previous checkpoints: ckp_files",
"'\\n') f.write('tau: {0: 1.3f}'.format(tau) + '\\n') f.write('batch size: {0: 4}'.format(memory_capacity) + '\\n') #",
"grid search for lr_i, lr in enumerate([5e-4, 1e-4, 5e-5]): for max_grad_i, max_grad in",
"params=params ) # initialize the trainer: trainer = PointrobotTrainer( policy, env, params, test_env=test_env",
") test_env = gym.make( params[\"env\"][\"name\"], params=params ) # deleting the previous runs logs:",
"= DDPG( env=env, params=params ) # initialize the trainer: trainer = PointrobotTrainer( policy,",
"logdir_files: if os.path.isdir(f): shutil.rmtree(f) else: os.remove(f) # Hyperparameter grid search for lr_i, lr",
"gym_pointrobo from hwr.agents.pointrobo_ddpg import DDPG from hwr.cae.cae import CAE from hwr.training.pointrobot_trainer import PointrobotTrainer",
"search for lr_i, lr in enumerate([5e-4, 1e-4, 5e-5]): for max_grad_i, max_grad in enumerate([1,",
"in enumerate([5e-4, 1e-4, 5e-5]): for max_grad_i, max_grad in enumerate([1, 0.5, 0.1]): for tau_i,",
"load_params # loading params: params = load_params('params/hyperparam_tuning_params.json') #Initialize the environment env = gym.make(",
"in ckp_files: os.remove(f) # initialize the agent: policy = DDPG( env=env, params=params )",
"params[\"agent\"][\"max_grad\"] = max_grad params[\"agent\"][\"tau\"] = tau params[\"agent\"][\"memory_capacity\"] = memory_capacity # setting up logdir",
"tau, memory_capacity)) # the actual parameters: params[\"agent\"][\"lr_actor\"] = lr params[\"agent\"][\"lr_critic\"] = lr params[\"agent\"][\"max_grad\"]",
"memory_capacity_i, memory_capacity in enumerate([1e6]): print(\"Learning rate: {0: 1.8f} max_grad: {1: 3.2f} Tau_Target_update: {2:",
"writing the hyperparameters into a file: info_file = os.path.join(logdir, 'params.txt') with open(info_file, 'a')",
"1.8f}'.format(lr) + '\\n') f.write('max_grad: {0: 3.2f}'.format(max_grad) + '\\n') f.write('tau: {0: 1.3f}'.format(tau) + '\\n')",
"f: f.write('learning rate: {0: 1.8f}'.format(lr) + '\\n') f.write('max_grad: {0: 3.2f}'.format(max_grad) + '\\n') f.write('tau:",
"in enumerate([1e6]): print(\"Learning rate: {0: 1.8f} max_grad: {1: 3.2f} Tau_Target_update: {2: 1.3f} memory_capacity:",
"+ '\\n') f.write('batch size: {0: 4}'.format(memory_capacity) + '\\n') # deleting the previous checkpoints:",
"hwr.training.pointrobot_trainer import PointrobotTrainer from hwr.utils import load_params # loading params: params = load_params('params/hyperparam_tuning_params.json')",
"loading params: params = load_params('params/hyperparam_tuning_params.json') #Initialize the environment env = gym.make( params[\"env\"][\"name\"], params=params,",
"deleting the previous checkpoints: ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for f in ckp_files: os.remove(f)",
"params=params, ) test_env = gym.make( params[\"env\"][\"name\"], params=params ) # deleting the previous runs",
"glob.glob(os.path.join('results', 'hyperparam_tuning', '*')) for f in logdir_files: if os.path.isdir(f): shutil.rmtree(f) else: os.remove(f) #",
") # deleting the previous runs logs: logdir_files = glob.glob(os.path.join('results', 'hyperparam_tuning', '*')) for",
"# deleting the previous runs logs: logdir_files = glob.glob(os.path.join('results', 'hyperparam_tuning', '*')) for f",
"memory_capacity # setting up logdir for the current hyperparams: logdir = os.path.join('results', 'hyperparam_tuning',",
"{0: 3.2f}'.format(max_grad) + '\\n') f.write('tau: {0: 1.3f}'.format(tau) + '\\n') f.write('batch size: {0: 4}'.format(memory_capacity)",
"print(\"Learning rate: {0: 1.8f} max_grad: {1: 3.2f} Tau_Target_update: {2: 1.3f} memory_capacity: {3: 4}\".format(",
"tensorflow as tf import gym import gym_pointrobo from hwr.agents.pointrobo_ddpg import DDPG from hwr.cae.cae",
"# loading params: params = load_params('params/hyperparam_tuning_params.json') #Initialize the environment env = gym.make( params[\"env\"][\"name\"],",
"in enumerate([0.005, 0.001, 0.0005]): for memory_capacity_i, memory_capacity in enumerate([1e6]): print(\"Learning rate: {0: 1.8f}",
"current hyperparams: logdir = os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"] = logdir # writing",
"= os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"] = logdir # writing the hyperparameters into",
"test_env = gym.make( params[\"env\"][\"name\"], params=params ) # deleting the previous runs logs: logdir_files",
"as np import tensorflow as tf import gym import gym_pointrobo from hwr.agents.pointrobo_ddpg import",
"params[\"trainer\"][\"logdir\"] = logdir # writing the hyperparameters into a file: info_file = os.path.join(logdir,",
"os.remove(f) # Hyperparameter grid search for lr_i, lr in enumerate([5e-4, 1e-4, 5e-5]): for",
"actual parameters: params[\"agent\"][\"lr_actor\"] = lr params[\"agent\"][\"lr_critic\"] = lr params[\"agent\"][\"max_grad\"] = max_grad params[\"agent\"][\"tau\"] =",
"#Initialize the environment env = gym.make( params[\"env\"][\"name\"], params=params, ) test_env = gym.make( params[\"env\"][\"name\"],",
"file: info_file = os.path.join(logdir, 'params.txt') with open(info_file, 'a') as f: f.write('learning rate: {0:",
"os.path.join(logdir, 'params.txt') with open(info_file, 'a') as f: f.write('learning rate: {0: 1.8f}'.format(lr) + '\\n')",
"os.makedirs(logdir) params[\"trainer\"][\"logdir\"] = logdir # writing the hyperparameters into a file: info_file =",
"+ '\\n') # deleting the previous checkpoints: ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for f",
"runs logs: logdir_files = glob.glob(os.path.join('results', 'hyperparam_tuning', '*')) for f in logdir_files: if os.path.isdir(f):",
"if os.path.isdir(f): shutil.rmtree(f) else: os.remove(f) # Hyperparameter grid search for lr_i, lr in",
"shutil.rmtree(f) else: os.remove(f) # Hyperparameter grid search for lr_i, lr in enumerate([5e-4, 1e-4,",
"'params.txt') with open(info_file, 'a') as f: f.write('learning rate: {0: 1.8f}'.format(lr) + '\\n') f.write('max_grad:",
"f in ckp_files: os.remove(f) # initialize the agent: policy = DDPG( env=env, params=params",
"CAE from hwr.training.pointrobot_trainer import PointrobotTrainer from hwr.utils import load_params # loading params: params",
"import load_params # loading params: params = load_params('params/hyperparam_tuning_params.json') #Initialize the environment env =",
"with open(info_file, 'a') as f: f.write('learning rate: {0: 1.8f}'.format(lr) + '\\n') f.write('max_grad: {0:",
"DDPG( env=env, params=params ) # initialize the trainer: trainer = PointrobotTrainer( policy, env,",
"in enumerate([1, 0.5, 0.1]): for tau_i, tau in enumerate([0.005, 0.001, 0.0005]): for memory_capacity_i,",
"hyperparameters into a file: info_file = os.path.join(logdir, 'params.txt') with open(info_file, 'a') as f:",
"{0: 4}'.format(memory_capacity) + '\\n') # deleting the previous checkpoints: ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\"))",
"'a') as f: f.write('learning rate: {0: 1.8f}'.format(lr) + '\\n') f.write('max_grad: {0: 3.2f}'.format(max_grad) +",
"\"*\")) for f in ckp_files: os.remove(f) # initialize the agent: policy = DDPG(",
"parameters: params[\"agent\"][\"lr_actor\"] = lr params[\"agent\"][\"lr_critic\"] = lr params[\"agent\"][\"max_grad\"] = max_grad params[\"agent\"][\"tau\"] = tau",
"{2: 1.3f} memory_capacity: {3: 4}\".format( lr, max_grad, tau, memory_capacity)) # the actual parameters:",
"# writing the hyperparameters into a file: info_file = os.path.join(logdir, 'params.txt') with open(info_file,",
"as f: f.write('learning rate: {0: 1.8f}'.format(lr) + '\\n') f.write('max_grad: {0: 3.2f}'.format(max_grad) + '\\n')",
"logs: logdir_files = glob.glob(os.path.join('results', 'hyperparam_tuning', '*')) for f in logdir_files: if os.path.isdir(f): shutil.rmtree(f)",
"0.5, 0.1]): for tau_i, tau in enumerate([0.005, 0.001, 0.0005]): for memory_capacity_i, memory_capacity in",
"os.path.isdir(f): shutil.rmtree(f) else: os.remove(f) # Hyperparameter grid search for lr_i, lr in enumerate([5e-4,",
"into a file: info_file = os.path.join(logdir, 'params.txt') with open(info_file, 'a') as f: f.write('learning",
"+ '\\n') f.write('max_grad: {0: 3.2f}'.format(max_grad) + '\\n') f.write('tau: {0: 1.3f}'.format(tau) + '\\n') f.write('batch",
"{0: 1.3f}'.format(tau) + '\\n') f.write('batch size: {0: 4}'.format(memory_capacity) + '\\n') # deleting the",
"the previous checkpoints: ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for f in ckp_files: os.remove(f) #",
"load_params('params/hyperparam_tuning_params.json') #Initialize the environment env = gym.make( params[\"env\"][\"name\"], params=params, ) test_env = gym.make(",
"params[\"agent\"][\"lr_critic\"] = lr params[\"agent\"][\"max_grad\"] = max_grad params[\"agent\"][\"tau\"] = tau params[\"agent\"][\"memory_capacity\"] = memory_capacity #",
"{0: 1.8f} max_grad: {1: 3.2f} Tau_Target_update: {2: 1.3f} memory_capacity: {3: 4}\".format( lr, max_grad,",
"from hwr.cae.cae import CAE from hwr.training.pointrobot_trainer import PointrobotTrainer from hwr.utils import load_params #",
"import DDPG from hwr.cae.cae import CAE from hwr.training.pointrobot_trainer import PointrobotTrainer from hwr.utils import",
"f in logdir_files: if os.path.isdir(f): shutil.rmtree(f) else: os.remove(f) # Hyperparameter grid search for",
"# initialize the trainer: trainer = PointrobotTrainer( policy, env, params, test_env=test_env ) trainer.train()",
"import os import sys import glob import shutil import numpy as np import",
"lr params[\"agent\"][\"lr_critic\"] = lr params[\"agent\"][\"max_grad\"] = max_grad params[\"agent\"][\"tau\"] = tau params[\"agent\"][\"memory_capacity\"] = memory_capacity",
"f.write('tau: {0: 1.3f}'.format(tau) + '\\n') f.write('batch size: {0: 4}'.format(memory_capacity) + '\\n') # deleting",
"1.3f} memory_capacity: {3: 4}\".format( lr, max_grad, tau, memory_capacity)) # the actual parameters: params[\"agent\"][\"lr_actor\"]",
"enumerate([1e6]): print(\"Learning rate: {0: 1.8f} max_grad: {1: 3.2f} Tau_Target_update: {2: 1.3f} memory_capacity: {3:",
"else: os.remove(f) # Hyperparameter grid search for lr_i, lr in enumerate([5e-4, 1e-4, 5e-5]):",
"= os.path.join(logdir, 'params.txt') with open(info_file, 'a') as f: f.write('learning rate: {0: 1.8f}'.format(lr) +",
"os.remove(f) # initialize the agent: policy = DDPG( env=env, params=params ) # initialize",
"import numpy as np import tensorflow as tf import gym import gym_pointrobo from",
"hwr.agents.pointrobo_ddpg import DDPG from hwr.cae.cae import CAE from hwr.training.pointrobot_trainer import PointrobotTrainer from hwr.utils",
"params[\"agent\"][\"tau\"] = tau params[\"agent\"][\"memory_capacity\"] = memory_capacity # setting up logdir for the current",
"memory_capacity in enumerate([1e6]): print(\"Learning rate: {0: 1.8f} max_grad: {1: 3.2f} Tau_Target_update: {2: 1.3f}",
"f.write('learning rate: {0: 1.8f}'.format(lr) + '\\n') f.write('max_grad: {0: 3.2f}'.format(max_grad) + '\\n') f.write('tau: {0:",
"= tau params[\"agent\"][\"memory_capacity\"] = memory_capacity # setting up logdir for the current hyperparams:",
"import glob import shutil import numpy as np import tensorflow as tf import",
"+ '\\n') f.write('tau: {0: 1.3f}'.format(tau) + '\\n') f.write('batch size: {0: 4}'.format(memory_capacity) + '\\n')",
"5e-5]): for max_grad_i, max_grad in enumerate([1, 0.5, 0.1]): for tau_i, tau in enumerate([0.005,",
"'\\n') f.write('max_grad: {0: 3.2f}'.format(max_grad) + '\\n') f.write('tau: {0: 1.3f}'.format(tau) + '\\n') f.write('batch size:",
"= gym.make( params[\"env\"][\"name\"], params=params, ) test_env = gym.make( params[\"env\"][\"name\"], params=params ) # deleting",
"setting up logdir for the current hyperparams: logdir = os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir)",
"params[\"agent\"][\"memory_capacity\"] = memory_capacity # setting up logdir for the current hyperparams: logdir =",
"= glob.glob(os.path.join('results', 'hyperparam_tuning', '*')) for f in logdir_files: if os.path.isdir(f): shutil.rmtree(f) else: os.remove(f)",
"tf import gym import gym_pointrobo from hwr.agents.pointrobo_ddpg import DDPG from hwr.cae.cae import CAE",
"for f in logdir_files: if os.path.isdir(f): shutil.rmtree(f) else: os.remove(f) # Hyperparameter grid search",
"logdir # writing the hyperparameters into a file: info_file = os.path.join(logdir, 'params.txt') with",
"deleting the previous runs logs: logdir_files = glob.glob(os.path.join('results', 'hyperparam_tuning', '*')) for f in",
"gym.make( params[\"env\"][\"name\"], params=params ) # deleting the previous runs logs: logdir_files = glob.glob(os.path.join('results',",
"np import tensorflow as tf import gym import gym_pointrobo from hwr.agents.pointrobo_ddpg import DDPG",
"<gh_stars>1-10 import os import sys import glob import shutil import numpy as np",
"{1: 3.2f} Tau_Target_update: {2: 1.3f} memory_capacity: {3: 4}\".format( lr, max_grad, tau, memory_capacity)) #",
"lr_i, lr in enumerate([5e-4, 1e-4, 5e-5]): for max_grad_i, max_grad in enumerate([1, 0.5, 0.1]):",
"0.1]): for tau_i, tau in enumerate([0.005, 0.001, 0.0005]): for memory_capacity_i, memory_capacity in enumerate([1e6]):",
"import CAE from hwr.training.pointrobot_trainer import PointrobotTrainer from hwr.utils import load_params # loading params:",
"for max_grad_i, max_grad in enumerate([1, 0.5, 0.1]): for tau_i, tau in enumerate([0.005, 0.001,",
"checkpoints: ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for f in ckp_files: os.remove(f) # initialize the",
"os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"] = logdir # writing the hyperparameters into a",
"size: {0: 4}'.format(memory_capacity) + '\\n') # deleting the previous checkpoints: ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"],",
"os import sys import glob import shutil import numpy as np import tensorflow",
"hwr.cae.cae import CAE from hwr.training.pointrobot_trainer import PointrobotTrainer from hwr.utils import load_params # loading",
"tau params[\"agent\"][\"memory_capacity\"] = memory_capacity # setting up logdir for the current hyperparams: logdir",
"in logdir_files: if os.path.isdir(f): shutil.rmtree(f) else: os.remove(f) # Hyperparameter grid search for lr_i,",
"env=env, params=params ) # initialize the trainer: trainer = PointrobotTrainer( policy, env, params,",
") # initialize the trainer: trainer = PointrobotTrainer( policy, env, params, test_env=test_env )",
"for lr_i, lr in enumerate([5e-4, 1e-4, 5e-5]): for max_grad_i, max_grad in enumerate([1, 0.5,",
"the agent: policy = DDPG( env=env, params=params ) # initialize the trainer: trainer",
"for the current hyperparams: logdir = os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"] = logdir",
"glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for f in ckp_files: os.remove(f) # initialize the agent: policy =",
"= lr params[\"agent\"][\"max_grad\"] = max_grad params[\"agent\"][\"tau\"] = tau params[\"agent\"][\"memory_capacity\"] = memory_capacity # setting",
"previous checkpoints: ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for f in ckp_files: os.remove(f) # initialize",
"shutil import numpy as np import tensorflow as tf import gym import gym_pointrobo",
"str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"] = logdir # writing the hyperparameters into a file: info_file",
"enumerate([5e-4, 1e-4, 5e-5]): for max_grad_i, max_grad in enumerate([1, 0.5, 0.1]): for tau_i, tau",
"params: params = load_params('params/hyperparam_tuning_params.json') #Initialize the environment env = gym.make( params[\"env\"][\"name\"], params=params, )",
"logdir for the current hyperparams: logdir = os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"] =",
"agent: policy = DDPG( env=env, params=params ) # initialize the trainer: trainer =",
"'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"] = logdir # writing the hyperparameters into a file:",
"# setting up logdir for the current hyperparams: logdir = os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i))",
"params=params ) # deleting the previous runs logs: logdir_files = glob.glob(os.path.join('results', 'hyperparam_tuning', '*'))",
"max_grad, tau, memory_capacity)) # the actual parameters: params[\"agent\"][\"lr_actor\"] = lr params[\"agent\"][\"lr_critic\"] = lr",
"numpy as np import tensorflow as tf import gym import gym_pointrobo from hwr.agents.pointrobo_ddpg",
"params[\"env\"][\"name\"], params=params ) # deleting the previous runs logs: logdir_files = glob.glob(os.path.join('results', 'hyperparam_tuning',",
"hwr.utils import load_params # loading params: params = load_params('params/hyperparam_tuning_params.json') #Initialize the environment env",
"# deleting the previous checkpoints: ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for f in ckp_files:",
"f.write('max_grad: {0: 3.2f}'.format(max_grad) + '\\n') f.write('tau: {0: 1.3f}'.format(tau) + '\\n') f.write('batch size: {0:",
"max_grad in enumerate([1, 0.5, 0.1]): for tau_i, tau in enumerate([0.005, 0.001, 0.0005]): for",
"previous runs logs: logdir_files = glob.glob(os.path.join('results', 'hyperparam_tuning', '*')) for f in logdir_files: if",
"logdir = os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"] = logdir # writing the hyperparameters",
"up logdir for the current hyperparams: logdir = os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"]",
"for memory_capacity_i, memory_capacity in enumerate([1e6]): print(\"Learning rate: {0: 1.8f} max_grad: {1: 3.2f} Tau_Target_update:",
"1.8f} max_grad: {1: 3.2f} Tau_Target_update: {2: 1.3f} memory_capacity: {3: 4}\".format( lr, max_grad, tau,",
"{0: 1.8f}'.format(lr) + '\\n') f.write('max_grad: {0: 3.2f}'.format(max_grad) + '\\n') f.write('tau: {0: 1.3f}'.format(tau) +",
"tau_i, tau in enumerate([0.005, 0.001, 0.0005]): for memory_capacity_i, memory_capacity in enumerate([1e6]): print(\"Learning rate:",
"4}'.format(memory_capacity) + '\\n') # deleting the previous checkpoints: ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for",
"hyperparams: logdir = os.path.join('results', 'hyperparam_tuning', str(lr_i)+str(max_grad_i)+str(tau_i)+str(memory_capacity_i)) os.makedirs(logdir) params[\"trainer\"][\"logdir\"] = logdir # writing the",
"max_grad: {1: 3.2f} Tau_Target_update: {2: 1.3f} memory_capacity: {3: 4}\".format( lr, max_grad, tau, memory_capacity))",
"the actual parameters: params[\"agent\"][\"lr_actor\"] = lr params[\"agent\"][\"lr_critic\"] = lr params[\"agent\"][\"max_grad\"] = max_grad params[\"agent\"][\"tau\"]",
"a file: info_file = os.path.join(logdir, 'params.txt') with open(info_file, 'a') as f: f.write('learning rate:",
"logdir_files = glob.glob(os.path.join('results', 'hyperparam_tuning', '*')) for f in logdir_files: if os.path.isdir(f): shutil.rmtree(f) else:",
"params[\"env\"][\"name\"], params=params, ) test_env = gym.make( params[\"env\"][\"name\"], params=params ) # deleting the previous",
"= glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], \"*\")) for f in ckp_files: os.remove(f) # initialize the agent: policy",
"4}\".format( lr, max_grad, tau, memory_capacity)) # the actual parameters: params[\"agent\"][\"lr_actor\"] = lr params[\"agent\"][\"lr_critic\"]",
"from hwr.training.pointrobot_trainer import PointrobotTrainer from hwr.utils import load_params # loading params: params =",
"from hwr.agents.pointrobo_ddpg import DDPG from hwr.cae.cae import CAE from hwr.training.pointrobot_trainer import PointrobotTrainer from",
"the previous runs logs: logdir_files = glob.glob(os.path.join('results', 'hyperparam_tuning', '*')) for f in logdir_files:",
"gym import gym_pointrobo from hwr.agents.pointrobo_ddpg import DDPG from hwr.cae.cae import CAE from hwr.training.pointrobot_trainer",
"{3: 4}\".format( lr, max_grad, tau, memory_capacity)) # the actual parameters: params[\"agent\"][\"lr_actor\"] = lr",
"env = gym.make( params[\"env\"][\"name\"], params=params, ) test_env = gym.make( params[\"env\"][\"name\"], params=params ) #",
"= lr params[\"agent\"][\"lr_critic\"] = lr params[\"agent\"][\"max_grad\"] = max_grad params[\"agent\"][\"tau\"] = tau params[\"agent\"][\"memory_capacity\"] =",
"rate: {0: 1.8f}'.format(lr) + '\\n') f.write('max_grad: {0: 3.2f}'.format(max_grad) + '\\n') f.write('tau: {0: 1.3f}'.format(tau)"
] |
[
"r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' +",
"'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED",
"self.df_response_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name = key_word + r'-Question'",
"key_word)) new_question_clm_name = key_word + r'-Question' new_answer_clm_name = key_word + r'-Answer' self.df_response_serialized =",
"if __name__ == \"__main__\": cs = column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' +",
"self.df_score_serialized = self.df_score_serialized.rename( columns={r'Content' : new_score_clm_name}) lang_columns = self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir",
"self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized = self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized =",
"+ add_data.iloc[i]] df_to_be_mod.index = new_index df_to_be_mod.index.name = r'Student_Question_Index' return df_to_be_mod if __name__ ==",
"original_index = df_to_be_mod.index df_to_be_mod = pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID'] df_to_be_mod.index",
"qid_csv_file_in is assumed to have the columns 'Question_ID' and 'Question' ''' def __init__(self,",
": new_question_clm_name, r'Content' : new_answer_clm_name}) score_columns = self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized = clsr.ac_column_serializer(self.data_dir +",
"= self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized, r'-' + key_word, new_question_clm_name) self.df_all_serialized = self.add_questin_id(self.df_all_serialized,",
"self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def columms_to_be_serialized(self, csv_file_in, key_word): df_file_in = pd.read_csv(self.data_dir + csv_file_in, encoding= 'latin1')",
"= pd.read_csv(self.data_dir + qid_csv_file_in, encoding= 'latin1') df_file_in = df_file_in.rename(columns={'Question': column_to_be_matched}) original_index = df_to_be_mod.index",
"add_questin_id(self, df_to_be_mod, qid_csv_file_in, column_to_be_matched): df_file_in = pd.read_csv(self.data_dir + qid_csv_file_in, encoding= 'latin1') df_file_in =",
"= clsr.ac_column_serializer(self.data_dir + csv_file_in, r'Student_Index', score_columns) new_score_clm_name = key_word + r'-Score' self.df_score_serialized =",
"pd.DataFrame({column_to_be_mod : new_data}, index = df_to_be_mod.index) df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod] return df_to_be_mod def add_questin_id(self,",
"original_index return df_to_be_mod def add_clm_values_to_index(self, df_to_be_mod, column_to_be_added): mod_index = df_to_be_mod.index add_data = df_to_be_mod[column_to_be_added]",
"new_index = new_index + [str(mod_index[i]) + r'-' + add_data.iloc[i]] df_to_be_mod.index = new_index df_to_be_mod.index.name",
"new_answer_clm_name = key_word + r'-Answer' self.df_response_serialized = self.df_response_serialized.rename( columns={r'Pre_Col_Name' : new_question_clm_name, r'Content' :",
"+ r'-' + add_data.iloc[i]] df_to_be_mod.index = new_index df_to_be_mod.index.name = r'Student_Question_Index' return df_to_be_mod if",
"r'-' + key_word, new_question_clm_name) self.df_all_serialized = self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name)",
"+ r'-Score' self.df_score_serialized = self.df_score_serialized.rename( columns={r'Content' : new_score_clm_name}) lang_columns = self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized",
"key_word + r'-Answer' self.df_response_serialized = self.df_response_serialized.rename( columns={r'Pre_Col_Name' : new_question_clm_name, r'Content' : new_answer_clm_name}) score_columns",
"= self.df_lang_serialized.rename( columns={r'Content' : new_lang_clm_name}) self.df_all_serialized = self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] =",
": new_answer_clm_name}) score_columns = self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, r'Student_Index', score_columns)",
"cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv',",
"df_to_be_mod.index = new_index df_to_be_mod.index.name = r'Student_Question_Index' return df_to_be_mod if __name__ == \"__main__\": cs",
"''' qid_csv_file_in is assumed to have the columns 'Question_ID' and 'Question' ''' def",
"self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name = key_word + r'-Question' new_answer_clm_name = key_word + r'-Answer' self.df_response_serialized",
"cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding=",
"new_data = new_data + [x.replace(rm_word, r\"\")] df_new_data = pd.DataFrame({column_to_be_mod : new_data}, index =",
"if key_word in x: ser_columns = ser_columns + [x] return ser_columns def remove_word_from_clm_values(self,",
"= new_index df_to_be_mod.index.name = r'Student_Question_Index' return df_to_be_mod if __name__ == \"__main__\": cs =",
"= key_word + r'-Language' self.df_lang_serialized = self.df_lang_serialized.rename( columns={r'Content' : new_lang_clm_name}) self.df_all_serialized = self.df_response_serialized.copy()",
"column_to_be_added): mod_index = df_to_be_mod.index add_data = df_to_be_mod[column_to_be_added] new_index = [] for i in",
"\"__main__\": cs = column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1')",
"r'Score') self.df_score_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, r'Student_Index', score_columns) new_score_clm_name = key_word + r'-Score'",
"r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.POST-TEST",
"#df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID'] df_to_be_mod.index = original_index return df_to_be_mod def add_clm_values_to_index(self, df_to_be_mod, column_to_be_added): mod_index",
"= df_file_in.rename(columns={'Question': column_to_be_matched}) original_index = df_to_be_mod.index df_to_be_mod = pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec']",
"r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1')",
"pd import ac_column_serializer as clsr ''' Put a path file like \"plimac-custom.pth\" into",
"df_file_in.rename(columns={'Question': column_to_be_matched}) original_index = df_to_be_mod.index df_to_be_mod = pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec'] =",
"add_data.iloc[i]] df_to_be_mod.index = new_index df_to_be_mod.index.name = r'Student_Question_Index' return df_to_be_mod if __name__ == \"__main__\":",
"== \"__main__\": cs = column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding=",
"# .pth file for the PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### ''' class column_serializer:",
"r'-Score' self.df_score_serialized = self.df_score_serialized.rename( columns={r'Content' : new_score_clm_name}) lang_columns = self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized =",
"= df_new_data[column_to_be_mod] return df_to_be_mod def add_questin_id(self, df_to_be_mod, qid_csv_file_in, column_to_be_matched): df_file_in = pd.read_csv(self.data_dir +",
"file like \"plimac-custom.pth\" into any of your sys.path directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth",
"= clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name = key_word + r'-Question' new_answer_clm_name",
"'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv',",
"axis=1) self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized, r'-' + key_word, new_question_clm_name) self.df_all_serialized = self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name)",
"= [] for x in mod_data: new_data = new_data + [x.replace(rm_word, r\"\")] df_new_data",
"C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### ''' class column_serializer: ''' qid_csv_file_in is assumed to have the",
"+ r'-Answer' self.df_response_serialized = self.df_response_serialized.rename( columns={r'Pre_Col_Name' : new_question_clm_name, r'Content' : new_answer_clm_name}) score_columns =",
"qid_csv_file_in def serialize_record(self, csv_file_in, key_word = r'Definition'): self.df_response_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index',",
"is assumed to have the columns 'Question_ID' and 'Question' ''' def __init__(self, data_dir=r'./',",
"PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### ''' class column_serializer: ''' qid_csv_file_in is assumed to",
"'Student_Index', lang_columns) new_lang_clm_name = key_word + r'-Language' self.df_lang_serialized = self.df_lang_serialized.rename( columns={r'Content' : new_lang_clm_name})",
"r'Language') self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', lang_columns) new_lang_clm_name = key_word + r'-Language'",
"= self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized = self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized, r'-' + key_word,",
"df_to_be_mod[column_to_be_mod] new_data = [] for x in mod_data: new_data = new_data + [x.replace(rm_word,",
"= r'Student_Question_Index' return df_to_be_mod if __name__ == \"__main__\": cs = column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED",
"index = df_to_be_mod.index) df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod] return df_to_be_mod def add_questin_id(self, df_to_be_mod, qid_csv_file_in, column_to_be_matched):",
"= key_word + r'-Answer' self.df_response_serialized = self.df_response_serialized.rename( columns={r'Pre_Col_Name' : new_question_clm_name, r'Content' : new_answer_clm_name})",
"new_question_clm_name) def columms_to_be_serialized(self, csv_file_in, key_word): df_file_in = pd.read_csv(self.data_dir + csv_file_in, encoding= 'latin1') in_columns",
"df_to_be_mod def add_questin_id(self, df_to_be_mod, qid_csv_file_in, column_to_be_matched): df_file_in = pd.read_csv(self.data_dir + qid_csv_file_in, encoding= 'latin1')",
"def serialize_record(self, csv_file_in, key_word = r'Definition'): self.df_response_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in,",
"new_index df_to_be_mod.index.name = r'Student_Question_Index' return df_to_be_mod if __name__ == \"__main__\": cs = column_serializer(r'../data/')",
"clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name = key_word + r'-Question' new_answer_clm_name =",
"<reponame>mack-the-psych/vdok3<filename>prep/column_serializer.py #!/usr/bin/env python import pandas as pd import ac_column_serializer as clsr ''' Put",
"self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized = self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized, r'-' + key_word, new_question_clm_name)",
"r'Definition'): self.df_response_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name = key_word +",
".pth file for the PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### ''' class column_serializer: '''",
"= data_dir self.qid_csv_file_in = qid_csv_file_in def serialize_record(self, csv_file_in, key_word = r'Definition'): self.df_response_serialized =",
"pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID'] df_to_be_mod.index = original_index return df_to_be_mod def",
"return df_to_be_mod def add_questin_id(self, df_to_be_mod, qid_csv_file_in, column_to_be_matched): df_file_in = pd.read_csv(self.data_dir + qid_csv_file_in, encoding=",
"+ key_word, new_question_clm_name) self.df_all_serialized = self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def",
"df_to_be_mod.index.name = r'Student_Question_Index' return df_to_be_mod if __name__ == \"__main__\": cs = column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST",
"def add_clm_values_to_index(self, df_to_be_mod, column_to_be_added): mod_index = df_to_be_mod.index add_data = df_to_be_mod[column_to_be_added] new_index = []",
"= ser_columns + [x] return ser_columns def remove_word_from_clm_values(self, df_to_be_mod, rm_word, column_to_be_mod): mod_data =",
"+ [x] return ser_columns def remove_word_from_clm_values(self, df_to_be_mod, rm_word, column_to_be_mod): mod_data = df_to_be_mod[column_to_be_mod] new_data",
"self.df_all_serialized = self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def columms_to_be_serialized(self, csv_file_in, key_word):",
"def columms_to_be_serialized(self, csv_file_in, key_word): df_file_in = pd.read_csv(self.data_dir + csv_file_in, encoding= 'latin1') in_columns =",
"self.df_response_serialized = self.df_response_serialized.rename( columns={r'Pre_Col_Name' : new_question_clm_name, r'Content' : new_answer_clm_name}) score_columns = self.columms_to_be_serialized(csv_file_in, r'Score')",
"column_serializer: ''' qid_csv_file_in is assumed to have the columns 'Question_ID' and 'Question' '''",
"'Question_ID' and 'Question' ''' def __init__(self, data_dir=r'./', qid_csv_file_in = r'Questin_ID_Definition.csv'): self.data_dir = data_dir",
"csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name = key_word + r'-Question' new_answer_clm_name = key_word +",
"new_index = [] for i in range(len(mod_index)): new_index = new_index + [str(mod_index[i]) +",
"data_dir=r'./', qid_csv_file_in = r'Questin_ID_Definition.csv'): self.data_dir = data_dir self.qid_csv_file_in = qid_csv_file_in def serialize_record(self, csv_file_in,",
"df_to_be_mod, column_to_be_added): mod_index = df_to_be_mod.index add_data = df_to_be_mod[column_to_be_added] new_index = [] for i",
"rm_word, column_to_be_mod): mod_data = df_to_be_mod[column_to_be_mod] new_data = [] for x in mod_data: new_data",
"= column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST",
"= df_file_in.columns ser_columns = [] for x in in_columns: if key_word in x:",
"r'Questin_ID_Definition.csv'): self.data_dir = data_dir self.qid_csv_file_in = qid_csv_file_in def serialize_record(self, csv_file_in, key_word = r'Definition'):",
"############################### # .pth file for the PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### ''' class",
"ac_column_serializer as clsr ''' Put a path file like \"plimac-custom.pth\" into any of",
"return df_to_be_mod def add_clm_values_to_index(self, df_to_be_mod, column_to_be_added): mod_index = df_to_be_mod.index add_data = df_to_be_mod[column_to_be_added] new_index",
"\"plimac-custom.pth\" into any of your sys.path directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth ############################### #",
"columns={r'Content' : new_lang_clm_name}) self.df_all_serialized = self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized",
"mod_data = df_to_be_mod[column_to_be_mod] new_data = [] for x in mod_data: new_data = new_data",
"= self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def columms_to_be_serialized(self, csv_file_in, key_word): df_file_in = pd.read_csv(self.data_dir + csv_file_in, encoding=",
"df_file_in = pd.read_csv(self.data_dir + csv_file_in, encoding= 'latin1') in_columns = df_file_in.columns ser_columns = []",
"csv_file_in, r'Student_Index', score_columns) new_score_clm_name = key_word + r'-Score' self.df_score_serialized = self.df_score_serialized.rename( columns={r'Content' :",
"column_to_be_matched): df_file_in = pd.read_csv(self.data_dir + qid_csv_file_in, encoding= 'latin1') df_file_in = df_file_in.rename(columns={'Question': column_to_be_matched}) original_index",
"in_columns = df_file_in.columns ser_columns = [] for x in in_columns: if key_word in",
"add_clm_values_to_index(self, df_to_be_mod, column_to_be_added): mod_index = df_to_be_mod.index add_data = df_to_be_mod[column_to_be_added] new_index = [] for",
"df_to_be_mod = pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID'] df_to_be_mod.index = original_index return",
"self.remove_word_from_clm_values(self.df_all_serialized, r'-' + key_word, new_question_clm_name) self.df_all_serialized = self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized,",
"self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def columms_to_be_serialized(self, csv_file_in, key_word): df_file_in =",
"self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def columms_to_be_serialized(self, csv_file_in, key_word): df_file_in = pd.read_csv(self.data_dir",
"i in range(len(mod_index)): new_index = new_index + [str(mod_index[i]) + r'-' + add_data.iloc[i]] df_to_be_mod.index",
"self.df_all_serialized = self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized, r'-' + key_word, new_question_clm_name) self.df_all_serialized =",
"for the PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### ''' class column_serializer: ''' qid_csv_file_in is",
"qid_csv_file_in = r'Questin_ID_Definition.csv'): self.data_dir = data_dir self.qid_csv_file_in = qid_csv_file_in def serialize_record(self, csv_file_in, key_word",
"= df_to_be_mod[column_to_be_mod] new_data = [] for x in mod_data: new_data = new_data +",
"in range(len(mod_index)): new_index = new_index + [str(mod_index[i]) + r'-' + add_data.iloc[i]] df_to_be_mod.index =",
"new_score_clm_name = key_word + r'-Score' self.df_score_serialized = self.df_score_serialized.rename( columns={r'Content' : new_score_clm_name}) lang_columns =",
"qid_csv_file_in, column_to_be_matched): df_file_in = pd.read_csv(self.data_dir + qid_csv_file_in, encoding= 'latin1') df_file_in = df_file_in.rename(columns={'Question': column_to_be_matched})",
"new_data = [] for x in mod_data: new_data = new_data + [x.replace(rm_word, r\"\")]",
"df_new_data[column_to_be_mod] return df_to_be_mod def add_questin_id(self, df_to_be_mod, qid_csv_file_in, column_to_be_matched): df_file_in = pd.read_csv(self.data_dir + qid_csv_file_in,",
"into any of your sys.path directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth ############################### # .pth",
"x in mod_data: new_data = new_data + [x.replace(rm_word, r\"\")] df_new_data = pd.DataFrame({column_to_be_mod :",
"= r'Definition'): self.df_response_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name = key_word",
"clsr ''' Put a path file like \"plimac-custom.pth\" into any of your sys.path",
"import ac_column_serializer as clsr ''' Put a path file like \"plimac-custom.pth\" into any",
"= [] for i in range(len(mod_index)): new_index = new_index + [str(mod_index[i]) + r'-'",
"= pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID'] df_to_be_mod.index = original_index return df_to_be_mod",
"r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.POST-TEST.csv',",
"pd.read_csv(self.data_dir + qid_csv_file_in, encoding= 'latin1') df_file_in = df_file_in.rename(columns={'Question': column_to_be_matched}) original_index = df_to_be_mod.index df_to_be_mod",
"= self.remove_word_from_clm_values(self.df_all_serialized, r'-' + key_word, new_question_clm_name) self.df_all_serialized = self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized =",
"= df_to_be_mod.index add_data = df_to_be_mod[column_to_be_added] new_index = [] for i in range(len(mod_index)): new_index",
"python import pandas as pd import ac_column_serializer as clsr ''' Put a path",
"path file like \"plimac-custom.pth\" into any of your sys.path directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages). #",
"def add_questin_id(self, df_to_be_mod, qid_csv_file_in, column_to_be_matched): df_file_in = pd.read_csv(self.data_dir + qid_csv_file_in, encoding= 'latin1') df_file_in",
"df_to_be_mod.index = original_index return df_to_be_mod def add_clm_values_to_index(self, df_to_be_mod, column_to_be_added): mod_index = df_to_be_mod.index add_data",
"'latin1') in_columns = df_file_in.columns ser_columns = [] for x in in_columns: if key_word",
"def __init__(self, data_dir=r'./', qid_csv_file_in = r'Questin_ID_Definition.csv'): self.data_dir = data_dir self.qid_csv_file_in = qid_csv_file_in def",
"def remove_word_from_clm_values(self, df_to_be_mod, rm_word, column_to_be_mod): mod_data = df_to_be_mod[column_to_be_mod] new_data = [] for x",
"qid_csv_file_in, encoding= 'latin1') df_file_in = df_file_in.rename(columns={'Question': column_to_be_matched}) original_index = df_to_be_mod.index df_to_be_mod = pd.merge(df_to_be_mod,",
"################################################### ''' class column_serializer: ''' qid_csv_file_in is assumed to have the columns 'Question_ID'",
"file for the PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### ''' class column_serializer: ''' qid_csv_file_in",
"ser_columns = [] for x in in_columns: if key_word in x: ser_columns =",
"df_to_be_mod.index add_data = df_to_be_mod[column_to_be_added] new_index = [] for i in range(len(mod_index)): new_index =",
"new_answer_clm_name}) score_columns = self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, r'Student_Index', score_columns) new_score_clm_name",
"df_to_be_mod, qid_csv_file_in, column_to_be_matched): df_file_in = pd.read_csv(self.data_dir + qid_csv_file_in, encoding= 'latin1') df_file_in = df_file_in.rename(columns={'Question':",
"df_to_be_mod['Question_ID'] df_to_be_mod.index = original_index return df_to_be_mod def add_clm_values_to_index(self, df_to_be_mod, column_to_be_added): mod_index = df_to_be_mod.index",
"lang_columns) new_lang_clm_name = key_word + r'-Language' self.df_lang_serialized = self.df_lang_serialized.rename( columns={r'Content' : new_lang_clm_name}) self.df_all_serialized",
"sys.path directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth ############################### # .pth file for the PLIMAC",
"+ [x.replace(rm_word, r\"\")] df_new_data = pd.DataFrame({column_to_be_mod : new_data}, index = df_to_be_mod.index) df_to_be_mod[column_to_be_mod] =",
"r'-Question' new_answer_clm_name = key_word + r'-Answer' self.df_response_serialized = self.df_response_serialized.rename( columns={r'Pre_Col_Name' : new_question_clm_name, r'Content'",
"columns={r'Pre_Col_Name' : new_question_clm_name, r'Content' : new_answer_clm_name}) score_columns = self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized = clsr.ac_column_serializer(self.data_dir",
"like \"plimac-custom.pth\" into any of your sys.path directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth ###############################",
"csv_file_in, 'Student_Index', lang_columns) new_lang_clm_name = key_word + r'-Language' self.df_lang_serialized = self.df_lang_serialized.rename( columns={r'Content' :",
": new_score_clm_name}) lang_columns = self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', lang_columns)",
"[] for x in in_columns: if key_word in x: ser_columns = ser_columns +",
"SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' +",
"csv_file_in, key_word = r'Definition'): self.df_response_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name",
"= self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', lang_columns) new_lang_clm_name = key_word",
"in mod_data: new_data = new_data + [x.replace(rm_word, r\"\")] df_new_data = pd.DataFrame({column_to_be_mod : new_data},",
"self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, r'Student_Index', score_columns) new_score_clm_name = key_word +",
"+ csv_file_in, 'Student_Index', lang_columns) new_lang_clm_name = key_word + r'-Language' self.df_lang_serialized = self.df_lang_serialized.rename( columns={r'Content'",
"new_lang_clm_name}) self.df_all_serialized = self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized = self.df_all_serialized.drop(score_columns,",
"df_new_data = pd.DataFrame({column_to_be_mod : new_data}, index = df_to_be_mod.index) df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod] return df_to_be_mod",
"= new_data + [x.replace(rm_word, r\"\")] df_new_data = pd.DataFrame({column_to_be_mod : new_data}, index = df_to_be_mod.index)",
"[x] return ser_columns def remove_word_from_clm_values(self, df_to_be_mod, rm_word, column_to_be_mod): mod_data = df_to_be_mod[column_to_be_mod] new_data =",
"= new_index + [str(mod_index[i]) + r'-' + add_data.iloc[i]] df_to_be_mod.index = new_index df_to_be_mod.index.name =",
"clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', lang_columns) new_lang_clm_name = key_word + r'-Language' self.df_lang_serialized = self.df_lang_serialized.rename(",
"r'-Answer' self.df_response_serialized = self.df_response_serialized.rename( columns={r'Pre_Col_Name' : new_question_clm_name, r'Content' : new_answer_clm_name}) score_columns = self.columms_to_be_serialized(csv_file_in,",
"= self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized = self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized = self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized,",
"= pd.read_csv(self.data_dir + csv_file_in, encoding= 'latin1') in_columns = df_file_in.columns ser_columns = [] for",
"self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized = self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized = self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized",
"your sys.path directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth ############################### # .pth file for the",
"= df_to_be_mod.index) df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod] return df_to_be_mod def add_questin_id(self, df_to_be_mod, qid_csv_file_in, column_to_be_matched): df_file_in",
"= key_word + r'-Question' new_answer_clm_name = key_word + r'-Answer' self.df_response_serialized = self.df_response_serialized.rename( columns={r'Pre_Col_Name'",
"return df_to_be_mod if __name__ == \"__main__\": cs = column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition')",
"mod_data: new_data = new_data + [x.replace(rm_word, r\"\")] df_new_data = pd.DataFrame({column_to_be_mod : new_data}, index",
"[str(mod_index[i]) + r'-' + add_data.iloc[i]] df_to_be_mod.index = new_index df_to_be_mod.index.name = r'Student_Question_Index' return df_to_be_mod",
"remove_word_from_clm_values(self, df_to_be_mod, rm_word, column_to_be_mod): mod_data = df_to_be_mod[column_to_be_mod] new_data = [] for x in",
"have the columns 'Question_ID' and 'Question' ''' def __init__(self, data_dir=r'./', qid_csv_file_in = r'Questin_ID_Definition.csv'):",
"= self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized = self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized = self.df_all_serialized.drop(lang_columns, axis=1)",
"(MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/'",
"in in_columns: if key_word in x: ser_columns = ser_columns + [x] return ser_columns",
"cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition')",
"ser_columns = ser_columns + [x] return ser_columns def remove_word_from_clm_values(self, df_to_be_mod, rm_word, column_to_be_mod): mod_data",
"on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID'] df_to_be_mod.index = original_index return df_to_be_mod def add_clm_values_to_index(self, df_to_be_mod,",
"+ csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name = key_word + r'-Question' new_answer_clm_name = key_word",
"C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth ############################### # .pth file for the PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools",
"self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized, r'-' + key_word, new_question_clm_name) self.df_all_serialized = self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized",
"[] for x in mod_data: new_data = new_data + [x.replace(rm_word, r\"\")] df_new_data =",
"self.df_all_serialized = self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized = self.df_all_serialized.drop(score_columns, axis=1)",
"(MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence')",
"cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.POST-TEST.csv', encoding=",
"axis=1) self.df_all_serialized = self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized, r'-' + key_word, new_question_clm_name) self.df_all_serialized",
"column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED",
"= df_to_be_mod[column_to_be_added] new_index = [] for i in range(len(mod_index)): new_index = new_index +",
"self.data_dir = data_dir self.qid_csv_file_in = qid_csv_file_in def serialize_record(self, csv_file_in, key_word = r'Definition'): self.df_response_serialized",
"r'Student_Index', score_columns) new_score_clm_name = key_word + r'-Score' self.df_score_serialized = self.df_score_serialized.rename( columns={r'Content' : new_score_clm_name})",
"+ csv_file_in, encoding= 'latin1') in_columns = df_file_in.columns ser_columns = [] for x in",
"any of your sys.path directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth ############################### # .pth file",
"df_to_be_mod.index) df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod] return df_to_be_mod def add_questin_id(self, df_to_be_mod, qid_csv_file_in, column_to_be_matched): df_file_in =",
"for x in in_columns: if key_word in x: ser_columns = ser_columns + [x]",
"to have the columns 'Question_ID' and 'Question' ''' def __init__(self, data_dir=r'./', qid_csv_file_in =",
"= [] for x in in_columns: if key_word in x: ser_columns = ser_columns",
"df_to_be_mod, rm_word, column_to_be_mod): mod_data = df_to_be_mod[column_to_be_mod] new_data = [] for x in mod_data:",
"x in in_columns: if key_word in x: ser_columns = ser_columns + [x] return",
"new_data}, index = df_to_be_mod.index) df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod] return df_to_be_mod def add_questin_id(self, df_to_be_mod, qid_csv_file_in,",
"(e.g. C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth ############################### # .pth file for the PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib",
"for i in range(len(mod_index)): new_index = new_index + [str(mod_index[i]) + r'-' + add_data.iloc[i]]",
"= pd.DataFrame({column_to_be_mod : new_data}, index = df_to_be_mod.index) df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod] return df_to_be_mod def",
"new_question_clm_name) self.df_all_serialized = self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def columms_to_be_serialized(self, csv_file_in,",
"new_lang_clm_name = key_word + r'-Language' self.df_lang_serialized = self.df_lang_serialized.rename( columns={r'Content' : new_lang_clm_name}) self.df_all_serialized =",
"the PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### ''' class column_serializer: ''' qid_csv_file_in is assumed",
"''' Put a path file like \"plimac-custom.pth\" into any of your sys.path directories",
"assumed to have the columns 'Question_ID' and 'Question' ''' def __init__(self, data_dir=r'./', qid_csv_file_in",
"= qid_csv_file_in def serialize_record(self, csv_file_in, key_word = r'Definition'): self.df_response_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in,",
"ser_columns def remove_word_from_clm_values(self, df_to_be_mod, rm_word, column_to_be_mod): mod_data = df_to_be_mod[column_to_be_mod] new_data = [] for",
"self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized = self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized = self.df_all_serialized.drop(lang_columns,",
"df_to_be_mod def add_clm_values_to_index(self, df_to_be_mod, column_to_be_added): mod_index = df_to_be_mod.index add_data = df_to_be_mod[column_to_be_added] new_index =",
"self.df_all_serialized = self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized = self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized, r'-' +",
"lang_columns = self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', lang_columns) new_lang_clm_name =",
"= self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized = self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized",
"''' def __init__(self, data_dir=r'./', qid_csv_file_in = r'Questin_ID_Definition.csv'): self.data_dir = data_dir self.qid_csv_file_in = qid_csv_file_in",
"and 'Question' ''' def __init__(self, data_dir=r'./', qid_csv_file_in = r'Questin_ID_Definition.csv'): self.data_dir = data_dir self.qid_csv_file_in",
"key_word + r'-Question' new_answer_clm_name = key_word + r'-Answer' self.df_response_serialized = self.df_response_serialized.rename( columns={r'Pre_Col_Name' :",
"of your sys.path directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth ############################### # .pth file for",
"encoding= 'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST",
"self.df_lang_serialized = self.df_lang_serialized.rename( columns={r'Content' : new_lang_clm_name}) self.df_all_serialized = self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name]",
"column_to_be_matched}) original_index = df_to_be_mod.index df_to_be_mod = pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID']",
"'latin1') df_file_in = df_file_in.rename(columns={'Question': column_to_be_matched}) original_index = df_to_be_mod.index df_to_be_mod = pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched,",
"columms_to_be_serialized(self, csv_file_in, key_word): df_file_in = pd.read_csv(self.data_dir + csv_file_in, encoding= 'latin1') in_columns = df_file_in.columns",
"cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Sentence')",
"[] for i in range(len(mod_index)): new_index = new_index + [str(mod_index[i]) + r'-' +",
"+ r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1')",
"score_columns = self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, r'Student_Index', score_columns) new_score_clm_name =",
"'Question' ''' def __init__(self, data_dir=r'./', qid_csv_file_in = r'Questin_ID_Definition.csv'): self.data_dir = data_dir self.qid_csv_file_in =",
"= original_index return df_to_be_mod def add_clm_values_to_index(self, df_to_be_mod, column_to_be_added): mod_index = df_to_be_mod.index add_data =",
"serialize_record(self, csv_file_in, key_word = r'Definition'): self.df_response_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word))",
"= df_to_be_mod.index df_to_be_mod = pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID'] df_to_be_mod.index =",
"#!/usr/bin/env python import pandas as pd import ac_column_serializer as clsr ''' Put a",
"= self.df_response_serialized.rename( columns={r'Pre_Col_Name' : new_question_clm_name, r'Content' : new_answer_clm_name}) score_columns = self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized",
"r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv',",
"+ qid_csv_file_in, encoding= 'latin1') df_file_in = df_file_in.rename(columns={'Question': column_to_be_matched}) original_index = df_to_be_mod.index df_to_be_mod =",
"df_to_be_mod.index df_to_be_mod = pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID'] df_to_be_mod.index = original_index",
"r'-Language' self.df_lang_serialized = self.df_lang_serialized.rename( columns={r'Content' : new_lang_clm_name}) self.df_all_serialized = self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name]",
"SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' +",
"(MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/'",
"df_file_in = pd.read_csv(self.data_dir + qid_csv_file_in, encoding= 'latin1') df_file_in = df_file_in.rename(columns={'Question': column_to_be_matched}) original_index =",
"= r'Questin_ID_Definition.csv'): self.data_dir = data_dir self.qid_csv_file_in = qid_csv_file_in def serialize_record(self, csv_file_in, key_word =",
"self.df_score_serialized.rename( columns={r'Content' : new_score_clm_name}) lang_columns = self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in,",
"add_data = df_to_be_mod[column_to_be_added] new_index = [] for i in range(len(mod_index)): new_index = new_index",
"extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### ''' class column_serializer: ''' qid_csv_file_in is assumed to have",
"new_question_clm_name) self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def columms_to_be_serialized(self, csv_file_in, key_word): df_file_in = pd.read_csv(self.data_dir +",
"key_word in x: ser_columns = ser_columns + [x] return ser_columns def remove_word_from_clm_values(self, df_to_be_mod,",
"csv_file_in, key_word): df_file_in = pd.read_csv(self.data_dir + csv_file_in, encoding= 'latin1') in_columns = df_file_in.columns ser_columns",
"''' class column_serializer: ''' qid_csv_file_in is assumed to have the columns 'Question_ID' and",
"new_question_clm_name, r'Content' : new_answer_clm_name}) score_columns = self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in,",
"self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', lang_columns) new_lang_clm_name = key_word + r'-Language' self.df_lang_serialized",
"self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def columms_to_be_serialized(self, csv_file_in, key_word): df_file_in = pd.read_csv(self.data_dir + csv_file_in,",
"cs = column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') '''",
"self.df_score_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, r'Student_Index', score_columns) new_score_clm_name = key_word + r'-Score' self.df_score_serialized",
"+ r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1')",
"= self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, r'Student_Index', score_columns) new_score_clm_name = key_word",
"# plimac-custom.pth ############################### # .pth file for the PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ###################################################",
"encoding= 'latin1') df_file_in = df_file_in.rename(columns={'Question': column_to_be_matched}) original_index = df_to_be_mod.index df_to_be_mod = pd.merge(df_to_be_mod, df_file_in,",
"key_word = r'Definition'): self.df_response_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name =",
"columns 'Question_ID' and 'Question' ''' def __init__(self, data_dir=r'./', qid_csv_file_in = r'Questin_ID_Definition.csv'): self.data_dir =",
"encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.POST-TEST (MODIFIED",
"score_columns) new_score_clm_name = key_word + r'-Score' self.df_score_serialized = self.df_score_serialized.rename( columns={r'Content' : new_score_clm_name}) lang_columns",
"df_to_be_mod if __name__ == \"__main__\": cs = column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/'",
"Put a path file like \"plimac-custom.pth\" into any of your sys.path directories (e.g.",
"cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv',",
"in x: ser_columns = ser_columns + [x] return ser_columns def remove_word_from_clm_values(self, df_to_be_mod, rm_word,",
"key_word): df_file_in = pd.read_csv(self.data_dir + csv_file_in, encoding= 'latin1') in_columns = df_file_in.columns ser_columns =",
"new_question_clm_name = key_word + r'-Question' new_answer_clm_name = key_word + r'-Answer' self.df_response_serialized = self.df_response_serialized.rename(",
"ser_columns + [x] return ser_columns def remove_word_from_clm_values(self, df_to_be_mod, rm_word, column_to_be_mod): mod_data = df_to_be_mod[column_to_be_mod]",
"clsr.ac_column_serializer(self.data_dir + csv_file_in, r'Student_Index', score_columns) new_score_clm_name = key_word + r'-Score' self.df_score_serialized = self.df_score_serialized.rename(",
"columns={r'Content' : new_score_clm_name}) lang_columns = self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index',",
"'Student_Index', self.columms_to_be_serialized(csv_file_in, key_word)) new_question_clm_name = key_word + r'-Question' new_answer_clm_name = key_word + r'-Answer'",
"key_word + r'-Language' self.df_lang_serialized = self.df_lang_serialized.rename( columns={r'Content' : new_lang_clm_name}) self.df_all_serialized = self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name]",
"directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages). # plimac-custom.pth ############################### # .pth file for the PLIMAC extension",
"range(len(mod_index)): new_index = new_index + [str(mod_index[i]) + r'-' + add_data.iloc[i]] df_to_be_mod.index = new_index",
"return ser_columns def remove_word_from_clm_values(self, df_to_be_mod, rm_word, column_to_be_mod): mod_data = df_to_be_mod[column_to_be_mod] new_data = []",
"SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/'",
"r'Content' : new_answer_clm_name}) score_columns = self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, r'Student_Index',",
"df_file_in, on=column_to_be_matched, how='left') #df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID'] df_to_be_mod.index = original_index return df_to_be_mod def add_clm_values_to_index(self,",
"for x in mod_data: new_data = new_data + [x.replace(rm_word, r\"\")] df_new_data = pd.DataFrame({column_to_be_mod",
"''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv',",
"as pd import ac_column_serializer as clsr ''' Put a path file like \"plimac-custom.pth\"",
"csv_file_in, encoding= 'latin1') in_columns = df_file_in.columns ser_columns = [] for x in in_columns:",
"+ r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv', encoding= 'latin1') ''' cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.PRE-TEST.csv', encoding=",
"= key_word + r'-Score' self.df_score_serialized = self.df_score_serialized.rename( columns={r'Content' : new_score_clm_name}) lang_columns = self.columms_to_be_serialized(csv_file_in,",
"+ [str(mod_index[i]) + r'-' + add_data.iloc[i]] df_to_be_mod.index = new_index df_to_be_mod.index.name = r'Student_Question_Index' return",
"+ r'-Language' self.df_lang_serialized = self.df_lang_serialized.rename( columns={r'Content' : new_lang_clm_name}) self.df_all_serialized = self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] =",
"new_data + [x.replace(rm_word, r\"\")] df_new_data = pd.DataFrame({column_to_be_mod : new_data}, index = df_to_be_mod.index) df_to_be_mod[column_to_be_mod]",
"pandas as pd import ac_column_serializer as clsr ''' Put a path file like",
"C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### ''' class column_serializer: ''' qid_csv_file_in is assumed to have the columns",
"key_word, new_question_clm_name) self.df_all_serialized = self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def columms_to_be_serialized(self,",
"new_index + [str(mod_index[i]) + r'-' + add_data.iloc[i]] df_to_be_mod.index = new_index df_to_be_mod.index.name = r'Student_Question_Index'",
"as clsr ''' Put a path file like \"plimac-custom.pth\" into any of your",
"column_to_be_mod): mod_data = df_to_be_mod[column_to_be_mod] new_data = [] for x in mod_data: new_data =",
"data_dir self.qid_csv_file_in = qid_csv_file_in def serialize_record(self, csv_file_in, key_word = r'Definition'): self.df_response_serialized = clsr.ac_column_serializer(self.data_dir",
"self.df_lang_serialized.rename( columns={r'Content' : new_lang_clm_name}) self.df_all_serialized = self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name]",
"df_to_be_mod[column_to_be_added] new_index = [] for i in range(len(mod_index)): new_index = new_index + [str(mod_index[i])",
"= clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', lang_columns) new_lang_clm_name = key_word + r'-Language' self.df_lang_serialized =",
"import pandas as pd import ac_column_serializer as clsr ''' Put a path file",
"in_columns: if key_word in x: ser_columns = ser_columns + [x] return ser_columns def",
"= self.df_score_serialized.rename( columns={r'Content' : new_score_clm_name}) lang_columns = self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir +",
"r'Student_Question_Index' return df_to_be_mod if __name__ == \"__main__\": cs = column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv',",
"__name__ == \"__main__\": cs = column_serializer(r'../data/') cs.serialize_record(r'Cleaned-Def-ELVA.PILOT.PRE-TEST (MODIFIED SCORES.Deidentified.11.19.17)12.13.2017.csv', r'Definition') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Def-ELVA.PILOT.PRE-TEST.csv',",
"__init__(self, data_dir=r'./', qid_csv_file_in = r'Questin_ID_Definition.csv'): self.data_dir = data_dir self.qid_csv_file_in = qid_csv_file_in def serialize_record(self,",
"df_file_in.columns ser_columns = [] for x in in_columns: if key_word in x: ser_columns",
"+ r'-Question' new_answer_clm_name = key_word + r'-Answer' self.df_response_serialized = self.df_response_serialized.rename( columns={r'Pre_Col_Name' : new_question_clm_name,",
"r\"\")] df_new_data = pd.DataFrame({column_to_be_mod : new_data}, index = df_to_be_mod.index) df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod] return",
"self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', lang_columns) new_lang_clm_name = key_word +",
"new_score_clm_name}) lang_columns = self.columms_to_be_serialized(csv_file_in, r'Language') self.df_lang_serialized = clsr.ac_column_serializer(self.data_dir + csv_file_in, 'Student_Index', lang_columns) new_lang_clm_name",
"self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized = self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized = self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized =",
"r'Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') cs.serialize_record(r'Cleaned-Sen-ELVA.PILOT.POST-TEST (MODIFIED SCORES.Deidentifed11.19.17)12.13.2017.csv', r'Sentence') cs.df_all_serialized.to_csv(r'../data/' + r'Serialized-Sen-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1') '''",
"pd.read_csv(self.data_dir + csv_file_in, encoding= 'latin1') in_columns = df_file_in.columns ser_columns = [] for x",
"a path file like \"plimac-custom.pth\" into any of your sys.path directories (e.g. C:/ProgramData/Anaconda3/Lib/site-packages).",
"+ csv_file_in, r'Student_Index', score_columns) new_score_clm_name = key_word + r'-Score' self.df_score_serialized = self.df_score_serialized.rename( columns={r'Content'",
"self.df_response_serialized.rename( columns={r'Pre_Col_Name' : new_question_clm_name, r'Content' : new_answer_clm_name}) score_columns = self.columms_to_be_serialized(csv_file_in, r'Score') self.df_score_serialized =",
"self.qid_csv_file_in = qid_csv_file_in def serialize_record(self, csv_file_in, key_word = r'Definition'): self.df_response_serialized = clsr.ac_column_serializer(self.data_dir +",
"the columns 'Question_ID' and 'Question' ''' def __init__(self, data_dir=r'./', qid_csv_file_in = r'Questin_ID_Definition.csv'): self.data_dir",
"class column_serializer: ''' qid_csv_file_in is assumed to have the columns 'Question_ID' and 'Question'",
"self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized = self.df_all_serialized.drop(score_columns, axis=1) self.df_all_serialized = self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized, r'-'",
"mod_index = df_to_be_mod.index add_data = df_to_be_mod[column_to_be_added] new_index = [] for i in range(len(mod_index)):",
": new_lang_clm_name}) self.df_all_serialized = self.df_response_serialized.copy() self.df_all_serialized[new_score_clm_name] = self.df_score_serialized[new_score_clm_name] self.df_all_serialized[new_lang_clm_name] = self.df_lang_serialized[new_lang_clm_name] self.df_all_serialized =",
"self.df_all_serialized.drop(lang_columns, axis=1) self.df_all_serialized = self.remove_word_from_clm_values(self.df_all_serialized, r'-' + key_word, new_question_clm_name) self.df_all_serialized = self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in,",
"key_word + r'-Score' self.df_score_serialized = self.df_score_serialized.rename( columns={r'Content' : new_score_clm_name}) lang_columns = self.columms_to_be_serialized(csv_file_in, r'Language')",
"= df_to_be_mod['Question_ID'] df_to_be_mod.index = original_index return df_to_be_mod def add_clm_values_to_index(self, df_to_be_mod, column_to_be_added): mod_index =",
"how='left') #df_to_be_mod['Question_ID_Sec'] = df_to_be_mod['Question_ID'] df_to_be_mod.index = original_index return df_to_be_mod def add_clm_values_to_index(self, df_to_be_mod, column_to_be_added):",
"[x.replace(rm_word, r\"\")] df_new_data = pd.DataFrame({column_to_be_mod : new_data}, index = df_to_be_mod.index) df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod]",
": new_data}, index = df_to_be_mod.index) df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod] return df_to_be_mod def add_questin_id(self, df_to_be_mod,",
"plimac-custom.pth ############################### # .pth file for the PLIMAC extension C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Lib C:/Users/macks/Documents/Research/ContentTextAnalysis/plimac/3.00/Tools ################################################### '''",
"df_file_in = df_file_in.rename(columns={'Question': column_to_be_matched}) original_index = df_to_be_mod.index df_to_be_mod = pd.merge(df_to_be_mod, df_file_in, on=column_to_be_matched, how='left')",
"x: ser_columns = ser_columns + [x] return ser_columns def remove_word_from_clm_values(self, df_to_be_mod, rm_word, column_to_be_mod):",
"r'-' + add_data.iloc[i]] df_to_be_mod.index = new_index df_to_be_mod.index.name = r'Student_Question_Index' return df_to_be_mod if __name__",
"encoding= 'latin1') in_columns = df_file_in.columns ser_columns = [] for x in in_columns: if",
"df_to_be_mod[column_to_be_mod] = df_new_data[column_to_be_mod] return df_to_be_mod def add_questin_id(self, df_to_be_mod, qid_csv_file_in, column_to_be_matched): df_file_in = pd.read_csv(self.data_dir",
"= self.add_questin_id(self.df_all_serialized, self.qid_csv_file_in, new_question_clm_name) self.df_all_serialized = self.add_clm_values_to_index(self.df_all_serialized, new_question_clm_name) def columms_to_be_serialized(self, csv_file_in, key_word): df_file_in"
] |
[
"from microbit import* import gc import micropython def mem_stat(): print('MEMORY STATS') gc.collect() micropython.mem_info()",
"print('MEMORY STATS') gc.collect() micropython.mem_info() print('Initial free: {} allocated: {}'.format( gc.mem_free(), gc.mem_alloc())) print('END OF",
"gc.mem_alloc())) print('END OF REPORT') sleep(500) mem_stat() # Output will be printed via serial",
"mem_stat(): print('MEMORY STATS') gc.collect() micropython.mem_info() print('Initial free: {} allocated: {}'.format( gc.mem_free(), gc.mem_alloc())) print('END",
"gc.collect() micropython.mem_info() print('Initial free: {} allocated: {}'.format( gc.mem_free(), gc.mem_alloc())) print('END OF REPORT') sleep(500)",
"def mem_stat(): print('MEMORY STATS') gc.collect() micropython.mem_info() print('Initial free: {} allocated: {}'.format( gc.mem_free(), gc.mem_alloc()))",
"print('END OF REPORT') sleep(500) mem_stat() # Output will be printed via serial (115200",
"import micropython def mem_stat(): print('MEMORY STATS') gc.collect() micropython.mem_info() print('Initial free: {} allocated: {}'.format(",
"micropython.mem_info() print('Initial free: {} allocated: {}'.format( gc.mem_free(), gc.mem_alloc())) print('END OF REPORT') sleep(500) mem_stat()",
"micropython def mem_stat(): print('MEMORY STATS') gc.collect() micropython.mem_info() print('Initial free: {} allocated: {}'.format( gc.mem_free(),",
"{} allocated: {}'.format( gc.mem_free(), gc.mem_alloc())) print('END OF REPORT') sleep(500) mem_stat() # Output will",
"import* import gc import micropython def mem_stat(): print('MEMORY STATS') gc.collect() micropython.mem_info() print('Initial free:",
"gc import micropython def mem_stat(): print('MEMORY STATS') gc.collect() micropython.mem_info() print('Initial free: {} allocated:",
"print('Initial free: {} allocated: {}'.format( gc.mem_free(), gc.mem_alloc())) print('END OF REPORT') sleep(500) mem_stat() #",
"OF REPORT') sleep(500) mem_stat() # Output will be printed via serial (115200 baud",
"{}'.format( gc.mem_free(), gc.mem_alloc())) print('END OF REPORT') sleep(500) mem_stat() # Output will be printed",
"import gc import micropython def mem_stat(): print('MEMORY STATS') gc.collect() micropython.mem_info() print('Initial free: {}",
"gc.mem_free(), gc.mem_alloc())) print('END OF REPORT') sleep(500) mem_stat() # Output will be printed via",
"REPORT') sleep(500) mem_stat() # Output will be printed via serial (115200 baud rate)",
"allocated: {}'.format( gc.mem_free(), gc.mem_alloc())) print('END OF REPORT') sleep(500) mem_stat() # Output will be",
"STATS') gc.collect() micropython.mem_info() print('Initial free: {} allocated: {}'.format( gc.mem_free(), gc.mem_alloc())) print('END OF REPORT')",
"free: {} allocated: {}'.format( gc.mem_free(), gc.mem_alloc())) print('END OF REPORT') sleep(500) mem_stat() # Output",
"microbit import* import gc import micropython def mem_stat(): print('MEMORY STATS') gc.collect() micropython.mem_info() print('Initial"
] |
[
"\"Location\") weather_intent = IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent) def get_intent(message): for intent",
"loc in locations: engine.register_entity(loc, \"Location\") weather_intent = IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent)",
".require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent) def get_intent(message): for intent in engine.determine_intent(message): if intent.get('confidence')",
"weather_keyword: engine.register_entity(wk, \"WeatherKeyword\") weather_types = [ \"snow\", \"rain\", \"wind\", \"sleet\", \"sun\" ] for",
"] for wt in weather_types: engine.register_entity(wt, \"WeatherType\") locations = [ \"Seattle\", \"San Francisco\",",
"adapt.engine import IntentDeterminationEngine engine = IntentDeterminationEngine() weather_keyword = [ \"weather\" ] for wk",
"\"wind\", \"sleet\", \"sun\" ] for wt in weather_types: engine.register_entity(wt, \"WeatherType\") locations = [",
"\"sleet\", \"sun\" ] for wt in weather_types: engine.register_entity(wt, \"WeatherType\") locations = [ \"Seattle\",",
"wt in weather_types: engine.register_entity(wt, \"WeatherType\") locations = [ \"Seattle\", \"San Francisco\", \"Tokyo\", \"Vancouver\"",
"IntentDeterminationEngine engine = IntentDeterminationEngine() weather_keyword = [ \"weather\" ] for wk in weather_keyword:",
"weather_types = [ \"snow\", \"rain\", \"wind\", \"sleet\", \"sun\" ] for wt in weather_types:",
"= [ \"Seattle\", \"San Francisco\", \"Tokyo\", \"Vancouver\" ] for loc in locations: engine.register_entity(loc,",
"= IntentDeterminationEngine() weather_keyword = [ \"weather\" ] for wk in weather_keyword: engine.register_entity(wk, \"WeatherKeyword\")",
"wk in weather_keyword: engine.register_entity(wk, \"WeatherKeyword\") weather_types = [ \"snow\", \"rain\", \"wind\", \"sleet\", \"sun\"",
"= [ \"weather\" ] for wk in weather_keyword: engine.register_entity(wk, \"WeatherKeyword\") weather_types = [",
"locations: engine.register_entity(loc, \"Location\") weather_intent = IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent) def get_intent(message):",
"weather_intent = IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent) def get_intent(message): for intent in",
"engine.register_intent_parser(weather_intent) def get_intent(message): for intent in engine.determine_intent(message): if intent.get('confidence') > 0: return intent",
"\"weather\" ] for wk in weather_keyword: engine.register_entity(wk, \"WeatherKeyword\") weather_types = [ \"snow\", \"rain\",",
"<filename>home/adapt.py from adapt.intent import IntentBuilder from adapt.engine import IntentDeterminationEngine engine = IntentDeterminationEngine() weather_keyword",
"= IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent) def get_intent(message): for intent in engine.determine_intent(message):",
"import IntentDeterminationEngine engine = IntentDeterminationEngine() weather_keyword = [ \"weather\" ] for wk in",
"[ \"snow\", \"rain\", \"wind\", \"sleet\", \"sun\" ] for wt in weather_types: engine.register_entity(wt, \"WeatherType\")",
"\"San Francisco\", \"Tokyo\", \"Vancouver\" ] for loc in locations: engine.register_entity(loc, \"Location\") weather_intent =",
"import IntentBuilder from adapt.engine import IntentDeterminationEngine engine = IntentDeterminationEngine() weather_keyword = [ \"weather\"",
"IntentBuilder from adapt.engine import IntentDeterminationEngine engine = IntentDeterminationEngine() weather_keyword = [ \"weather\" ]",
"locations = [ \"Seattle\", \"San Francisco\", \"Tokyo\", \"Vancouver\" ] for loc in locations:",
"engine.register_entity(loc, \"Location\") weather_intent = IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent) def get_intent(message): for",
"IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent) def get_intent(message): for intent in engine.determine_intent(message): if",
".require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent) def get_intent(message): for intent in engine.determine_intent(message): if intent.get('confidence') > 0:",
"= [ \"snow\", \"rain\", \"wind\", \"sleet\", \"sun\" ] for wt in weather_types: engine.register_entity(wt,",
"[ \"Seattle\", \"San Francisco\", \"Tokyo\", \"Vancouver\" ] for loc in locations: engine.register_entity(loc, \"Location\")",
"in locations: engine.register_entity(loc, \"Location\") weather_intent = IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent) def",
"from adapt.engine import IntentDeterminationEngine engine = IntentDeterminationEngine() weather_keyword = [ \"weather\" ] for",
"in weather_types: engine.register_entity(wt, \"WeatherType\") locations = [ \"Seattle\", \"San Francisco\", \"Tokyo\", \"Vancouver\" ]",
"for loc in locations: engine.register_entity(loc, \"Location\") weather_intent = IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build()",
".optionally(\"WeatherType\")\\ .require(\"Location\")\\ .build() engine.register_intent_parser(weather_intent) def get_intent(message): for intent in engine.determine_intent(message): if intent.get('confidence') >",
"from adapt.intent import IntentBuilder from adapt.engine import IntentDeterminationEngine engine = IntentDeterminationEngine() weather_keyword =",
"\"sun\" ] for wt in weather_types: engine.register_entity(wt, \"WeatherType\") locations = [ \"Seattle\", \"San",
"IntentDeterminationEngine() weather_keyword = [ \"weather\" ] for wk in weather_keyword: engine.register_entity(wk, \"WeatherKeyword\") weather_types",
"] for loc in locations: engine.register_entity(loc, \"Location\") weather_intent = IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\ .require(\"Location\")\\",
".build() engine.register_intent_parser(weather_intent) def get_intent(message): for intent in engine.determine_intent(message): if intent.get('confidence') > 0: return",
"engine.register_entity(wt, \"WeatherType\") locations = [ \"Seattle\", \"San Francisco\", \"Tokyo\", \"Vancouver\" ] for loc",
"[ \"weather\" ] for wk in weather_keyword: engine.register_entity(wk, \"WeatherKeyword\") weather_types = [ \"snow\",",
"\"WeatherType\") locations = [ \"Seattle\", \"San Francisco\", \"Tokyo\", \"Vancouver\" ] for loc in",
"\"snow\", \"rain\", \"wind\", \"sleet\", \"sun\" ] for wt in weather_types: engine.register_entity(wt, \"WeatherType\") locations",
"\"Vancouver\" ] for loc in locations: engine.register_entity(loc, \"Location\") weather_intent = IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\ .optionally(\"WeatherType\")\\",
"weather_keyword = [ \"weather\" ] for wk in weather_keyword: engine.register_entity(wk, \"WeatherKeyword\") weather_types =",
"engine.register_entity(wk, \"WeatherKeyword\") weather_types = [ \"snow\", \"rain\", \"wind\", \"sleet\", \"sun\" ] for wt",
"engine = IntentDeterminationEngine() weather_keyword = [ \"weather\" ] for wk in weather_keyword: engine.register_entity(wk,",
"Francisco\", \"Tokyo\", \"Vancouver\" ] for loc in locations: engine.register_entity(loc, \"Location\") weather_intent = IntentBuilder(\"WeatherIntent\")\\",
"\"Seattle\", \"San Francisco\", \"Tokyo\", \"Vancouver\" ] for loc in locations: engine.register_entity(loc, \"Location\") weather_intent",
"] for wk in weather_keyword: engine.register_entity(wk, \"WeatherKeyword\") weather_types = [ \"snow\", \"rain\", \"wind\",",
"\"Tokyo\", \"Vancouver\" ] for loc in locations: engine.register_entity(loc, \"Location\") weather_intent = IntentBuilder(\"WeatherIntent\")\\ .require(\"WeatherKeyword\")\\",
"for wt in weather_types: engine.register_entity(wt, \"WeatherType\") locations = [ \"Seattle\", \"San Francisco\", \"Tokyo\",",
"in weather_keyword: engine.register_entity(wk, \"WeatherKeyword\") weather_types = [ \"snow\", \"rain\", \"wind\", \"sleet\", \"sun\" ]",
"\"WeatherKeyword\") weather_types = [ \"snow\", \"rain\", \"wind\", \"sleet\", \"sun\" ] for wt in",
"weather_types: engine.register_entity(wt, \"WeatherType\") locations = [ \"Seattle\", \"San Francisco\", \"Tokyo\", \"Vancouver\" ] for",
"adapt.intent import IntentBuilder from adapt.engine import IntentDeterminationEngine engine = IntentDeterminationEngine() weather_keyword = [",
"\"rain\", \"wind\", \"sleet\", \"sun\" ] for wt in weather_types: engine.register_entity(wt, \"WeatherType\") locations =",
"for wk in weather_keyword: engine.register_entity(wk, \"WeatherKeyword\") weather_types = [ \"snow\", \"rain\", \"wind\", \"sleet\","
] |
[
"= [0., 0., 0., 1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0.7071, 0.7071] PRINT_TIME",
"= 1 CAMERA_DT = 0.05 KP = 0. KD = 0. INITIAL_POS_WORLD_TO_BASEJOINT =",
"INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0., 1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0.7071, 0.7071]",
"[0., 0., 0.7071, 0.7071] PRINT_TIME = False PRINT_ROBOT_INFO = False VIDEO_RECORD = False",
"0.05 KP = 0. KD = 0. INITIAL_POS_WORLD_TO_BASEJOINT = [0, 0, 1.5 -",
"KP = 0. KD = 0. INITIAL_POS_WORLD_TO_BASEJOINT = [0, 0, 1.5 - 0.761]",
"np class Config(object): CONTROLLER_DT = 0.001 N_SUBSTEP = 1 CAMERA_DT = 0.05 KP",
"class Config(object): CONTROLLER_DT = 0.001 N_SUBSTEP = 1 CAMERA_DT = 0.05 KP =",
"PRINT_TIME = False PRINT_ROBOT_INFO = False VIDEO_RECORD = False RECORD_FREQ = 10 SIMULATE_CAMERA",
"0., 0., 1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0.7071, 0.7071] PRINT_TIME = False",
"INITIAL_POS_WORLD_TO_BASEJOINT = [0, 0, 1.5 - 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0., 1.]",
"[0, 0, 1.5 - 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0., 1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT",
"False PRINT_ROBOT_INFO = False VIDEO_RECORD = False RECORD_FREQ = 10 SIMULATE_CAMERA = False",
"INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0.7071, 0.7071] PRINT_TIME = False PRINT_ROBOT_INFO = False VIDEO_RECORD",
"= 0.05 KP = 0. KD = 0. INITIAL_POS_WORLD_TO_BASEJOINT = [0, 0, 1.5",
"0.7071] PRINT_TIME = False PRINT_ROBOT_INFO = False VIDEO_RECORD = False RECORD_FREQ = 10",
"0.001 N_SUBSTEP = 1 CAMERA_DT = 0.05 KP = 0. KD = 0.",
"= [0., 0., 0.7071, 0.7071] PRINT_TIME = False PRINT_ROBOT_INFO = False VIDEO_RECORD =",
"= 0. INITIAL_POS_WORLD_TO_BASEJOINT = [0, 0, 1.5 - 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0.,",
"= 0. KD = 0. INITIAL_POS_WORLD_TO_BASEJOINT = [0, 0, 1.5 - 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT",
"0.7071, 0.7071] PRINT_TIME = False PRINT_ROBOT_INFO = False VIDEO_RECORD = False RECORD_FREQ =",
"1 CAMERA_DT = 0.05 KP = 0. KD = 0. INITIAL_POS_WORLD_TO_BASEJOINT = [0,",
"= [0, 0, 1.5 - 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0., 1.] #",
"# INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0.7071, 0.7071] PRINT_TIME = False PRINT_ROBOT_INFO = False",
"0, 1.5 - 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0., 1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT =",
"0. INITIAL_POS_WORLD_TO_BASEJOINT = [0, 0, 1.5 - 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0.,",
"Config(object): CONTROLLER_DT = 0.001 N_SUBSTEP = 1 CAMERA_DT = 0.05 KP = 0.",
"CAMERA_DT = 0.05 KP = 0. KD = 0. INITIAL_POS_WORLD_TO_BASEJOINT = [0, 0,",
"- 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0., 1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0.,",
"KD = 0. INITIAL_POS_WORLD_TO_BASEJOINT = [0, 0, 1.5 - 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT = [0.,",
"[0., 0., 0., 1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0.7071, 0.7071] PRINT_TIME =",
"0., 1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0.7071, 0.7071] PRINT_TIME = False PRINT_ROBOT_INFO",
"N_SUBSTEP = 1 CAMERA_DT = 0.05 KP = 0. KD = 0. INITIAL_POS_WORLD_TO_BASEJOINT",
"0. KD = 0. INITIAL_POS_WORLD_TO_BASEJOINT = [0, 0, 1.5 - 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT =",
"as np class Config(object): CONTROLLER_DT = 0.001 N_SUBSTEP = 1 CAMERA_DT = 0.05",
"0., 0.7071, 0.7071] PRINT_TIME = False PRINT_ROBOT_INFO = False VIDEO_RECORD = False RECORD_FREQ",
"0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0., 1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0.7071,",
"CONTROLLER_DT = 0.001 N_SUBSTEP = 1 CAMERA_DT = 0.05 KP = 0. KD",
"import numpy as np class Config(object): CONTROLLER_DT = 0.001 N_SUBSTEP = 1 CAMERA_DT",
"1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0.7071, 0.7071] PRINT_TIME = False PRINT_ROBOT_INFO =",
"numpy as np class Config(object): CONTROLLER_DT = 0.001 N_SUBSTEP = 1 CAMERA_DT =",
"= False PRINT_ROBOT_INFO = False VIDEO_RECORD = False RECORD_FREQ = 10 SIMULATE_CAMERA =",
"= 0.001 N_SUBSTEP = 1 CAMERA_DT = 0.05 KP = 0. KD =",
"1.5 - 0.761] INITIAL_QUAT_WORLD_TO_BASEJOINT = [0., 0., 0., 1.] # INITIAL_QUAT_WORLD_TO_BASEJOINT = [0.,"
] |
[
"04:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0002_alter_blogmodel_slug'),",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0002_alter_blogmodel_slug'), ]",
"by Django 3.2.9 on 2021-11-25 04:10 from django.db import migrations, models class Migration(migrations.Migration):",
"dependencies = [ ('home', '0002_alter_blogmodel_slug'), ] operations = [ migrations.AlterField( model_name='blogmodel', name='image', field=models.ImageField(upload_to='uploads'),",
"class Migration(migrations.Migration): dependencies = [ ('home', '0002_alter_blogmodel_slug'), ] operations = [ migrations.AlterField( model_name='blogmodel',",
"# Generated by Django 3.2.9 on 2021-11-25 04:10 from django.db import migrations, models",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0002_alter_blogmodel_slug'), ] operations",
"3.2.9 on 2021-11-25 04:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0002_alter_blogmodel_slug'), ] operations =",
"on 2021-11-25 04:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0002_alter_blogmodel_slug'), ] operations = [",
"models class Migration(migrations.Migration): dependencies = [ ('home', '0002_alter_blogmodel_slug'), ] operations = [ migrations.AlterField(",
"Generated by Django 3.2.9 on 2021-11-25 04:10 from django.db import migrations, models class",
"Django 3.2.9 on 2021-11-25 04:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"2021-11-25 04:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home',",
"Migration(migrations.Migration): dependencies = [ ('home', '0002_alter_blogmodel_slug'), ] operations = [ migrations.AlterField( model_name='blogmodel', name='image',",
"= [ ('home', '0002_alter_blogmodel_slug'), ] operations = [ migrations.AlterField( model_name='blogmodel', name='image', field=models.ImageField(upload_to='uploads'), ),",
"[ ('home', '0002_alter_blogmodel_slug'), ] operations = [ migrations.AlterField( model_name='blogmodel', name='image', field=models.ImageField(upload_to='uploads'), ), ]"
] |
[
"os from workflow.task import Task from workflow.utils.ansible import Ansible class Start(Task): def __init__(self,",
"import Task from workflow.utils.ansible import Ansible class Start(Task): def __init__(self, *args, **kwargs): self.cmd",
"Start(Task): def __init__(self, *args, **kwargs): self.cmd = kwargs.get('cmd') self.servers = kwargs.get('servers') def info(self):",
"self.servers = kwargs.get('servers') def info(self): self.logger.info('TaskName=Start') def exec(self): self.info() ansible = Ansible(inventory=self.servers['inventory'], connection='smart',",
"self.cmd = kwargs.get('cmd') self.servers = kwargs.get('servers') def info(self): self.logger.info('TaskName=Start') def exec(self): self.info() ansible",
"= kwargs.get('cmd') self.servers = kwargs.get('servers') def info(self): self.logger.info('TaskName=Start') def exec(self): self.info() ansible =",
"*args, **kwargs): self.cmd = kwargs.get('cmd') self.servers = kwargs.get('servers') def info(self): self.logger.info('TaskName=Start') def exec(self):",
"Task from workflow.utils.ansible import Ansible class Start(Task): def __init__(self, *args, **kwargs): self.cmd =",
"from workflow.task import Task from workflow.utils.ansible import Ansible class Start(Task): def __init__(self, *args,",
"class Start(Task): def __init__(self, *args, **kwargs): self.cmd = kwargs.get('cmd') self.servers = kwargs.get('servers') def",
"info(self): self.logger.info('TaskName=Start') def exec(self): self.info() ansible = Ansible(inventory=self.servers['inventory'], connection='smart', become=True, become_method='sudo') ansible.run(hosts=','.join(self.servers['hosts']), module='shell',",
"import Ansible class Start(Task): def __init__(self, *args, **kwargs): self.cmd = kwargs.get('cmd') self.servers =",
"kwargs.get('cmd') self.servers = kwargs.get('servers') def info(self): self.logger.info('TaskName=Start') def exec(self): self.info() ansible = Ansible(inventory=self.servers['inventory'],",
"__init__(self, *args, **kwargs): self.cmd = kwargs.get('cmd') self.servers = kwargs.get('servers') def info(self): self.logger.info('TaskName=Start') def",
"self.logger.info('TaskName=Start') def exec(self): self.info() ansible = Ansible(inventory=self.servers['inventory'], connection='smart', become=True, become_method='sudo') ansible.run(hosts=','.join(self.servers['hosts']), module='shell', args=self.cmd)",
"<gh_stars>1-10 import os from workflow.task import Task from workflow.utils.ansible import Ansible class Start(Task):",
"import os from workflow.task import Task from workflow.utils.ansible import Ansible class Start(Task): def",
"**kwargs): self.cmd = kwargs.get('cmd') self.servers = kwargs.get('servers') def info(self): self.logger.info('TaskName=Start') def exec(self): self.info()",
"workflow.task import Task from workflow.utils.ansible import Ansible class Start(Task): def __init__(self, *args, **kwargs):",
"Ansible class Start(Task): def __init__(self, *args, **kwargs): self.cmd = kwargs.get('cmd') self.servers = kwargs.get('servers')",
"from workflow.utils.ansible import Ansible class Start(Task): def __init__(self, *args, **kwargs): self.cmd = kwargs.get('cmd')",
"workflow.utils.ansible import Ansible class Start(Task): def __init__(self, *args, **kwargs): self.cmd = kwargs.get('cmd') self.servers",
"= kwargs.get('servers') def info(self): self.logger.info('TaskName=Start') def exec(self): self.info() ansible = Ansible(inventory=self.servers['inventory'], connection='smart', become=True,",
"kwargs.get('servers') def info(self): self.logger.info('TaskName=Start') def exec(self): self.info() ansible = Ansible(inventory=self.servers['inventory'], connection='smart', become=True, become_method='sudo')",
"def __init__(self, *args, **kwargs): self.cmd = kwargs.get('cmd') self.servers = kwargs.get('servers') def info(self): self.logger.info('TaskName=Start')",
"def info(self): self.logger.info('TaskName=Start') def exec(self): self.info() ansible = Ansible(inventory=self.servers['inventory'], connection='smart', become=True, become_method='sudo') ansible.run(hosts=','.join(self.servers['hosts']),",
"def exec(self): self.info() ansible = Ansible(inventory=self.servers['inventory'], connection='smart', become=True, become_method='sudo') ansible.run(hosts=','.join(self.servers['hosts']), module='shell', args=self.cmd) ansible.get_result()"
] |
[
"(hh * 3600)) / 60) ss = math.floor((seconds - (hh * 3600) -",
"60))) readable_time = f'{hh:02}:{mm:02}:{ss:02}' return readable_time if __name__ == '__main__': make_readable(0) make_readable(5) make_readable(60)",
"= math.floor(seconds / 3600) mm = math.floor((seconds - (hh * 3600)) / 60)",
"hh = math.floor(seconds / 3600) mm = math.floor((seconds - (hh * 3600)) /",
"readable_time = f'{hh:02}:{mm:02}:{ss:02}' return readable_time if __name__ == '__main__': make_readable(0) make_readable(5) make_readable(60) make_readable(86399)",
"3600) mm = math.floor((seconds - (hh * 3600)) / 60) ss = math.floor((seconds",
"60) ss = math.floor((seconds - (hh * 3600) - (mm * 60))) readable_time",
"ss = math.floor((seconds - (hh * 3600) - (mm * 60))) readable_time =",
"math.floor((seconds - (hh * 3600) - (mm * 60))) readable_time = f'{hh:02}:{mm:02}:{ss:02}' return",
"3600) - (mm * 60))) readable_time = f'{hh:02}:{mm:02}:{ss:02}' return readable_time if __name__ ==",
"mm = math.floor((seconds - (hh * 3600)) / 60) ss = math.floor((seconds -",
"import math def make_readable(seconds): hh = math.floor(seconds / 3600) mm = math.floor((seconds -",
"math.floor(seconds / 3600) mm = math.floor((seconds - (hh * 3600)) / 60) ss",
"= math.floor((seconds - (hh * 3600)) / 60) ss = math.floor((seconds - (hh",
"/ 60) ss = math.floor((seconds - (hh * 3600) - (mm * 60)))",
"def make_readable(seconds): hh = math.floor(seconds / 3600) mm = math.floor((seconds - (hh *",
"math def make_readable(seconds): hh = math.floor(seconds / 3600) mm = math.floor((seconds - (hh",
"make_readable(seconds): hh = math.floor(seconds / 3600) mm = math.floor((seconds - (hh * 3600))",
"* 3600) - (mm * 60))) readable_time = f'{hh:02}:{mm:02}:{ss:02}' return readable_time if __name__",
"= math.floor((seconds - (hh * 3600) - (mm * 60))) readable_time = f'{hh:02}:{mm:02}:{ss:02}'",
"= f'{hh:02}:{mm:02}:{ss:02}' return readable_time if __name__ == '__main__': make_readable(0) make_readable(5) make_readable(60) make_readable(86399) make_readable(359999)",
"- (hh * 3600) - (mm * 60))) readable_time = f'{hh:02}:{mm:02}:{ss:02}' return readable_time",
"3600)) / 60) ss = math.floor((seconds - (hh * 3600) - (mm *",
"* 3600)) / 60) ss = math.floor((seconds - (hh * 3600) - (mm",
"- (mm * 60))) readable_time = f'{hh:02}:{mm:02}:{ss:02}' return readable_time if __name__ == '__main__':",
"(hh * 3600) - (mm * 60))) readable_time = f'{hh:02}:{mm:02}:{ss:02}' return readable_time if",
"- (hh * 3600)) / 60) ss = math.floor((seconds - (hh * 3600)",
"(mm * 60))) readable_time = f'{hh:02}:{mm:02}:{ss:02}' return readable_time if __name__ == '__main__': make_readable(0)",
"/ 3600) mm = math.floor((seconds - (hh * 3600)) / 60) ss =",
"* 60))) readable_time = f'{hh:02}:{mm:02}:{ss:02}' return readable_time if __name__ == '__main__': make_readable(0) make_readable(5)",
"math.floor((seconds - (hh * 3600)) / 60) ss = math.floor((seconds - (hh *"
] |
[
"print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin))) # print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin) / 8)) count = 0 while(True):",
"utils import RTU_PERIOD_SEC from utils import IP # rtu2a tags from utils import",
"len(wadi1): {}'.format(len(wadi1))) # print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin))) # print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin) / 8)) count",
"/ 8)) count = 0 while(True): if count >= len(wadi1_bin): count = 0",
"time.sleep(sleep) def main_loop(self): \"\"\"rtu2a main loop. - challenge 1 \"\"\" # print('DEBUG: wadi1:",
"CO_1_2a, CO_2_2a, CO_3_2a from utils import HR_0_2a, HR_1_2a, HR_2_2a from utils import wadi1,",
"8)) count = 0 while(True): if count >= len(wadi1_bin): count = 0 if",
"= 0 while(True): if count >= len(wadi1_bin): count = 0 if wadi1_bin[count] ==",
"wadi1_bin import time RTU2A_ADDR = IP['rtu2a'] + ':502' RTU2B_ADDR = IP['rtu2b'] + ':502'",
"def main_loop(self): \"\"\"rtu2a main loop. - challenge 1 \"\"\" # print('DEBUG: wadi1: {}'.format(wadi1))",
"#self.send(CO_0_2a, False, RTU2A_ADDR) self.send(CO_0_2a, False, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(False,",
"= IP['scada'] + ':502' class RTU2a(RTU): def pre_loop(self, sleep=0.6): \"\"\"rtu2a pre loop. -",
"{}'.format(len(wadi1))) # print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin))) # print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin) / 8)) count =",
"import IP # rtu2a tags from utils import CO_0_2a, CO_1_2a, CO_2_2a, CO_3_2a from",
"co_0_2a = True if self.get(CO_0_2a) == '1' else False # print(\"DEBUG: rtu2a co_0_2a:",
"import time RTU2A_ADDR = IP['rtu2a'] + ':502' RTU2B_ADDR = IP['rtu2b'] + ':502' SCADA_ADDR",
"CO_2_2a, CO_3_2a from utils import HR_0_2a, HR_1_2a, HR_2_2a from utils import wadi1, wadi1_bin",
"print('DEBUG: wadi1_bin: {}'.format(wadi1_bin)) assert (len(wadi1_bin) / 8) == len(wadi1) # print('DEBUG: len(wadi1): {}'.format(len(wadi1)))",
"#self.send(CO_0_2a, True, RTU2A_ADDR) self.send(CO_0_2a, True, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(True,",
"count)) else: #self.send(CO_0_2a, False, RTU2A_ADDR) self.send(CO_0_2a, False, SCADA_ADDR) # print(\"DEBUG: rtu2a send {}",
"RTU2A_ADDR = IP['rtu2a'] + ':502' RTU2B_ADDR = IP['rtu2b'] + ':502' SCADA_ADDR = IP['scada']",
"rtu2a send {} count {}\".format(False, count)) count += 1 # NOTE: read sensors",
"print('DEBUG: wadi1: {}'.format(wadi1)) # print('DEBUG: wadi1_bin: {}'.format(wadi1_bin)) assert (len(wadi1_bin) / 8) == len(wadi1)",
"+= 1 # NOTE: read sensors # co_0_2a = True if self.get(CO_0_2a) ==",
"send {} count {}\".format(False, count)) count += 1 # NOTE: read sensors #",
"(len(wadi1_bin) / 8) == len(wadi1) # print('DEBUG: len(wadi1): {}'.format(len(wadi1))) # print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin)))",
"from utils import STATE, RTU2A_PROTOCOL from utils import RTU_PERIOD_SEC from utils import IP",
"HR_2_2a from utils import wadi1, wadi1_bin import time RTU2A_ADDR = IP['rtu2a'] + ':502'",
"- sleep \"\"\" time.sleep(sleep) def main_loop(self): \"\"\"rtu2a main loop. - challenge 1 \"\"\"",
"pre loop. - sleep \"\"\" time.sleep(sleep) def main_loop(self): \"\"\"rtu2a main loop. - challenge",
"# rtu2a tags from utils import CO_0_2a, CO_1_2a, CO_2_2a, CO_3_2a from utils import",
"RTU2A_ADDR) self.send(CO_0_2a, False, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(False, count)) count",
"False, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(False, count)) count += 1",
"count += 1 # NOTE: read sensors # co_0_2a = True if self.get(CO_0_2a)",
"\"\"\" rtu2a.py \"\"\" from minicps.devices import RTU from utils import STATE, RTU2A_PROTOCOL from",
"len(wadi1) # print('DEBUG: len(wadi1): {}'.format(len(wadi1))) # print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin))) # print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin)",
"8) == len(wadi1) # print('DEBUG: len(wadi1): {}'.format(len(wadi1))) # print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin))) # print('DEBUG:",
"from utils import IP # rtu2a tags from utils import CO_0_2a, CO_1_2a, CO_2_2a,",
"{}\".format(False, count)) count += 1 # NOTE: read sensors # co_0_2a = True",
"count {}\".format(False, count)) count += 1 # NOTE: read sensors # co_0_2a =",
"else: #self.send(CO_0_2a, False, RTU2A_ADDR) self.send(CO_0_2a, False, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count",
"SCADA_ADDR = IP['scada'] + ':502' class RTU2a(RTU): def pre_loop(self, sleep=0.6): \"\"\"rtu2a pre loop.",
"== '1': #self.send(CO_0_2a, True, RTU2A_ADDR) self.send(CO_0_2a, True, SCADA_ADDR) # print(\"DEBUG: rtu2a send {}",
"0 if wadi1_bin[count] == '1': #self.send(CO_0_2a, True, RTU2A_ADDR) self.send(CO_0_2a, True, SCADA_ADDR) # print(\"DEBUG:",
"rtu2a tags from utils import CO_0_2a, CO_1_2a, CO_2_2a, CO_3_2a from utils import HR_0_2a,",
"IP['rtu2b'] + ':502' SCADA_ADDR = IP['scada'] + ':502' class RTU2a(RTU): def pre_loop(self, sleep=0.6):",
"RTU from utils import STATE, RTU2A_PROTOCOL from utils import RTU_PERIOD_SEC from utils import",
"utils import STATE, RTU2A_PROTOCOL from utils import RTU_PERIOD_SEC from utils import IP #",
"0 while(True): if count >= len(wadi1_bin): count = 0 if wadi1_bin[count] == '1':",
"NOTE: read sensors # co_0_2a = True if self.get(CO_0_2a) == '1' else False",
"read sensors # co_0_2a = True if self.get(CO_0_2a) == '1' else False #",
"print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin) / 8)) count = 0 while(True): if count >= len(wadi1_bin):",
"print(\"DEBUG: self.receive co_0_2a: \\ # {}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) # print(\"DEBUG: rtu2a main loop\") time.sleep(RTU_PERIOD_SEC)",
"CO_0_2a, CO_1_2a, CO_2_2a, CO_3_2a from utils import HR_0_2a, HR_1_2a, HR_2_2a from utils import",
"self.send(CO_0_2a, True, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(True, count)) else: #self.send(CO_0_2a,",
"{} count {}\".format(False, count)) count += 1 # NOTE: read sensors # co_0_2a",
"= IP['rtu2b'] + ':502' SCADA_ADDR = IP['scada'] + ':502' class RTU2a(RTU): def pre_loop(self,",
"import HR_0_2a, HR_1_2a, HR_2_2a from utils import wadi1, wadi1_bin import time RTU2A_ADDR =",
"/ 8) == len(wadi1) # print('DEBUG: len(wadi1): {}'.format(len(wadi1))) # print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin))) #",
"HR_1_2a, HR_2_2a from utils import wadi1, wadi1_bin import time RTU2A_ADDR = IP['rtu2a'] +",
"main loop\") time.sleep(RTU_PERIOD_SEC) if __name__ == \"__main__\": rtu2a = RTU2a( name='rtu2a', state=STATE, protocol=RTU2A_PROTOCOL)",
"wadi1: {}'.format(wadi1)) # print('DEBUG: wadi1_bin: {}'.format(wadi1_bin)) assert (len(wadi1_bin) / 8) == len(wadi1) #",
"\"\"\"rtu2a main loop. - challenge 1 \"\"\" # print('DEBUG: wadi1: {}'.format(wadi1)) # print('DEBUG:",
"count)) count += 1 # NOTE: read sensors # co_0_2a = True if",
"import RTU_PERIOD_SEC from utils import IP # rtu2a tags from utils import CO_0_2a,",
"rtu2a.py \"\"\" from minicps.devices import RTU from utils import STATE, RTU2A_PROTOCOL from utils",
"# print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin))) # print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin) / 8)) count = 0",
"\"\"\"rtu2a pre loop. - sleep \"\"\" time.sleep(sleep) def main_loop(self): \"\"\"rtu2a main loop. -",
"main_loop(self): \"\"\"rtu2a main loop. - challenge 1 \"\"\" # print('DEBUG: wadi1: {}'.format(wadi1)) #",
"wadi1_bin[count] == '1': #self.send(CO_0_2a, True, RTU2A_ADDR) self.send(CO_0_2a, True, SCADA_ADDR) # print(\"DEBUG: rtu2a send",
"{}'.format(wadi1_bin)) assert (len(wadi1_bin) / 8) == len(wadi1) # print('DEBUG: len(wadi1): {}'.format(len(wadi1))) # print('DEBUG:",
"if self.get(CO_0_2a) == '1' else False # print(\"DEBUG: rtu2a co_0_2a: {}\".format(co_0_2a)) # print(\"DEBUG:",
"print(\"DEBUG: rtu2a send {} count {}\".format(True, count)) else: #self.send(CO_0_2a, False, RTU2A_ADDR) self.send(CO_0_2a, False,",
"STATE, RTU2A_PROTOCOL from utils import RTU_PERIOD_SEC from utils import IP # rtu2a tags",
"'1': #self.send(CO_0_2a, True, RTU2A_ADDR) self.send(CO_0_2a, True, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count",
"from minicps.devices import RTU from utils import STATE, RTU2A_PROTOCOL from utils import RTU_PERIOD_SEC",
"RTU2B_ADDR = IP['rtu2b'] + ':502' SCADA_ADDR = IP['scada'] + ':502' class RTU2a(RTU): def",
"class RTU2a(RTU): def pre_loop(self, sleep=0.6): \"\"\"rtu2a pre loop. - sleep \"\"\" time.sleep(sleep) def",
"# print(\"DEBUG: self.receive co_0_2a: \\ # {}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) # print(\"DEBUG: rtu2a main loop\")",
"\"\"\" # print('DEBUG: wadi1: {}'.format(wadi1)) # print('DEBUG: wadi1_bin: {}'.format(wadi1_bin)) assert (len(wadi1_bin) / 8)",
"+ ':502' class RTU2a(RTU): def pre_loop(self, sleep=0.6): \"\"\"rtu2a pre loop. - sleep \"\"\"",
"= True if self.get(CO_0_2a) == '1' else False # print(\"DEBUG: rtu2a co_0_2a: {}\".format(co_0_2a))",
"len(wadi1_bin)/8: {}'.format(len(wadi1_bin) / 8)) count = 0 while(True): if count >= len(wadi1_bin): count",
"sensors # co_0_2a = True if self.get(CO_0_2a) == '1' else False # print(\"DEBUG:",
"minicps.devices import RTU from utils import STATE, RTU2A_PROTOCOL from utils import RTU_PERIOD_SEC from",
"sleep=0.6): \"\"\"rtu2a pre loop. - sleep \"\"\" time.sleep(sleep) def main_loop(self): \"\"\"rtu2a main loop.",
"len(wadi1_bin): {}'.format(len(wadi1_bin))) # print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin) / 8)) count = 0 while(True): if",
"sleep \"\"\" time.sleep(sleep) def main_loop(self): \"\"\"rtu2a main loop. - challenge 1 \"\"\" #",
"send {} count {}\".format(True, count)) else: #self.send(CO_0_2a, False, RTU2A_ADDR) self.send(CO_0_2a, False, SCADA_ADDR) #",
"time RTU2A_ADDR = IP['rtu2a'] + ':502' RTU2B_ADDR = IP['rtu2b'] + ':502' SCADA_ADDR =",
"from utils import CO_0_2a, CO_1_2a, CO_2_2a, CO_3_2a from utils import HR_0_2a, HR_1_2a, HR_2_2a",
"else False # print(\"DEBUG: rtu2a co_0_2a: {}\".format(co_0_2a)) # print(\"DEBUG: self.receive co_0_2a: \\ #",
"utils import IP # rtu2a tags from utils import CO_0_2a, CO_1_2a, CO_2_2a, CO_3_2a",
"RTU_PERIOD_SEC from utils import IP # rtu2a tags from utils import CO_0_2a, CO_1_2a,",
"pre_loop(self, sleep=0.6): \"\"\"rtu2a pre loop. - sleep \"\"\" time.sleep(sleep) def main_loop(self): \"\"\"rtu2a main",
"\"\"\" time.sleep(sleep) def main_loop(self): \"\"\"rtu2a main loop. - challenge 1 \"\"\" # print('DEBUG:",
"- challenge 1 \"\"\" # print('DEBUG: wadi1: {}'.format(wadi1)) # print('DEBUG: wadi1_bin: {}'.format(wadi1_bin)) assert",
"main loop. - challenge 1 \"\"\" # print('DEBUG: wadi1: {}'.format(wadi1)) # print('DEBUG: wadi1_bin:",
"if wadi1_bin[count] == '1': #self.send(CO_0_2a, True, RTU2A_ADDR) self.send(CO_0_2a, True, SCADA_ADDR) # print(\"DEBUG: rtu2a",
"\\ # {}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) # print(\"DEBUG: rtu2a main loop\") time.sleep(RTU_PERIOD_SEC) if __name__ ==",
"utils import CO_0_2a, CO_1_2a, CO_2_2a, CO_3_2a from utils import HR_0_2a, HR_1_2a, HR_2_2a from",
"RTU2A_PROTOCOL from utils import RTU_PERIOD_SEC from utils import IP # rtu2a tags from",
"from utils import wadi1, wadi1_bin import time RTU2A_ADDR = IP['rtu2a'] + ':502' RTU2B_ADDR",
">= len(wadi1_bin): count = 0 if wadi1_bin[count] == '1': #self.send(CO_0_2a, True, RTU2A_ADDR) self.send(CO_0_2a,",
"utils import HR_0_2a, HR_1_2a, HR_2_2a from utils import wadi1, wadi1_bin import time RTU2A_ADDR",
"self.receive co_0_2a: \\ # {}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) # print(\"DEBUG: rtu2a main loop\") time.sleep(RTU_PERIOD_SEC) if",
"loop. - challenge 1 \"\"\" # print('DEBUG: wadi1: {}'.format(wadi1)) # print('DEBUG: wadi1_bin: {}'.format(wadi1_bin))",
"1 \"\"\" # print('DEBUG: wadi1: {}'.format(wadi1)) # print('DEBUG: wadi1_bin: {}'.format(wadi1_bin)) assert (len(wadi1_bin) /",
"':502' RTU2B_ADDR = IP['rtu2b'] + ':502' SCADA_ADDR = IP['scada'] + ':502' class RTU2a(RTU):",
"count = 0 if wadi1_bin[count] == '1': #self.send(CO_0_2a, True, RTU2A_ADDR) self.send(CO_0_2a, True, SCADA_ADDR)",
"\"\"\" from minicps.devices import RTU from utils import STATE, RTU2A_PROTOCOL from utils import",
"RTU2A_ADDR))) # print(\"DEBUG: rtu2a main loop\") time.sleep(RTU_PERIOD_SEC) if __name__ == \"__main__\": rtu2a =",
"# print('DEBUG: len(wadi1): {}'.format(len(wadi1))) # print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin))) # print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin) /",
"challenge 1 \"\"\" # print('DEBUG: wadi1: {}'.format(wadi1)) # print('DEBUG: wadi1_bin: {}'.format(wadi1_bin)) assert (len(wadi1_bin)",
"# NOTE: read sensors # co_0_2a = True if self.get(CO_0_2a) == '1' else",
"{}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) # print(\"DEBUG: rtu2a main loop\") time.sleep(RTU_PERIOD_SEC) if __name__ == \"__main__\": rtu2a",
"count = 0 while(True): if count >= len(wadi1_bin): count = 0 if wadi1_bin[count]",
"IP['rtu2a'] + ':502' RTU2B_ADDR = IP['rtu2b'] + ':502' SCADA_ADDR = IP['scada'] + ':502'",
"rtu2a send {} count {}\".format(True, count)) else: #self.send(CO_0_2a, False, RTU2A_ADDR) self.send(CO_0_2a, False, SCADA_ADDR)",
"# print(\"DEBUG: rtu2a send {} count {}\".format(False, count)) count += 1 # NOTE:",
"# print(\"DEBUG: rtu2a co_0_2a: {}\".format(co_0_2a)) # print(\"DEBUG: self.receive co_0_2a: \\ # {}\".format(self.receive(CO_0_2a, RTU2A_ADDR)))",
"print(\"DEBUG: rtu2a co_0_2a: {}\".format(co_0_2a)) # print(\"DEBUG: self.receive co_0_2a: \\ # {}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) #",
"import STATE, RTU2A_PROTOCOL from utils import RTU_PERIOD_SEC from utils import IP # rtu2a",
"def pre_loop(self, sleep=0.6): \"\"\"rtu2a pre loop. - sleep \"\"\" time.sleep(sleep) def main_loop(self): \"\"\"rtu2a",
"+ ':502' RTU2B_ADDR = IP['rtu2b'] + ':502' SCADA_ADDR = IP['scada'] + ':502' class",
"# co_0_2a = True if self.get(CO_0_2a) == '1' else False # print(\"DEBUG: rtu2a",
"self.get(CO_0_2a) == '1' else False # print(\"DEBUG: rtu2a co_0_2a: {}\".format(co_0_2a)) # print(\"DEBUG: self.receive",
"rtu2a main loop\") time.sleep(RTU_PERIOD_SEC) if __name__ == \"__main__\": rtu2a = RTU2a( name='rtu2a', state=STATE,",
"{}\".format(co_0_2a)) # print(\"DEBUG: self.receive co_0_2a: \\ # {}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) # print(\"DEBUG: rtu2a main",
"False, RTU2A_ADDR) self.send(CO_0_2a, False, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(False, count))",
"False # print(\"DEBUG: rtu2a co_0_2a: {}\".format(co_0_2a)) # print(\"DEBUG: self.receive co_0_2a: \\ # {}\".format(self.receive(CO_0_2a,",
"# {}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) # print(\"DEBUG: rtu2a main loop\") time.sleep(RTU_PERIOD_SEC) if __name__ == \"__main__\":",
"= 0 if wadi1_bin[count] == '1': #self.send(CO_0_2a, True, RTU2A_ADDR) self.send(CO_0_2a, True, SCADA_ADDR) #",
"True, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(True, count)) else: #self.send(CO_0_2a, False,",
"True, RTU2A_ADDR) self.send(CO_0_2a, True, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(True, count))",
"# print(\"DEBUG: rtu2a main loop\") time.sleep(RTU_PERIOD_SEC) if __name__ == \"__main__\": rtu2a = RTU2a(",
"if count >= len(wadi1_bin): count = 0 if wadi1_bin[count] == '1': #self.send(CO_0_2a, True,",
"loop. - sleep \"\"\" time.sleep(sleep) def main_loop(self): \"\"\"rtu2a main loop. - challenge 1",
"':502' SCADA_ADDR = IP['scada'] + ':502' class RTU2a(RTU): def pre_loop(self, sleep=0.6): \"\"\"rtu2a pre",
"= IP['rtu2a'] + ':502' RTU2B_ADDR = IP['rtu2b'] + ':502' SCADA_ADDR = IP['scada'] +",
"SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(True, count)) else: #self.send(CO_0_2a, False, RTU2A_ADDR)",
"print('DEBUG: len(wadi1): {}'.format(len(wadi1))) # print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin))) # print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin) / 8))",
"HR_0_2a, HR_1_2a, HR_2_2a from utils import wadi1, wadi1_bin import time RTU2A_ADDR = IP['rtu2a']",
"tags from utils import CO_0_2a, CO_1_2a, CO_2_2a, CO_3_2a from utils import HR_0_2a, HR_1_2a,",
"== '1' else False # print(\"DEBUG: rtu2a co_0_2a: {}\".format(co_0_2a)) # print(\"DEBUG: self.receive co_0_2a:",
"'1' else False # print(\"DEBUG: rtu2a co_0_2a: {}\".format(co_0_2a)) # print(\"DEBUG: self.receive co_0_2a: \\",
"# print(\"DEBUG: rtu2a send {} count {}\".format(True, count)) else: #self.send(CO_0_2a, False, RTU2A_ADDR) self.send(CO_0_2a,",
"co_0_2a: {}\".format(co_0_2a)) # print(\"DEBUG: self.receive co_0_2a: \\ # {}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) # print(\"DEBUG: rtu2a",
"import wadi1, wadi1_bin import time RTU2A_ADDR = IP['rtu2a'] + ':502' RTU2B_ADDR = IP['rtu2b']",
"import RTU from utils import STATE, RTU2A_PROTOCOL from utils import RTU_PERIOD_SEC from utils",
"== len(wadi1) # print('DEBUG: len(wadi1): {}'.format(len(wadi1))) # print('DEBUG: len(wadi1_bin): {}'.format(len(wadi1_bin))) # print('DEBUG: len(wadi1_bin)/8:",
"IP # rtu2a tags from utils import CO_0_2a, CO_1_2a, CO_2_2a, CO_3_2a from utils",
"self.send(CO_0_2a, False, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(False, count)) count +=",
"print(\"DEBUG: rtu2a send {} count {}\".format(False, count)) count += 1 # NOTE: read",
"# print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin) / 8)) count = 0 while(True): if count >=",
"count {}\".format(True, count)) else: #self.send(CO_0_2a, False, RTU2A_ADDR) self.send(CO_0_2a, False, SCADA_ADDR) # print(\"DEBUG: rtu2a",
"rtu2a co_0_2a: {}\".format(co_0_2a)) # print(\"DEBUG: self.receive co_0_2a: \\ # {}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) # print(\"DEBUG:",
"':502' class RTU2a(RTU): def pre_loop(self, sleep=0.6): \"\"\"rtu2a pre loop. - sleep \"\"\" time.sleep(sleep)",
"{}'.format(len(wadi1_bin))) # print('DEBUG: len(wadi1_bin)/8: {}'.format(len(wadi1_bin) / 8)) count = 0 while(True): if count",
"import CO_0_2a, CO_1_2a, CO_2_2a, CO_3_2a from utils import HR_0_2a, HR_1_2a, HR_2_2a from utils",
"co_0_2a: \\ # {}\".format(self.receive(CO_0_2a, RTU2A_ADDR))) # print(\"DEBUG: rtu2a main loop\") time.sleep(RTU_PERIOD_SEC) if __name__",
"CO_3_2a from utils import HR_0_2a, HR_1_2a, HR_2_2a from utils import wadi1, wadi1_bin import",
"assert (len(wadi1_bin) / 8) == len(wadi1) # print('DEBUG: len(wadi1): {}'.format(len(wadi1))) # print('DEBUG: len(wadi1_bin):",
"utils import wadi1, wadi1_bin import time RTU2A_ADDR = IP['rtu2a'] + ':502' RTU2B_ADDR =",
"1 # NOTE: read sensors # co_0_2a = True if self.get(CO_0_2a) == '1'",
"{}'.format(wadi1)) # print('DEBUG: wadi1_bin: {}'.format(wadi1_bin)) assert (len(wadi1_bin) / 8) == len(wadi1) # print('DEBUG:",
"+ ':502' SCADA_ADDR = IP['scada'] + ':502' class RTU2a(RTU): def pre_loop(self, sleep=0.6): \"\"\"rtu2a",
"IP['scada'] + ':502' class RTU2a(RTU): def pre_loop(self, sleep=0.6): \"\"\"rtu2a pre loop. - sleep",
"while(True): if count >= len(wadi1_bin): count = 0 if wadi1_bin[count] == '1': #self.send(CO_0_2a,",
"len(wadi1_bin): count = 0 if wadi1_bin[count] == '1': #self.send(CO_0_2a, True, RTU2A_ADDR) self.send(CO_0_2a, True,",
"RTU2a(RTU): def pre_loop(self, sleep=0.6): \"\"\"rtu2a pre loop. - sleep \"\"\" time.sleep(sleep) def main_loop(self):",
"print(\"DEBUG: rtu2a main loop\") time.sleep(RTU_PERIOD_SEC) if __name__ == \"__main__\": rtu2a = RTU2a( name='rtu2a',",
"{}'.format(len(wadi1_bin) / 8)) count = 0 while(True): if count >= len(wadi1_bin): count =",
"True if self.get(CO_0_2a) == '1' else False # print(\"DEBUG: rtu2a co_0_2a: {}\".format(co_0_2a)) #",
"wadi1, wadi1_bin import time RTU2A_ADDR = IP['rtu2a'] + ':502' RTU2B_ADDR = IP['rtu2b'] +",
"from utils import RTU_PERIOD_SEC from utils import IP # rtu2a tags from utils",
"# print('DEBUG: wadi1: {}'.format(wadi1)) # print('DEBUG: wadi1_bin: {}'.format(wadi1_bin)) assert (len(wadi1_bin) / 8) ==",
"from utils import HR_0_2a, HR_1_2a, HR_2_2a from utils import wadi1, wadi1_bin import time",
"{} count {}\".format(True, count)) else: #self.send(CO_0_2a, False, RTU2A_ADDR) self.send(CO_0_2a, False, SCADA_ADDR) # print(\"DEBUG:",
"wadi1_bin: {}'.format(wadi1_bin)) assert (len(wadi1_bin) / 8) == len(wadi1) # print('DEBUG: len(wadi1): {}'.format(len(wadi1))) #",
"count >= len(wadi1_bin): count = 0 if wadi1_bin[count] == '1': #self.send(CO_0_2a, True, RTU2A_ADDR)",
"SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(False, count)) count += 1 #",
"<reponame>pgaulon/minicps \"\"\" rtu2a.py \"\"\" from minicps.devices import RTU from utils import STATE, RTU2A_PROTOCOL",
"# print('DEBUG: wadi1_bin: {}'.format(wadi1_bin)) assert (len(wadi1_bin) / 8) == len(wadi1) # print('DEBUG: len(wadi1):",
"{}\".format(True, count)) else: #self.send(CO_0_2a, False, RTU2A_ADDR) self.send(CO_0_2a, False, SCADA_ADDR) # print(\"DEBUG: rtu2a send",
"RTU2A_ADDR) self.send(CO_0_2a, True, SCADA_ADDR) # print(\"DEBUG: rtu2a send {} count {}\".format(True, count)) else:"
] |
[
"levels to modes, from the lowerest to the highest for plevel in range(num_modes):",
"levels we need to decide num_modes=0 for itask in tasks: num_modes+=len(itask) for imode",
"for i in range(len(tasks)): ##ignore lower priority tasks if priortyassigned[i]==1: continue itask=tasks[i] canAssign=1",
"range(len(tasks)): ##ignore lower priority tasks if priortyassigned[i]==1: continue itask=tasks[i] canAssign=1 ## get higher",
"checking if this mode can be assigned to this priority level by QT",
"range(len(tasks)): if priortyassigned[j]==0 and i != j: primeTasks.append(tasks[j]) #print \"all :\",tasks #print \"task:\",itask",
"priority level is assigned imode['ifassigned']=False ### assign priority levels to modes, from the",
"imode['ifassigned']==True: continue ## checking if this mode can be assigned to this priority",
"priority tasks if priortyassigned[i]==1: continue itask=tasks[i] canAssign=1 ## get higher prioirty tasks primeTasks=[]",
"to this priority level by QT test if tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1 break else:",
"can be assigned at this priority level, return unscheduable if canAssign==0: return False",
"from __future__ import division import random import math import QT,DP def modeAudsley(tasks,scheme): ##",
"canLevel=0 ## check whether task i can be assigned with the priority level",
"import random import math import QT,DP def modeAudsley(tasks,scheme): ## to know how many",
"greedily assign the first mode feasible to this priority level if canAssign==1: break",
"from the lowerest to the highest for plevel in range(num_modes): ## check whether",
"canAssign=0 for i in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for imode in tasks[i]: ##ignore modes whose",
"get higher prioirty tasks primeTasks=[] for j in range(len(tasks)): if priortyassigned[j]==0 and i",
"imode['ifassigned']=False ### assign priority levels to modes, from the lowerest to the highest",
"canLevel=1 #print \"assign success at\",i break if canLevel == 0: return False return",
"== 'VRBL2-FPT': if QT.VRBL2(imode,primeTasks) == False: canAssign=0 break elif scheme == 'DT-FPT': if",
"modes for imode in itask: Tn=imode['period'] Un=imode['execution']/imode['period'] if scheme == 'QT-FPT': if QT.QT(imode,primeTasks)",
"whether task i can be assigned with the priority level plevel for i",
"plevel for i in range(len(tasks)): ##ignore lower priority tasks if priortyassigned[i]==1: continue itask=tasks[i]",
"if scheme == 'QT-FPT': if QT.QT(imode,primeTasks) == False: canAssign=0 break elif scheme ==",
"in range(len(tasks))] for plevel in range(len(tasks)): canLevel=0 ## check whether task i can",
"for imode in itask: ## put an attribute for each mode used as",
"for imode in tasks[i]: ##ignore modes whose priority levels have been decided if",
"priortyassigned[i]==1: continue itask=tasks[i] canAssign=1 ## get higher prioirty tasks primeTasks=[] for j in",
"been decided if imode['ifassigned']==True: continue ## checking if this mode can be assigned",
"primeTasks=tasks[:i]+tasks[i+1:] for imode in tasks[i]: ##ignore modes whose priority levels have been decided",
"plevel canAssign=0 for i in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for imode in tasks[i]: ##ignore modes",
"to this priority level if canAssign==1: break ## if none of the modes",
"## if none of the modes can be assigned at this priority level,",
"#print \"task:\",itask #print \"prime:\",primeTasks #print \"\" if len(primeTasks) ==0: priortyassigned[i]=1 canLevel=1 #print \"assign",
"tasks: num_modes+=len(itask) for imode in itask: ## put an attribute for each mode",
"!= j: primeTasks.append(tasks[j]) #print \"all :\",tasks #print \"task:\",itask #print \"prime:\",primeTasks #print \"\" if",
"this mode can be assigned to this priority level by QT test if",
"__future__ import division import random import math import QT,DP def modeAudsley(tasks,scheme): ## to",
"levels have been decided if imode['ifassigned']==True: continue ## checking if this mode can",
"assign the first mode feasible to this priority level if canAssign==1: break ##",
"all modes for imode in itask: Tn=imode['period'] Un=imode['execution']/imode['period'] if scheme == 'QT-FPT': if",
"level by QT test if tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1 break else: continue ## greedily",
"as an indicator for whether or not its priority level is assigned imode['ifassigned']=False",
"if QT.VRBL2(imode,primeTasks) == False: canAssign=0 break elif scheme == 'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned) ==",
"an indicator for whether or not its priority level is assigned imode['ifassigned']=False ###",
"whether task i can be assigned with the priority level plevel canAssign=0 for",
"'DT-FPT': DP.table_init(tasks) #Optimal Priority Assignment priortyassigned=[0 for i in range(len(tasks))] for plevel in",
"\"\" if len(primeTasks) ==0: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break ## check",
"plevel in range(len(tasks)): canLevel=0 ## check whether task i can be assigned with",
"##ignore lower priority tasks if priortyassigned[i]==1: continue itask=tasks[i] canAssign=1 ## get higher prioirty",
"'VRBL2-FPT': if QT.VRBL2(imode,primeTasks) == False: canAssign=0 break elif scheme == 'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned)",
"feasible to this priority level if canAssign==1: break ## if none of the",
"if QT.QT(imode,primeTasks) == False: canAssign=0 break elif scheme == 'VRBL2-FPT': if QT.VRBL2(imode,primeTasks) ==",
"know how many priority levels we need to decide num_modes=0 for itask in",
"## checking if this mode can be assigned to this priority level by",
"continue ## checking if this mode can be assigned to this priority level",
"\"task:\",itask #print \"prime:\",primeTasks #print \"\" if len(primeTasks) ==0: priortyassigned[i]=1 canLevel=1 #print \"assign success",
"of all modes for imode in itask: Tn=imode['period'] Un=imode['execution']/imode['period'] if scheme == 'QT-FPT':",
"imode['ifassigned']=True canAssign=1 break else: continue ## greedily assign the first mode feasible to",
"level plevel for i in range(len(tasks)): ##ignore lower priority tasks if priortyassigned[i]==1: continue",
"be assigned to this priority level by QT test if tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1",
"level, return unscheduable if canAssign==0: return False return True def Audsley(tasks,scheme): if scheme",
"to decide num_modes=0 for itask in tasks: num_modes+=len(itask) for imode in itask: ##",
"unscheduable if canAssign==0: return False return True def Audsley(tasks,scheme): if scheme == 'DT-FPT':",
"each mode used as an indicator for whether or not its priority level",
"i in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for imode in tasks[i]: ##ignore modes whose priority levels",
"task i can be assigned with the priority level plevel canAssign=0 for i",
"range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for imode in tasks[i]: ##ignore modes whose priority levels have been",
"## greedily assign the first mode feasible to this priority level if canAssign==1:",
"imode in itask: Tn=imode['period'] Un=imode['execution']/imode['period'] if scheme == 'QT-FPT': if QT.QT(imode,primeTasks) == False:",
"break ## if none of the modes can be assigned at this priority",
"## to know how many priority levels we need to decide num_modes=0 for",
"to modes, from the lowerest to the highest for plevel in range(num_modes): ##",
"modes, from the lowerest to the highest for plevel in range(num_modes): ## check",
"range(num_modes): ## check whether task i can be assigned with the priority level",
"prioirty tasks primeTasks=[] for j in range(len(tasks)): if priortyassigned[j]==0 and i != j:",
"be assigned with the priority level plevel canAssign=0 for i in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:]",
"else: sys.exit(0) if canAssign == 1: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break",
"priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break ## check feasiability of all modes",
"itask: ## put an attribute for each mode used as an indicator for",
"with the priority level plevel for i in range(len(tasks)): ##ignore lower priority tasks",
"primeTasks=[] for j in range(len(tasks)): if priortyassigned[j]==0 and i != j: primeTasks.append(tasks[j]) #print",
"in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for imode in tasks[i]: ##ignore modes whose priority levels have",
"priortyassigned=[0 for i in range(len(tasks))] for plevel in range(len(tasks)): canLevel=0 ## check whether",
"for plevel in range(len(tasks)): canLevel=0 ## check whether task i can be assigned",
"return True def Audsley(tasks,scheme): if scheme == 'DT-FPT': DP.table_init(tasks) #Optimal Priority Assignment priortyassigned=[0",
"division import random import math import QT,DP def modeAudsley(tasks,scheme): ## to know how",
"Tn=imode['period'] Un=imode['execution']/imode['period'] if scheme == 'QT-FPT': if QT.QT(imode,primeTasks) == False: canAssign=0 break elif",
"priority levels to modes, from the lowerest to the highest for plevel in",
"the first mode feasible to this priority level if canAssign==1: break ## if",
"success at\",i break ## check feasiability of all modes for imode in itask:",
"used as an indicator for whether or not its priority level is assigned",
"the highest for plevel in range(num_modes): ## check whether task i can be",
"assigned to this priority level by QT test if tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1 break",
"the modes can be assigned at this priority level, return unscheduable if canAssign==0:",
"i in range(len(tasks))] for plevel in range(len(tasks)): canLevel=0 ## check whether task i",
"in itask: Tn=imode['period'] Un=imode['execution']/imode['period'] if scheme == 'QT-FPT': if QT.QT(imode,primeTasks) == False: canAssign=0",
"in tasks: num_modes+=len(itask) for imode in itask: ## put an attribute for each",
"none of the modes can be assigned at this priority level, return unscheduable",
"QT.QT(imode,primeTasks) == False: canAssign=0 break elif scheme == 'VRBL2-FPT': if QT.VRBL2(imode,primeTasks) == False:",
"QT.VRBL2(imode,primeTasks) == False: canAssign=0 break elif scheme == 'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned) == False:",
"check whether task i can be assigned with the priority level plevel canAssign=0",
"for i in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for imode in tasks[i]: ##ignore modes whose priority",
"this priority level by QT test if tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1 break else: continue",
"priority level, return unscheduable if canAssign==0: return False return True def Audsley(tasks,scheme): if",
"itask: Tn=imode['period'] Un=imode['execution']/imode['period'] if scheme == 'QT-FPT': if QT.QT(imode,primeTasks) == False: canAssign=0 break",
"be assigned at this priority level, return unscheduable if canAssign==0: return False return",
"lowerest to the highest for plevel in range(num_modes): ## check whether task i",
"by QT test if tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1 break else: continue ## greedily assign",
"if scheme == 'DT-FPT': DP.table_init(tasks) #Optimal Priority Assignment priortyassigned=[0 for i in range(len(tasks))]",
"lower priority tasks if priortyassigned[i]==1: continue itask=tasks[i] canAssign=1 ## get higher prioirty tasks",
"i can be assigned with the priority level plevel for i in range(len(tasks)):",
"math import QT,DP def modeAudsley(tasks,scheme): ## to know how many priority levels we",
"canAssign=0 break elif scheme == 'VRBL2-FPT': if QT.VRBL2(imode,primeTasks) == False: canAssign=0 break elif",
"many priority levels we need to decide num_modes=0 for itask in tasks: num_modes+=len(itask)",
"assigned with the priority level plevel for i in range(len(tasks)): ##ignore lower priority",
"QT,DP def modeAudsley(tasks,scheme): ## to know how many priority levels we need to",
"to know how many priority levels we need to decide num_modes=0 for itask",
"of the modes can be assigned at this priority level, return unscheduable if",
"#print \"prime:\",primeTasks #print \"\" if len(primeTasks) ==0: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i",
"imode in itask: ## put an attribute for each mode used as an",
"feasiability of all modes for imode in itask: Tn=imode['period'] Un=imode['execution']/imode['period'] if scheme ==",
"imode in tasks[i]: ##ignore modes whose priority levels have been decided if imode['ifassigned']==True:",
"import math import QT,DP def modeAudsley(tasks,scheme): ## to know how many priority levels",
"in itask: ## put an attribute for each mode used as an indicator",
"mode used as an indicator for whether or not its priority level is",
"mode can be assigned to this priority level by QT test if tests.modeQT(imode,primeTasks):",
"in range(len(tasks)): ##ignore lower priority tasks if priortyassigned[i]==1: continue itask=tasks[i] canAssign=1 ## get",
"i != j: primeTasks.append(tasks[j]) #print \"all :\",tasks #print \"task:\",itask #print \"prime:\",primeTasks #print \"\"",
"import QT,DP def modeAudsley(tasks,scheme): ## to know how many priority levels we need",
"len(primeTasks) ==0: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break ## check feasiability of",
"== False: canAssign=0 break else: sys.exit(0) if canAssign == 1: priortyassigned[i]=1 canLevel=1 #print",
"True def Audsley(tasks,scheme): if scheme == 'DT-FPT': DP.table_init(tasks) #Optimal Priority Assignment priortyassigned=[0 for",
"'QT-FPT': if QT.QT(imode,primeTasks) == False: canAssign=0 break elif scheme == 'VRBL2-FPT': if QT.VRBL2(imode,primeTasks)",
"## put an attribute for each mode used as an indicator for whether",
"range(len(tasks))] for plevel in range(len(tasks)): canLevel=0 ## check whether task i can be",
"canLevel=1 #print \"assign success at\",i break ## check feasiability of all modes for",
"scheme == 'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned) == False: canAssign=0 break else: sys.exit(0) if canAssign",
"higher prioirty tasks primeTasks=[] for j in range(len(tasks)): if priortyassigned[j]==0 and i !=",
"itask=tasks[i] canAssign=1 ## get higher prioirty tasks primeTasks=[] for j in range(len(tasks)): if",
"== False: canAssign=0 break elif scheme == 'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned) == False: canAssign=0",
"not its priority level is assigned imode['ifassigned']=False ### assign priority levels to modes,",
"this priority level if canAssign==1: break ## if none of the modes can",
"break ## check feasiability of all modes for imode in itask: Tn=imode['period'] Un=imode['execution']/imode['period']",
"canAssign=0 break elif scheme == 'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned) == False: canAssign=0 break else:",
"mode feasible to this priority level if canAssign==1: break ## if none of",
"with the priority level plevel canAssign=0 for i in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for imode",
"elif scheme == 'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned) == False: canAssign=0 break else: sys.exit(0) if",
"modes can be assigned at this priority level, return unscheduable if canAssign==0: return",
"Assignment priortyassigned=[0 for i in range(len(tasks))] for plevel in range(len(tasks)): canLevel=0 ## check",
"tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1 break else: continue ## greedily assign the first mode feasible",
"def Audsley(tasks,scheme): if scheme == 'DT-FPT': DP.table_init(tasks) #Optimal Priority Assignment priortyassigned=[0 for i",
"== False: canAssign=0 break elif scheme == 'VRBL2-FPT': if QT.VRBL2(imode,primeTasks) == False: canAssign=0",
"scheme == 'VRBL2-FPT': if QT.VRBL2(imode,primeTasks) == False: canAssign=0 break elif scheme == 'DT-FPT':",
"whether or not its priority level is assigned imode['ifassigned']=False ### assign priority levels",
"== 'QT-FPT': if QT.QT(imode,primeTasks) == False: canAssign=0 break elif scheme == 'VRBL2-FPT': if",
"if canAssign == 1: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break if canLevel",
"highest for plevel in range(num_modes): ## check whether task i can be assigned",
"Priority Assignment priortyassigned=[0 for i in range(len(tasks))] for plevel in range(len(tasks)): canLevel=0 ##",
"priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break if canLevel == 0: return False",
"priority level plevel for i in range(len(tasks)): ##ignore lower priority tasks if priortyassigned[i]==1:",
"level is assigned imode['ifassigned']=False ### assign priority levels to modes, from the lowerest",
"level if canAssign==1: break ## if none of the modes can be assigned",
"have been decided if imode['ifassigned']==True: continue ## checking if this mode can be",
"==0: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break ## check feasiability of all",
"to the highest for plevel in range(num_modes): ## check whether task i can",
"can be assigned with the priority level plevel canAssign=0 for i in range(len(tasks)):",
"break else: sys.exit(0) if canAssign == 1: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i",
"priority level by QT test if tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1 break else: continue ##",
"check feasiability of all modes for imode in itask: Tn=imode['period'] Un=imode['execution']/imode['period'] if scheme",
"the lowerest to the highest for plevel in range(num_modes): ## check whether task",
"assigned imode['ifassigned']=False ### assign priority levels to modes, from the lowerest to the",
"##ignore modes whose priority levels have been decided if imode['ifassigned']==True: continue ## checking",
"tasks primeTasks=[] for j in range(len(tasks)): if priortyassigned[j]==0 and i != j: primeTasks.append(tasks[j])",
"for plevel in range(num_modes): ## check whether task i can be assigned with",
"assigned at this priority level, return unscheduable if canAssign==0: return False return True",
"for each mode used as an indicator for whether or not its priority",
"## get higher prioirty tasks primeTasks=[] for j in range(len(tasks)): if priortyassigned[j]==0 and",
":\",tasks #print \"task:\",itask #print \"prime:\",primeTasks #print \"\" if len(primeTasks) ==0: priortyassigned[i]=1 canLevel=1 #print",
"at\",i break ## check feasiability of all modes for imode in itask: Tn=imode['period']",
"continue itask=tasks[i] canAssign=1 ## get higher prioirty tasks primeTasks=[] for j in range(len(tasks)):",
"canAssign=0 break else: sys.exit(0) if canAssign == 1: priortyassigned[i]=1 canLevel=1 #print \"assign success",
"the priority level plevel for i in range(len(tasks)): ##ignore lower priority tasks if",
"Un=imode['execution']/imode['period'] if scheme == 'QT-FPT': if QT.QT(imode,primeTasks) == False: canAssign=0 break elif scheme",
"## check whether task i can be assigned with the priority level plevel",
"canAssign=1 break else: continue ## greedily assign the first mode feasible to this",
"in range(len(tasks)): canLevel=0 ## check whether task i can be assigned with the",
"## check feasiability of all modes for imode in itask: Tn=imode['period'] Un=imode['execution']/imode['period'] if",
"if canAssign==1: break ## if none of the modes can be assigned at",
"can be assigned with the priority level plevel for i in range(len(tasks)): ##ignore",
"elif scheme == 'VRBL2-FPT': if QT.VRBL2(imode,primeTasks) == False: canAssign=0 break elif scheme ==",
"False: canAssign=0 break elif scheme == 'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned) == False: canAssign=0 break",
"1: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break if canLevel == 0: return",
"return unscheduable if canAssign==0: return False return True def Audsley(tasks,scheme): if scheme ==",
"== 'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned) == False: canAssign=0 break else: sys.exit(0) if canAssign ==",
"decided if imode['ifassigned']==True: continue ## checking if this mode can be assigned to",
"random import math import QT,DP def modeAudsley(tasks,scheme): ## to know how many priority",
"if canAssign==0: return False return True def Audsley(tasks,scheme): if scheme == 'DT-FPT': DP.table_init(tasks)",
"how many priority levels we need to decide num_modes=0 for itask in tasks:",
"assign priority levels to modes, from the lowerest to the highest for plevel",
"this priority level, return unscheduable if canAssign==0: return False return True def Audsley(tasks,scheme):",
"'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned) == False: canAssign=0 break else: sys.exit(0) if canAssign == 1:",
"#print \"\" if len(primeTasks) ==0: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break ##",
"#print \"assign success at\",i break if canLevel == 0: return False return True",
"False: canAssign=0 break else: sys.exit(0) if canAssign == 1: priortyassigned[i]=1 canLevel=1 #print \"assign",
"i can be assigned with the priority level plevel canAssign=0 for i in",
"if len(primeTasks) ==0: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break ## check feasiability",
"sys.exit(0) if canAssign == 1: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break if",
"tasks if priortyassigned[i]==1: continue itask=tasks[i] canAssign=1 ## get higher prioirty tasks primeTasks=[] for",
"priority level plevel canAssign=0 for i in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for imode in tasks[i]:",
"num_modes+=len(itask) for imode in itask: ## put an attribute for each mode used",
"if imode['ifassigned']==True: continue ## checking if this mode can be assigned to this",
"False return True def Audsley(tasks,scheme): if scheme == 'DT-FPT': DP.table_init(tasks) #Optimal Priority Assignment",
"at this priority level, return unscheduable if canAssign==0: return False return True def",
"primeTasks.append(tasks[j]) #print \"all :\",tasks #print \"task:\",itask #print \"prime:\",primeTasks #print \"\" if len(primeTasks) ==0:",
"if none of the modes can be assigned at this priority level, return",
"in tasks[i]: ##ignore modes whose priority levels have been decided if imode['ifassigned']==True: continue",
"scheme == 'QT-FPT': if QT.QT(imode,primeTasks) == False: canAssign=0 break elif scheme == 'VRBL2-FPT':",
"need to decide num_modes=0 for itask in tasks: num_modes+=len(itask) for imode in itask:",
"is assigned imode['ifassigned']=False ### assign priority levels to modes, from the lowerest to",
"j in range(len(tasks)): if priortyassigned[j]==0 and i != j: primeTasks.append(tasks[j]) #print \"all :\",tasks",
"the priority level plevel canAssign=0 for i in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for imode in",
"continue ## greedily assign the first mode feasible to this priority level if",
"in range(num_modes): ## check whether task i can be assigned with the priority",
"#print \"assign success at\",i break ## check feasiability of all modes for imode",
"for j in range(len(tasks)): if priortyassigned[j]==0 and i != j: primeTasks.append(tasks[j]) #print \"all",
"Audsley(tasks,scheme): if scheme == 'DT-FPT': DP.table_init(tasks) #Optimal Priority Assignment priortyassigned=[0 for i in",
"i in range(len(tasks)): ##ignore lower priority tasks if priortyassigned[i]==1: continue itask=tasks[i] canAssign=1 ##",
"j: primeTasks.append(tasks[j]) #print \"all :\",tasks #print \"task:\",itask #print \"prime:\",primeTasks #print \"\" if len(primeTasks)",
"False: canAssign=0 break elif scheme == 'VRBL2-FPT': if QT.VRBL2(imode,primeTasks) == False: canAssign=0 break",
"check whether task i can be assigned with the priority level plevel for",
"we need to decide num_modes=0 for itask in tasks: num_modes+=len(itask) for imode in",
"for whether or not its priority level is assigned imode['ifassigned']=False ### assign priority",
"indicator for whether or not its priority level is assigned imode['ifassigned']=False ### assign",
"in range(len(tasks)): if priortyassigned[j]==0 and i != j: primeTasks.append(tasks[j]) #print \"all :\",tasks #print",
"priority levels have been decided if imode['ifassigned']==True: continue ## checking if this mode",
"an attribute for each mode used as an indicator for whether or not",
"if tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1 break else: continue ## greedily assign the first mode",
"<gh_stars>0 from __future__ import division import random import math import QT,DP def modeAudsley(tasks,scheme):",
"== 1: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break if canLevel == 0:",
"task i can be assigned with the priority level plevel for i in",
"canAssign == 1: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break if canLevel ==",
"else: continue ## greedily assign the first mode feasible to this priority level",
"first mode feasible to this priority level if canAssign==1: break ## if none",
"for imode in itask: Tn=imode['period'] Un=imode['execution']/imode['period'] if scheme == 'QT-FPT': if QT.QT(imode,primeTasks) ==",
"test if tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1 break else: continue ## greedily assign the first",
"modeAudsley(tasks,scheme): ## to know how many priority levels we need to decide num_modes=0",
"if priortyassigned[j]==0 and i != j: primeTasks.append(tasks[j]) #print \"all :\",tasks #print \"task:\",itask #print",
"scheme == 'DT-FPT': DP.table_init(tasks) #Optimal Priority Assignment priortyassigned=[0 for i in range(len(tasks))] for",
"canAssign==0: return False return True def Audsley(tasks,scheme): if scheme == 'DT-FPT': DP.table_init(tasks) #Optimal",
"break elif scheme == 'VRBL2-FPT': if QT.VRBL2(imode,primeTasks) == False: canAssign=0 break elif scheme",
"range(len(tasks)): canLevel=0 ## check whether task i can be assigned with the priority",
"or not its priority level is assigned imode['ifassigned']=False ### assign priority levels to",
"canAssign==1: break ## if none of the modes can be assigned at this",
"break else: continue ## greedily assign the first mode feasible to this priority",
"return False return True def Audsley(tasks,scheme): if scheme == 'DT-FPT': DP.table_init(tasks) #Optimal Priority",
"for itask in tasks: num_modes+=len(itask) for imode in itask: ## put an attribute",
"QT test if tests.modeQT(imode,primeTasks): imode['ifassigned']=True canAssign=1 break else: continue ## greedily assign the",
"def modeAudsley(tasks,scheme): ## to know how many priority levels we need to decide",
"priority level if canAssign==1: break ## if none of the modes can be",
"== 'DT-FPT': DP.table_init(tasks) #Optimal Priority Assignment priortyassigned=[0 for i in range(len(tasks))] for plevel",
"priortyassigned[j]==0 and i != j: primeTasks.append(tasks[j]) #print \"all :\",tasks #print \"task:\",itask #print \"prime:\",primeTasks",
"whose priority levels have been decided if imode['ifassigned']==True: continue ## checking if this",
"put an attribute for each mode used as an indicator for whether or",
"and i != j: primeTasks.append(tasks[j]) #print \"all :\",tasks #print \"task:\",itask #print \"prime:\",primeTasks #print",
"\"all :\",tasks #print \"task:\",itask #print \"prime:\",primeTasks #print \"\" if len(primeTasks) ==0: priortyassigned[i]=1 canLevel=1",
"priority levels we need to decide num_modes=0 for itask in tasks: num_modes+=len(itask) for",
"### assign priority levels to modes, from the lowerest to the highest for",
"DP.table_init(tasks) #Optimal Priority Assignment priortyassigned=[0 for i in range(len(tasks))] for plevel in range(len(tasks)):",
"for i in range(len(tasks))] for plevel in range(len(tasks)): canLevel=0 ## check whether task",
"break elif scheme == 'DT-FPT': if DP.DTest(i,tasks,imode,priortyassigned) == False: canAssign=0 break else: sys.exit(0)",
"attribute for each mode used as an indicator for whether or not its",
"num_modes=0 for itask in tasks: num_modes+=len(itask) for imode in itask: ## put an",
"#Optimal Priority Assignment priortyassigned=[0 for i in range(len(tasks))] for plevel in range(len(tasks)): canLevel=0",
"if DP.DTest(i,tasks,imode,priortyassigned) == False: canAssign=0 break else: sys.exit(0) if canAssign == 1: priortyassigned[i]=1",
"modes whose priority levels have been decided if imode['ifassigned']==True: continue ## checking if",
"be assigned with the priority level plevel for i in range(len(tasks)): ##ignore lower",
"\"assign success at\",i break ## check feasiability of all modes for imode in",
"import division import random import math import QT,DP def modeAudsley(tasks,scheme): ## to know",
"\"prime:\",primeTasks #print \"\" if len(primeTasks) ==0: priortyassigned[i]=1 canLevel=1 #print \"assign success at\",i break",
"if this mode can be assigned to this priority level by QT test",
"itask in tasks: num_modes+=len(itask) for imode in itask: ## put an attribute for",
"level plevel canAssign=0 for i in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for imode in tasks[i]: ##ignore",
"canAssign=1 ## get higher prioirty tasks primeTasks=[] for j in range(len(tasks)): if priortyassigned[j]==0",
"DP.DTest(i,tasks,imode,priortyassigned) == False: canAssign=0 break else: sys.exit(0) if canAssign == 1: priortyassigned[i]=1 canLevel=1",
"can be assigned to this priority level by QT test if tests.modeQT(imode,primeTasks): imode['ifassigned']=True",
"assigned with the priority level plevel canAssign=0 for i in range(len(tasks)): primeTasks=tasks[:i]+tasks[i+1:] for",
"tasks[i]: ##ignore modes whose priority levels have been decided if imode['ifassigned']==True: continue ##",
"its priority level is assigned imode['ifassigned']=False ### assign priority levels to modes, from",
"#print \"all :\",tasks #print \"task:\",itask #print \"prime:\",primeTasks #print \"\" if len(primeTasks) ==0: priortyassigned[i]=1",
"decide num_modes=0 for itask in tasks: num_modes+=len(itask) for imode in itask: ## put",
"if priortyassigned[i]==1: continue itask=tasks[i] canAssign=1 ## get higher prioirty tasks primeTasks=[] for j",
"plevel in range(num_modes): ## check whether task i can be assigned with the"
] |
[
"the dev() and hydroProjector() of the vectors if measuring # angle from deviatoric",
"dot v)/(||u|| dot ||v||)) switch_type = { 1: 2, #Stress 2: 0.5, #Strain",
"} factor = switch_type.get(type, 'Invalid type') angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees #else: #angle",
"of the vectors if measuring # angle from deviatoric view # #if vec1.shape",
"def vectorAngle(vec1, vec2, type): # First take the dev() and hydroProjector() of the",
"cos-1((u dot v)/(||u|| dot ||v||)) switch_type = { 1: 2, #Stress 2: 0.5,",
"(6,1) or vec1.shape(6,) or vec1.shape == (1,6): #theta = cos-1((u dot v)/(||u|| dot",
"#Stress 2: 0.5, #Strain 3: 1 #Stress Strain } factor = switch_type.get(type, 'Invalid",
"0.5, #Strain 3: 1 #Stress Strain } factor = switch_type.get(type, 'Invalid type') angle",
"or vec1.shape == (1,6): #theta = cos-1((u dot v)/(||u|| dot ||v||)) switch_type =",
"angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees #else: #angle = 'Incorrect input vector shape' return",
"deviatoric view # #if vec1.shape == (6,1) or vec1.shape(6,) or vec1.shape == (1,6):",
"First take the dev() and hydroProjector() of the vectors if measuring # angle",
"<gh_stars>0 def vectorAngle(vec1, vec2, type): # First take the dev() and hydroProjector() of",
"vec1.shape == (1,6): #theta = cos-1((u dot v)/(||u|| dot ||v||)) switch_type = {",
"vectors if measuring # angle from deviatoric view # #if vec1.shape == (6,1)",
"2, #Stress 2: 0.5, #Strain 3: 1 #Stress Strain } factor = switch_type.get(type,",
"and hydroProjector() of the vectors if measuring # angle from deviatoric view #",
"v)/(||u|| dot ||v||)) switch_type = { 1: 2, #Stress 2: 0.5, #Strain 3:",
"# #if vec1.shape == (6,1) or vec1.shape(6,) or vec1.shape == (1,6): #theta =",
"== (6,1) or vec1.shape(6,) or vec1.shape == (1,6): #theta = cos-1((u dot v)/(||u||",
"vectorAngle(vec1, vec2, type): # First take the dev() and hydroProjector() of the vectors",
"2: 0.5, #Strain 3: 1 #Stress Strain } factor = switch_type.get(type, 'Invalid type')",
"#Strain 3: 1 #Stress Strain } factor = switch_type.get(type, 'Invalid type') angle =",
"from deviatoric view # #if vec1.shape == (6,1) or vec1.shape(6,) or vec1.shape ==",
"switch_type.get(type, 'Invalid type') angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees #else: #angle = 'Incorrect input",
"(1,6): #theta = cos-1((u dot v)/(||u|| dot ||v||)) switch_type = { 1: 2,",
"switch_type = { 1: 2, #Stress 2: 0.5, #Strain 3: 1 #Stress Strain",
"vec2, type): # First take the dev() and hydroProjector() of the vectors if",
"'Invalid type') angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees #else: #angle = 'Incorrect input vector",
"# angle from deviatoric view # #if vec1.shape == (6,1) or vec1.shape(6,) or",
"#theta = cos-1((u dot v)/(||u|| dot ||v||)) switch_type = { 1: 2, #Stress",
"type') angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees #else: #angle = 'Incorrect input vector shape'",
"# First take the dev() and hydroProjector() of the vectors if measuring #",
"or vec1.shape(6,) or vec1.shape == (1,6): #theta = cos-1((u dot v)/(||u|| dot ||v||))",
"3: 1 #Stress Strain } factor = switch_type.get(type, 'Invalid type') angle = float(np.arccos(innerProduct(vec1,",
"= float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees #else: #angle = 'Incorrect input vector shape' return angle",
"{ 1: 2, #Stress 2: 0.5, #Strain 3: 1 #Stress Strain } factor",
"Strain } factor = switch_type.get(type, 'Invalid type') angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees #else:",
"factor = switch_type.get(type, 'Invalid type') angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees #else: #angle =",
"= switch_type.get(type, 'Invalid type') angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees #else: #angle = 'Incorrect",
"dev() and hydroProjector() of the vectors if measuring # angle from deviatoric view",
"== (1,6): #theta = cos-1((u dot v)/(||u|| dot ||v||)) switch_type = { 1:",
"vec1.shape == (6,1) or vec1.shape(6,) or vec1.shape == (1,6): #theta = cos-1((u dot",
"1: 2, #Stress 2: 0.5, #Strain 3: 1 #Stress Strain } factor =",
"if measuring # angle from deviatoric view # #if vec1.shape == (6,1) or",
"||v||)) switch_type = { 1: 2, #Stress 2: 0.5, #Strain 3: 1 #Stress",
"#Stress Strain } factor = switch_type.get(type, 'Invalid type') angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees",
"1 #Stress Strain } factor = switch_type.get(type, 'Invalid type') angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi))",
"view # #if vec1.shape == (6,1) or vec1.shape(6,) or vec1.shape == (1,6): #theta",
"vec1.shape(6,) or vec1.shape == (1,6): #theta = cos-1((u dot v)/(||u|| dot ||v||)) switch_type",
"take the dev() and hydroProjector() of the vectors if measuring # angle from",
"measuring # angle from deviatoric view # #if vec1.shape == (6,1) or vec1.shape(6,)",
"dot ||v||)) switch_type = { 1: 2, #Stress 2: 0.5, #Strain 3: 1",
"#if vec1.shape == (6,1) or vec1.shape(6,) or vec1.shape == (1,6): #theta = cos-1((u",
"type): # First take the dev() and hydroProjector() of the vectors if measuring",
"the vectors if measuring # angle from deviatoric view # #if vec1.shape ==",
"= { 1: 2, #Stress 2: 0.5, #Strain 3: 1 #Stress Strain }",
"hydroProjector() of the vectors if measuring # angle from deviatoric view # #if",
"= cos-1((u dot v)/(||u|| dot ||v||)) switch_type = { 1: 2, #Stress 2:",
"angle from deviatoric view # #if vec1.shape == (6,1) or vec1.shape(6,) or vec1.shape"
] |
[
"viewed; it was removed.') if not context.CanViewViewpoint(episode.viewpoint_id): # Always allow system viewpoints to",
"exists and is not modified, so no need for client to PUT it",
"I'll re-enable the check. #if post.IsRemoved(): # raise web.HTTPError(403, 'This photo can no",
"the photo if so. \"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id, write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store,",
"verified and the requester is redirected to a pre-authorized, expiring S3 URL. PhotoStoreHandler:",
"None or context.user is None: raise web.HTTPError(401, 'You are not logged in. Only",
"import Viewpoint from viewfinder.backend.www import base options.define('validate_cert', default=True, help='set to False to allow",
"if expected_md5 != actual_md5: if etag is None: # Since there is not",
"obj_store.GenerateUrl(photo_id + suffix, cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT requests by storing image assets",
"that the image data always matches # what is in the metadata, and",
"Reserved. \"\"\"HTTP request handler for serving viewfinder photo image file assets. In case",
"PUT of the image data is needed). match_etag = self.request.headers.get('If-None-Match', None) if match_etag",
"All Rights Reserved. \"\"\"HTTP request handler for serving viewfinder photo image file assets.",
"credentials. \"\"\" @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def get(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials",
"expiring S3 URL. PhotoStoreHandler: Request handler for authorizing photo requests \"\"\" __authors__ =",
"the actual image bits are stored. \"\"\" url = yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id,",
"Only log the mismatch if it's an original photo to avoid spamming logs.",
"web.HTTPError(403, 'This photo can no longer be viewed; it was removed.') if not",
"self._obj_store, episode_id, photo_id, suffix) self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def put(self, episode_id, photo_id, suffix):",
"write access to the photo, and if an 'If-None-Match' is present, sends a",
"# Redirect to the S3 location. self.redirect(_GetUploadUrl(photo, request_md5)) else: # The client often",
"and episode.user_id != user_id: raise web.HTTPError(403, 'You do not have permission to upload",
"to fetch a photo, even if the photo is part of a conversation.",
"asset Etag. If the Etag matches, returns a 304. Otherwise, generates an upload",
"header \"%s\" does not match expected MD5 \"%s\"' % (actual_md5, expected_md5)) self.set_status(400) self.finish()",
"do not have permission to view it.') if write_access and episode.user_id != user_id:",
"where it always passes in the library episode id # when trying to",
"If the user has write access to the photo, and if an 'If-None-Match'",
"store to determine asset Etag. If the Etag matches, returns a 304. Otherwise,",
"suffix) expected_md5 = getattr(photo, attr_name) if expected_md5 != actual_md5: if etag is None:",
"raise web.HTTPError(403, 'This photo can no longer be viewed; it was removed.') if",
"not viewpoint.IsSystem(): raise web.HTTPError(403, 'You do not have permission to view this photo.",
"Copyright 2012 Viewfinder Inc. All Rights Reserved. \"\"\"HTTP request handler for serving viewfinder",
"if 'Content-MD5' not in self.request.headers: raise web.HTTPError(400, 'Missing Content-MD5 header.') try: request_md5 =",
"client to PUT it again. self.set_status(httplib.NOT_MODIFIED) self.finish() else: # Redirect to the S3",
"viewfinder photo image file assets. In case of a local file store, permissions",
"in the photo metadata. if suffix == '.o': attr_name = 'orig_md5' elif suffix",
"\"\"\"Checks that the current user (in Viewfinder context) user is authorized to access",
"if it's an original photo to avoid spamming logs. if suffix == '.o':",
"store for testing') def GeneratePhotoUrl(obj_store, photo_id, suffix): \"\"\"Generate S3 signed URL for the",
"photo image file assets. In case of a local file store, permissions for",
"base options.define('validate_cert', default=True, help='set to False to allow insecure file obj store for",
"'This photo can no longer be viewed; it was removed.') if not context.CanViewViewpoint(episode.viewpoint_id):",
"authorized to access the given photo: 1. The photo must exist, and be",
"options, web from viewfinder.backend.base import handler from viewfinder.backend.db.episode import Episode from viewfinder.backend.db.photo import",
"\"\"\" url = yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id, suffix) self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True) @gen.engine",
"obj_store=True) @gen.engine def put(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials. If the user",
"= yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix) expected_md5 = getattr(photo, attr_name) if expected_md5 !=",
"In case of a local file store, permissions for the current user and",
"requester is redirected to the FileObjectStoreHandler. For an s3 file store, permissions for",
"\"%s\" suffix is invalid.' % suffix) # Ensure that user has permission to",
"\"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id, write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix)) @classmethod @gen.coroutine",
"= photo.content_type or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type, content_md5=verified_md5) # Always expect",
"by client to check whether photo image data # already exists (and therefore",
"'.o': attr_name = 'orig_md5' elif suffix == '.f': attr_name = 'full_md5' elif suffix",
"expect well-formed Content-MD5 header. This ensures that the image data always matches #",
"the MD5 value stored in the photo metadata. if suffix not in ['.t',",
"None or post is None: raise web.HTTPError(404, 'Photo was not found or you",
"context.CanViewViewpoint(episode.viewpoint_id): # Always allow system viewpoints to be accessed by a prospective user.",
"the upload URL. photo = yield gen.Task(Photo.Query, self._client, photo_id, None) # Get name",
"upload this photo; it is not owned by you.') if post.IsUnshared(): raise web.HTTPError(403,",
"stored. \"\"\" url = yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id, suffix) self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True)",
"\"\"\"Checks that the current user (in Viewfinder context) is authorized to get the",
"can no longer be viewed; it was removed.') if not context.CanViewViewpoint(episode.viewpoint_id): # Always",
"case of a local file store, permissions for the current user and the",
"None: raise web.HTTPError(401, 'You are not logged in. Only users that have logged",
"Viewfinder context) is authorized to get the specified photo, and returns a signed",
"user is authorized to access the given photo: 1. The photo must exist,",
"the object store to determine asset Etag. If the Etag matches, returns a",
"matches, returns a 304. Otherwise, generates an upload URL and redirects. \"\"\" def",
"not found; \"%s\" suffix is invalid.' % suffix) # Check for the existence",
"\"\"\" __authors__ = ['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)'] import base64 import httplib import logging",
"URL and redirects. \"\"\" def _GetUploadUrl(photo, verified_md5): content_type = photo.content_type or 'image/jpeg' return",
"determine asset Etag. If the Etag matches, returns a 304. Otherwise, generates an",
"raise web.HTTPError(401, 'You are not logged in. Only users that have logged in",
"context = base.ViewfinderContext.current() if context is None or context.user is None: raise web.HTTPError(401,",
"self.finish() else: # Check for If-None-Match header, which is used by client to",
"data always matches # what is in the metadata, and also enables the",
"register an account.') def _IsInteractiveRequest(self): \"\"\"Always returns false, as this API is accessed",
"if context is None or context.user is None: raise web.HTTPError(401, 'You are not",
"was removed.') if not context.CanViewViewpoint(episode.viewpoint_id): # Always allow system viewpoints to be accessed",
"gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix) expected_md5 = getattr(photo, attr_name) if expected_md5 != actual_md5: if",
"import Episode from viewfinder.backend.db.photo import Photo from viewfinder.backend.db.post import Post from viewfinder.backend.db.user_post import",
"and then redirects to the URL where the actual image bits are stored.",
"is None: raise web.HTTPError(404, 'Photo was not found or you do not have",
"authorizing photo requests \"\"\" __authors__ = ['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)'] import base64 import",
"GET request retrieve image assets. Each method type verifies user authentication credentials. \"\"\"",
"has write access to the photo, and if an 'If-None-Match' is present, sends",
"logged in. Only users that have logged in can access this URL.') user_id",
"== '.t': attr_name = 'tn_md5' else: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix",
"do not have permission to view this photo. ' 'To see it, you",
"if etag is None: # Since there is not yet any photo image",
"in the object store. GET request retrieve image assets. Each method type verifies",
"requests by storing image assets in the object store. GET request retrieve image",
"image assets in the object store. GET request retrieve image assets. Each method",
"name of MD5 attribute in the photo metadata. if suffix == '.o': attr_name",
"data in S3. etag = yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix) expected_md5 = getattr(photo,",
"to be equal to the # actual MD5 value. setattr(photo, attr_name, actual_md5) yield",
"attr_name, actual_md5) yield gen.Task(photo.Update, self._client) # Redirect to the S3 location. self.redirect(_GetUploadUrl(photo, request_md5))",
"access the given photo: 1. The photo must exist, and be in the",
"raise web.HTTPError(404, 'Photo was not found or you do not have permission to",
"their library. For now, I'm disabling this # check. Once 2.0 has established",
"the photo, and if an 'If-None-Match' is present, sends a HEAD request to",
"raise web.HTTPError(400, 'Missing Content-MD5 header.') try: request_md5 = self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex') except:",
"if match_etag is not None and etag is not None and (match_etag ==",
"to PUT it again. self.set_status(httplib.NOT_MODIFIED) self.finish() else: # Redirect to the S3 upload",
"write_access and episode.user_id != user_id: raise web.HTTPError(403, 'You do not have permission to",
"# what is in the metadata, and also enables the detection of any",
"create the upload URL. photo = yield gen.Task(Photo.Query, self._client, photo_id, None) # Get",
"import Photo from viewfinder.backend.db.post import Post from viewfinder.backend.db.user_post import UserPost from viewfinder.backend.db.viewpoint import",
"\"%s\" does not match expected MD5 \"%s\"' % (actual_md5, expected_md5)) self.set_status(400) self.finish() else:",
"attr_name = 'orig_md5' elif suffix == '.f': attr_name = 'full_md5' elif suffix ==",
"return self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type, content_md5=verified_md5) # Always expect well-formed Content-MD5 header. This",
"no longer be viewed; it was removed.') if not context.CanViewViewpoint(episode.viewpoint_id): # Always allow",
"metadata, and also enables the detection of any bit corruption on the wire.",
"'tn_md5' else: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.' % suffix)",
"# Photo image data exists and is not modified, so no need for",
"user (in Viewfinder context) user is authorized to access the given photo: 1.",
"have permission to view this photo. ' 'To see it, you must register",
"are stored. \"\"\" url = yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id, suffix) self.redirect(url) @handler.asynchronous(datastore=True,",
"S3 upload location. self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod @gen.coroutine def GetPhotoUrl(cls, client, obj_store, episode_id, photo_id,",
"elif suffix == '.f': attr_name = 'full_md5' elif suffix == '.m': attr_name =",
"Viewfinder context) user is authorized to access the given photo: 1. The photo",
"the given photo: 1. The photo must exist, and be in the given",
"verified_md5): content_type = photo.content_type or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type, content_md5=verified_md5) #",
"response will contain a Cache-Control header specifying private caching and a 1 year",
"_AuthorizeUser(cls, client, episode_id, photo_id, write_access): \"\"\"Checks that the current user (in Viewfinder context)",
"expected_md5 = getattr(photo, attr_name) if expected_md5 != actual_md5: if etag is None: #",
"object store to determine asset Etag. If the Etag matches, returns a 304.",
"to photos in the viewpoint specified in the cookie \"\"\" context = base.ViewfinderContext.current()",
"library. For now, I'm disabling this # check. Once 2.0 has established itself,",
"is not owned by you.') if post.IsUnshared(): raise web.HTTPError(403, 'This photo can no",
"bits are stored. \"\"\" url = yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id, suffix) self.redirect(url)",
"is in the metadata, and also enables the detection of any bit corruption",
"redirects to the URL where the actual image bits are stored. \"\"\" url",
"must_exist=False)] if episode is None or post is None: raise web.HTTPError(404, 'Photo was",
"Post from viewfinder.backend.db.user_post import UserPost from viewfinder.backend.db.viewpoint import Viewpoint from viewfinder.backend.www import base",
"and (match_etag == '*' or match_etag == etag): # Photo image data exists",
"If-None-Match header, which is used by client to check whether photo image data",
"== '.o': logging.error('Content-MD5 header \"%s\" does not match expected MD5 \"%s\"' % (actual_md5,",
"(and therefore no PUT of the image data is needed). match_etag = self.request.headers.get('If-None-Match',",
"actual_md5: if etag is None: # Since there is not yet any photo",
"file store, permissions for the current user and the requested photo are verified",
"access to the photo, and if an 'If-None-Match' is present, sends a HEAD",
"gen.Task(Viewpoint.Query, client, episode.viewpoint_id, None) if not viewpoint.IsSystem(): raise web.HTTPError(403, 'You do not have",
"(<NAME>)', '<EMAIL> (<NAME>)'] import base64 import httplib import logging from tornado import gen,",
"S3 URL for the photo if so. \"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id,",
"always matches # what is in the metadata, and also enables the detection",
"account.') def _IsInteractiveRequest(self): \"\"\"Always returns false, as this API is accessed programatically.\"\"\" return",
"requested photo are verified and the requester is redirected to a pre-authorized, expiring",
"invalid.' % suffix) # Check for the existence of the photo's image data",
"JPG creation IOS code. # Only log the mismatch if it's an original",
"post = yield [gen.Task(Episode.QueryIfVisible, client, user_id, episode_id, must_exist=False), gen.Task(Post.Query, client, episode_id, photo_id, None,",
"viewfinder.backend.db.viewpoint import Viewpoint from viewfinder.backend.www import base options.define('validate_cert', default=True, help='set to False to",
"self.request.headers.get('If-None-Match', None) if match_etag is not None and etag is not None and",
"have logged in can access this URL.') user_id = context.user.user_id post_id = Post.ConstructPostId(episode_id,",
"of the photo's image data in S3. etag = yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id,",
"must exist, and be in the given episode 2. The photo must not",
"yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True) # Get photo metadata, which will be used",
"in 403 errors when a user tries to sync to their library. For",
"age. \"\"\" return obj_store.GenerateUrl(photo_id + suffix, cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT requests by",
"# Ensure that user has permission to PUT the photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id,",
"'<EMAIL> (<NAME>)'] import base64 import httplib import logging from tornado import gen, options,",
"used by client to check whether photo image data # already exists (and",
"modified, so no need for client to PUT it again. self.set_status(httplib.NOT_MODIFIED) self.finish() else:",
"self.redirect(_GetUploadUrl(photo, request_md5)) else: # The client often sends mismatched MD5 values due to",
"user must be the episode owner 4. A prospective user has access only",
"the S3 location. self.redirect(_GetUploadUrl(photo, request_md5)) else: # The client often sends mismatched MD5",
"If the Etag matches, returns a 304. Otherwise, generates an upload URL and",
"photo, and returns a signed S3 URL for the photo if so. \"\"\"",
"are verified and the requester is redirected to the FileObjectStoreHandler. For an s3",
"photo_id, write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix)) @classmethod @gen.coroutine def _AuthorizeUser(cls, client, episode_id, photo_id,",
"client, obj_store, episode_id, photo_id, suffix): \"\"\"Checks that the current user (in Viewfinder context)",
"client to check whether photo image data # already exists (and therefore no",
"and the requested photo are verified and the requester is redirected to a",
"be used to create the upload URL. photo = yield gen.Task(Photo.Query, self._client, photo_id,",
"insecure file obj store for testing') def GeneratePhotoUrl(obj_store, photo_id, suffix): \"\"\"Generate S3 signed",
"permission to view it.') if write_access and episode.user_id != user_id: raise web.HTTPError(403, 'You",
"yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix) expected_md5 = getattr(photo, attr_name) if expected_md5 != actual_md5:",
"self._obj_store, photo.photo_id, suffix) expected_md5 = getattr(photo, attr_name) if expected_md5 != actual_md5: if etag",
"exist, and be in the given episode 2. The photo must not be",
"= 'full_md5' elif suffix == '.m': attr_name = 'med_md5' elif suffix == '.t':",
"For an s3 file store, permissions for the current user and the requested",
"specified photo, and returns a signed S3 URL for the photo if so.",
"no longer be viewed; it was unshared.') # BUGBUG(Andy): The 1.5 client has",
"is None or post is None: raise web.HTTPError(404, 'Photo was not found or",
"'If-None-Match' is present, sends a HEAD request to the object store to determine",
"@gen.coroutine def GetPhotoUrl(cls, client, obj_store, episode_id, photo_id, suffix): \"\"\"Checks that the current user",
"always passes in the library episode id # when trying to fetch a",
"photo's image data in S3. etag = yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix) expected_md5",
"user_id, episode_id, must_exist=False), gen.Task(Post.Query, client, episode_id, photo_id, None, must_exist=False)] if episode is None",
"logging from tornado import gen, options, web from viewfinder.backend.base import handler from viewfinder.backend.db.episode",
"the current user (in Viewfinder context) user is authorized to access the given",
"This results # in 403 errors when a user tries to sync to",
"this # check. Once 2.0 has established itself, I'll re-enable the check. #if",
"be accessed by a prospective user. viewpoint = yield gen.Task(Viewpoint.Query, client, episode.viewpoint_id, None)",
"values due to non-deterministic JPG creation IOS code. # Only log the mismatch",
"enables the detection of any bit corruption on the wire. if 'Content-MD5' not",
"match_etag is not None and etag is not None and (match_etag == '*'",
"\"\"\" def _GetUploadUrl(photo, verified_md5): content_type = photo.content_type or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id + suffix,",
"well-formed Content-MD5 header. This ensures that the image data always matches # what",
"data, update the photo metadata to be equal to the # actual MD5",
"viewfinder.backend.db.user_post import UserPost from viewfinder.backend.db.viewpoint import Viewpoint from viewfinder.backend.www import base options.define('validate_cert', default=True,",
"# Check for the existence of the photo's image data in S3. etag",
"['.t', '.m', '.f', '.o']: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.'",
"if suffix == '.o': attr_name = 'orig_md5' elif suffix == '.f': attr_name =",
"= 'tn_md5' else: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.' %",
"write_access=True) # Get photo metadata, which will be used to create the upload",
"it again. self.set_status(httplib.NOT_MODIFIED) self.finish() else: # Redirect to the S3 upload location. self.redirect(_GetUploadUrl(photo,",
"caching and a 1 year max age. \"\"\" return obj_store.GenerateUrl(photo_id + suffix, cache_control='private,max-age=31536000')",
"Only users that have logged in can access this URL.') user_id = context.user.user_id",
"to check whether photo image data # already exists (and therefore no PUT",
"= yield [gen.Task(Episode.QueryIfVisible, client, user_id, episode_id, must_exist=False), gen.Task(Post.Query, client, episode_id, photo_id, None, must_exist=False)]",
"for the existence of the photo's image data in S3. etag = yield",
"and etag is not None and (match_etag == '*' or match_etag == etag):",
"The photo must exist, and be in the given episode 2. The photo",
"S3 location. self.redirect(_GetUploadUrl(photo, request_md5)) else: # The client often sends mismatched MD5 values",
"False to allow insecure file obj store for testing') def GeneratePhotoUrl(obj_store, photo_id, suffix):",
"# Always expect well-formed Content-MD5 header. This ensures that the image data always",
"pre-authorized, expiring S3 URL. PhotoStoreHandler: Request handler for authorizing photo requests \"\"\" __authors__",
"elif suffix == '.m': attr_name = 'med_md5' elif suffix == '.t': attr_name =",
"Content-MD5 header.') try: request_md5 = self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400, 'Content-MD5",
"(<NAME>)'] import base64 import httplib import logging from tornado import gen, options, web",
"Content-MD5 header. This ensures that the image data always matches # what is",
"photo image data, update the photo metadata to be equal to the #",
"= base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400, 'Content-MD5 header \"%s\" is not a valid base-64",
"header, which is used by client to check whether photo image data #",
"specifying private caching and a 1 year max age. \"\"\" return obj_store.GenerateUrl(photo_id +",
"\"%s\" is not a valid base-64 value.' % request_md5) # Match against the",
"invalid.' % suffix) # Ensure that user has permission to PUT the photo.",
"of any bit corruption on the wire. if 'Content-MD5' not in self.request.headers: raise",
"= yield gen.Task(Photo.Query, self._client, photo_id, None) # Get name of MD5 attribute in",
"a bug where it always passes in the library episode id # when",
"(in Viewfinder context) is authorized to get the specified photo, and returns a",
"verifies user authentication credentials. \"\"\" @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def get(self, episode_id, photo_id, suffix):",
"def _GetUploadUrl(photo, verified_md5): content_type = photo.content_type or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type,",
"'.o']: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.' % suffix) #",
"system viewpoints to be accessed by a prospective user. viewpoint = yield gen.Task(Viewpoint.Query,",
"returns a 304. Otherwise, generates an upload URL and redirects. \"\"\" def _GetUploadUrl(photo,",
"suffix) # Check for the existence of the photo's image data in S3.",
"current user (in Viewfinder context) user is authorized to access the given photo:",
"self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400, 'Content-MD5 header \"%s\" is not a",
"photo.content_type or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type, content_md5=verified_md5) # Always expect well-formed",
"can no longer be viewed; it was unshared.') # BUGBUG(Andy): The 1.5 client",
"this URL.') user_id = context.user.user_id post_id = Post.ConstructPostId(episode_id, photo_id) episode, post = yield",
"a Cache-Control header specifying private caching and a 1 year max age. \"\"\"",
"an 'If-None-Match' is present, sends a HEAD request to the object store to",
"photo must exist, and be in the given episode 2. The photo must",
"yield [gen.Task(Episode.QueryIfVisible, client, user_id, episode_id, must_exist=False), gen.Task(Post.Query, client, episode_id, photo_id, None, must_exist=False)] if",
"web.HTTPError(403, 'You do not have permission to upload this photo; it is not",
"disabling this # check. Once 2.0 has established itself, I'll re-enable the check.",
"\"\"\"Generate S3 signed URL for the given photo. The S3 response will contain",
"not be unshared 3. If uploading the photo, the user must be the",
"episode_id, photo_id, None, must_exist=False)] if episode is None or post is None: raise",
"# Since there is not yet any photo image data, update the photo",
"the wire. if 'Content-MD5' not in self.request.headers: raise web.HTTPError(400, 'Missing Content-MD5 header.') try:",
"that have logged in can access this URL.') user_id = context.user.user_id post_id =",
"can access this URL.') user_id = context.user.user_id post_id = Post.ConstructPostId(episode_id, photo_id) episode, post",
"# Always allow system viewpoints to be accessed by a prospective user. viewpoint",
"== '*' or match_etag == etag): # Photo image data exists and is",
"to upload this photo; it is not owned by you.') if post.IsUnshared(): raise",
"for serving viewfinder photo image file assets. In case of a local file",
"the viewpoint specified in the cookie \"\"\" context = base.ViewfinderContext.current() if context is",
"context) user is authorized to access the given photo: 1. The photo must",
"import gen, options, web from viewfinder.backend.base import handler from viewfinder.backend.db.episode import Episode from",
"Episode from viewfinder.backend.db.photo import Photo from viewfinder.backend.db.post import Post from viewfinder.backend.db.user_post import UserPost",
"get(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials and then redirects to the URL",
"permission to view this photo. ' 'To see it, you must register an",
"any photo image data, update the photo metadata to be equal to the",
"MD5 value. setattr(photo, attr_name, actual_md5) yield gen.Task(photo.Update, self._client) # Redirect to the S3",
"the photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True) # Get photo metadata, which will",
"bit corruption on the wire. if 'Content-MD5' not in self.request.headers: raise web.HTTPError(400, 'Missing",
"in self.request.headers: raise web.HTTPError(400, 'Missing Content-MD5 header.') try: request_md5 = self.request.headers['Content-MD5'] actual_md5 =",
"trying to fetch a photo, even if the photo is part of a",
"web.HTTPError(403, 'You do not have permission to view this photo. ' 'To see",
"viewed; it was unshared.') # BUGBUG(Andy): The 1.5 client has a bug where",
"the check. #if post.IsRemoved(): # raise web.HTTPError(403, 'This photo can no longer be",
"the requester is redirected to the FileObjectStoreHandler. For an s3 file store, permissions",
"Photo from viewfinder.backend.db.post import Post from viewfinder.backend.db.user_post import UserPost from viewfinder.backend.db.viewpoint import Viewpoint",
"self.set_status(400) self.finish() else: # Check for If-None-Match header, which is used by client",
"is authorized to get the specified photo, and returns a signed S3 URL",
"the requester is redirected to a pre-authorized, expiring S3 URL. PhotoStoreHandler: Request handler",
"['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)'] import base64 import httplib import logging from tornado import",
"# Redirect to the S3 upload location. self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod @gen.coroutine def GetPhotoUrl(cls,",
"part of a conversation. This results # in 403 errors when a user",
"see it, you must register an account.') def _IsInteractiveRequest(self): \"\"\"Always returns false, as",
"if not viewpoint.IsSystem(): raise web.HTTPError(403, 'You do not have permission to view this",
"serving viewfinder photo image file assets. In case of a local file store,",
"sends a HEAD request to the object store to determine asset Etag. If",
"unshared 3. If uploading the photo, the user must be the episode owner",
"actual_md5 = base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400, 'Content-MD5 header \"%s\" is not a valid",
"value. setattr(photo, attr_name, actual_md5) yield gen.Task(photo.Update, self._client) # Redirect to the S3 location.",
"episode_id, photo_id, write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix)) @classmethod @gen.coroutine def _AuthorizeUser(cls, client, episode_id,",
"has established itself, I'll re-enable the check. #if post.IsRemoved(): # raise web.HTTPError(403, 'This",
"and the requester is redirected to the FileObjectStoreHandler. For an s3 file store,",
"= yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id, suffix) self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def put(self,",
"uploading the photo, the user must be the episode owner 4. A prospective",
"1.5 client has a bug where it always passes in the library episode",
"the S3 upload location. self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod @gen.coroutine def GetPhotoUrl(cls, client, obj_store, episode_id,",
"from viewfinder.backend.db.user_post import UserPost from viewfinder.backend.db.viewpoint import Viewpoint from viewfinder.backend.www import base options.define('validate_cert',",
"the metadata, and also enables the detection of any bit corruption on the",
"it's an original photo to avoid spamming logs. if suffix == '.o': logging.error('Content-MD5",
"the current user (in Viewfinder context) is authorized to get the specified photo,",
"def _AuthorizeUser(cls, client, episode_id, photo_id, write_access): \"\"\"Checks that the current user (in Viewfinder",
"image data in S3. etag = yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix) expected_md5 =",
"request_md5)) @classmethod @gen.coroutine def GetPhotoUrl(cls, client, obj_store, episode_id, photo_id, suffix): \"\"\"Checks that the",
"by you.') if post.IsUnshared(): raise web.HTTPError(403, 'This photo can no longer be viewed;",
"header. This ensures that the image data always matches # what is in",
"and the requested photo are verified and the requester is redirected to the",
"and if an 'If-None-Match' is present, sends a HEAD request to the object",
"established itself, I'll re-enable the check. #if post.IsRemoved(): # raise web.HTTPError(403, 'This photo",
"to create the upload URL. photo = yield gen.Task(Photo.Query, self._client, photo_id, None) #",
"credentials and then redirects to the URL where the actual image bits are",
"current user (in Viewfinder context) is authorized to get the specified photo, and",
"photo must not be unshared 3. If uploading the photo, the user must",
"it.') if write_access and episode.user_id != user_id: raise web.HTTPError(403, 'You do not have",
"'Photo not found; \"%s\" suffix is invalid.' % suffix) # Ensure that user",
"credentials. If the user has write access to the photo, and if an",
"the existence of the photo's image data in S3. etag = yield gen.Task(Photo.IsImageUploaded,",
"logging.error('Content-MD5 header \"%s\" does not match expected MD5 \"%s\"' % (actual_md5, expected_md5)) self.set_status(400)",
"S3. etag = yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix) expected_md5 = getattr(photo, attr_name) if",
"getattr(photo, attr_name) if expected_md5 != actual_md5: if etag is None: # Since there",
"# already exists (and therefore no PUT of the image data is needed).",
"request handler for serving viewfinder photo image file assets. In case of a",
"non-deterministic JPG creation IOS code. # Only log the mismatch if it's an",
"yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id, write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix)) @classmethod @gen.coroutine def",
"gen, options, web from viewfinder.backend.base import handler from viewfinder.backend.db.episode import Episode from viewfinder.backend.db.photo",
"gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id, write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix)) @classmethod @gen.coroutine def _AuthorizeUser(cls,",
"testing') def GeneratePhotoUrl(obj_store, photo_id, suffix): \"\"\"Generate S3 signed URL for the given photo.",
"the episode owner 4. A prospective user has access only to photos in",
"2. The photo must not be unshared 3. If uploading the photo, the",
"have permission to upload this photo; it is not owned by you.') if",
"actual_md5) yield gen.Task(photo.Update, self._client) # Redirect to the S3 location. self.redirect(_GetUploadUrl(photo, request_md5)) else:",
"does not match expected MD5 \"%s\"' % (actual_md5, expected_md5)) self.set_status(400) self.finish() else: #",
"image file assets. In case of a local file store, permissions for the",
"yield gen.Task(Photo.Query, self._client, photo_id, None) # Get name of MD5 attribute in the",
"photo are verified and the requester is redirected to the FileObjectStoreHandler. For an",
"post_id = Post.ConstructPostId(episode_id, photo_id) episode, post = yield [gen.Task(Episode.QueryIfVisible, client, user_id, episode_id, must_exist=False),",
"found; \"%s\" suffix is invalid.' % suffix) # Ensure that user has permission",
"longer be viewed; it was unshared.') # BUGBUG(Andy): The 1.5 client has a",
"S3 URL. PhotoStoreHandler: Request handler for authorizing photo requests \"\"\" __authors__ = ['<EMAIL>",
"conversation. This results # in 403 errors when a user tries to sync",
"== '.o': attr_name = 'orig_md5' elif suffix == '.f': attr_name = 'full_md5' elif",
"id # when trying to fetch a photo, even if the photo is",
"there is not yet any photo image data, update the photo metadata to",
"post.IsRemoved(): # raise web.HTTPError(403, 'This photo can no longer be viewed; it was",
"and redirects. \"\"\" def _GetUploadUrl(photo, verified_md5): content_type = photo.content_type or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id",
"you must register an account.') def _IsInteractiveRequest(self): \"\"\"Always returns false, as this API",
"it, you must register an account.') def _IsInteractiveRequest(self): \"\"\"Always returns false, as this",
"the Etag matches, returns a 304. Otherwise, generates an upload URL and redirects.",
"I'm disabling this # check. Once 2.0 has established itself, I'll re-enable the",
"metadata. if suffix not in ['.t', '.m', '.f', '.o']: raise web.HTTPError(404, 'Photo not",
"3. If uploading the photo, the user must be the episode owner 4.",
"user has permission to PUT the photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True) #",
"present, sends a HEAD request to the object store to determine asset Etag.",
"= context.user.user_id post_id = Post.ConstructPostId(episode_id, photo_id) episode, post = yield [gen.Task(Episode.QueryIfVisible, client, user_id,",
"URL. PhotoStoreHandler: Request handler for authorizing photo requests \"\"\" __authors__ = ['<EMAIL> (<NAME>)',",
"logs. if suffix == '.o': logging.error('Content-MD5 header \"%s\" does not match expected MD5",
"if suffix == '.o': logging.error('Content-MD5 header \"%s\" does not match expected MD5 \"%s\"'",
"if the photo is part of a conversation. This results # in 403",
"# check. Once 2.0 has established itself, I'll re-enable the check. #if post.IsRemoved():",
"to view this photo. ' 'To see it, you must register an account.')",
"web from viewfinder.backend.base import handler from viewfinder.backend.db.episode import Episode from viewfinder.backend.db.photo import Photo",
"URL. photo = yield gen.Task(Photo.Query, self._client, photo_id, None) # Get name of MD5",
"MD5 value stored in the photo metadata. if suffix not in ['.t', '.m',",
"that the current user (in Viewfinder context) is authorized to get the specified",
"class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT requests by storing image assets in the object store.",
"# Match against the MD5 value stored in the photo metadata. if suffix",
"in the viewpoint specified in the cookie \"\"\" context = base.ViewfinderContext.current() if context",
"= base.ViewfinderContext.current() if context is None or context.user is None: raise web.HTTPError(401, 'You",
"requested photo are verified and the requester is redirected to the FileObjectStoreHandler. For",
"if post.IsUnshared(): raise web.HTTPError(403, 'This photo can no longer be viewed; it was",
"photo, the user must be the episode owner 4. A prospective user has",
"original photo to avoid spamming logs. if suffix == '.o': logging.error('Content-MD5 header \"%s\"",
"photo_id, write_access=True) # Get photo metadata, which will be used to create the",
"% (actual_md5, expected_md5)) self.set_status(400) self.finish() else: # Check for If-None-Match header, which is",
"value stored in the photo metadata. if suffix not in ['.t', '.m', '.f',",
"it was removed.') if not context.CanViewViewpoint(episode.viewpoint_id): # Always allow system viewpoints to be",
"to False to allow insecure file obj store for testing') def GeneratePhotoUrl(obj_store, photo_id,",
"viewfinder.backend.www import base options.define('validate_cert', default=True, help='set to False to allow insecure file obj",
"the URL where the actual image bits are stored. \"\"\" url = yield",
"to the # actual MD5 value. setattr(photo, attr_name, actual_md5) yield gen.Task(photo.Update, self._client) #",
"it is not owned by you.') if post.IsUnshared(): raise web.HTTPError(403, 'This photo can",
"logged in can access this URL.') user_id = context.user.user_id post_id = Post.ConstructPostId(episode_id, photo_id)",
"if not context.CanViewViewpoint(episode.viewpoint_id): # Always allow system viewpoints to be accessed by a",
"import base options.define('validate_cert', default=True, help='set to False to allow insecure file obj store",
"again. self.set_status(httplib.NOT_MODIFIED) self.finish() else: # Redirect to the S3 upload location. self.redirect(_GetUploadUrl(photo, request_md5))",
"in the given episode 2. The photo must not be unshared 3. If",
"\"\"\"Verifies user credentials. If the user has write access to the photo, and",
"URL where the actual image bits are stored. \"\"\" url = yield PhotoStoreHandler.GetPhotoUrl(self._client,",
"import UserPost from viewfinder.backend.db.viewpoint import Viewpoint from viewfinder.backend.www import base options.define('validate_cert', default=True, help='set",
"not logged in. Only users that have logged in can access this URL.')",
"image assets. Each method type verifies user authentication credentials. \"\"\" @handler.asynchronous(datastore=True, obj_store=True) @gen.engine",
"of MD5 attribute in the photo metadata. if suffix == '.o': attr_name =",
"results # in 403 errors when a user tries to sync to their",
"base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400, 'Content-MD5 header \"%s\" is not a valid base-64 value.'",
"viewpoints to be accessed by a prospective user. viewpoint = yield gen.Task(Viewpoint.Query, client,",
"'You do not have permission to upload this photo; it is not owned",
"GetPhotoUrl(cls, client, obj_store, episode_id, photo_id, suffix): \"\"\"Checks that the current user (in Viewfinder",
"@gen.engine def get(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials and then redirects to",
"4. A prospective user has access only to photos in the viewpoint specified",
"of a local file store, permissions for the current user and the requested",
"# when trying to fetch a photo, even if the photo is part",
"what is in the metadata, and also enables the detection of any bit",
"# Check for If-None-Match header, which is used by client to check whether",
"on the wire. if 'Content-MD5' not in self.request.headers: raise web.HTTPError(400, 'Missing Content-MD5 header.')",
"the given episode 2. The photo must not be unshared 3. If uploading",
"Inc. All Rights Reserved. \"\"\"HTTP request handler for serving viewfinder photo image file",
"raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.' % suffix) # Check",
"a user tries to sync to their library. For now, I'm disabling this",
"to view it.') if write_access and episode.user_id != user_id: raise web.HTTPError(403, 'You do",
"photo. ' 'To see it, you must register an account.') def _IsInteractiveRequest(self): \"\"\"Always",
"obj store for testing') def GeneratePhotoUrl(obj_store, photo_id, suffix): \"\"\"Generate S3 signed URL for",
"photo requests \"\"\" __authors__ = ['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)'] import base64 import httplib",
"be equal to the # actual MD5 value. setattr(photo, attr_name, actual_md5) yield gen.Task(photo.Update,",
"MD5 values due to non-deterministic JPG creation IOS code. # Only log the",
"for testing') def GeneratePhotoUrl(obj_store, photo_id, suffix): \"\"\"Generate S3 signed URL for the given",
"be in the given episode 2. The photo must not be unshared 3.",
"an upload URL and redirects. \"\"\" def _GetUploadUrl(photo, verified_md5): content_type = photo.content_type or",
"redirected to a pre-authorized, expiring S3 URL. PhotoStoreHandler: Request handler for authorizing photo",
"'You are not logged in. Only users that have logged in can access",
"URL.') user_id = context.user.user_id post_id = Post.ConstructPostId(episode_id, photo_id) episode, post = yield [gen.Task(Episode.QueryIfVisible,",
"'.t': attr_name = 'tn_md5' else: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is",
"a conversation. This results # in 403 errors when a user tries to",
"an s3 file store, permissions for the current user and the requested photo",
"content_md5=verified_md5) # Always expect well-formed Content-MD5 header. This ensures that the image data",
"a HEAD request to the object store to determine asset Etag. If the",
"type verifies user authentication credentials. \"\"\" @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def get(self, episode_id, photo_id,",
"url = yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id, suffix) self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def",
"suffix == '.o': attr_name = 'orig_md5' elif suffix == '.f': attr_name = 'full_md5'",
"default=True, help='set to False to allow insecure file obj store for testing') def",
"= 'med_md5' elif suffix == '.t': attr_name = 'tn_md5' else: raise web.HTTPError(404, 'Photo",
"to a pre-authorized, expiring S3 URL. PhotoStoreHandler: Request handler for authorizing photo requests",
"for the given photo. The S3 response will contain a Cache-Control header specifying",
"suffix, content_type=content_type, content_md5=verified_md5) # Always expect well-formed Content-MD5 header. This ensures that the",
"S3 response will contain a Cache-Control header specifying private caching and a 1",
"self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod @gen.coroutine def GetPhotoUrl(cls, client, obj_store, episode_id, photo_id, suffix): \"\"\"Checks that",
"photo_id, None) # Get name of MD5 attribute in the photo metadata. if",
"photo; it is not owned by you.') if post.IsUnshared(): raise web.HTTPError(403, 'This photo",
"suffix is invalid.' % suffix) # Check for the existence of the photo's",
"post.IsUnshared(): raise web.HTTPError(403, 'This photo can no longer be viewed; it was unshared.')",
"content_type=content_type, content_md5=verified_md5) # Always expect well-formed Content-MD5 header. This ensures that the image",
"even if the photo is part of a conversation. This results # in",
"tornado import gen, options, web from viewfinder.backend.base import handler from viewfinder.backend.db.episode import Episode",
"be viewed; it was unshared.') # BUGBUG(Andy): The 1.5 client has a bug",
"redirects. \"\"\" def _GetUploadUrl(photo, verified_md5): content_type = photo.content_type or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id +",
"@classmethod @gen.coroutine def GetPhotoUrl(cls, client, obj_store, episode_id, photo_id, suffix): \"\"\"Checks that the current",
"not context.CanViewViewpoint(episode.viewpoint_id): # Always allow system viewpoints to be accessed by a prospective",
"user credentials and then redirects to the URL where the actual image bits",
"= self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400, 'Content-MD5 header \"%s\" is not",
"# BUGBUG(Andy): The 1.5 client has a bug where it always passes in",
"is authorized to access the given photo: 1. The photo must exist, and",
"generates an upload URL and redirects. \"\"\" def _GetUploadUrl(photo, verified_md5): content_type = photo.content_type",
"Ensure that user has permission to PUT the photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id,",
"or context.user is None: raise web.HTTPError(401, 'You are not logged in. Only users",
"Always allow system viewpoints to be accessed by a prospective user. viewpoint =",
"the photo metadata. if suffix == '.o': attr_name = 'orig_md5' elif suffix ==",
"the photo metadata. if suffix not in ['.t', '.m', '.f', '.o']: raise web.HTTPError(404,",
"is not a valid base-64 value.' % request_md5) # Match against the MD5",
"not a valid base-64 value.' % request_md5) # Match against the MD5 value",
"'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type, content_md5=verified_md5) # Always expect well-formed Content-MD5 header.",
"suffix): \"\"\"Checks that the current user (in Viewfinder context) is authorized to get",
"not have permission to upload this photo; it is not owned by you.')",
"of a conversation. This results # in 403 errors when a user tries",
"not None and etag is not None and (match_etag == '*' or match_etag",
"is None: raise web.HTTPError(401, 'You are not logged in. Only users that have",
"FileObjectStoreHandler. For an s3 file store, permissions for the current user and the",
"exists (and therefore no PUT of the image data is needed). match_etag =",
"if episode is None or post is None: raise web.HTTPError(404, 'Photo was not",
"client, episode_id, photo_id, None, must_exist=False)] if episode is None or post is None:",
"from viewfinder.backend.db.photo import Photo from viewfinder.backend.db.post import Post from viewfinder.backend.db.user_post import UserPost from",
"and the requester is redirected to a pre-authorized, expiring S3 URL. PhotoStoreHandler: Request",
"self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def put(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials. If",
"None) if not viewpoint.IsSystem(): raise web.HTTPError(403, 'You do not have permission to view",
"suffix == '.m': attr_name = 'med_md5' elif suffix == '.t': attr_name = 'tn_md5'",
"# Only log the mismatch if it's an original photo to avoid spamming",
"not found; \"%s\" suffix is invalid.' % suffix) # Ensure that user has",
"'To see it, you must register an account.') def _IsInteractiveRequest(self): \"\"\"Always returns false,",
"# Get photo metadata, which will be used to create the upload URL.",
"def get(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials and then redirects to the",
"context is None or context.user is None: raise web.HTTPError(401, 'You are not logged",
"so no need for client to PUT it again. self.set_status(httplib.NOT_MODIFIED) self.finish() else: #",
"location. self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod @gen.coroutine def GetPhotoUrl(cls, client, obj_store, episode_id, photo_id, suffix): \"\"\"Checks",
"except: raise web.HTTPError(400, 'Content-MD5 header \"%s\" is not a valid base-64 value.' %",
"match_etag == etag): # Photo image data exists and is not modified, so",
"photo_id) episode, post = yield [gen.Task(Episode.QueryIfVisible, client, user_id, episode_id, must_exist=False), gen.Task(Post.Query, client, episode_id,",
"given photo: 1. The photo must exist, and be in the given episode",
"the user has write access to the photo, and if an 'If-None-Match' is",
"and also enables the detection of any bit corruption on the wire. if",
"image bits are stored. \"\"\" url = yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id, suffix)",
"yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id, suffix) self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def put(self, episode_id,",
"the FileObjectStoreHandler. For an s3 file store, permissions for the current user and",
"now, I'm disabling this # check. Once 2.0 has established itself, I'll re-enable",
"by storing image assets in the object store. GET request retrieve image assets.",
"web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.' % suffix) # Ensure that",
"suffix) # Ensure that user has permission to PUT the photo. yield PhotoStoreHandler._AuthorizeUser(self._client,",
"matches # what is in the metadata, and also enables the detection of",
"viewfinder.backend.base import handler from viewfinder.backend.db.episode import Episode from viewfinder.backend.db.photo import Photo from viewfinder.backend.db.post",
"for If-None-Match header, which is used by client to check whether photo image",
"view it.') if write_access and episode.user_id != user_id: raise web.HTTPError(403, 'You do not",
"help='set to False to allow insecure file obj store for testing') def GeneratePhotoUrl(obj_store,",
"PUT requests by storing image assets in the object store. GET request retrieve",
"when trying to fetch a photo, even if the photo is part of",
"to the object store to determine asset Etag. If the Etag matches, returns",
"image data is needed). match_etag = self.request.headers.get('If-None-Match', None) if match_etag is not None",
"requests \"\"\" __authors__ = ['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)'] import base64 import httplib import",
"an original photo to avoid spamming logs. if suffix == '.o': logging.error('Content-MD5 header",
"'You do not have permission to view this photo. ' 'To see it,",
"viewpoint.IsSystem(): raise web.HTTPError(403, 'You do not have permission to view this photo. '",
"== '.m': attr_name = 'med_md5' elif suffix == '.t': attr_name = 'tn_md5' else:",
"suffix): \"\"\"Verifies user credentials. If the user has write access to the photo,",
"photo, even if the photo is part of a conversation. This results #",
"photo_id, suffix)) @classmethod @gen.coroutine def _AuthorizeUser(cls, client, episode_id, photo_id, write_access): \"\"\"Checks that the",
"The S3 response will contain a Cache-Control header specifying private caching and a",
"self._client) # Redirect to the S3 location. self.redirect(_GetUploadUrl(photo, request_md5)) else: # The client",
"to the S3 upload location. self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod @gen.coroutine def GetPhotoUrl(cls, client, obj_store,",
"PUT it again. self.set_status(httplib.NOT_MODIFIED) self.finish() else: # Redirect to the S3 upload location.",
"suffix not in ['.t', '.m', '.f', '.o']: raise web.HTTPError(404, 'Photo not found; \"%s\"",
"episode 2. The photo must not be unshared 3. If uploading the photo,",
"was not found or you do not have permission to view it.') if",
"to PUT the photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True) # Get photo metadata,",
"gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix)) @classmethod @gen.coroutine def _AuthorizeUser(cls, client, episode_id, photo_id, write_access): \"\"\"Checks that",
"obj_store, episode_id, photo_id, suffix): \"\"\"Checks that the current user (in Viewfinder context) is",
"it always passes in the library episode id # when trying to fetch",
"context.user is None: raise web.HTTPError(401, 'You are not logged in. Only users that",
"Request handler for authorizing photo requests \"\"\" __authors__ = ['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)']",
"and be in the given episode 2. The photo must not be unshared",
"Photo image data exists and is not modified, so no need for client",
"handler for authorizing photo requests \"\"\" __authors__ = ['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)'] import",
"verified and the requester is redirected to the FileObjectStoreHandler. For an s3 file",
"s3 file store, permissions for the current user and the requested photo are",
"not modified, so no need for client to PUT it again. self.set_status(httplib.NOT_MODIFIED) self.finish()",
"the current user and the requested photo are verified and the requester is",
"S3 signed URL for the given photo. The S3 response will contain a",
"Get photo metadata, which will be used to create the upload URL. photo",
"photo if so. \"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id, write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id,",
"actual MD5 value. setattr(photo, attr_name, actual_md5) yield gen.Task(photo.Update, self._client) # Redirect to the",
"client often sends mismatched MD5 values due to non-deterministic JPG creation IOS code.",
"raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix)) @classmethod @gen.coroutine def _AuthorizeUser(cls, client, episode_id, photo_id, write_access): \"\"\"Checks",
"Once 2.0 has established itself, I'll re-enable the check. #if post.IsRemoved(): # raise",
"if so. \"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id, write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix))",
"episode owner 4. A prospective user has access only to photos in the",
"when a user tries to sync to their library. For now, I'm disabling",
"not have permission to view this photo. ' 'To see it, you must",
"(in Viewfinder context) user is authorized to access the given photo: 1. The",
"found or you do not have permission to view it.') if write_access and",
"For now, I'm disabling this # check. Once 2.0 has established itself, I'll",
"PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id, suffix) self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def put(self, episode_id, photo_id,",
"'.f', '.o']: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.' % suffix)",
"'.m': attr_name = 'med_md5' elif suffix == '.t': attr_name = 'tn_md5' else: raise",
"an account.') def _IsInteractiveRequest(self): \"\"\"Always returns false, as this API is accessed programatically.\"\"\"",
"'*' or match_etag == etag): # Photo image data exists and is not",
"gen.Task(photo.Update, self._client) # Redirect to the S3 location. self.redirect(_GetUploadUrl(photo, request_md5)) else: # The",
"Viewfinder Inc. All Rights Reserved. \"\"\"HTTP request handler for serving viewfinder photo image",
"must register an account.') def _IsInteractiveRequest(self): \"\"\"Always returns false, as this API is",
"is None or context.user is None: raise web.HTTPError(401, 'You are not logged in.",
"import logging from tornado import gen, options, web from viewfinder.backend.base import handler from",
"from viewfinder.backend.www import base options.define('validate_cert', default=True, help='set to False to allow insecure file",
"a signed S3 URL for the photo if so. \"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser, client,",
"whether photo image data # already exists (and therefore no PUT of the",
"assets. Each method type verifies user authentication credentials. \"\"\" @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def",
"then redirects to the URL where the actual image bits are stored. \"\"\"",
"client, episode_id, photo_id, write_access): \"\"\"Checks that the current user (in Viewfinder context) user",
"= Post.ConstructPostId(episode_id, photo_id) episode, post = yield [gen.Task(Episode.QueryIfVisible, client, user_id, episode_id, must_exist=False), gen.Task(Post.Query,",
"@handler.asynchronous(datastore=True, obj_store=True) @gen.engine def put(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials. If the",
"cookie \"\"\" context = base.ViewfinderContext.current() if context is None or context.user is None:",
"that the current user (in Viewfinder context) user is authorized to access the",
"the cookie \"\"\" context = base.ViewfinderContext.current() if context is None or context.user is",
"the requested photo are verified and the requester is redirected to a pre-authorized,",
"assets. In case of a local file store, permissions for the current user",
"the # actual MD5 value. setattr(photo, attr_name, actual_md5) yield gen.Task(photo.Update, self._client) # Redirect",
"handler for serving viewfinder photo image file assets. In case of a local",
"import base64 import httplib import logging from tornado import gen, options, web from",
"'Missing Content-MD5 header.') try: request_md5 = self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400,",
"yet any photo image data, update the photo metadata to be equal to",
"is not yet any photo image data, update the photo metadata to be",
"The client often sends mismatched MD5 values due to non-deterministic JPG creation IOS",
"metadata. if suffix == '.o': attr_name = 'orig_md5' elif suffix == '.f': attr_name",
"Cache-Control header specifying private caching and a 1 year max age. \"\"\" return",
"1. The photo must exist, and be in the given episode 2. The",
"avoid spamming logs. if suffix == '.o': logging.error('Content-MD5 header \"%s\" does not match",
"(actual_md5, expected_md5)) self.set_status(400) self.finish() else: # Check for If-None-Match header, which is used",
"or you do not have permission to view it.') if write_access and episode.user_id",
"viewpoint specified in the cookie \"\"\" context = base.ViewfinderContext.current() if context is None",
"photo metadata. if suffix not in ['.t', '.m', '.f', '.o']: raise web.HTTPError(404, 'Photo",
"web.HTTPError(401, 'You are not logged in. Only users that have logged in can",
"photo_id, suffix): \"\"\"Generate S3 signed URL for the given photo. The S3 response",
"the photo's image data in S3. etag = yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix)",
"1 year max age. \"\"\" return obj_store.GenerateUrl(photo_id + suffix, cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles",
"web.HTTPError(400, 'Content-MD5 header \"%s\" is not a valid base-64 value.' % request_md5) #",
"suffix is invalid.' % suffix) # Ensure that user has permission to PUT",
"be viewed; it was removed.') if not context.CanViewViewpoint(episode.viewpoint_id): # Always allow system viewpoints",
"user (in Viewfinder context) is authorized to get the specified photo, and returns",
"expected MD5 \"%s\"' % (actual_md5, expected_md5)) self.set_status(400) self.finish() else: # Check for If-None-Match",
"image data exists and is not modified, so no need for client to",
"if write_access and episode.user_id != user_id: raise web.HTTPError(403, 'You do not have permission",
"= yield gen.Task(Viewpoint.Query, client, episode.viewpoint_id, None) if not viewpoint.IsSystem(): raise web.HTTPError(403, 'You do",
"% suffix) # Check for the existence of the photo's image data in",
"actual image bits are stored. \"\"\" url = yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id,",
"only to photos in the viewpoint specified in the cookie \"\"\" context =",
"Viewpoint from viewfinder.backend.www import base options.define('validate_cert', default=True, help='set to False to allow insecure",
"' 'To see it, you must register an account.') def _IsInteractiveRequest(self): \"\"\"Always returns",
"def GeneratePhotoUrl(obj_store, photo_id, suffix): \"\"\"Generate S3 signed URL for the given photo. The",
"'.o': logging.error('Content-MD5 header \"%s\" does not match expected MD5 \"%s\"' % (actual_md5, expected_md5))",
"image data always matches # what is in the metadata, and also enables",
"store. GET request retrieve image assets. Each method type verifies user authentication credentials.",
"to be accessed by a prospective user. viewpoint = yield gen.Task(Viewpoint.Query, client, episode.viewpoint_id,",
"max age. \"\"\" return obj_store.GenerateUrl(photo_id + suffix, cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT requests",
"'orig_md5' elif suffix == '.f': attr_name = 'full_md5' elif suffix == '.m': attr_name",
"are not logged in. Only users that have logged in can access this",
"__authors__ = ['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)'] import base64 import httplib import logging from",
"None) if match_etag is not None and etag is not None and (match_etag",
"None: raise web.HTTPError(404, 'Photo was not found or you do not have permission",
"Always expect well-formed Content-MD5 header. This ensures that the image data always matches",
"suffix): \"\"\"Generate S3 signed URL for the given photo. The S3 response will",
"due to non-deterministic JPG creation IOS code. # Only log the mismatch if",
"the mismatch if it's an original photo to avoid spamming logs. if suffix",
"sends mismatched MD5 values due to non-deterministic JPG creation IOS code. # Only",
"mismatch if it's an original photo to avoid spamming logs. if suffix ==",
"If uploading the photo, the user must be the episode owner 4. A",
"header.') try: request_md5 = self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400, 'Content-MD5 header",
"to the S3 location. self.redirect(_GetUploadUrl(photo, request_md5)) else: # The client often sends mismatched",
"= getattr(photo, attr_name) if expected_md5 != actual_md5: if etag is None: # Since",
"method type verifies user authentication credentials. \"\"\" @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def get(self, episode_id,",
"user credentials. If the user has write access to the photo, and if",
"episode_id, photo_id, write_access=True) # Get photo metadata, which will be used to create",
"a prospective user. viewpoint = yield gen.Task(Viewpoint.Query, client, episode.viewpoint_id, None) if not viewpoint.IsSystem():",
"be unshared 3. If uploading the photo, the user must be the episode",
"= ['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)'] import base64 import httplib import logging from tornado",
"raise web.HTTPError(403, 'You do not have permission to upload this photo; it is",
"episode id # when trying to fetch a photo, even if the photo",
"if an 'If-None-Match' is present, sends a HEAD request to the object store",
"= 'orig_md5' elif suffix == '.f': attr_name = 'full_md5' elif suffix == '.m':",
"expected_md5 != actual_md5: if etag is None: # Since there is not yet",
"and returns a signed S3 URL for the photo if so. \"\"\" yield",
"code. # Only log the mismatch if it's an original photo to avoid",
"# raise web.HTTPError(403, 'This photo can no longer be viewed; it was removed.')",
"'med_md5' elif suffix == '.t': attr_name = 'tn_md5' else: raise web.HTTPError(404, 'Photo not",
"2012 Viewfinder Inc. All Rights Reserved. \"\"\"HTTP request handler for serving viewfinder photo",
"suffix == '.t': attr_name = 'tn_md5' else: raise web.HTTPError(404, 'Photo not found; \"%s\"",
"header \"%s\" is not a valid base-64 value.' % request_md5) # Match against",
"episode.user_id != user_id: raise web.HTTPError(403, 'You do not have permission to upload this",
"tries to sync to their library. For now, I'm disabling this # check.",
"therefore no PUT of the image data is needed). match_etag = self.request.headers.get('If-None-Match', None)",
"has a bug where it always passes in the library episode id #",
"and a 1 year max age. \"\"\" return obj_store.GenerateUrl(photo_id + suffix, cache_control='private,max-age=31536000') class",
"not found or you do not have permission to view it.') if write_access",
"Post.ConstructPostId(episode_id, photo_id) episode, post = yield [gen.Task(Episode.QueryIfVisible, client, user_id, episode_id, must_exist=False), gen.Task(Post.Query, client,",
"owned by you.') if post.IsUnshared(): raise web.HTTPError(403, 'This photo can no longer be",
"request_md5)) else: # The client often sends mismatched MD5 values due to non-deterministic",
"will be used to create the upload URL. photo = yield gen.Task(Photo.Query, self._client,",
"the photo metadata to be equal to the # actual MD5 value. setattr(photo,",
"longer be viewed; it was removed.') if not context.CanViewViewpoint(episode.viewpoint_id): # Always allow system",
"from viewfinder.backend.db.episode import Episode from viewfinder.backend.db.photo import Photo from viewfinder.backend.db.post import Post from",
"accessed by a prospective user. viewpoint = yield gen.Task(Viewpoint.Query, client, episode.viewpoint_id, None) if",
"The 1.5 client has a bug where it always passes in the library",
"get the specified photo, and returns a signed S3 URL for the photo",
"value.' % request_md5) # Match against the MD5 value stored in the photo",
"data is needed). match_etag = self.request.headers.get('If-None-Match', None) if match_etag is not None and",
"'.f': attr_name = 'full_md5' elif suffix == '.m': attr_name = 'med_md5' elif suffix",
"or post is None: raise web.HTTPError(404, 'Photo was not found or you do",
"not owned by you.') if post.IsUnshared(): raise web.HTTPError(403, 'This photo can no longer",
"of the image data is needed). match_etag = self.request.headers.get('If-None-Match', None) if match_etag is",
"fetch a photo, even if the photo is part of a conversation. This",
"Match against the MD5 value stored in the photo metadata. if suffix not",
"which will be used to create the upload URL. photo = yield gen.Task(Photo.Query,",
"for the current user and the requested photo are verified and the requester",
"must_exist=False), gen.Task(Post.Query, client, episode_id, photo_id, None, must_exist=False)] if episode is None or post",
"to sync to their library. For now, I'm disabling this # check. Once",
"must not be unshared 3. If uploading the photo, the user must be",
"episode_id, photo_id, write_access): \"\"\"Checks that the current user (in Viewfinder context) user is",
"attr_name = 'full_md5' elif suffix == '.m': attr_name = 'med_md5' elif suffix ==",
"expected_md5)) self.set_status(400) self.finish() else: # Check for If-None-Match header, which is used by",
"not match expected MD5 \"%s\"' % (actual_md5, expected_md5)) self.set_status(400) self.finish() else: # Check",
"% request_md5) # Match against the MD5 value stored in the photo metadata.",
"which is used by client to check whether photo image data # already",
"is not None and etag is not None and (match_etag == '*' or",
"be the episode owner 4. A prospective user has access only to photos",
"suffix == '.o': logging.error('Content-MD5 header \"%s\" does not match expected MD5 \"%s\"' %",
"the photo, the user must be the episode owner 4. A prospective user",
"to access the given photo: 1. The photo must exist, and be in",
"you do not have permission to view it.') if write_access and episode.user_id !=",
"raise web.HTTPError(403, 'You do not have permission to view this photo. ' 'To",
"to the FileObjectStoreHandler. For an s3 file store, permissions for the current user",
"for client to PUT it again. self.set_status(httplib.NOT_MODIFIED) self.finish() else: # Redirect to the",
"unshared.') # BUGBUG(Andy): The 1.5 client has a bug where it always passes",
"photo_id, suffix): \"\"\"Verifies user credentials. If the user has write access to the",
"file assets. In case of a local file store, permissions for the current",
"yield gen.Task(photo.Update, self._client) # Redirect to the S3 location. self.redirect(_GetUploadUrl(photo, request_md5)) else: #",
"# The client often sends mismatched MD5 values due to non-deterministic JPG creation",
"else: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.' % suffix) #",
"web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.' % suffix) # Check for",
"view this photo. ' 'To see it, you must register an account.') def",
"Otherwise, generates an upload URL and redirects. \"\"\" def _GetUploadUrl(photo, verified_md5): content_type =",
"Redirect to the S3 upload location. self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod @gen.coroutine def GetPhotoUrl(cls, client,",
"suffix)) @classmethod @gen.coroutine def _AuthorizeUser(cls, client, episode_id, photo_id, write_access): \"\"\"Checks that the current",
"are verified and the requester is redirected to a pre-authorized, expiring S3 URL.",
"setattr(photo, attr_name, actual_md5) yield gen.Task(photo.Update, self._client) # Redirect to the S3 location. self.redirect(_GetUploadUrl(photo,",
"None: # Since there is not yet any photo image data, update the",
"owner 4. A prospective user has access only to photos in the viewpoint",
"'Content-MD5' not in self.request.headers: raise web.HTTPError(400, 'Missing Content-MD5 header.') try: request_md5 = self.request.headers['Content-MD5']",
"to allow insecure file obj store for testing') def GeneratePhotoUrl(obj_store, photo_id, suffix): \"\"\"Generate",
"given photo. The S3 response will contain a Cache-Control header specifying private caching",
"is invalid.' % suffix) # Ensure that user has permission to PUT the",
"photo.photo_id, suffix) expected_md5 = getattr(photo, attr_name) if expected_md5 != actual_md5: if etag is",
"the library episode id # when trying to fetch a photo, even if",
"it was unshared.') # BUGBUG(Andy): The 1.5 client has a bug where it",
"also enables the detection of any bit corruption on the wire. if 'Content-MD5'",
"'full_md5' elif suffix == '.m': attr_name = 'med_md5' elif suffix == '.t': attr_name",
"and is not modified, so no need for client to PUT it again.",
"the specified photo, and returns a signed S3 URL for the photo if",
"@gen.coroutine def _AuthorizeUser(cls, client, episode_id, photo_id, write_access): \"\"\"Checks that the current user (in",
"where the actual image bits are stored. \"\"\" url = yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store,",
"\"\"\"Verifies user credentials and then redirects to the URL where the actual image",
"import Post from viewfinder.backend.db.user_post import UserPost from viewfinder.backend.db.viewpoint import Viewpoint from viewfinder.backend.www import",
"# Copyright 2012 Viewfinder Inc. All Rights Reserved. \"\"\"HTTP request handler for serving",
"storing image assets in the object store. GET request retrieve image assets. Each",
"A prospective user has access only to photos in the viewpoint specified in",
"gen.Task(Post.Query, client, episode_id, photo_id, None, must_exist=False)] if episode is None or post is",
"request to the object store to determine asset Etag. If the Etag matches,",
"allow insecure file obj store for testing') def GeneratePhotoUrl(obj_store, photo_id, suffix): \"\"\"Generate S3",
"@gen.engine def put(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials. If the user has",
"to determine asset Etag. If the Etag matches, returns a 304. Otherwise, generates",
"etag is None: # Since there is not yet any photo image data,",
"photo_id, write_access): \"\"\"Checks that the current user (in Viewfinder context) user is authorized",
"data # already exists (and therefore no PUT of the image data is",
"None and etag is not None and (match_etag == '*' or match_etag ==",
"URL for the given photo. The S3 response will contain a Cache-Control header",
"photo. The S3 response will contain a Cache-Control header specifying private caching and",
"user authentication credentials. \"\"\" @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def get(self, episode_id, photo_id, suffix): \"\"\"Verifies",
"if suffix not in ['.t', '.m', '.f', '.o']: raise web.HTTPError(404, 'Photo not found;",
"or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type, content_md5=verified_md5) # Always expect well-formed Content-MD5",
"'Photo was not found or you do not have permission to view it.')",
"the object store. GET request retrieve image assets. Each method type verifies user",
"photo_id, None, must_exist=False)] if episode is None or post is None: raise web.HTTPError(404,",
"GeneratePhotoUrl(obj_store, photo_id, suffix): \"\"\"Generate S3 signed URL for the given photo. The S3",
"[gen.Task(Episode.QueryIfVisible, client, user_id, episode_id, must_exist=False), gen.Task(Post.Query, client, episode_id, photo_id, None, must_exist=False)] if episode",
"is invalid.' % suffix) # Check for the existence of the photo's image",
"the given photo. The S3 response will contain a Cache-Control header specifying private",
"data exists and is not modified, so no need for client to PUT",
"photo_id, suffix): \"\"\"Checks that the current user (in Viewfinder context) is authorized to",
"photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True) # Get photo metadata, which will be",
"not None and (match_etag == '*' or match_etag == etag): # Photo image",
"signed S3 URL for the photo if so. \"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id,",
"users that have logged in can access this URL.') user_id = context.user.user_id post_id",
"\"\"\" context = base.ViewfinderContext.current() if context is None or context.user is None: raise",
"not have permission to view it.') if write_access and episode.user_id != user_id: raise",
"import httplib import logging from tornado import gen, options, web from viewfinder.backend.base import",
"contain a Cache-Control header specifying private caching and a 1 year max age.",
"detection of any bit corruption on the wire. if 'Content-MD5' not in self.request.headers:",
"is redirected to a pre-authorized, expiring S3 URL. PhotoStoreHandler: Request handler for authorizing",
"request_md5 = self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400, 'Content-MD5 header \"%s\" is",
"\"\"\"HTTP request handler for serving viewfinder photo image file assets. In case of",
"(match_etag == '*' or match_etag == etag): # Photo image data exists and",
"existence of the photo's image data in S3. etag = yield gen.Task(Photo.IsImageUploaded, self._obj_store,",
"photo = yield gen.Task(Photo.Query, self._client, photo_id, None) # Get name of MD5 attribute",
"@classmethod @gen.coroutine def _AuthorizeUser(cls, client, episode_id, photo_id, write_access): \"\"\"Checks that the current user",
"suffix) self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def put(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials.",
"is needed). match_etag = self.request.headers.get('If-None-Match', None) if match_etag is not None and etag",
"permissions for the current user and the requested photo are verified and the",
"_GetUploadUrl(photo, verified_md5): content_type = photo.content_type or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type, content_md5=verified_md5)",
"= self.request.headers.get('If-None-Match', None) if match_etag is not None and etag is not None",
"attr_name = 'med_md5' elif suffix == '.t': attr_name = 'tn_md5' else: raise web.HTTPError(404,",
"== '.f': attr_name = 'full_md5' elif suffix == '.m': attr_name = 'med_md5' elif",
"needed). match_etag = self.request.headers.get('If-None-Match', None) if match_etag is not None and etag is",
"in the photo metadata. if suffix not in ['.t', '.m', '.f', '.o']: raise",
"raise web.HTTPError(400, 'Content-MD5 header \"%s\" is not a valid base-64 value.' % request_md5)",
"post is None: raise web.HTTPError(404, 'Photo was not found or you do not",
"== etag): # Photo image data exists and is not modified, so no",
"image data, update the photo metadata to be equal to the # actual",
"local file store, permissions for the current user and the requested photo are",
"have permission to view it.') if write_access and episode.user_id != user_id: raise web.HTTPError(403,",
"upload URL. photo = yield gen.Task(Photo.Query, self._client, photo_id, None) # Get name of",
"in the metadata, and also enables the detection of any bit corruption on",
"Since there is not yet any photo image data, update the photo metadata",
"self.request.headers: raise web.HTTPError(400, 'Missing Content-MD5 header.') try: request_md5 = self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex')",
"match_etag = self.request.headers.get('If-None-Match', None) if match_etag is not None and etag is not",
"base.ViewfinderContext.current() if context is None or context.user is None: raise web.HTTPError(401, 'You are",
"raise web.HTTPError(403, 'This photo can no longer be viewed; it was unshared.') #",
"None) # Get name of MD5 attribute in the photo metadata. if suffix",
"self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type, content_md5=verified_md5) # Always expect well-formed Content-MD5 header. This ensures",
"httplib import logging from tornado import gen, options, web from viewfinder.backend.base import handler",
"check. #if post.IsRemoved(): # raise web.HTTPError(403, 'This photo can no longer be viewed;",
"self.finish() else: # Redirect to the S3 upload location. self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod @gen.coroutine",
"Rights Reserved. \"\"\"HTTP request handler for serving viewfinder photo image file assets. In",
"user and the requested photo are verified and the requester is redirected to",
"from viewfinder.backend.db.viewpoint import Viewpoint from viewfinder.backend.www import base options.define('validate_cert', default=True, help='set to False",
"specified in the cookie \"\"\" context = base.ViewfinderContext.current() if context is None or",
"already exists (and therefore no PUT of the image data is needed). match_etag",
"a local file store, permissions for the current user and the requested photo",
"context.user.user_id post_id = Post.ConstructPostId(episode_id, photo_id) episode, post = yield [gen.Task(Episode.QueryIfVisible, client, user_id, episode_id,",
"# Get name of MD5 attribute in the photo metadata. if suffix ==",
"prospective user has access only to photos in the viewpoint specified in the",
"import handler from viewfinder.backend.db.episode import Episode from viewfinder.backend.db.photo import Photo from viewfinder.backend.db.post import",
"no need for client to PUT it again. self.set_status(httplib.NOT_MODIFIED) self.finish() else: # Redirect",
"PUT the photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True) # Get photo metadata, which",
"access this URL.') user_id = context.user.user_id post_id = Post.ConstructPostId(episode_id, photo_id) episode, post =",
"not in self.request.headers: raise web.HTTPError(400, 'Missing Content-MD5 header.') try: request_md5 = self.request.headers['Content-MD5'] actual_md5",
"in S3. etag = yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix) expected_md5 = getattr(photo, attr_name)",
"you.') if post.IsUnshared(): raise web.HTTPError(403, 'This photo can no longer be viewed; it",
"a 304. Otherwise, generates an upload URL and redirects. \"\"\" def _GetUploadUrl(photo, verified_md5):",
"retrieve image assets. Each method type verifies user authentication credentials. \"\"\" @handler.asynchronous(datastore=True, obj_store=True)",
"metadata to be equal to the # actual MD5 value. setattr(photo, attr_name, actual_md5)",
"mismatched MD5 values due to non-deterministic JPG creation IOS code. # Only log",
"user has write access to the photo, and if an 'If-None-Match' is present,",
"user. viewpoint = yield gen.Task(Viewpoint.Query, client, episode.viewpoint_id, None) if not viewpoint.IsSystem(): raise web.HTTPError(403,",
"request_md5) # Match against the MD5 value stored in the photo metadata. if",
"year max age. \"\"\" return obj_store.GenerateUrl(photo_id + suffix, cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT",
"the image data always matches # what is in the metadata, and also",
"for the photo if so. \"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id, write_access=False) raise",
"creation IOS code. # Only log the mismatch if it's an original photo",
"client, user_id, episode_id, must_exist=False), gen.Task(Post.Query, client, episode_id, photo_id, None, must_exist=False)] if episode is",
"episode.viewpoint_id, None) if not viewpoint.IsSystem(): raise web.HTTPError(403, 'You do not have permission to",
"# actual MD5 value. setattr(photo, attr_name, actual_md5) yield gen.Task(photo.Update, self._client) # Redirect to",
"used to create the upload URL. photo = yield gen.Task(Photo.Query, self._client, photo_id, None)",
"403 errors when a user tries to sync to their library. For now,",
"in ['.t', '.m', '.f', '.o']: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is",
"so. \"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id, write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix)) @classmethod",
"the user must be the episode owner 4. A prospective user has access",
"episode_id, photo_id, suffix): \"\"\"Verifies user credentials. If the user has write access to",
"sync to their library. For now, I'm disabling this # check. Once 2.0",
"photo are verified and the requester is redirected to a pre-authorized, expiring S3",
"photo is part of a conversation. This results # in 403 errors when",
"the detection of any bit corruption on the wire. if 'Content-MD5' not in",
"prospective user. viewpoint = yield gen.Task(Viewpoint.Query, client, episode.viewpoint_id, None) if not viewpoint.IsSystem(): raise",
"obj_store=True) @gen.engine def get(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials and then redirects",
"ensures that the image data always matches # what is in the metadata,",
"need for client to PUT it again. self.set_status(httplib.NOT_MODIFIED) self.finish() else: # Redirect to",
"attr_name) if expected_md5 != actual_md5: if etag is None: # Since there is",
"location. self.redirect(_GetUploadUrl(photo, request_md5)) else: # The client often sends mismatched MD5 values due",
"header specifying private caching and a 1 year max age. \"\"\" return obj_store.GenerateUrl(photo_id",
"against the MD5 value stored in the photo metadata. if suffix not in",
"not yet any photo image data, update the photo metadata to be equal",
"suffix, cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT requests by storing image assets in the",
"photo can no longer be viewed; it was unshared.') # BUGBUG(Andy): The 1.5",
"passes in the library episode id # when trying to fetch a photo,",
"write_access): \"\"\"Checks that the current user (in Viewfinder context) user is authorized to",
"HEAD request to the object store to determine asset Etag. If the Etag",
"assets in the object store. GET request retrieve image assets. Each method type",
"in can access this URL.') user_id = context.user.user_id post_id = Post.ConstructPostId(episode_id, photo_id) episode,",
"to avoid spamming logs. if suffix == '.o': logging.error('Content-MD5 header \"%s\" does not",
"from viewfinder.backend.db.post import Post from viewfinder.backend.db.user_post import UserPost from viewfinder.backend.db.viewpoint import Viewpoint from",
"!= user_id: raise web.HTTPError(403, 'You do not have permission to upload this photo;",
"viewfinder.backend.db.post import Post from viewfinder.backend.db.user_post import UserPost from viewfinder.backend.db.viewpoint import Viewpoint from viewfinder.backend.www",
"file obj store for testing') def GeneratePhotoUrl(obj_store, photo_id, suffix): \"\"\"Generate S3 signed URL",
"UserPost from viewfinder.backend.db.viewpoint import Viewpoint from viewfinder.backend.www import base options.define('validate_cert', default=True, help='set to",
"signed URL for the given photo. The S3 response will contain a Cache-Control",
"suffix): \"\"\"Verifies user credentials and then redirects to the URL where the actual",
"!= actual_md5: if etag is None: # Since there is not yet any",
"client, episode_id, photo_id, write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix)) @classmethod @gen.coroutine def _AuthorizeUser(cls, client,",
"PhotoStoreHandler: Request handler for authorizing photo requests \"\"\" __authors__ = ['<EMAIL> (<NAME>)', '<EMAIL>",
"\"%s\" suffix is invalid.' % suffix) # Check for the existence of the",
"in. Only users that have logged in can access this URL.') user_id =",
"access only to photos in the viewpoint specified in the cookie \"\"\" context",
"to the URL where the actual image bits are stored. \"\"\" url =",
"episode_id, photo_id, suffix) self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def put(self, episode_id, photo_id, suffix): \"\"\"Verifies",
"image data # already exists (and therefore no PUT of the image data",
"+ suffix, cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT requests by storing image assets in",
"permission to PUT the photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True) # Get photo",
"is redirected to the FileObjectStoreHandler. For an s3 file store, permissions for the",
"user_id = context.user.user_id post_id = Post.ConstructPostId(episode_id, photo_id) episode, post = yield [gen.Task(Episode.QueryIfVisible, client,",
"object store. GET request retrieve image assets. Each method type verifies user authentication",
"library episode id # when trying to fetch a photo, even if the",
"gen.Task(Photo.Query, self._client, photo_id, None) # Get name of MD5 attribute in the photo",
"try: request_md5 = self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400, 'Content-MD5 header \"%s\"",
"episode, post = yield [gen.Task(Episode.QueryIfVisible, client, user_id, episode_id, must_exist=False), gen.Task(Post.Query, client, episode_id, photo_id,",
"re-enable the check. #if post.IsRemoved(): # raise web.HTTPError(403, 'This photo can no longer",
"current user and the requested photo are verified and the requester is redirected",
"write_access=False) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix)) @classmethod @gen.coroutine def _AuthorizeUser(cls, client, episode_id, photo_id, write_access):",
"from tornado import gen, options, web from viewfinder.backend.base import handler from viewfinder.backend.db.episode import",
"context) is authorized to get the specified photo, and returns a signed S3",
"#if post.IsRemoved(): # raise web.HTTPError(403, 'This photo can no longer be viewed; it",
"for authorizing photo requests \"\"\" __authors__ = ['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)'] import base64",
"\"%s\"' % (actual_md5, expected_md5)) self.set_status(400) self.finish() else: # Check for If-None-Match header, which",
"URL for the photo if so. \"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id, write_access=False)",
"PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True) # Get photo metadata, which will be used to",
"is None: # Since there is not yet any photo image data, update",
"to non-deterministic JPG creation IOS code. # Only log the mismatch if it's",
"web.HTTPError(404, 'Photo was not found or you do not have permission to view",
"web.HTTPError(400, 'Missing Content-MD5 header.') try: request_md5 = self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex') except: raise",
"upload URL and redirects. \"\"\" def _GetUploadUrl(photo, verified_md5): content_type = photo.content_type or 'image/jpeg'",
"client has a bug where it always passes in the library episode id",
"yield gen.Task(Viewpoint.Query, client, episode.viewpoint_id, None) if not viewpoint.IsSystem(): raise web.HTTPError(403, 'You do not",
"in the library episode id # when trying to fetch a photo, even",
"None, must_exist=False)] if episode is None or post is None: raise web.HTTPError(404, 'Photo",
"corruption on the wire. if 'Content-MD5' not in self.request.headers: raise web.HTTPError(400, 'Missing Content-MD5",
"valid base-64 value.' % request_md5) # Match against the MD5 value stored in",
"wire. if 'Content-MD5' not in self.request.headers: raise web.HTTPError(400, 'Missing Content-MD5 header.') try: request_md5",
"to get the specified photo, and returns a signed S3 URL for the",
"equal to the # actual MD5 value. setattr(photo, attr_name, actual_md5) yield gen.Task(photo.Update, self._client)",
"episode_id, photo_id, suffix): \"\"\"Verifies user credentials and then redirects to the URL where",
"permission to upload this photo; it is not owned by you.') if post.IsUnshared():",
"self.set_status(httplib.NOT_MODIFIED) self.finish() else: # Redirect to the S3 upload location. self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod",
"episode_id, photo_id, suffix): \"\"\"Checks that the current user (in Viewfinder context) is authorized",
"request retrieve image assets. Each method type verifies user authentication credentials. \"\"\" @handler.asynchronous(datastore=True,",
"episode_id, must_exist=False), gen.Task(Post.Query, client, episode_id, photo_id, None, must_exist=False)] if episode is None or",
"handler from viewfinder.backend.db.episode import Episode from viewfinder.backend.db.photo import Photo from viewfinder.backend.db.post import Post",
"Check for the existence of the photo's image data in S3. etag =",
"@handler.asynchronous(datastore=True, obj_store=True) @gen.engine def get(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials and then",
"None and (match_etag == '*' or match_etag == etag): # Photo image data",
"% suffix) # Ensure that user has permission to PUT the photo. yield",
"photo metadata, which will be used to create the upload URL. photo =",
"the image data is needed). match_etag = self.request.headers.get('If-None-Match', None) if match_etag is not",
"given episode 2. The photo must not be unshared 3. If uploading the",
"self._client, photo_id, None) # Get name of MD5 attribute in the photo metadata.",
"Etag matches, returns a 304. Otherwise, generates an upload URL and redirects. \"\"\"",
"raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.' % suffix) # Ensure",
"has permission to PUT the photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True) # Get",
"metadata, which will be used to create the upload URL. photo = yield",
"Get name of MD5 attribute in the photo metadata. if suffix == '.o':",
"304. Otherwise, generates an upload URL and redirects. \"\"\" def _GetUploadUrl(photo, verified_md5): content_type",
"MD5 attribute in the photo metadata. if suffix == '.o': attr_name = 'orig_md5'",
"spamming logs. if suffix == '.o': logging.error('Content-MD5 header \"%s\" does not match expected",
"upload location. self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod @gen.coroutine def GetPhotoUrl(cls, client, obj_store, episode_id, photo_id, suffix):",
"def GetPhotoUrl(cls, client, obj_store, episode_id, photo_id, suffix): \"\"\"Checks that the current user (in",
"user has access only to photos in the viewpoint specified in the cookie",
"base-64 value.' % request_md5) # Match against the MD5 value stored in the",
"allow system viewpoints to be accessed by a prospective user. viewpoint = yield",
"Each method type verifies user authentication credentials. \"\"\" @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def get(self,",
"attribute in the photo metadata. if suffix == '.o': attr_name = 'orig_md5' elif",
"else: # Redirect to the S3 upload location. self.redirect(_GetUploadUrl(photo, request_md5)) @classmethod @gen.coroutine def",
"\"\"\"Handles PUT requests by storing image assets in the object store. GET request",
"match expected MD5 \"%s\"' % (actual_md5, expected_md5)) self.set_status(400) self.finish() else: # Check for",
"'Photo not found; \"%s\" suffix is invalid.' % suffix) # Check for the",
"has access only to photos in the viewpoint specified in the cookie \"\"\"",
"redirected to the FileObjectStoreHandler. For an s3 file store, permissions for the current",
"user_id: raise web.HTTPError(403, 'You do not have permission to upload this photo; it",
"private caching and a 1 year max age. \"\"\" return obj_store.GenerateUrl(photo_id + suffix,",
"photo: 1. The photo must exist, and be in the given episode 2.",
"a pre-authorized, expiring S3 URL. PhotoStoreHandler: Request handler for authorizing photo requests \"\"\"",
"photo can no longer be viewed; it was removed.') if not context.CanViewViewpoint(episode.viewpoint_id): #",
"photo_id, suffix): \"\"\"Verifies user credentials and then redirects to the URL where the",
"by a prospective user. viewpoint = yield gen.Task(Viewpoint.Query, client, episode.viewpoint_id, None) if not",
"'Content-MD5 header \"%s\" is not a valid base-64 value.' % request_md5) # Match",
"suffix == '.f': attr_name = 'full_md5' elif suffix == '.m': attr_name = 'med_md5'",
"a photo, even if the photo is part of a conversation. This results",
"store, permissions for the current user and the requested photo are verified and",
"else: # The client often sends mismatched MD5 values due to non-deterministic JPG",
"any bit corruption on the wire. if 'Content-MD5' not in self.request.headers: raise web.HTTPError(400,",
"photo_id, suffix) self.redirect(url) @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def put(self, episode_id, photo_id, suffix): \"\"\"Verifies user",
"is part of a conversation. This results # in 403 errors when a",
"options.define('validate_cert', default=True, help='set to False to allow insecure file obj store for testing')",
"is present, sends a HEAD request to the object store to determine asset",
"IOS code. # Only log the mismatch if it's an original photo to",
"to the photo, and if an 'If-None-Match' is present, sends a HEAD request",
"else: # Check for If-None-Match header, which is used by client to check",
"is not None and (match_etag == '*' or match_etag == etag): # Photo",
"The photo must not be unshared 3. If uploading the photo, the user",
"itself, I'll re-enable the check. #if post.IsRemoved(): # raise web.HTTPError(403, 'This photo can",
"stored in the photo metadata. if suffix not in ['.t', '.m', '.f', '.o']:",
"from viewfinder.backend.base import handler from viewfinder.backend.db.episode import Episode from viewfinder.backend.db.photo import Photo from",
"that user has permission to PUT the photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True)",
"put(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials. If the user has write access",
"'.m', '.f', '.o']: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.' %",
"\"\"\" @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def get(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials and",
"returns a signed S3 URL for the photo if so. \"\"\" yield gen.Task(PhotoStoreHandler._AuthorizeUser,",
"MD5 \"%s\"' % (actual_md5, expected_md5)) self.set_status(400) self.finish() else: # Check for If-None-Match header,",
"or match_etag == etag): # Photo image data exists and is not modified,",
"viewpoint = yield gen.Task(Viewpoint.Query, client, episode.viewpoint_id, None) if not viewpoint.IsSystem(): raise web.HTTPError(403, 'You",
"check whether photo image data # already exists (and therefore no PUT of",
"photo metadata to be equal to the # actual MD5 value. setattr(photo, attr_name,",
"attr_name = 'tn_md5' else: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix is invalid.'",
"client, episode.viewpoint_id, None) if not viewpoint.IsSystem(): raise web.HTTPError(403, 'You do not have permission",
"bug where it always passes in the library episode id # when trying",
"must be the episode owner 4. A prospective user has access only to",
"do not have permission to upload this photo; it is not owned by",
"the requested photo are verified and the requester is redirected to the FileObjectStoreHandler.",
"def put(self, episode_id, photo_id, suffix): \"\"\"Verifies user credentials. If the user has write",
"photo to avoid spamming logs. if suffix == '.o': logging.error('Content-MD5 header \"%s\" does",
"a 1 year max age. \"\"\" return obj_store.GenerateUrl(photo_id + suffix, cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler):",
"a valid base-64 value.' % request_md5) # Match against the MD5 value stored",
"Redirect to the S3 location. self.redirect(_GetUploadUrl(photo, request_md5)) else: # The client often sends",
"content_type = photo.content_type or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type, content_md5=verified_md5) # Always",
"log the mismatch if it's an original photo to avoid spamming logs. if",
"the photo is part of a conversation. This results # in 403 errors",
"often sends mismatched MD5 values due to non-deterministic JPG creation IOS code. #",
"'This photo can no longer be viewed; it was unshared.') # BUGBUG(Andy): The",
"photo metadata. if suffix == '.o': attr_name = 'orig_md5' elif suffix == '.f':",
"return obj_store.GenerateUrl(photo_id + suffix, cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT requests by storing image",
"etag = yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix) expected_md5 = getattr(photo, attr_name) if expected_md5",
"found; \"%s\" suffix is invalid.' % suffix) # Check for the existence of",
"is used by client to check whether photo image data # already exists",
"photo image data # already exists (and therefore no PUT of the image",
"in the cookie \"\"\" context = base.ViewfinderContext.current() if context is None or context.user",
"cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT requests by storing image assets in the object",
"photo, and if an 'If-None-Match' is present, sends a HEAD request to the",
"elif suffix == '.t': attr_name = 'tn_md5' else: raise web.HTTPError(404, 'Photo not found;",
"web.HTTPError(403, 'This photo can no longer be viewed; it was unshared.') # BUGBUG(Andy):",
"was unshared.') # BUGBUG(Andy): The 1.5 client has a bug where it always",
"def _IsInteractiveRequest(self): \"\"\"Always returns false, as this API is accessed programatically.\"\"\" return False",
"will contain a Cache-Control header specifying private caching and a 1 year max",
"\"\"\" return obj_store.GenerateUrl(photo_id + suffix, cache_control='private,max-age=31536000') class PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT requests by storing",
"PhotoStoreHandler(base.BaseHandler): \"\"\"Handles PUT requests by storing image assets in the object store. GET",
"# in 403 errors when a user tries to sync to their library.",
"BUGBUG(Andy): The 1.5 client has a bug where it always passes in the",
"check. Once 2.0 has established itself, I'll re-enable the check. #if post.IsRemoved(): #",
"requester is redirected to a pre-authorized, expiring S3 URL. PhotoStoreHandler: Request handler for",
"etag): # Photo image data exists and is not modified, so no need",
"authorized to get the specified photo, and returns a signed S3 URL for",
"errors when a user tries to sync to their library. For now, I'm",
"authentication credentials. \"\"\" @handler.asynchronous(datastore=True, obj_store=True) @gen.engine def get(self, episode_id, photo_id, suffix): \"\"\"Verifies user",
"2.0 has established itself, I'll re-enable the check. #if post.IsRemoved(): # raise web.HTTPError(403,",
"this photo; it is not owned by you.') if post.IsUnshared(): raise web.HTTPError(403, 'This",
"This ensures that the image data always matches # what is in the",
"not in ['.t', '.m', '.f', '.o']: raise web.HTTPError(404, 'Photo not found; \"%s\" suffix",
"viewfinder.backend.db.episode import Episode from viewfinder.backend.db.photo import Photo from viewfinder.backend.db.post import Post from viewfinder.backend.db.user_post",
"is not modified, so no need for client to PUT it again. self.set_status(httplib.NOT_MODIFIED)",
"this photo. ' 'To see it, you must register an account.') def _IsInteractiveRequest(self):",
"to their library. For now, I'm disabling this # check. Once 2.0 has",
"user tries to sync to their library. For now, I'm disabling this #",
"viewfinder.backend.db.photo import Photo from viewfinder.backend.db.post import Post from viewfinder.backend.db.user_post import UserPost from viewfinder.backend.db.viewpoint",
"Check for If-None-Match header, which is used by client to check whether photo",
"episode is None or post is None: raise web.HTTPError(404, 'Photo was not found",
"no PUT of the image data is needed). match_etag = self.request.headers.get('If-None-Match', None) if",
"update the photo metadata to be equal to the # actual MD5 value.",
"etag is not None and (match_etag == '*' or match_etag == etag): #",
"photos in the viewpoint specified in the cookie \"\"\" context = base.ViewfinderContext.current() if",
"base64 import httplib import logging from tornado import gen, options, web from viewfinder.backend.base",
"removed.') if not context.CanViewViewpoint(episode.viewpoint_id): # Always allow system viewpoints to be accessed by",
"+ suffix, content_type=content_type, content_md5=verified_md5) # Always expect well-formed Content-MD5 header. This ensures that",
"Etag. If the Etag matches, returns a 304. Otherwise, generates an upload URL"
] |
[
"return ground_shot def any_shot(self, car: Car, target: vec3, intercept: Intercept) -> Maneuver: ball",
"1500 and ground_distance(car, ball) < 1500 and ground_distance(ball, self.info.my_goal.center) > 1000 ): if",
"if alignment < 0.1 and abs(ball.position[1] - target[1]) > 3000: return MirrorStrike(car, self.info,",
"distance, ground_distance, align class Offense: def __init__(self, info: GameInfo): self.info = info self.allow_dribbles",
"def __init__(self, info: GameInfo): self.info = info self.allow_dribbles = False def direct_shot(self, car:",
"maneuvers.strikes.close_shot import CloseShot from maneuvers.strikes.dodge_strike import DodgeStrike from maneuvers.strikes.ground_strike import GroundStrike from maneuvers.strikes.mirror_strike",
"< 4000 or distance(ground_shot.intercept.ball.velocity, car.velocity) < 500 ): if ( distance(dodge_shot.intercept.ground_pos, target) <",
"and (100 < ball.position[2] or abs(ball.velocity[2]) > 300) and abs(ball.velocity[2]) < 1500 and",
"TODO aerial_strike = AerialStrike(car, self.info, target) fast_aerial = FastAerialStrike(car, self.info, target) better_aerial_strike =",
"250 < ball.position[2] < 550 and self.is_opponent_close(car, ball): # return DoubleJumpStrike(car, self.info, target)",
"MirrorStrike(car, self.info, target) # if 250 < ball.position[2] < 550 and self.is_opponent_close(car, ball):",
"any_shot(self, car: Car, target: vec3, intercept: Intercept) -> Maneuver: ball = intercept.ball if",
"if ( self.allow_dribbles and (100 < ball.position[2] or abs(ball.velocity[2]) > 300) and abs(ball.velocity[2])",
"if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) < 5000: return DoubleTouch(better_aerial_strike) return better_aerial_strike if ( dodge_shot.intercept.time <",
"align(car.position, ball, target) if alignment < 0.1 and abs(ball.position[1] - target[1]) > 3000:",
"from tools.vector_math import distance, ground_distance, align class Offense: def __init__(self, info: GameInfo): self.info",
"ground_shot.intercept.time - 0.1 or ground_distance(dodge_shot.intercept, target) < 4000 or distance(ground_shot.intercept.ball.velocity, car.velocity) < 500",
"# return DoubleJumpStrike(car, self.info, target) return self.direct_shot(car, target) def is_opponent_close(self, car, ball) ->",
"def is_opponent_close(self, car, ball) -> bool: for opponent in self.info.get_opponents(car): if ground_distance(opponent, ball)",
"abs(ball.velocity[2]) > 300) and abs(ball.velocity[2]) < 1500 and ground_distance(car, ball) < 1500 and",
"Car, target: vec3) -> Maneuver: dodge_shot = DodgeStrike(car, self.info, target) ground_shot = GroundStrike(car,",
"self.direct_shot(car, target) def is_opponent_close(self, car, ball) -> bool: for opponent in self.info.get_opponents(car): if",
"vec3, intercept: Intercept) -> Maneuver: ball = intercept.ball if ( self.allow_dribbles and (100",
"3000 ): return CloseShot(car, self.info, target) return dodge_shot return ground_shot def any_shot(self, car:",
"self.info, target) fast_aerial = FastAerialStrike(car, self.info, target) better_aerial_strike = min([aerial_strike, fast_aerial], key=lambda strike:",
"align class Offense: def __init__(self, info: GameInfo): self.info = info self.allow_dribbles = False",
"FastAerialStrike(car, self.info, target) better_aerial_strike = min([aerial_strike, fast_aerial], key=lambda strike: strike.intercept.time) if better_aerial_strike.intercept.time <",
"or ground_distance(dodge_shot.intercept, target) < 4000 or distance(ground_shot.intercept.ball.velocity, car.velocity) < 500 ): if (",
"direct_shot(self, car: Car, target: vec3) -> Maneuver: dodge_shot = DodgeStrike(car, self.info, target) ground_shot",
"< 4000 and abs(dodge_shot.intercept.ground_pos[0]) < 3000 ): return CloseShot(car, self.info, target) return dodge_shot",
"4000 and abs(dodge_shot.intercept.ground_pos[0]) < 3000 ): return CloseShot(car, self.info, target) return dodge_shot return",
"target) alignment = align(car.position, ball, target) if alignment < 0.1 and abs(ball.position[1] -",
"and abs(ball.position[1] - target[1]) > 3000: return MirrorStrike(car, self.info, target) # if 250",
"from maneuvers.maneuver import Maneuver from maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot import CloseShot",
"ground_shot = GroundStrike(car, self.info, target) if car.boost > 40: # TODO aerial_strike =",
"dodge_shot return ground_shot def any_shot(self, car: Car, target: vec3, intercept: Intercept) -> Maneuver:",
"target[1]) > 3000: return MirrorStrike(car, self.info, target) # if 250 < ball.position[2] <",
"self.info, target) return self.direct_shot(car, target) def is_opponent_close(self, car, ball) -> bool: for opponent",
"target) return self.direct_shot(car, target) def is_opponent_close(self, car, ball) -> bool: for opponent in",
"< 3000 ): return CloseShot(car, self.info, target) return dodge_shot return ground_shot def any_shot(self,",
"car.boost > 40: # TODO aerial_strike = AerialStrike(car, self.info, target) fast_aerial = FastAerialStrike(car,",
"car, ball) -> bool: for opponent in self.info.get_opponents(car): if ground_distance(opponent, ball) < ball.position[2]",
"import DoubleTouch from maneuvers.dribbling.carry_and_flick import CarryAndFlick from maneuvers.maneuver import Maneuver from maneuvers.strikes.aerial_strike import",
"FastAerialStrike from maneuvers.strikes.close_shot import CloseShot from maneuvers.strikes.dodge_strike import DodgeStrike from maneuvers.strikes.ground_strike import GroundStrike",
"distance(ground_shot.intercept.ball.velocity, car.velocity) < 500 ): if ( distance(dodge_shot.intercept.ground_pos, target) < 4000 and abs(dodge_shot.intercept.ground_pos[0])",
"def any_shot(self, car: Car, target: vec3, intercept: Intercept) -> Maneuver: ball = intercept.ball",
"if ( dodge_shot.intercept.time < ground_shot.intercept.time - 0.1 or ground_distance(dodge_shot.intercept, target) < 4000 or",
"self.is_opponent_close(car, ball): # return DoubleJumpStrike(car, self.info, target) return self.direct_shot(car, target) def is_opponent_close(self, car,",
"from maneuvers.dribbling.carry_and_flick import CarryAndFlick from maneuvers.maneuver import Maneuver from maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike",
"if not self.is_opponent_close(car, ball): return CarryAndFlick(car, self.info, target) alignment = align(car.position, ball, target)",
"Car from tools.game_info import GameInfo from tools.intercept import Intercept from tools.vector_math import distance,",
"import vec3 from rlutilities.simulation import Car from tools.game_info import GameInfo from tools.intercept import",
"> 1000 ): if not self.is_opponent_close(car, ball): return CarryAndFlick(car, self.info, target) alignment =",
"= DodgeStrike(car, self.info, target) ground_shot = GroundStrike(car, self.info, target) if car.boost > 40:",
"False def direct_shot(self, car: Car, target: vec3) -> Maneuver: dodge_shot = DodgeStrike(car, self.info,",
"key=lambda strike: strike.intercept.time) if better_aerial_strike.intercept.time < dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) < 5000: return",
"return DoubleTouch(better_aerial_strike) return better_aerial_strike if ( dodge_shot.intercept.time < ground_shot.intercept.time - 0.1 or ground_distance(dodge_shot.intercept,",
"0.1 or ground_distance(dodge_shot.intercept, target) < 4000 or distance(ground_shot.intercept.ball.velocity, car.velocity) < 500 ): if",
"< ball.position[2] or abs(ball.velocity[2]) > 300) and abs(ball.velocity[2]) < 1500 and ground_distance(car, ball)",
"self.info.get_opponents(car): if ground_distance(opponent, ball) < ball.position[2] * 2 + 1000: return True return",
"( self.allow_dribbles and (100 < ball.position[2] or abs(ball.velocity[2]) > 300) and abs(ball.velocity[2]) <",
"ball.position[2] < 550 and self.is_opponent_close(car, ball): # return DoubleJumpStrike(car, self.info, target) return self.direct_shot(car,",
"= align(car.position, ball, target) if alignment < 0.1 and abs(ball.position[1] - target[1]) >",
"strike: strike.intercept.time) if better_aerial_strike.intercept.time < dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) < 5000: return DoubleTouch(better_aerial_strike)",
"MirrorStrike from rlutilities.linear_algebra import vec3 from rlutilities.simulation import Car from tools.game_info import GameInfo",
"ball = intercept.ball if ( self.allow_dribbles and (100 < ball.position[2] or abs(ball.velocity[2]) >",
"= intercept.ball if ( self.allow_dribbles and (100 < ball.position[2] or abs(ball.velocity[2]) > 300)",
"better_aerial_strike = min([aerial_strike, fast_aerial], key=lambda strike: strike.intercept.time) if better_aerial_strike.intercept.time < dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept,",
"AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot import CloseShot from maneuvers.strikes.dodge_strike import DodgeStrike from maneuvers.strikes.ground_strike import",
"< 1500 and ground_distance(car, ball) < 1500 and ground_distance(ball, self.info.my_goal.center) > 1000 ):",
"1000 ): if not self.is_opponent_close(car, ball): return CarryAndFlick(car, self.info, target) alignment = align(car.position,",
"return DoubleJumpStrike(car, self.info, target) return self.direct_shot(car, target) def is_opponent_close(self, car, ball) -> bool:",
"intercept: Intercept) -> Maneuver: ball = intercept.ball if ( self.allow_dribbles and (100 <",
"better_aerial_strike if ( dodge_shot.intercept.time < ground_shot.intercept.time - 0.1 or ground_distance(dodge_shot.intercept, target) < 4000",
"return CarryAndFlick(car, self.info, target) alignment = align(car.position, ball, target) if alignment < 0.1",
"if 250 < ball.position[2] < 550 and self.is_opponent_close(car, ball): # return DoubleJumpStrike(car, self.info,",
"= min([aerial_strike, fast_aerial], key=lambda strike: strike.intercept.time) if better_aerial_strike.intercept.time < dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center)",
"bool: for opponent in self.info.get_opponents(car): if ground_distance(opponent, ball) < ball.position[2] * 2 +",
"ground_distance(dodge_shot.intercept, target) < 4000 or distance(ground_shot.intercept.ball.velocity, car.velocity) < 500 ): if ( distance(dodge_shot.intercept.ground_pos,",
"fast_aerial], key=lambda strike: strike.intercept.time) if better_aerial_strike.intercept.time < dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) < 5000:",
"< 1500 and ground_distance(ball, self.info.my_goal.center) > 1000 ): if not self.is_opponent_close(car, ball): return",
"from rlutilities.simulation import Car from tools.game_info import GameInfo from tools.intercept import Intercept from",
"maneuvers.strikes.double_touch import DoubleTouch from maneuvers.dribbling.carry_and_flick import CarryAndFlick from maneuvers.maneuver import Maneuver from maneuvers.strikes.aerial_strike",
"maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot import CloseShot from maneuvers.strikes.dodge_strike import DodgeStrike from",
"> 40: # TODO aerial_strike = AerialStrike(car, self.info, target) fast_aerial = FastAerialStrike(car, self.info,",
"target) fast_aerial = FastAerialStrike(car, self.info, target) better_aerial_strike = min([aerial_strike, fast_aerial], key=lambda strike: strike.intercept.time)",
"import Car from tools.game_info import GameInfo from tools.intercept import Intercept from tools.vector_math import",
"import GroundStrike from maneuvers.strikes.mirror_strike import MirrorStrike from rlutilities.linear_algebra import vec3 from rlutilities.simulation import",
"import GameInfo from tools.intercept import Intercept from tools.vector_math import distance, ground_distance, align class",
"maneuvers.maneuver import Maneuver from maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot import CloseShot from",
"= FastAerialStrike(car, self.info, target) better_aerial_strike = min([aerial_strike, fast_aerial], key=lambda strike: strike.intercept.time) if better_aerial_strike.intercept.time",
"import distance, ground_distance, align class Offense: def __init__(self, info: GameInfo): self.info = info",
"if better_aerial_strike.intercept.time < dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) < 5000: return DoubleTouch(better_aerial_strike) return better_aerial_strike",
"car.velocity) < 500 ): if ( distance(dodge_shot.intercept.ground_pos, target) < 4000 and abs(dodge_shot.intercept.ground_pos[0]) <",
"Offense: def __init__(self, info: GameInfo): self.info = info self.allow_dribbles = False def direct_shot(self,",
"AerialStrike(car, self.info, target) fast_aerial = FastAerialStrike(car, self.info, target) better_aerial_strike = min([aerial_strike, fast_aerial], key=lambda",
"ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) < 5000: return DoubleTouch(better_aerial_strike) return better_aerial_strike if ( dodge_shot.intercept.time < ground_shot.intercept.time",
"self.info, target) ground_shot = GroundStrike(car, self.info, target) if car.boost > 40: # TODO",
"maneuvers.dribbling.carry_and_flick import CarryAndFlick from maneuvers.maneuver import Maneuver from maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike from",
"= False def direct_shot(self, car: Car, target: vec3) -> Maneuver: dodge_shot = DodgeStrike(car,",
"class Offense: def __init__(self, info: GameInfo): self.info = info self.allow_dribbles = False def",
"import DodgeStrike from maneuvers.strikes.ground_strike import GroundStrike from maneuvers.strikes.mirror_strike import MirrorStrike from rlutilities.linear_algebra import",
"-> Maneuver: dodge_shot = DodgeStrike(car, self.info, target) ground_shot = GroundStrike(car, self.info, target) if",
"dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) < 5000: return DoubleTouch(better_aerial_strike) return better_aerial_strike if ( dodge_shot.intercept.time",
"dodge_shot.intercept.time < ground_shot.intercept.time - 0.1 or ground_distance(dodge_shot.intercept, target) < 4000 or distance(ground_shot.intercept.ball.velocity, car.velocity)",
"and self.is_opponent_close(car, ball): # return DoubleJumpStrike(car, self.info, target) return self.direct_shot(car, target) def is_opponent_close(self,",
"if car.boost > 40: # TODO aerial_strike = AerialStrike(car, self.info, target) fast_aerial =",
"from maneuvers.strikes.ground_strike import GroundStrike from maneuvers.strikes.mirror_strike import MirrorStrike from rlutilities.linear_algebra import vec3 from",
"dodge_shot = DodgeStrike(car, self.info, target) ground_shot = GroundStrike(car, self.info, target) if car.boost >",
"): if ( distance(dodge_shot.intercept.ground_pos, target) < 4000 and abs(dodge_shot.intercept.ground_pos[0]) < 3000 ): return",
"-> bool: for opponent in self.info.get_opponents(car): if ground_distance(opponent, ball) < ball.position[2] * 2",
"DoubleJumpStrike(car, self.info, target) return self.direct_shot(car, target) def is_opponent_close(self, car, ball) -> bool: for",
"self.info, target) if car.boost > 40: # TODO aerial_strike = AerialStrike(car, self.info, target)",
"GameInfo from tools.intercept import Intercept from tools.vector_math import distance, ground_distance, align class Offense:",
"rlutilities.linear_algebra import vec3 from rlutilities.simulation import Car from tools.game_info import GameInfo from tools.intercept",
"vec3) -> Maneuver: dodge_shot = DodgeStrike(car, self.info, target) ground_shot = GroundStrike(car, self.info, target)",
"ball.position[2] or abs(ball.velocity[2]) > 300) and abs(ball.velocity[2]) < 1500 and ground_distance(car, ball) <",
"( dodge_shot.intercept.time < ground_shot.intercept.time - 0.1 or ground_distance(dodge_shot.intercept, target) < 4000 or distance(ground_shot.intercept.ball.velocity,",
"and abs(ball.velocity[2]) < 1500 and ground_distance(car, ball) < 1500 and ground_distance(ball, self.info.my_goal.center) >",
"not self.is_opponent_close(car, ball): return CarryAndFlick(car, self.info, target) alignment = align(car.position, ball, target) if",
"GroundStrike(car, self.info, target) if car.boost > 40: # TODO aerial_strike = AerialStrike(car, self.info,",
"self.is_opponent_close(car, ball): return CarryAndFlick(car, self.info, target) alignment = align(car.position, ball, target) if alignment",
"import AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot import CloseShot from maneuvers.strikes.dodge_strike import DodgeStrike from maneuvers.strikes.ground_strike",
"tools.vector_math import distance, ground_distance, align class Offense: def __init__(self, info: GameInfo): self.info =",
"maneuvers.strikes.mirror_strike import MirrorStrike from rlutilities.linear_algebra import vec3 from rlutilities.simulation import Car from tools.game_info",
"40: # TODO aerial_strike = AerialStrike(car, self.info, target) fast_aerial = FastAerialStrike(car, self.info, target)",
"if ( distance(dodge_shot.intercept.ground_pos, target) < 4000 and abs(dodge_shot.intercept.ground_pos[0]) < 3000 ): return CloseShot(car,",
"self.info, target) return dodge_shot return ground_shot def any_shot(self, car: Car, target: vec3, intercept:",
"CloseShot from maneuvers.strikes.dodge_strike import DodgeStrike from maneuvers.strikes.ground_strike import GroundStrike from maneuvers.strikes.mirror_strike import MirrorStrike",
"target) better_aerial_strike = min([aerial_strike, fast_aerial], key=lambda strike: strike.intercept.time) if better_aerial_strike.intercept.time < dodge_shot.intercept.time: if",
"1500 and ground_distance(ball, self.info.my_goal.center) > 1000 ): if not self.is_opponent_close(car, ball): return CarryAndFlick(car,",
"): if not self.is_opponent_close(car, ball): return CarryAndFlick(car, self.info, target) alignment = align(car.position, ball,",
"tools.game_info import GameInfo from tools.intercept import Intercept from tools.vector_math import distance, ground_distance, align",
"__init__(self, info: GameInfo): self.info = info self.allow_dribbles = False def direct_shot(self, car: Car,",
"< dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) < 5000: return DoubleTouch(better_aerial_strike) return better_aerial_strike if (",
"tools.intercept import Intercept from tools.vector_math import distance, ground_distance, align class Offense: def __init__(self,",
"return self.direct_shot(car, target) def is_opponent_close(self, car, ball) -> bool: for opponent in self.info.get_opponents(car):",
"ball): # return DoubleJumpStrike(car, self.info, target) return self.direct_shot(car, target) def is_opponent_close(self, car, ball)",
"Intercept) -> Maneuver: ball = intercept.ball if ( self.allow_dribbles and (100 < ball.position[2]",
"DoubleTouch(better_aerial_strike) return better_aerial_strike if ( dodge_shot.intercept.time < ground_shot.intercept.time - 0.1 or ground_distance(dodge_shot.intercept, target)",
"< 500 ): if ( distance(dodge_shot.intercept.ground_pos, target) < 4000 and abs(dodge_shot.intercept.ground_pos[0]) < 3000",
"def direct_shot(self, car: Car, target: vec3) -> Maneuver: dodge_shot = DodgeStrike(car, self.info, target)",
"300) and abs(ball.velocity[2]) < 1500 and ground_distance(car, ball) < 1500 and ground_distance(ball, self.info.my_goal.center)",
"target) if car.boost > 40: # TODO aerial_strike = AerialStrike(car, self.info, target) fast_aerial",
"if ground_distance(opponent, ball) < ball.position[2] * 2 + 1000: return True return False",
"from maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot import CloseShot from maneuvers.strikes.dodge_strike import DodgeStrike",
"is_opponent_close(self, car, ball) -> bool: for opponent in self.info.get_opponents(car): if ground_distance(opponent, ball) <",
"from rlutilities.linear_algebra import vec3 from rlutilities.simulation import Car from tools.game_info import GameInfo from",
"> 300) and abs(ball.velocity[2]) < 1500 and ground_distance(car, ball) < 1500 and ground_distance(ball,",
"intercept.ball if ( self.allow_dribbles and (100 < ball.position[2] or abs(ball.velocity[2]) > 300) and",
"= AerialStrike(car, self.info, target) fast_aerial = FastAerialStrike(car, self.info, target) better_aerial_strike = min([aerial_strike, fast_aerial],",
"): return CloseShot(car, self.info, target) return dodge_shot return ground_shot def any_shot(self, car: Car,",
"self.info = info self.allow_dribbles = False def direct_shot(self, car: Car, target: vec3) ->",
"(100 < ball.position[2] or abs(ball.velocity[2]) > 300) and abs(ball.velocity[2]) < 1500 and ground_distance(car,",
"self.allow_dribbles and (100 < ball.position[2] or abs(ball.velocity[2]) > 300) and abs(ball.velocity[2]) < 1500",
"target: vec3) -> Maneuver: dodge_shot = DodgeStrike(car, self.info, target) ground_shot = GroundStrike(car, self.info,",
"alignment = align(car.position, ball, target) if alignment < 0.1 and abs(ball.position[1] - target[1])",
"abs(ball.position[1] - target[1]) > 3000: return MirrorStrike(car, self.info, target) # if 250 <",
"ball, target) if alignment < 0.1 and abs(ball.position[1] - target[1]) > 3000: return",
"target: vec3, intercept: Intercept) -> Maneuver: ball = intercept.ball if ( self.allow_dribbles and",
"target) return dodge_shot return ground_shot def any_shot(self, car: Car, target: vec3, intercept: Intercept)",
"abs(dodge_shot.intercept.ground_pos[0]) < 3000 ): return CloseShot(car, self.info, target) return dodge_shot return ground_shot def",
"DodgeStrike from maneuvers.strikes.ground_strike import GroundStrike from maneuvers.strikes.mirror_strike import MirrorStrike from rlutilities.linear_algebra import vec3",
"self.info, target) better_aerial_strike = min([aerial_strike, fast_aerial], key=lambda strike: strike.intercept.time) if better_aerial_strike.intercept.time < dodge_shot.intercept.time:",
"( distance(dodge_shot.intercept.ground_pos, target) < 4000 and abs(dodge_shot.intercept.ground_pos[0]) < 3000 ): return CloseShot(car, self.info,",
"ground_shot def any_shot(self, car: Car, target: vec3, intercept: Intercept) -> Maneuver: ball =",
"maneuvers.strikes.ground_strike import GroundStrike from maneuvers.strikes.mirror_strike import MirrorStrike from rlutilities.linear_algebra import vec3 from rlutilities.simulation",
"5000: return DoubleTouch(better_aerial_strike) return better_aerial_strike if ( dodge_shot.intercept.time < ground_shot.intercept.time - 0.1 or",
"ball) -> bool: for opponent in self.info.get_opponents(car): if ground_distance(opponent, ball) < ball.position[2] *",
"550 and self.is_opponent_close(car, ball): # return DoubleJumpStrike(car, self.info, target) return self.direct_shot(car, target) def",
"or distance(ground_shot.intercept.ball.velocity, car.velocity) < 500 ): if ( distance(dodge_shot.intercept.ground_pos, target) < 4000 and",
"distance(dodge_shot.intercept.ground_pos, target) < 4000 and abs(dodge_shot.intercept.ground_pos[0]) < 3000 ): return CloseShot(car, self.info, target)",
"return dodge_shot return ground_shot def any_shot(self, car: Car, target: vec3, intercept: Intercept) ->",
"better_aerial_strike.intercept.time < dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) < 5000: return DoubleTouch(better_aerial_strike) return better_aerial_strike if",
"aerial_strike = AerialStrike(car, self.info, target) fast_aerial = FastAerialStrike(car, self.info, target) better_aerial_strike = min([aerial_strike,",
"target) ground_shot = GroundStrike(car, self.info, target) if car.boost > 40: # TODO aerial_strike",
"self.info.their_goal.center) < 5000: return DoubleTouch(better_aerial_strike) return better_aerial_strike if ( dodge_shot.intercept.time < ground_shot.intercept.time -",
"target) < 4000 or distance(ground_shot.intercept.ball.velocity, car.velocity) < 500 ): if ( distance(dodge_shot.intercept.ground_pos, target)",
"ball): return CarryAndFlick(car, self.info, target) alignment = align(car.position, ball, target) if alignment <",
"ball) < 1500 and ground_distance(ball, self.info.my_goal.center) > 1000 ): if not self.is_opponent_close(car, ball):",
"< 0.1 and abs(ball.position[1] - target[1]) > 3000: return MirrorStrike(car, self.info, target) #",
"maneuvers.strikes.dodge_strike import DodgeStrike from maneuvers.strikes.ground_strike import GroundStrike from maneuvers.strikes.mirror_strike import MirrorStrike from rlutilities.linear_algebra",
"DoubleTouch from maneuvers.dribbling.carry_and_flick import CarryAndFlick from maneuvers.maneuver import Maneuver from maneuvers.strikes.aerial_strike import AerialStrike,",
"self.info, target) # if 250 < ball.position[2] < 550 and self.is_opponent_close(car, ball): #",
"CarryAndFlick(car, self.info, target) alignment = align(car.position, ball, target) if alignment < 0.1 and",
"Car, target: vec3, intercept: Intercept) -> Maneuver: ball = intercept.ball if ( self.allow_dribbles",
"car: Car, target: vec3) -> Maneuver: dodge_shot = DodgeStrike(car, self.info, target) ground_shot =",
"CarryAndFlick from maneuvers.maneuver import Maneuver from maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot import",
"import Maneuver from maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot import CloseShot from maneuvers.strikes.dodge_strike",
"alignment < 0.1 and abs(ball.position[1] - target[1]) > 3000: return MirrorStrike(car, self.info, target)",
"for opponent in self.info.get_opponents(car): if ground_distance(opponent, ball) < ball.position[2] * 2 + 1000:",
"< 550 and self.is_opponent_close(car, ball): # return DoubleJumpStrike(car, self.info, target) return self.direct_shot(car, target)",
"rlutilities.simulation import Car from tools.game_info import GameInfo from tools.intercept import Intercept from tools.vector_math",
"and ground_distance(ball, self.info.my_goal.center) > 1000 ): if not self.is_opponent_close(car, ball): return CarryAndFlick(car, self.info,",
"from maneuvers.strikes.dodge_strike import DodgeStrike from maneuvers.strikes.ground_strike import GroundStrike from maneuvers.strikes.mirror_strike import MirrorStrike from",
"GroundStrike from maneuvers.strikes.mirror_strike import MirrorStrike from rlutilities.linear_algebra import vec3 from rlutilities.simulation import Car",
"abs(ball.velocity[2]) < 1500 and ground_distance(car, ball) < 1500 and ground_distance(ball, self.info.my_goal.center) > 1000",
"from maneuvers.strikes.double_touch import DoubleTouch from maneuvers.dribbling.carry_and_flick import CarryAndFlick from maneuvers.maneuver import Maneuver from",
"from tools.intercept import Intercept from tools.vector_math import distance, ground_distance, align class Offense: def",
"return CloseShot(car, self.info, target) return dodge_shot return ground_shot def any_shot(self, car: Car, target:",
"DodgeStrike(car, self.info, target) ground_shot = GroundStrike(car, self.info, target) if car.boost > 40: #",
"import Intercept from tools.vector_math import distance, ground_distance, align class Offense: def __init__(self, info:",
"Intercept from tools.vector_math import distance, ground_distance, align class Offense: def __init__(self, info: GameInfo):",
"and abs(dodge_shot.intercept.ground_pos[0]) < 3000 ): return CloseShot(car, self.info, target) return dodge_shot return ground_shot",
"in self.info.get_opponents(car): if ground_distance(opponent, ball) < ball.position[2] * 2 + 1000: return True",
"500 ): if ( distance(dodge_shot.intercept.ground_pos, target) < 4000 and abs(dodge_shot.intercept.ground_pos[0]) < 3000 ):",
"= info self.allow_dribbles = False def direct_shot(self, car: Car, target: vec3) -> Maneuver:",
"< ground_shot.intercept.time - 0.1 or ground_distance(dodge_shot.intercept, target) < 4000 or distance(ground_shot.intercept.ball.velocity, car.velocity) <",
"opponent in self.info.get_opponents(car): if ground_distance(opponent, ball) < ball.position[2] * 2 + 1000: return",
"return MirrorStrike(car, self.info, target) # if 250 < ball.position[2] < 550 and self.is_opponent_close(car,",
"- 0.1 or ground_distance(dodge_shot.intercept, target) < 4000 or distance(ground_shot.intercept.ball.velocity, car.velocity) < 500 ):",
"from maneuvers.strikes.mirror_strike import MirrorStrike from rlutilities.linear_algebra import vec3 from rlutilities.simulation import Car from",
"info: GameInfo): self.info = info self.allow_dribbles = False def direct_shot(self, car: Car, target:",
"4000 or distance(ground_shot.intercept.ball.velocity, car.velocity) < 500 ): if ( distance(dodge_shot.intercept.ground_pos, target) < 4000",
"import CloseShot from maneuvers.strikes.dodge_strike import DodgeStrike from maneuvers.strikes.ground_strike import GroundStrike from maneuvers.strikes.mirror_strike import",
"target) def is_opponent_close(self, car, ball) -> bool: for opponent in self.info.get_opponents(car): if ground_distance(opponent,",
"target) < 4000 and abs(dodge_shot.intercept.ground_pos[0]) < 3000 ): return CloseShot(car, self.info, target) return",
"target) # if 250 < ball.position[2] < 550 and self.is_opponent_close(car, ball): # return",
"Maneuver from maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot import CloseShot from maneuvers.strikes.dodge_strike import",
"return better_aerial_strike if ( dodge_shot.intercept.time < ground_shot.intercept.time - 0.1 or ground_distance(dodge_shot.intercept, target) <",
"Maneuver: ball = intercept.ball if ( self.allow_dribbles and (100 < ball.position[2] or abs(ball.velocity[2])",
"info self.allow_dribbles = False def direct_shot(self, car: Car, target: vec3) -> Maneuver: dodge_shot",
"or abs(ball.velocity[2]) > 300) and abs(ball.velocity[2]) < 1500 and ground_distance(car, ball) < 1500",
"0.1 and abs(ball.position[1] - target[1]) > 3000: return MirrorStrike(car, self.info, target) # if",
"# if 250 < ball.position[2] < 550 and self.is_opponent_close(car, ball): # return DoubleJumpStrike(car,",
"> 3000: return MirrorStrike(car, self.info, target) # if 250 < ball.position[2] < 550",
"import MirrorStrike from rlutilities.linear_algebra import vec3 from rlutilities.simulation import Car from tools.game_info import",
"vec3 from rlutilities.simulation import Car from tools.game_info import GameInfo from tools.intercept import Intercept",
"Maneuver: dodge_shot = DodgeStrike(car, self.info, target) ground_shot = GroundStrike(car, self.info, target) if car.boost",
"min([aerial_strike, fast_aerial], key=lambda strike: strike.intercept.time) if better_aerial_strike.intercept.time < dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) <",
"= GroundStrike(car, self.info, target) if car.boost > 40: # TODO aerial_strike = AerialStrike(car,",
"-> Maneuver: ball = intercept.ball if ( self.allow_dribbles and (100 < ball.position[2] or",
"fast_aerial = FastAerialStrike(car, self.info, target) better_aerial_strike = min([aerial_strike, fast_aerial], key=lambda strike: strike.intercept.time) if",
"strike.intercept.time) if better_aerial_strike.intercept.time < dodge_shot.intercept.time: if ground_distance(better_aerial_strike.intercept, self.info.their_goal.center) < 5000: return DoubleTouch(better_aerial_strike) return",
"< 5000: return DoubleTouch(better_aerial_strike) return better_aerial_strike if ( dodge_shot.intercept.time < ground_shot.intercept.time - 0.1",
"and ground_distance(car, ball) < 1500 and ground_distance(ball, self.info.my_goal.center) > 1000 ): if not",
"ground_distance(ball, self.info.my_goal.center) > 1000 ): if not self.is_opponent_close(car, ball): return CarryAndFlick(car, self.info, target)",
"self.info.my_goal.center) > 1000 ): if not self.is_opponent_close(car, ball): return CarryAndFlick(car, self.info, target) alignment",
"self.info, target) alignment = align(car.position, ball, target) if alignment < 0.1 and abs(ball.position[1]",
"target) if alignment < 0.1 and abs(ball.position[1] - target[1]) > 3000: return MirrorStrike(car,",
"< ball.position[2] < 550 and self.is_opponent_close(car, ball): # return DoubleJumpStrike(car, self.info, target) return",
"import CarryAndFlick from maneuvers.maneuver import Maneuver from maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot",
"CloseShot(car, self.info, target) return dodge_shot return ground_shot def any_shot(self, car: Car, target: vec3,",
"- target[1]) > 3000: return MirrorStrike(car, self.info, target) # if 250 < ball.position[2]",
"from maneuvers.strikes.close_shot import CloseShot from maneuvers.strikes.dodge_strike import DodgeStrike from maneuvers.strikes.ground_strike import GroundStrike from",
"from tools.game_info import GameInfo from tools.intercept import Intercept from tools.vector_math import distance, ground_distance,",
"car: Car, target: vec3, intercept: Intercept) -> Maneuver: ball = intercept.ball if (",
"self.allow_dribbles = False def direct_shot(self, car: Car, target: vec3) -> Maneuver: dodge_shot =",
"3000: return MirrorStrike(car, self.info, target) # if 250 < ball.position[2] < 550 and",
"ground_distance, align class Offense: def __init__(self, info: GameInfo): self.info = info self.allow_dribbles =",
"# TODO aerial_strike = AerialStrike(car, self.info, target) fast_aerial = FastAerialStrike(car, self.info, target) better_aerial_strike",
"GameInfo): self.info = info self.allow_dribbles = False def direct_shot(self, car: Car, target: vec3)",
"ground_distance(car, ball) < 1500 and ground_distance(ball, self.info.my_goal.center) > 1000 ): if not self.is_opponent_close(car,"
] |
[
"out_dataset = train if split_num > 0: split_num -= 1 out_dataset = test",
"dataset): all_sessions = dataset.all_sessions_list() sorted(all_sessions, key=lambda s: s.timestamp_start) split_num = len(all_sessions) * self.split_percent",
"= train if n <= test_session_num else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes()",
"\"\"\" Do not split dataset at all. It returns for both, train and",
"else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test def _get_max_timestamp(self, dataset):",
"u, sid = user_session_ids[n] out_dataset = train if n <= test_session_num else test",
"def __init__(self, split_sec=24 * 60 * 60): super(TimestampSessionSplitter, self).__init__() self.split_sec = split_sec def",
"= len(all_sessions) * self.split_percent train, test = self._prepare_target_datasets(dataset) # iterate from last event",
"* self.split_percent train, test = self._prepare_target_datasets(dataset) # iterate from last event till split",
"<= self.train_size + self.test_size: test.sessions[u] = u_sessions else: break n += len(u_sessions) train._create_indexes()",
"return train, test def _get_max_timestamp(self, dataset): max_ts = 0 for u, u_sessions in",
"def __init__(self, split_percent=.05): self.split_percent = split_percent def split(self, dataset): all_sessions = dataset.all_sessions_list() sorted(all_sessions,",
"max_ts: max_ts = session.timestamp_end return max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self, split_percent=.05): self.split_percent =",
"= 0 for u, u_sessions in list(dataset.sessions.items()): if n <= self.train_size: train.sessions[u] =",
"= test_size def split(self, dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) n =",
"self._prepare_target_datasets(dataset) test_session_num = self.test_ratio * dataset.sessions_num() user_session_ids = [] for u, u_sessions in",
"n = 0 for u, u_sessions in list(dataset.sessions.items()): if n <= self.train_size: train.sessions[u]",
"in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): out_dataset = train if session.timestamp_end <",
"list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): out_dataset = train if session.timestamp_end < threshold",
"split(self, dataset): super(RandomSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) test_session_num = self.test_ratio * dataset.sessions_num()",
"return train, test class TimestampSessionSplitter(DatasetSplitter): def __init__(self, split_sec=24 * 60 * 60): super(TimestampSessionSplitter,",
"IdentitySplitter(DatasetSplitter): \"\"\" Do not split dataset at all. It returns for both, train",
"= train if session.timestamp_end < threshold else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes()",
"elif n <= self.train_size + self.test_size: test.sessions[u] = u_sessions else: break n +=",
"self.test_ratio * dataset.sessions_num() user_session_ids = [] for u, u_sessions in list(dataset.sessions.items()): for sid",
"split_sec=24 * 60 * 60): super(TimestampSessionSplitter, self).__init__() self.split_sec = split_sec def split(self, dataset):",
"returns for both, train and test, the same object. This implementation is mainly",
"if session.timestamp_end < threshold else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train,",
"< threshold else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test def",
"super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size = train_size self.test_size = test_size def split(self, dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset)",
"test._create_indexes() return train, test class RandomSessionSplitter(DatasetSplitter): def __init__(self, train_ratio=0.7): super(RandomSessionSplitter, self).__init__() self.test_ratio =",
"ParametrizedObject from rec.dataset.dataset import Dataset class DatasetSplitter(ParametrizedObject): @abstractmethod def split(self, dataset): assert isinstance(dataset,",
"def split(self, dataset): return dataset, dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self, train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter,",
"if n <= test_session_num else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train,",
"+ self.test_size: test.sessions[u] = u_sessions else: break n += len(u_sessions) train._create_indexes() test._create_indexes() return",
"testing purpose. It shouldn't be used in a real-life training schedule. \"\"\" def",
"self.split_sec = split_sec def split(self, dataset): super(TimestampSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) max_ts",
"till split is filled for s in reversed(all_sessions): out_dataset = train if split_num",
"> max_ts: max_ts = session.timestamp_end return max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self, split_percent=.05): self.split_percent",
"test.sessions[u] = u_sessions else: break n += len(u_sessions) train._create_indexes() test._create_indexes() return train, test",
"= u_sessions else: break n += len(u_sessions) train._create_indexes() test._create_indexes() return train, test class",
"def split(self, dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) n = 0 for",
"class DatasetSplitter(ParametrizedObject): @abstractmethod def split(self, dataset): assert isinstance(dataset, Dataset) pass def _prepare_target_datasets(self, dataset):",
"\"\"\" def split(self, dataset): return dataset, dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self, train_size=0, test_size=0):",
"split(self, dataset): return dataset, dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self, train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__()",
"train, test = self._prepare_target_datasets(dataset) n = 0 for u, u_sessions in list(dataset.sessions.items()): if",
"train.items = dataset.items test.items = dataset.items return train, test class IdentitySplitter(DatasetSplitter): \"\"\" Do",
"training schedule. \"\"\" def split(self, dataset): return dataset, dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self,",
"object. This implementation is mainly for testing purpose. It shouldn't be used in",
"dataset, dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self, train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size = train_size",
"schedule. \"\"\" def split(self, dataset): return dataset, dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self, train_size=0,",
"in a real-life training schedule. \"\"\" def split(self, dataset): return dataset, dataset class",
"split_num -= 1 out_dataset = test out_dataset.sessions[s.user_id][s.id] = s train._create_indexes() test._create_indexes() return train,",
"def split(self, dataset): all_sessions = dataset.all_sessions_list() sorted(all_sessions, key=lambda s: s.timestamp_start) split_num = len(all_sessions)",
"all. It returns for both, train and test, the same object. This implementation",
"session in list(u_sessions.items()): if session.timestamp_end > max_ts: max_ts = session.timestamp_end return max_ts class",
"split(self, dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) n = 0 for u,",
"max_ts = self._get_max_timestamp(dataset) threshold = max_ts - self.split_sec for u, u_sessions in list(dataset.sessions.items()):",
"DatasetSplitter(ParametrizedObject): @abstractmethod def split(self, dataset): assert isinstance(dataset, Dataset) pass def _prepare_target_datasets(self, dataset): train",
"self.train_size + self.test_size: test.sessions[u] = u_sessions else: break n += len(u_sessions) train._create_indexes() test._create_indexes()",
"max_ts = 0 for u, u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()):",
"last event till split is filled for s in reversed(all_sessions): out_dataset = train",
"dataset): train = Dataset(dataset.name) test = Dataset(dataset.name) train.items = dataset.items test.items = dataset.items",
"test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test class TimestampSessionSplitter(DatasetSplitter): def __init__(self,",
"dataset): super(TimestampSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) max_ts = self._get_max_timestamp(dataset) threshold = max_ts",
"super(RandomSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) test_session_num = self.test_ratio * dataset.sessions_num() user_session_ids =",
"split is filled for s in reversed(all_sessions): out_dataset = train if split_num >",
"a real-life training schedule. \"\"\" def split(self, dataset): return dataset, dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter):",
"list(dataset.sessions.items()): if n <= self.train_size: train.sessions[u] = u_sessions elif n <= self.train_size +",
"range(len(user_session_ids)): u, sid = user_session_ids[n] out_dataset = train if n <= test_session_num else",
"train if n <= test_session_num else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return",
"0 for u, u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): if session.timestamp_end",
"at all. It returns for both, train and test, the same object. This",
"0 for u, u_sessions in list(dataset.sessions.items()): if n <= self.train_size: train.sessions[u] = u_sessions",
"list(u_sessions.items()): if session.timestamp_end > max_ts: max_ts = session.timestamp_end return max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter): def",
"u, u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): if session.timestamp_end > max_ts:",
"rec.base import ParametrizedObject from rec.dataset.dataset import Dataset class DatasetSplitter(ParametrizedObject): @abstractmethod def split(self, dataset):",
"split_sec def split(self, dataset): super(TimestampSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) max_ts = self._get_max_timestamp(dataset)",
"train._create_indexes() test._create_indexes() return train, test class TimestampSessionSplitter(DatasetSplitter): def __init__(self, split_sec=24 * 60 *",
"> 0: split_num -= 1 out_dataset = test out_dataset.sessions[s.user_id][s.id] = s train._create_indexes() test._create_indexes()",
"rec.dataset.dataset import Dataset class DatasetSplitter(ParametrizedObject): @abstractmethod def split(self, dataset): assert isinstance(dataset, Dataset) pass",
"* 60): super(TimestampSessionSplitter, self).__init__() self.split_sec = split_sec def split(self, dataset): super(TimestampSessionSplitter, self).split(dataset) train,",
"else: break n += len(u_sessions) train._create_indexes() test._create_indexes() return train, test class RandomSessionSplitter(DatasetSplitter): def",
"class IdentitySplitter(DatasetSplitter): \"\"\" Do not split dataset at all. It returns for both,",
"def __init__(self, train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size = train_size self.test_size = test_size def",
"train, test = self._prepare_target_datasets(dataset) max_ts = self._get_max_timestamp(dataset) threshold = max_ts - self.split_sec for",
"Dataset class DatasetSplitter(ParametrizedObject): @abstractmethod def split(self, dataset): assert isinstance(dataset, Dataset) pass def _prepare_target_datasets(self,",
"in list(u_sessions.items()): if session.timestamp_end > max_ts: max_ts = session.timestamp_end return max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter):",
"self.train_size = train_size self.test_size = test_size def split(self, dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset) train, test",
"test = Dataset(dataset.name) train.items = dataset.items test.items = dataset.items return train, test class",
"reversed(all_sessions): out_dataset = train if split_num > 0: split_num -= 1 out_dataset =",
"s.timestamp_start) split_num = len(all_sessions) * self.split_percent train, test = self._prepare_target_datasets(dataset) # iterate from",
"list(u_sessions.items()): out_dataset = train if session.timestamp_end < threshold else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid]",
"= dataset.items test.items = dataset.items return train, test class IdentitySplitter(DatasetSplitter): \"\"\" Do not",
"threshold = max_ts - self.split_sec for u, u_sessions in list(dataset.sessions.items()): for sid, session",
"# iterate from last event till split is filled for s in reversed(all_sessions):",
"def split(self, dataset): super(TimestampSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) max_ts = self._get_max_timestamp(dataset) threshold",
"= dataset.all_sessions_list() sorted(all_sessions, key=lambda s: s.timestamp_start) split_num = len(all_sessions) * self.split_percent train, test",
"return max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self, split_percent=.05): self.split_percent = split_percent def split(self, dataset):",
"dataset at all. It returns for both, train and test, the same object.",
"train, test def _get_max_timestamp(self, dataset): max_ts = 0 for u, u_sessions in list(dataset.sessions.items()):",
"for testing purpose. It shouldn't be used in a real-life training schedule. \"\"\"",
"_get_max_timestamp(self, dataset): max_ts = 0 for u, u_sessions in list(dataset.sessions.items()): for sid, session",
"break n += len(u_sessions) train._create_indexes() test._create_indexes() return train, test class RandomSessionSplitter(DatasetSplitter): def __init__(self,",
"RandomSessionSplitter(DatasetSplitter): def __init__(self, train_ratio=0.7): super(RandomSessionSplitter, self).__init__() self.test_ratio = train_ratio def split(self, dataset): super(RandomSessionSplitter,",
"self.split_percent = split_percent def split(self, dataset): all_sessions = dataset.all_sessions_list() sorted(all_sessions, key=lambda s: s.timestamp_start)",
"= split_percent def split(self, dataset): all_sessions = dataset.all_sessions_list() sorted(all_sessions, key=lambda s: s.timestamp_start) split_num",
"self.split_percent train, test = self._prepare_target_datasets(dataset) # iterate from last event till split is",
"the same object. This implementation is mainly for testing purpose. It shouldn't be",
"_prepare_target_datasets(self, dataset): train = Dataset(dataset.name) test = Dataset(dataset.name) train.items = dataset.items test.items =",
"in list(dataset.sessions.items()): if n <= self.train_size: train.sessions[u] = u_sessions elif n <= self.train_size",
"and test, the same object. This implementation is mainly for testing purpose. It",
"<= self.train_size: train.sessions[u] = u_sessions elif n <= self.train_size + self.test_size: test.sessions[u] =",
"= train if split_num > 0: split_num -= 1 out_dataset = test out_dataset.sessions[s.user_id][s.id]",
"from last event till split is filled for s in reversed(all_sessions): out_dataset =",
"return train, test class IdentitySplitter(DatasetSplitter): \"\"\" Do not split dataset at all. It",
"purpose. It shouldn't be used in a real-life training schedule. \"\"\" def split(self,",
"Dataset(dataset.name) test = Dataset(dataset.name) train.items = dataset.items test.items = dataset.items return train, test",
"= self._prepare_target_datasets(dataset) n = 0 for u, u_sessions in list(dataset.sessions.items()): if n <=",
"user_session_ids = [] for u, u_sessions in list(dataset.sessions.items()): for sid in u_sessions.keys(): user_session_ids.append((u,",
"= train_ratio def split(self, dataset): super(RandomSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) test_session_num =",
"split dataset at all. It returns for both, train and test, the same",
"def __init__(self, train_ratio=0.7): super(RandomSessionSplitter, self).__init__() self.test_ratio = train_ratio def split(self, dataset): super(RandomSessionSplitter, self).split(dataset)",
"- self.split_sec for u, u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): out_dataset",
"s in reversed(all_sessions): out_dataset = train if split_num > 0: split_num -= 1",
"random from rec.base import ParametrizedObject from rec.dataset.dataset import Dataset class DatasetSplitter(ParametrizedObject): @abstractmethod def",
"= u_sessions elif n <= self.train_size + self.test_size: test.sessions[u] = u_sessions else: break",
"threshold else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test def _get_max_timestamp(self,",
"= user_session_ids[n] out_dataset = train if n <= test_session_num else test out_dataset.sessions[u][sid] =",
"dataset.all_sessions_list() sorted(all_sessions, key=lambda s: s.timestamp_start) split_num = len(all_sessions) * self.split_percent train, test =",
"both, train and test, the same object. This implementation is mainly for testing",
"same object. This implementation is mainly for testing purpose. It shouldn't be used",
"@abstractmethod def split(self, dataset): assert isinstance(dataset, Dataset) pass def _prepare_target_datasets(self, dataset): train =",
"= dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test class TimestampSessionSplitter(DatasetSplitter): def __init__(self, split_sec=24 *",
"for sid in u_sessions.keys(): user_session_ids.append((u, sid)) random.shuffle(user_session_ids) for n in range(len(user_session_ids)): u, sid",
"= self._prepare_target_datasets(dataset) test_session_num = self.test_ratio * dataset.sessions_num() user_session_ids = [] for u, u_sessions",
"event till split is filled for s in reversed(all_sessions): out_dataset = train if",
"60 * 60): super(TimestampSessionSplitter, self).__init__() self.split_sec = split_sec def split(self, dataset): super(TimestampSessionSplitter, self).split(dataset)",
"dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test def _get_max_timestamp(self, dataset): max_ts = 0 for",
"if n <= self.train_size: train.sessions[u] = u_sessions elif n <= self.train_size + self.test_size:",
"self.test_size: test.sessions[u] = u_sessions else: break n += len(u_sessions) train._create_indexes() test._create_indexes() return train,",
"split(self, dataset): assert isinstance(dataset, Dataset) pass def _prepare_target_datasets(self, dataset): train = Dataset(dataset.name) test",
"self._prepare_target_datasets(dataset) n = 0 for u, u_sessions in list(dataset.sessions.items()): if n <= self.train_size:",
"split_percent def split(self, dataset): all_sessions = dataset.all_sessions_list() sorted(all_sessions, key=lambda s: s.timestamp_start) split_num =",
"session.timestamp_end return max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self, split_percent=.05): self.split_percent = split_percent def split(self,",
"PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self, train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size = train_size self.test_size = test_size",
"self.train_size: train.sessions[u] = u_sessions elif n <= self.train_size + self.test_size: test.sessions[u] = u_sessions",
"abstractmethod from numpy import random from rec.base import ParametrizedObject from rec.dataset.dataset import Dataset",
"* 60 * 60): super(TimestampSessionSplitter, self).__init__() self.split_sec = split_sec def split(self, dataset): super(TimestampSessionSplitter,",
"for n in range(len(user_session_ids)): u, sid = user_session_ids[n] out_dataset = train if n",
"for sid, session in list(u_sessions.items()): if session.timestamp_end > max_ts: max_ts = session.timestamp_end return",
"= max_ts - self.split_sec for u, u_sessions in list(dataset.sessions.items()): for sid, session in",
"= self._prepare_target_datasets(dataset) # iterate from last event till split is filled for s",
"u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): if session.timestamp_end > max_ts: max_ts",
"return dataset, dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self, train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size =",
"train, test class RandomSessionSplitter(DatasetSplitter): def __init__(self, train_ratio=0.7): super(RandomSessionSplitter, self).__init__() self.test_ratio = train_ratio def",
"u_sessions in list(dataset.sessions.items()): for sid in u_sessions.keys(): user_session_ids.append((u, sid)) random.shuffle(user_session_ids) for n in",
"u_sessions in list(dataset.sessions.items()): if n <= self.train_size: train.sessions[u] = u_sessions elif n <=",
"[] for u, u_sessions in list(dataset.sessions.items()): for sid in u_sessions.keys(): user_session_ids.append((u, sid)) random.shuffle(user_session_ids)",
"split_num > 0: split_num -= 1 out_dataset = test out_dataset.sessions[s.user_id][s.id] = s train._create_indexes()",
"from numpy import random from rec.base import ParametrizedObject from rec.dataset.dataset import Dataset class",
"TimestampSessionSplitter(DatasetSplitter): def __init__(self, split_sec=24 * 60 * 60): super(TimestampSessionSplitter, self).__init__() self.split_sec = split_sec",
"train_ratio=0.7): super(RandomSessionSplitter, self).__init__() self.test_ratio = train_ratio def split(self, dataset): super(RandomSessionSplitter, self).split(dataset) train, test",
"= train_size self.test_size = test_size def split(self, dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset) train, test =",
"dataset.sessions_num() user_session_ids = [] for u, u_sessions in list(dataset.sessions.items()): for sid in u_sessions.keys():",
"for u, u_sessions in list(dataset.sessions.items()): if n <= self.train_size: train.sessions[u] = u_sessions elif",
"self.test_size = test_size def split(self, dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) n",
"in list(u_sessions.items()): out_dataset = train if session.timestamp_end < threshold else test out_dataset.sessions[u][sid] =",
"for u, u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): if session.timestamp_end >",
"shouldn't be used in a real-life training schedule. \"\"\" def split(self, dataset): return",
"+= len(u_sessions) train._create_indexes() test._create_indexes() return train, test class RandomSessionSplitter(DatasetSplitter): def __init__(self, train_ratio=0.7): super(RandomSessionSplitter,",
"dataset): super(RandomSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) test_session_num = self.test_ratio * dataset.sessions_num() user_session_ids",
"test_session_num = self.test_ratio * dataset.sessions_num() user_session_ids = [] for u, u_sessions in list(dataset.sessions.items()):",
"from rec.dataset.dataset import Dataset class DatasetSplitter(ParametrizedObject): @abstractmethod def split(self, dataset): assert isinstance(dataset, Dataset)",
"= Dataset(dataset.name) train.items = dataset.items test.items = dataset.items return train, test class IdentitySplitter(DatasetSplitter):",
"class PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self, train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size = train_size self.test_size =",
"for u, u_sessions in list(dataset.sessions.items()): for sid in u_sessions.keys(): user_session_ids.append((u, sid)) random.shuffle(user_session_ids) for",
"out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test class TimestampSessionSplitter(DatasetSplitter): def __init__(self, split_sec=24",
"__init__(self, train_ratio=0.7): super(RandomSessionSplitter, self).__init__() self.test_ratio = train_ratio def split(self, dataset): super(RandomSessionSplitter, self).split(dataset) train,",
"session.timestamp_end < threshold else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test",
"if split_num > 0: split_num -= 1 out_dataset = test out_dataset.sessions[s.user_id][s.id] = s",
"max_ts - self.split_sec for u, u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()):",
"test class IdentitySplitter(DatasetSplitter): \"\"\" Do not split dataset at all. It returns for",
"dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test class TimestampSessionSplitter(DatasetSplitter): def __init__(self, split_sec=24 * 60",
"test._create_indexes() return train, test def _get_max_timestamp(self, dataset): max_ts = 0 for u, u_sessions",
"numpy import random from rec.base import ParametrizedObject from rec.dataset.dataset import Dataset class DatasetSplitter(ParametrizedObject):",
"= dataset.items return train, test class IdentitySplitter(DatasetSplitter): \"\"\" Do not split dataset at",
"user_session_ids[n] out_dataset = train if n <= test_session_num else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid]",
"all_sessions = dataset.all_sessions_list() sorted(all_sessions, key=lambda s: s.timestamp_start) split_num = len(all_sessions) * self.split_percent train,",
"-= 1 out_dataset = test out_dataset.sessions[s.user_id][s.id] = s train._create_indexes() test._create_indexes() return train, test",
"= Dataset(dataset.name) test = Dataset(dataset.name) train.items = dataset.items test.items = dataset.items return train,",
"s: s.timestamp_start) split_num = len(all_sessions) * self.split_percent train, test = self._prepare_target_datasets(dataset) # iterate",
"super(TimestampSessionSplitter, self).__init__() self.split_sec = split_sec def split(self, dataset): super(TimestampSessionSplitter, self).split(dataset) train, test =",
"sorted(all_sessions, key=lambda s: s.timestamp_start) split_num = len(all_sessions) * self.split_percent train, test = self._prepare_target_datasets(dataset)",
"LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self, split_percent=.05): self.split_percent = split_percent def split(self, dataset): all_sessions = dataset.all_sessions_list()",
"u, u_sessions in list(dataset.sessions.items()): if n <= self.train_size: train.sessions[u] = u_sessions elif n",
"max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self, split_percent=.05): self.split_percent = split_percent def split(self, dataset): all_sessions",
"from rec.base import ParametrizedObject from rec.dataset.dataset import Dataset class DatasetSplitter(ParametrizedObject): @abstractmethod def split(self,",
"in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): if session.timestamp_end > max_ts: max_ts =",
"train, test = self._prepare_target_datasets(dataset) # iterate from last event till split is filled",
"u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): out_dataset = train if session.timestamp_end",
"super(PreciseUserNumberDatasetSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) n = 0 for u, u_sessions in",
"test = self._prepare_target_datasets(dataset) n = 0 for u, u_sessions in list(dataset.sessions.items()): if n",
"sid = user_session_ids[n] out_dataset = train if n <= test_session_num else test out_dataset.sessions[u][sid]",
"n <= test_session_num else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test",
"n <= self.train_size + self.test_size: test.sessions[u] = u_sessions else: break n += len(u_sessions)",
"test_size def split(self, dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) n = 0",
"* dataset.sessions_num() user_session_ids = [] for u, u_sessions in list(dataset.sessions.items()): for sid in",
"from abc import abstractmethod from numpy import random from rec.base import ParametrizedObject from",
"Dataset(dataset.name) train.items = dataset.items test.items = dataset.items return train, test class IdentitySplitter(DatasetSplitter): \"\"\"",
"u, u_sessions in list(dataset.sessions.items()): for sid in u_sessions.keys(): user_session_ids.append((u, sid)) random.shuffle(user_session_ids) for n",
"dataset): max_ts = 0 for u, u_sessions in list(dataset.sessions.items()): for sid, session in",
"def split(self, dataset): assert isinstance(dataset, Dataset) pass def _prepare_target_datasets(self, dataset): train = Dataset(dataset.name)",
"test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test def _get_max_timestamp(self, dataset): max_ts",
"self).split(dataset) train, test = self._prepare_target_datasets(dataset) test_session_num = self.test_ratio * dataset.sessions_num() user_session_ids = []",
"<= test_session_num else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test class",
"self).split(dataset) train, test = self._prepare_target_datasets(dataset) max_ts = self._get_max_timestamp(dataset) threshold = max_ts - self.split_sec",
"not split dataset at all. It returns for both, train and test, the",
"def _prepare_target_datasets(self, dataset): train = Dataset(dataset.name) test = Dataset(dataset.name) train.items = dataset.items test.items",
"def split(self, dataset): super(RandomSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) test_session_num = self.test_ratio *",
"test = self._prepare_target_datasets(dataset) test_session_num = self.test_ratio * dataset.sessions_num() user_session_ids = [] for u,",
"sid, session in list(u_sessions.items()): out_dataset = train if session.timestamp_end < threshold else test",
"in u_sessions.keys(): user_session_ids.append((u, sid)) random.shuffle(user_session_ids) for n in range(len(user_session_ids)): u, sid = user_session_ids[n]",
"isinstance(dataset, Dataset) pass def _prepare_target_datasets(self, dataset): train = Dataset(dataset.name) test = Dataset(dataset.name) train.items",
"n in range(len(user_session_ids)): u, sid = user_session_ids[n] out_dataset = train if n <=",
"for both, train and test, the same object. This implementation is mainly for",
"split_percent=.05): self.split_percent = split_percent def split(self, dataset): all_sessions = dataset.all_sessions_list() sorted(all_sessions, key=lambda s:",
"train and test, the same object. This implementation is mainly for testing purpose.",
"used in a real-life training schedule. \"\"\" def split(self, dataset): return dataset, dataset",
"super(TimestampSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) max_ts = self._get_max_timestamp(dataset) threshold = max_ts -",
"for sid, session in list(u_sessions.items()): out_dataset = train if session.timestamp_end < threshold else",
"self._prepare_target_datasets(dataset) max_ts = self._get_max_timestamp(dataset) threshold = max_ts - self.split_sec for u, u_sessions in",
"dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self, train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size = train_size self.test_size",
"__init__(self, split_percent=.05): self.split_percent = split_percent def split(self, dataset): all_sessions = dataset.all_sessions_list() sorted(all_sessions, key=lambda",
"out_dataset = train if n <= test_session_num else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes()",
"implementation is mainly for testing purpose. It shouldn't be used in a real-life",
"This implementation is mainly for testing purpose. It shouldn't be used in a",
"self).__init__() self.train_size = train_size self.test_size = test_size def split(self, dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset) train,",
"__init__(self, train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size = train_size self.test_size = test_size def split(self,",
"len(all_sessions) * self.split_percent train, test = self._prepare_target_datasets(dataset) # iterate from last event till",
"u_sessions.keys(): user_session_ids.append((u, sid)) random.shuffle(user_session_ids) for n in range(len(user_session_ids)): u, sid = user_session_ids[n] out_dataset",
"n += len(u_sessions) train._create_indexes() test._create_indexes() return train, test class RandomSessionSplitter(DatasetSplitter): def __init__(self, train_ratio=0.7):",
"= session.timestamp_end return max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self, split_percent=.05): self.split_percent = split_percent def",
"self.split_sec for u, u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): out_dataset =",
"split(self, dataset): super(TimestampSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) max_ts = self._get_max_timestamp(dataset) threshold =",
"self).__init__() self.test_ratio = train_ratio def split(self, dataset): super(RandomSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset)",
"in range(len(user_session_ids)): u, sid = user_session_ids[n] out_dataset = train if n <= test_session_num",
"split_num = len(all_sessions) * self.split_percent train, test = self._prepare_target_datasets(dataset) # iterate from last",
"test def _get_max_timestamp(self, dataset): max_ts = 0 for u, u_sessions in list(dataset.sessions.items()): for",
"u_sessions elif n <= self.train_size + self.test_size: test.sessions[u] = u_sessions else: break n",
"Do not split dataset at all. It returns for both, train and test,",
"test class RandomSessionSplitter(DatasetSplitter): def __init__(self, train_ratio=0.7): super(RandomSessionSplitter, self).__init__() self.test_ratio = train_ratio def split(self,",
"is mainly for testing purpose. It shouldn't be used in a real-life training",
"def _get_max_timestamp(self, dataset): max_ts = 0 for u, u_sessions in list(dataset.sessions.items()): for sid,",
"test_session_num else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test class TimestampSessionSplitter(DatasetSplitter):",
"= dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test def _get_max_timestamp(self, dataset): max_ts = 0",
"for s in reversed(all_sessions): out_dataset = train if split_num > 0: split_num -=",
"train if split_num > 0: split_num -= 1 out_dataset = test out_dataset.sessions[s.user_id][s.id] =",
"dataset.items test.items = dataset.items return train, test class IdentitySplitter(DatasetSplitter): \"\"\" Do not split",
"test = self._prepare_target_datasets(dataset) max_ts = self._get_max_timestamp(dataset) threshold = max_ts - self.split_sec for u,",
"u, u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): out_dataset = train if",
"random.shuffle(user_session_ids) for n in range(len(user_session_ids)): u, sid = user_session_ids[n] out_dataset = train if",
"list(dataset.sessions.items()): for sid in u_sessions.keys(): user_session_ids.append((u, sid)) random.shuffle(user_session_ids) for n in range(len(user_session_ids)): u,",
"self.test_ratio = train_ratio def split(self, dataset): super(RandomSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) test_session_num",
"test.items = dataset.items return train, test class IdentitySplitter(DatasetSplitter): \"\"\" Do not split dataset",
"real-life training schedule. \"\"\" def split(self, dataset): return dataset, dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter): def",
"train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size = train_size self.test_size = test_size def split(self, dataset):",
"if session.timestamp_end > max_ts: max_ts = session.timestamp_end return max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self,",
"is filled for s in reversed(all_sessions): out_dataset = train if split_num > 0:",
"import abstractmethod from numpy import random from rec.base import ParametrizedObject from rec.dataset.dataset import",
"super(RandomSessionSplitter, self).__init__() self.test_ratio = train_ratio def split(self, dataset): super(RandomSessionSplitter, self).split(dataset) train, test =",
"train, test = self._prepare_target_datasets(dataset) test_session_num = self.test_ratio * dataset.sessions_num() user_session_ids = [] for",
"self).split(dataset) train, test = self._prepare_target_datasets(dataset) n = 0 for u, u_sessions in list(dataset.sessions.items()):",
"in list(dataset.sessions.items()): for sid in u_sessions.keys(): user_session_ids.append((u, sid)) random.shuffle(user_session_ids) for n in range(len(user_session_ids)):",
"train.sessions[u] = u_sessions elif n <= self.train_size + self.test_size: test.sessions[u] = u_sessions else:",
"import random from rec.base import ParametrizedObject from rec.dataset.dataset import Dataset class DatasetSplitter(ParametrizedObject): @abstractmethod",
"class RandomSessionSplitter(DatasetSplitter): def __init__(self, train_ratio=0.7): super(RandomSessionSplitter, self).__init__() self.test_ratio = train_ratio def split(self, dataset):",
"session in list(u_sessions.items()): out_dataset = train if session.timestamp_end < threshold else test out_dataset.sessions[u][sid]",
"u_sessions else: break n += len(u_sessions) train._create_indexes() test._create_indexes() return train, test class RandomSessionSplitter(DatasetSplitter):",
"= self._prepare_target_datasets(dataset) max_ts = self._get_max_timestamp(dataset) threshold = max_ts - self.split_sec for u, u_sessions",
"dataset.items return train, test class IdentitySplitter(DatasetSplitter): \"\"\" Do not split dataset at all.",
"= self.test_ratio * dataset.sessions_num() user_session_ids = [] for u, u_sessions in list(dataset.sessions.items()): for",
"out_dataset = train if session.timestamp_end < threshold else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes()",
"__init__(self, split_sec=24 * 60 * 60): super(TimestampSessionSplitter, self).__init__() self.split_sec = split_sec def split(self,",
"= self._get_max_timestamp(dataset) threshold = max_ts - self.split_sec for u, u_sessions in list(dataset.sessions.items()): for",
"len(u_sessions) train._create_indexes() test._create_indexes() return train, test class RandomSessionSplitter(DatasetSplitter): def __init__(self, train_ratio=0.7): super(RandomSessionSplitter, self).__init__()",
"train, test class TimestampSessionSplitter(DatasetSplitter): def __init__(self, split_sec=24 * 60 * 60): super(TimestampSessionSplitter, self).__init__()",
"test class TimestampSessionSplitter(DatasetSplitter): def __init__(self, split_sec=24 * 60 * 60): super(TimestampSessionSplitter, self).__init__() self.split_sec",
"test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size = train_size self.test_size = test_size def split(self, dataset): super(PreciseUserNumberDatasetSplitter,",
"train if session.timestamp_end < threshold else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return",
"import Dataset class DatasetSplitter(ParametrizedObject): @abstractmethod def split(self, dataset): assert isinstance(dataset, Dataset) pass def",
"self._prepare_target_datasets(dataset) # iterate from last event till split is filled for s in",
"import ParametrizedObject from rec.dataset.dataset import Dataset class DatasetSplitter(ParametrizedObject): @abstractmethod def split(self, dataset): assert",
"pass def _prepare_target_datasets(self, dataset): train = Dataset(dataset.name) test = Dataset(dataset.name) train.items = dataset.items",
"split(self, dataset): all_sessions = dataset.all_sessions_list() sorted(all_sessions, key=lambda s: s.timestamp_start) split_num = len(all_sessions) *",
"return train, test class RandomSessionSplitter(DatasetSplitter): def __init__(self, train_ratio=0.7): super(RandomSessionSplitter, self).__init__() self.test_ratio = train_ratio",
"self._get_max_timestamp(dataset) threshold = max_ts - self.split_sec for u, u_sessions in list(dataset.sessions.items()): for sid,",
"sid)) random.shuffle(user_session_ids) for n in range(len(user_session_ids)): u, sid = user_session_ids[n] out_dataset = train",
"iterate from last event till split is filled for s in reversed(all_sessions): out_dataset",
"train_ratio def split(self, dataset): super(RandomSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) test_session_num = self.test_ratio",
"assert isinstance(dataset, Dataset) pass def _prepare_target_datasets(self, dataset): train = Dataset(dataset.name) test = Dataset(dataset.name)",
"self).__init__() self.split_sec = split_sec def split(self, dataset): super(TimestampSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset)",
"class TimestampSessionSplitter(DatasetSplitter): def __init__(self, split_sec=24 * 60 * 60): super(TimestampSessionSplitter, self).__init__() self.split_sec =",
"60): super(TimestampSessionSplitter, self).__init__() self.split_sec = split_sec def split(self, dataset): super(TimestampSessionSplitter, self).split(dataset) train, test",
"filled for s in reversed(all_sessions): out_dataset = train if split_num > 0: split_num",
"Dataset) pass def _prepare_target_datasets(self, dataset): train = Dataset(dataset.name) test = Dataset(dataset.name) train.items =",
"0: split_num -= 1 out_dataset = test out_dataset.sessions[s.user_id][s.id] = s train._create_indexes() test._create_indexes() return",
"in reversed(all_sessions): out_dataset = train if split_num > 0: split_num -= 1 out_dataset",
"= 0 for u, u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): if",
"mainly for testing purpose. It shouldn't be used in a real-life training schedule.",
"list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): if session.timestamp_end > max_ts: max_ts = session.timestamp_end",
"max_ts = session.timestamp_end return max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self, split_percent=.05): self.split_percent = split_percent",
"user_session_ids.append((u, sid)) random.shuffle(user_session_ids) for n in range(len(user_session_ids)): u, sid = user_session_ids[n] out_dataset =",
"for u, u_sessions in list(dataset.sessions.items()): for sid, session in list(u_sessions.items()): out_dataset = train",
"session.timestamp_end > max_ts: max_ts = session.timestamp_end return max_ts class LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self, split_percent=.05):",
"class LastNPercentOfSessionsInDataset(DatasetSplitter): def __init__(self, split_percent=.05): self.split_percent = split_percent def split(self, dataset): all_sessions =",
"It returns for both, train and test, the same object. This implementation is",
"dataset): return dataset, dataset class PreciseUserNumberDatasetSplitter(DatasetSplitter): def __init__(self, train_size=0, test_size=0): super(PreciseUserNumberDatasetSplitter, self).__init__() self.train_size",
"= split_sec def split(self, dataset): super(TimestampSessionSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) max_ts =",
"train_size self.test_size = test_size def split(self, dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset)",
"key=lambda s: s.timestamp_start) split_num = len(all_sessions) * self.split_percent train, test = self._prepare_target_datasets(dataset) #",
"n <= self.train_size: train.sessions[u] = u_sessions elif n <= self.train_size + self.test_size: test.sessions[u]",
"else test out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test class TimestampSessionSplitter(DatasetSplitter): def",
"= [] for u, u_sessions in list(dataset.sessions.items()): for sid in u_sessions.keys(): user_session_ids.append((u, sid))",
"dataset): assert isinstance(dataset, Dataset) pass def _prepare_target_datasets(self, dataset): train = Dataset(dataset.name) test =",
"train = Dataset(dataset.name) test = Dataset(dataset.name) train.items = dataset.items test.items = dataset.items return",
"It shouldn't be used in a real-life training schedule. \"\"\" def split(self, dataset):",
"train, test class IdentitySplitter(DatasetSplitter): \"\"\" Do not split dataset at all. It returns",
"sid, session in list(u_sessions.items()): if session.timestamp_end > max_ts: max_ts = session.timestamp_end return max_ts",
"train._create_indexes() test._create_indexes() return train, test class RandomSessionSplitter(DatasetSplitter): def __init__(self, train_ratio=0.7): super(RandomSessionSplitter, self).__init__() self.test_ratio",
"abc import abstractmethod from numpy import random from rec.base import ParametrizedObject from rec.dataset.dataset",
"test, the same object. This implementation is mainly for testing purpose. It shouldn't",
"test._create_indexes() return train, test class TimestampSessionSplitter(DatasetSplitter): def __init__(self, split_sec=24 * 60 * 60):",
"sid in u_sessions.keys(): user_session_ids.append((u, sid)) random.shuffle(user_session_ids) for n in range(len(user_session_ids)): u, sid =",
"dataset): super(PreciseUserNumberDatasetSplitter, self).split(dataset) train, test = self._prepare_target_datasets(dataset) n = 0 for u, u_sessions",
"train._create_indexes() test._create_indexes() return train, test def _get_max_timestamp(self, dataset): max_ts = 0 for u,",
"test = self._prepare_target_datasets(dataset) # iterate from last event till split is filled for",
"be used in a real-life training schedule. \"\"\" def split(self, dataset): return dataset,",
"out_dataset.sessions[u][sid] = dataset.sessions[u][sid] train._create_indexes() test._create_indexes() return train, test def _get_max_timestamp(self, dataset): max_ts ="
] |
[
"valores (a,b,c) Promedio --> int --> p \"\"\" # Entradas a = int(input(\"Dime",
"# Entradas a = int(input(\"Dime la primera edad\\n\")) b = int(input(\"Dime la primera",
"1 --> int --> a Edad 2 --> int --> b Edad 3",
"primera edad\\n\")) b = int(input(\"Dime la primera edad\\n\")) c = int(input(\"Dime la primera",
"a = int(input(\"Dime la primera edad\\n\")) b = int(input(\"Dime la primera edad\\n\")) c",
"--> b Edad 3 --> int --> c Salidas --> El promedio los",
"Entradas: 3 edades Edad 1 --> int --> a Edad 2 --> int",
"int --> a Edad 2 --> int --> b Edad 3 --> int",
"int --> p \"\"\" # Entradas a = int(input(\"Dime la primera edad\\n\")) b",
"Salidas --> El promedio los valores (a,b,c) Promedio --> int --> p \"\"\"",
"\"\"\" # Entradas a = int(input(\"Dime la primera edad\\n\")) b = int(input(\"Dime la",
"b Edad 3 --> int --> c Salidas --> El promedio los valores",
"<reponame>BarinasJ/Algoritmos_Programacion \"\"\" Entradas: 3 edades Edad 1 --> int --> a Edad 2",
"--> c Salidas --> El promedio los valores (a,b,c) Promedio --> int -->",
"Edad 1 --> int --> a Edad 2 --> int --> b Edad",
"--> int --> b Edad 3 --> int --> c Salidas --> El",
"--> p \"\"\" # Entradas a = int(input(\"Dime la primera edad\\n\")) b =",
"El promedio los valores (a,b,c) Promedio --> int --> p \"\"\" # Entradas",
"edad\\n\")) b = int(input(\"Dime la primera edad\\n\")) c = int(input(\"Dime la primera edad\\n\"))",
"int --> c Salidas --> El promedio los valores (a,b,c) Promedio --> int",
"--> a Edad 2 --> int --> b Edad 3 --> int -->",
"--> El promedio los valores (a,b,c) Promedio --> int --> p \"\"\" #",
"a Edad 2 --> int --> b Edad 3 --> int --> c",
"--> int --> a Edad 2 --> int --> b Edad 3 -->",
"--> int --> c Salidas --> El promedio los valores (a,b,c) Promedio -->",
"int(input(\"Dime la primera edad\\n\")) b = int(input(\"Dime la primera edad\\n\")) c = int(input(\"Dime",
"= int(input(\"Dime la primera edad\\n\")) b = int(input(\"Dime la primera edad\\n\")) c =",
"3 edades Edad 1 --> int --> a Edad 2 --> int -->",
"= int(input(\"Dime la primera edad\\n\")) c = int(input(\"Dime la primera edad\\n\")) # Caja",
"b = int(input(\"Dime la primera edad\\n\")) c = int(input(\"Dime la primera edad\\n\")) #",
"la primera edad\\n\")) b = int(input(\"Dime la primera edad\\n\")) c = int(input(\"Dime la",
"Promedio --> int --> p \"\"\" # Entradas a = int(input(\"Dime la primera",
"= int(input(\"Dime la primera edad\\n\")) # Caja negra p = (a+b+c)/3 # Salidas",
"2 --> int --> b Edad 3 --> int --> c Salidas -->",
"int --> b Edad 3 --> int --> c Salidas --> El promedio",
"--> int --> p \"\"\" # Entradas a = int(input(\"Dime la primera edad\\n\"))",
"Edad 2 --> int --> b Edad 3 --> int --> c Salidas",
"la primera edad\\n\")) c = int(input(\"Dime la primera edad\\n\")) # Caja negra p",
"int(input(\"Dime la primera edad\\n\")) # Caja negra p = (a+b+c)/3 # Salidas print(int(p))",
"c = int(input(\"Dime la primera edad\\n\")) # Caja negra p = (a+b+c)/3 #",
"\"\"\" Entradas: 3 edades Edad 1 --> int --> a Edad 2 -->",
"edades Edad 1 --> int --> a Edad 2 --> int --> b",
"p \"\"\" # Entradas a = int(input(\"Dime la primera edad\\n\")) b = int(input(\"Dime",
"Entradas a = int(input(\"Dime la primera edad\\n\")) b = int(input(\"Dime la primera edad\\n\"))",
"3 --> int --> c Salidas --> El promedio los valores (a,b,c) Promedio",
"Edad 3 --> int --> c Salidas --> El promedio los valores (a,b,c)",
"edad\\n\")) c = int(input(\"Dime la primera edad\\n\")) # Caja negra p = (a+b+c)/3",
"int(input(\"Dime la primera edad\\n\")) c = int(input(\"Dime la primera edad\\n\")) # Caja negra",
"(a,b,c) Promedio --> int --> p \"\"\" # Entradas a = int(input(\"Dime la",
"primera edad\\n\")) c = int(input(\"Dime la primera edad\\n\")) # Caja negra p =",
"c Salidas --> El promedio los valores (a,b,c) Promedio --> int --> p",
"promedio los valores (a,b,c) Promedio --> int --> p \"\"\" # Entradas a",
"los valores (a,b,c) Promedio --> int --> p \"\"\" # Entradas a ="
] |
[
"(top left of cropped bottom) start_row, start_col = int(0), int(width * .5) #",
"bottom) start_row, start_col = int(0), int(width * .5) # Let's get the ending",
"right of cropped bottom) end_row, end_col = int(height), int(width) cropped_right = img[start_row:end_row, start_col:end_col]",
"coordiantes (top left of cropped bottom) start_row, start_col = int(0), int(width * .5)",
"else path height, width = img.shape[:2] # Let's get the starting pixel coordiantes",
"def split_image_horizontally(path): img = cv2.imread(path) if type(path) == str else path height, width",
"cv2.imread(path) if type(path) == str else path height, width = img.shape[:2] # Let's",
"* .5) # Let's get the ending pixel coordinates (bottom right of cropped",
"cropped top) start_row, start_col = int(0), int(0) # Let's get the ending pixel",
"cropped top) end_row, end_col = int(height), int(width * .5) cropped_left = img[start_row:end_row, start_col:end_col]",
"Let's get the starting pixel coordiantes (top left of cropped top) start_row, start_col",
"if type(path) == str else path height, width = img.shape[:2] # Let's get",
"start_row, start_col = int(0), int(width * .5) # Let's get the ending pixel",
"of cropped bottom) start_row, start_col = int(0), int(width * .5) # Let's get",
"start_row, start_col = int(0), int(0) # Let's get the ending pixel coordinates (bottom",
"Let's get the ending pixel coordinates (bottom right of cropped bottom) end_row, end_col",
"of cropped top) end_row, end_col = int(height), int(width * .5) cropped_left = img[start_row:end_row,",
"height, width = img.shape[:2] # Let's get the starting pixel coordiantes (top left",
"cropped_left = img[start_row:end_row, start_col:end_col] # Let's get the starting pixel coordiantes (top left",
"int(width * .5) # Let's get the ending pixel coordinates (bottom right of",
"img = cv2.imread(path) if type(path) == str else path height, width = img.shape[:2]",
"end_col = int(height), int(width * .5) cropped_left = img[start_row:end_row, start_col:end_col] # Let's get",
"= img.shape[:2] # Let's get the starting pixel coordiantes (top left of cropped",
"pixel coordinates (bottom right of cropped bottom) end_row, end_col = int(height), int(width) cropped_right",
"type(path) == str else path height, width = img.shape[:2] # Let's get the",
"# Let's get the starting pixel coordiantes (top left of cropped top) start_row,",
"the starting pixel coordiantes (top left of cropped top) start_row, start_col = int(0),",
"(top left of cropped top) start_row, start_col = int(0), int(0) # Let's get",
"starting pixel coordiantes (top left of cropped bottom) start_row, start_col = int(0), int(width",
"int(width * .5) cropped_left = img[start_row:end_row, start_col:end_col] # Let's get the starting pixel",
"the starting pixel coordiantes (top left of cropped bottom) start_row, start_col = int(0),",
"int(0), int(width * .5) # Let's get the ending pixel coordinates (bottom right",
".5) cropped_left = img[start_row:end_row, start_col:end_col] # Let's get the starting pixel coordiantes (top",
"# Let's get the ending pixel coordinates (bottom right of cropped bottom) end_row,",
"the ending pixel coordinates (bottom right of cropped bottom) end_row, end_col = int(height),",
"end_row, end_col = int(height), int(width * .5) cropped_left = img[start_row:end_row, start_col:end_col] # Let's",
".5) # Let's get the ending pixel coordinates (bottom right of cropped bottom)",
"= int(0), int(0) # Let's get the ending pixel coordinates (bottom right of",
"the ending pixel coordinates (bottom right of cropped top) end_row, end_col = int(height),",
"pixel coordinates (bottom right of cropped top) end_row, end_col = int(height), int(width *",
"pixel coordiantes (top left of cropped top) start_row, start_col = int(0), int(0) #",
"bottom) end_row, end_col = int(height), int(width) cropped_right = img[start_row:end_row, start_col:end_col] return cropped_left, cropped_right",
"Let's get the ending pixel coordinates (bottom right of cropped top) end_row, end_col",
"(bottom right of cropped top) end_row, end_col = int(height), int(width * .5) cropped_left",
"cv2 def split_image_horizontally(path): img = cv2.imread(path) if type(path) == str else path height,",
"img.shape[:2] # Let's get the starting pixel coordiantes (top left of cropped top)",
"of cropped bottom) end_row, end_col = int(height), int(width) cropped_right = img[start_row:end_row, start_col:end_col] return",
"coordinates (bottom right of cropped bottom) end_row, end_col = int(height), int(width) cropped_right =",
"cropped bottom) start_row, start_col = int(0), int(width * .5) # Let's get the",
"coordiantes (top left of cropped top) start_row, start_col = int(0), int(0) # Let's",
"left of cropped top) start_row, start_col = int(0), int(0) # Let's get the",
"int(0), int(0) # Let's get the ending pixel coordinates (bottom right of cropped",
"start_col = int(0), int(0) # Let's get the ending pixel coordinates (bottom right",
"split_image_horizontally(path): img = cv2.imread(path) if type(path) == str else path height, width =",
"top) end_row, end_col = int(height), int(width * .5) cropped_left = img[start_row:end_row, start_col:end_col] #",
"= cv2.imread(path) if type(path) == str else path height, width = img.shape[:2] #",
"right of cropped top) end_row, end_col = int(height), int(width * .5) cropped_left =",
"ending pixel coordinates (bottom right of cropped top) end_row, end_col = int(height), int(width",
"= int(height), int(width * .5) cropped_left = img[start_row:end_row, start_col:end_col] # Let's get the",
"get the ending pixel coordinates (bottom right of cropped bottom) end_row, end_col =",
"coordinates (bottom right of cropped top) end_row, end_col = int(height), int(width * .5)",
"starting pixel coordiantes (top left of cropped top) start_row, start_col = int(0), int(0)",
"int(height), int(width * .5) cropped_left = img[start_row:end_row, start_col:end_col] # Let's get the starting",
"= img[start_row:end_row, start_col:end_col] # Let's get the starting pixel coordiantes (top left of",
"get the ending pixel coordinates (bottom right of cropped top) end_row, end_col =",
"str else path height, width = img.shape[:2] # Let's get the starting pixel",
"# Let's get the starting pixel coordiantes (top left of cropped bottom) start_row,",
"get the starting pixel coordiantes (top left of cropped bottom) start_row, start_col =",
"of cropped top) start_row, start_col = int(0), int(0) # Let's get the ending",
"pixel coordiantes (top left of cropped bottom) start_row, start_col = int(0), int(width *",
"* .5) cropped_left = img[start_row:end_row, start_col:end_col] # Let's get the starting pixel coordiantes",
"ending pixel coordinates (bottom right of cropped bottom) end_row, end_col = int(height), int(width)",
"path height, width = img.shape[:2] # Let's get the starting pixel coordiantes (top",
"get the starting pixel coordiantes (top left of cropped top) start_row, start_col =",
"start_col = int(0), int(width * .5) # Let's get the ending pixel coordinates",
"Let's get the starting pixel coordiantes (top left of cropped bottom) start_row, start_col",
"left of cropped bottom) start_row, start_col = int(0), int(width * .5) # Let's",
"(bottom right of cropped bottom) end_row, end_col = int(height), int(width) cropped_right = img[start_row:end_row,",
"img[start_row:end_row, start_col:end_col] # Let's get the starting pixel coordiantes (top left of cropped",
"width = img.shape[:2] # Let's get the starting pixel coordiantes (top left of",
"== str else path height, width = img.shape[:2] # Let's get the starting",
"cropped bottom) end_row, end_col = int(height), int(width) cropped_right = img[start_row:end_row, start_col:end_col] return cropped_left,",
"int(0) # Let's get the ending pixel coordinates (bottom right of cropped top)",
"import cv2 def split_image_horizontally(path): img = cv2.imread(path) if type(path) == str else path",
"# Let's get the ending pixel coordinates (bottom right of cropped top) end_row,",
"start_col:end_col] # Let's get the starting pixel coordiantes (top left of cropped bottom)",
"= int(0), int(width * .5) # Let's get the ending pixel coordinates (bottom",
"top) start_row, start_col = int(0), int(0) # Let's get the ending pixel coordinates"
] |
[
"practice of numerical classification. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary",
"float: \"\"\"Consonni and Todeschini similarity (v1) <NAME>., & <NAME>. (2012). New similarity coefficients",
"857-871. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns:",
"Returns: float: similarity of given vectors \"\"\" a, b, c, d = operational_taxonomic_units(x,",
"(b + c) + d) def gower( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector",
"mask) return math.log(1 + a + d) / math.log(1 + a + b",
") -> float: \"\"\"Sokal-Sneath similarity (v2) <NAME>., & <NAME>. (1973). Numerical taxonomy. The",
"BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Austin-Colwell similarity <NAME>., & <NAME>.",
"d = operational_taxonomic_units(x, y, mask) return (a + d - b - c)",
"= None ) -> float: \"\"\"Sokal-Sneath similarity (v3) <NAME>., & <NAME>. (1973). Numerical",
"float: \"\"\"Gower-Legendre similarity <NAME>., & <NAME>. (1986). Metric and Euclidean properties of dissimilarity",
"classifying plants. Science, 132(3434), 1115-1118. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector):",
"d))) def consonni_todeschini1( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) ->",
"y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower-Legendre similarity <NAME>., &",
"<NAME>. (1971). A general coefficient of similarity and some of its properties. Biometrics,",
"evaluating systematic relationships. Univ. Kansas, Sci. Bull., 38, 1409-1438. Args: x (BinaryFeatureVector): binary",
"+ d) def gower_legendre( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None )",
"BinaryFeatureVector = None ) -> float: \"\"\"Roges-Tanimoto similarity <NAME>., & <NAME>. (1960). A",
"+ d)) / (2 * (a + d) + b + c) def",
"BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity (v3) <NAME>., & <NAME>. (1973).",
"1115-1118. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns:",
"binary feature vector Returns: float: similarity of given vectors \"\"\" a, b, c,",
"\"\"\"Faith similarity <NAME>. (1983). Asymmetric binary similarity measures. Oecologia, 57(3), 287-290. Args: x",
"return (a + 0.5 * d) / (a + b + c +",
"\"\"\"Sokal-Sneath similarity (v2) <NAME>., & <NAME>. (1973). Numerical taxonomy. The principles and practice",
"* (c + d)) def austin_colwell( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector =",
"A computer program for classifying plants. Science, 132(3434), 1115-1118. Args: x (BinaryFeatureVector): binary",
"+ d) / (a + b + c + d) def rogers_tanimoto( x:",
"operational_taxonomic_units, BinaryFeatureVector def smc( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None )",
"y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Michener similarity (also called",
"+ 0.5 * d) / (a + b + c + d) def",
"Evaluation of some coefficients for use in numerical taxonomy of microorganisms. International Journal",
"(a + 0.5 * d) / (a + b + c + d)",
"similarity (v2) <NAME>., & <NAME>. (1973). Numerical taxonomy. The principles and practice of",
"27(3), 204-210. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector",
"(b + c) + d) def sokal_sneath2( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector",
"= None ) -> float: \"\"\"Gower similarity <NAME>. (1971). A general coefficient of",
"x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Hamman similarity",
"0.5 * (b + c) + d) def gower( x: BinaryFeatureVector, y: BinaryFeatureVector,",
"(v2) <NAME>., & <NAME>. (1973). Numerical taxonomy. The principles and practice of numerical",
"a, b, c, d = operational_taxonomic_units(x, y, mask) return math.log(1 + a +",
") -> float: \"\"\"Hamman similarity <NAME>. (1961). Merkmalsbestand und verwandtschaftsbeziehungen der farinosae: ein",
"(a + d - b - c) / (a + b + c",
"581. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns:",
"68(2), 581. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector",
"d) / (a + b + c + d) def gower_legendre( x: BinaryFeatureVector,",
"x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity",
"BinaryFeatureVector def smc( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) ->",
"d) def gower_legendre( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) ->",
"mask: BinaryFeatureVector = None ) -> float: \"\"\"Hamman similarity <NAME>. (1961). Merkmalsbestand und",
"0.5 * d) / (a + b + c + d) def gower_legendre(",
"+ c + d) def rogers_tanimoto( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector =",
"(1960). A computer program for classifying plants. Science, 132(3434), 1115-1118. Args: x (BinaryFeatureVector):",
"+ d) def gower( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None )",
"/ (a + b + c + d))) def consonni_todeschini1( x: BinaryFeatureVector, y:",
"Oecologia, 57(3), 287-290. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature",
"* (a + d) + b + c) def sokal_sneath3( x: BinaryFeatureVector, y:",
"float: \"\"\"Roges-Tanimoto similarity <NAME>., & <NAME>. (1960). A computer program for classifying plants.",
"vector y (BinaryFeatureVector): binary feature vector Returns: float: similarity of given vectors \"\"\"",
"<NAME>. (1973). Numerical taxonomy. The principles and practice of numerical classification. Args: x",
"BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity (v2) <NAME>., &",
"+ c + d) def gower_legendre( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector =",
"\"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return (a + d)",
"feature vector y (BinaryFeatureVector): binary feature vector Returns: float: similarity of given vectors",
"<NAME>., & <NAME>. (2012). New similarity coefficients for binary data. Match-Communications in Mathematical",
"math from binsdpy.utils import operational_taxonomic_units, BinaryFeatureVector def smc( x: BinaryFeatureVector, y: BinaryFeatureVector, mask:",
"(a + d) / math.sqrt((a + b) * (a + c) * (b",
") -> float: \"\"\"Austin-Colwell similarity <NAME>., & <NAME>. (1977). Evaluation of some coefficients",
"b, c, d = operational_taxonomic_units(x, y, mask) return math.log(1 + a + d)",
"None ) -> float: \"\"\"Hamman similarity <NAME>. (1961). Merkmalsbestand und verwandtschaftsbeziehungen der farinosae:",
"return (a + d) / (a + 0.5 * (b + c) +",
"<NAME>., & <NAME>. (1986). Metric and Euclidean properties of dissimilarity coefficients. Journal of",
"y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity (v3) <NAME>.,",
"-> float: \"\"\"Faith similarity <NAME>. (1983). Asymmetric binary similarity measures. Oecologia, 57(3), 287-290.",
"vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return 2 /",
"of given vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return",
"International Journal of Systematic and Evolutionary Microbiology, 27(3), 204-210. Args: x (BinaryFeatureVector): binary",
"float: \"\"\"Sokal-Sneath similarity (v3) <NAME>., & <NAME>. (1973). Numerical taxonomy. The principles and",
"Match-Communications in Mathematical and Computer Chemistry, 68(2), 581. Args: x (BinaryFeatureVector): binary feature",
"None ) -> float: \"\"\"Sokal-Sneath similarity (v3) <NAME>., & <NAME>. (1973). Numerical taxonomy.",
"+ d) / math.log(1 + a + b + c + d) def",
"c) def faith( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) ->",
"(a + d) / (a + 2 * (b + c) + d)",
"BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Michener similarity (also called simple",
"principles and practice of numerical classification. Args: x (BinaryFeatureVector): binary feature vector y",
"and Euclidean properties of dissimilarity coefficients. Journal of classification, 3(1), 5-48. Args: x",
"gower( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower",
"\"\"\"Austin-Colwell similarity <NAME>., & <NAME>. (1977). Evaluation of some coefficients for use in",
"sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath",
"(1983). Asymmetric binary similarity measures. Oecologia, 57(3), 287-290. Args: x (BinaryFeatureVector): binary feature",
"+ d) / (a + 2 * (b + c) + d) def",
") -> float: \"\"\"Sokal-Michener similarity (also called simple matching coefficient) <NAME>. (1958). A",
"monokotyledonen. Willdenowia, 639-768. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature",
"program for classifying plants. Science, 132(3434), 1115-1118. Args: x (BinaryFeatureVector): binary feature vector",
"(a + 0.5 * (b + c) + d) def gower( x: BinaryFeatureVector,",
"<NAME>. (1960). A computer program for classifying plants. Science, 132(3434), 1115-1118. Args: x",
"None ) -> float: \"\"\"Sokal-Michener similarity (also called simple matching coefficient) <NAME>. (1958).",
"= None ) -> float: \"\"\"Gower-Legendre similarity <NAME>., & <NAME>. (1986). Metric and",
"(1973). Numerical taxonomy. The principles and practice of numerical classification. Args: x (BinaryFeatureVector):",
"similarity and some of its properties. Biometrics, 857-871. Args: x (BinaryFeatureVector): binary feature",
"vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return math.log(1 +",
"BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Hamman similarity <NAME>. (1961). Merkmalsbestand",
"y, mask) return 2 / math.pi * math.asin(math.sqrt((a + d) / (a +",
"Univ. Kansas, Sci. Bull., 38, 1409-1438. Args: x (BinaryFeatureVector): binary feature vector y",
"mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower similarity <NAME>. (1971). A general",
"Kansas, Sci. Bull., 38, 1409-1438. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector):",
"y, mask) return (a + d) / (a + b + c +",
"<NAME>., & <NAME>. (1977). Evaluation of some coefficients for use in numerical taxonomy",
"mask) return (a + d) / (b + c) def faith( x: BinaryFeatureVector,",
"Bull., 38, 1409-1438. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature",
"d) def rogers_tanimoto( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) ->",
"(c + d)) def austin_colwell( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None",
"\"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return math.log(1 + a",
"\"\"\"Hamman similarity <NAME>. (1961). Merkmalsbestand und verwandtschaftsbeziehungen der farinosae: ein beitrag zum system",
"None ) -> float: \"\"\"Austin-Colwell similarity <NAME>., & <NAME>. (1977). Evaluation of some",
"its properties. Biometrics, 857-871. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary",
"data. Match-Communications in Mathematical and Computer Chemistry, 68(2), 581. Args: x (BinaryFeatureVector): binary",
"y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Hamman similarity <NAME>. (1961).",
"from binsdpy.utils import operational_taxonomic_units, BinaryFeatureVector def smc( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector",
"mask: BinaryFeatureVector = None ) -> float: \"\"\"Consonni and Todeschini similarity (v1) <NAME>.,",
"= operational_taxonomic_units(x, y, mask) return (a + d - b - c) /",
"mask: BinaryFeatureVector = None ) -> float: \"\"\"Faith similarity <NAME>. (1983). Asymmetric binary",
"return (a + d) / (a + 2 * (b + c) +",
"matching coefficient) <NAME>. (1958). A statistical method for evaluating systematic relationships. Univ. Kansas,",
"rogers_tanimoto( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Roges-Tanimoto",
"Todeschini similarity (v1) <NAME>., & <NAME>. (2012). New similarity coefficients for binary data.",
"\"\"\"Gower-Legendre similarity <NAME>., & <NAME>. (1986). Metric and Euclidean properties of dissimilarity coefficients.",
"y, mask) return (2 * (a + d)) / (2 * (a +",
"float: similarity of given vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y,",
"<NAME>. (1986). Metric and Euclidean properties of dissimilarity coefficients. Journal of classification, 3(1),",
"in numerical taxonomy of microorganisms. International Journal of Systematic and Evolutionary Microbiology, 27(3),",
"float: \"\"\"Faith similarity <NAME>. (1983). Asymmetric binary similarity measures. Oecologia, 57(3), 287-290. Args:",
"computer program for classifying plants. Science, 132(3434), 1115-1118. Args: x (BinaryFeatureVector): binary feature",
"y, mask) return (a + d - b - c) / (a +",
"measures. Oecologia, 57(3), 287-290. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary",
"beitrag zum system der monokotyledonen. Willdenowia, 639-768. Args: x (BinaryFeatureVector): binary feature vector",
"def austin_colwell( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float:",
"d = operational_taxonomic_units(x, y, mask) return (a + d) / (a + b",
"& <NAME>. (1973). Numerical taxonomy. The principles and practice of numerical classification. Args:",
"of similarity and some of its properties. Biometrics, 857-871. Args: x (BinaryFeatureVector): binary",
"<NAME>. (1983). Asymmetric binary similarity measures. Oecologia, 57(3), 287-290. Args: x (BinaryFeatureVector): binary",
"c, d = operational_taxonomic_units(x, y, mask) return (2 * (a + d)) /",
"b + c + d) def rogers_tanimoto( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector",
"d)) def austin_colwell( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) ->",
"operational_taxonomic_units(x, y, mask) return (a + d) / (a + 2 * (b",
"BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower-Legendre similarity <NAME>.,",
"similarity <NAME>., & <NAME>. (1960). A computer program for classifying plants. Science, 132(3434),",
"& <NAME>. (1986). Metric and Euclidean properties of dissimilarity coefficients. Journal of classification,",
"dissimilarity coefficients. Journal of classification, 3(1), 5-48. Args: x (BinaryFeatureVector): binary feature vector",
"similarity (v1) <NAME>., & <NAME>. (2012). New similarity coefficients for binary data. Match-Communications",
"(1986). Metric and Euclidean properties of dissimilarity coefficients. Journal of classification, 3(1), 5-48.",
"import operational_taxonomic_units, BinaryFeatureVector def smc( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None",
"math.log(1 + a + b + c + d) def hamman( x: BinaryFeatureVector,",
"coefficients for use in numerical taxonomy of microorganisms. International Journal of Systematic and",
"BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Austin-Colwell similarity <NAME>.,",
"= operational_taxonomic_units(x, y, mask) return (a + d) / (a + b +",
"(also called simple matching coefficient) <NAME>. (1958). A statistical method for evaluating systematic",
"/ (a + b + c + d) def gower_legendre( x: BinaryFeatureVector, y:",
"= None ) -> float: \"\"\"Hamman similarity <NAME>. (1961). Merkmalsbestand und verwandtschaftsbeziehungen der",
"+ b + c) def sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector =",
"a, b, c, d = operational_taxonomic_units(x, y, mask) return (2 * (a +",
"b) * (a + c) * (b + d) * (c + d))",
"None ) -> float: \"\"\"Consonni and Todeschini similarity (v1) <NAME>., & <NAME>. (2012).",
"38, 1409-1438. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector",
"-> float: \"\"\"Consonni and Todeschini similarity (v1) <NAME>., & <NAME>. (2012). New similarity",
"b, c, d = operational_taxonomic_units(x, y, mask) return (a + d - b",
"c, d = operational_taxonomic_units(x, y, mask) return math.log(1 + a + d) /",
"BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Consonni and Todeschini",
"mask) return 2 / math.pi * math.asin(math.sqrt((a + d) / (a + b",
"zum system der monokotyledonen. Willdenowia, 639-768. Args: x (BinaryFeatureVector): binary feature vector y",
"d = operational_taxonomic_units(x, y, mask) return (a + d) / (b + c)",
"similarity coefficients for binary data. Match-Communications in Mathematical and Computer Chemistry, 68(2), 581.",
"/ math.sqrt((a + b) * (a + c) * (b + d) *",
"mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity (v2) <NAME>., & <NAME>.",
"BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower-Legendre similarity <NAME>., & <NAME>.",
"None ) -> float: \"\"\"Gower similarity <NAME>. (1971). A general coefficient of similarity",
"c, d = operational_taxonomic_units(x, y, mask) return (a + d - b -",
"float: \"\"\"Sokal-Sneath similarity (v2) <NAME>., & <NAME>. (1973). Numerical taxonomy. The principles and",
"operational_taxonomic_units(x, y, mask) return 2 / math.pi * math.asin(math.sqrt((a + d) / (a",
"5-48. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns:",
"d) def hamman( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) ->",
"float: \"\"\"Gower similarity <NAME>. (1971). A general coefficient of similarity and some of",
"a, b, c, d = operational_taxonomic_units(x, y, mask) return 2 / math.pi *",
"(1971). A general coefficient of similarity and some of its properties. Biometrics, 857-871.",
"a, b, c, d = operational_taxonomic_units(x, y, mask) return (a + d) /",
"and practice of numerical classification. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector):",
"similarity <NAME>., & <NAME>. (1986). Metric and Euclidean properties of dissimilarity coefficients. Journal",
"properties of dissimilarity coefficients. Journal of classification, 3(1), 5-48. Args: x (BinaryFeatureVector): binary",
"d - b - c) / (a + b + c + d)",
"y, mask) return (a + 0.5 * d) / (a + b +",
"= None ) -> float: \"\"\"Roges-Tanimoto similarity <NAME>., & <NAME>. (1960). A computer",
"Mathematical and Computer Chemistry, 68(2), 581. Args: x (BinaryFeatureVector): binary feature vector y",
"= operational_taxonomic_units(x, y, mask) return (a + d) / (a + 2 *",
"= operational_taxonomic_units(x, y, mask) return (a + 0.5 * d) / (a +",
"a, b, c, d = operational_taxonomic_units(x, y, mask) return (a + 0.5 *",
"c) + d) def sokal_sneath2( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None",
"mask) return (a + d) / (a + 0.5 * (b + c)",
"BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity (v2) <NAME>., & <NAME>. (1973).",
"-> float: \"\"\"Roges-Tanimoto similarity <NAME>., & <NAME>. (1960). A computer program for classifying",
"der farinosae: ein beitrag zum system der monokotyledonen. Willdenowia, 639-768. Args: x (BinaryFeatureVector):",
"(a + d)) / (2 * (a + d) + b + c)",
"return math.log(1 + a + d) / math.log(1 + a + b +",
"b + c + d) def hamman( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector",
"<NAME>., & <NAME>. (1960). A computer program for classifying plants. Science, 132(3434), 1115-1118.",
"simple matching coefficient) <NAME>. (1958). A statistical method for evaluating systematic relationships. Univ.",
"BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower similarity <NAME>. (1971). A",
"mask) return (a + d) / (a + b + c + d)",
"-> float: \"\"\"Sokal-Michener similarity (also called simple matching coefficient) <NAME>. (1958). A statistical",
"use in numerical taxonomy of microorganisms. International Journal of Systematic and Evolutionary Microbiology,",
"hamman( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Hamman",
"a + b + c + d) def hamman( x: BinaryFeatureVector, y: BinaryFeatureVector,",
"der monokotyledonen. Willdenowia, 639-768. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary",
"b + c) def sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None",
"x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Austin-Colwell similarity",
"(a + d) / (a + b + c + d) def rogers_tanimoto(",
"+ c) + d) def sokal_sneath2( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector =",
"(b + c) def faith( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None",
"57(3), 287-290. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector",
"import math from binsdpy.utils import operational_taxonomic_units, BinaryFeatureVector def smc( x: BinaryFeatureVector, y: BinaryFeatureVector,",
"-> float: \"\"\"Austin-Colwell similarity <NAME>., & <NAME>. (1977). Evaluation of some coefficients for",
"operational_taxonomic_units(x, y, mask) return (a + d - b - c) / (a",
"for use in numerical taxonomy of microorganisms. International Journal of Systematic and Evolutionary",
"x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Consonni and",
"a, b, c, d = operational_taxonomic_units(x, y, mask) return (a + d -",
"+ 2 * (b + c) + d) def sokal_sneath2( x: BinaryFeatureVector, y:",
"x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Roges-Tanimoto similarity",
"Science, 132(3434), 1115-1118. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature",
"+ d) / (a + 0.5 * (b + c) + d) def",
"+ d) / (b + c) def faith( x: BinaryFeatureVector, y: BinaryFeatureVector, mask:",
"+ b + c + d) def gower_legendre( x: BinaryFeatureVector, y: BinaryFeatureVector, mask:",
"<NAME>. (1977). Evaluation of some coefficients for use in numerical taxonomy of microorganisms.",
"x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Faith similarity",
"2 / math.pi * math.asin(math.sqrt((a + d) / (a + b + c",
"und verwandtschaftsbeziehungen der farinosae: ein beitrag zum system der monokotyledonen. Willdenowia, 639-768. Args:",
"287-290. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns:",
"<NAME>. (2012). New similarity coefficients for binary data. Match-Communications in Mathematical and Computer",
"(BinaryFeatureVector): binary feature vector Returns: float: similarity of given vectors \"\"\" a, b,",
"mask: BinaryFeatureVector = None ) -> float: \"\"\"Austin-Colwell similarity <NAME>., & <NAME>. (1977).",
"+ b + c + d) def hamman( x: BinaryFeatureVector, y: BinaryFeatureVector, mask:",
"in Mathematical and Computer Chemistry, 68(2), 581. Args: x (BinaryFeatureVector): binary feature vector",
"-> float: \"\"\"Sokal-Sneath similarity (v2) <NAME>., & <NAME>. (1973). Numerical taxonomy. The principles",
"binary feature vector y (BinaryFeatureVector): binary feature vector Returns: float: similarity of given",
"math.sqrt((a + b) * (a + c) * (b + d) * (c",
"Numerical taxonomy. The principles and practice of numerical classification. Args: x (BinaryFeatureVector): binary",
"Willdenowia, 639-768. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector",
"c, d = operational_taxonomic_units(x, y, mask) return (a + d) / (a +",
"(2 * (a + d)) / (2 * (a + d) + b",
"b, c, d = operational_taxonomic_units(x, y, mask) return 2 / math.pi * math.asin(math.sqrt((a",
"given vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return 2",
"d = operational_taxonomic_units(x, y, mask) return (a + d) / math.sqrt((a + b)",
"(1961). Merkmalsbestand und verwandtschaftsbeziehungen der farinosae: ein beitrag zum system der monokotyledonen. Willdenowia,",
"Journal of classification, 3(1), 5-48. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector):",
"vector Returns: float: similarity of given vectors \"\"\" a, b, c, d =",
"def hamman( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float:",
"+ b) * (a + c) * (b + d) * (c +",
"d = operational_taxonomic_units(x, y, mask) return (a + d) / (a + 0.5",
"(a + b + c + d) def gower_legendre( x: BinaryFeatureVector, y: BinaryFeatureVector,",
"y (BinaryFeatureVector): binary feature vector Returns: float: similarity of given vectors \"\"\" a,",
"and some of its properties. Biometrics, 857-871. Args: x (BinaryFeatureVector): binary feature vector",
"(1958). A statistical method for evaluating systematic relationships. Univ. Kansas, Sci. Bull., 38,",
"Metric and Euclidean properties of dissimilarity coefficients. Journal of classification, 3(1), 5-48. Args:",
"plants. Science, 132(3434), 1115-1118. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary",
"The principles and practice of numerical classification. Args: x (BinaryFeatureVector): binary feature vector",
"of numerical classification. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature",
"\"\"\"Gower similarity <NAME>. (1971). A general coefficient of similarity and some of its",
"* (b + d) * (c + d)) def austin_colwell( x: BinaryFeatureVector, y:",
"* (a + c) * (b + d) * (c + d)) def",
"-> float: \"\"\"Sokal-Sneath similarity (v3) <NAME>., & <NAME>. (1973). Numerical taxonomy. The principles",
"(BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns: float: similarity of",
"132(3434), 1115-1118. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector",
"d = operational_taxonomic_units(x, y, mask) return 2 / math.pi * math.asin(math.sqrt((a + d)",
"return 2 / math.pi * math.asin(math.sqrt((a + d) / (a + b +",
"= None ) -> float: \"\"\"Austin-Colwell similarity <NAME>., & <NAME>. (1977). Evaluation of",
"b, c, d = operational_taxonomic_units(x, y, mask) return (a + d) / (a",
"d = operational_taxonomic_units(x, y, mask) return (a + d) / (a + 2",
"b, c, d = operational_taxonomic_units(x, y, mask) return (2 * (a + d))",
"verwandtschaftsbeziehungen der farinosae: ein beitrag zum system der monokotyledonen. Willdenowia, 639-768. Args: x",
"c) + d) def gower( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None",
"given vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return math.log(1",
"called simple matching coefficient) <NAME>. (1958). A statistical method for evaluating systematic relationships.",
"Evolutionary Microbiology, 27(3), 204-210. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary",
"of dissimilarity coefficients. Journal of classification, 3(1), 5-48. Args: x (BinaryFeatureVector): binary feature",
"for evaluating systematic relationships. Univ. Kansas, Sci. Bull., 38, 1409-1438. Args: x (BinaryFeatureVector):",
"2 * (b + c) + d) def sokal_sneath2( x: BinaryFeatureVector, y: BinaryFeatureVector,",
"+ c + d))) def consonni_todeschini1( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector =",
"+ d))) def consonni_todeschini1( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None )",
"(a + d) + b + c) def sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector,",
"+ b + c + d) def rogers_tanimoto( x: BinaryFeatureVector, y: BinaryFeatureVector, mask:",
"None ) -> float: \"\"\"Roges-Tanimoto similarity <NAME>., & <NAME>. (1960). A computer program",
"sokal_sneath2( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath",
"+ c) def sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None )",
"c) def sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) ->",
"\"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return (a + 0.5",
"+ d) / (a + b + c + d))) def consonni_todeschini1( x:",
"b, c, d = operational_taxonomic_units(x, y, mask) return (a + 0.5 * d)",
"<NAME>., & <NAME>. (1973). Numerical taxonomy. The principles and practice of numerical classification.",
"c + d) def gower_legendre( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None",
"& <NAME>. (2012). New similarity coefficients for binary data. Match-Communications in Mathematical and",
"def rogers_tanimoto( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float:",
"y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower similarity <NAME>. (1971).",
"some coefficients for use in numerical taxonomy of microorganisms. International Journal of Systematic",
"operational_taxonomic_units(x, y, mask) return (a + d) / math.sqrt((a + b) * (a",
"BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Consonni and Todeschini similarity (v1)",
"= None ) -> float: \"\"\"Sokal-Sneath similarity (v2) <NAME>., & <NAME>. (1973). Numerical",
"BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Faith similarity <NAME>. (1983). Asymmetric",
") -> float: \"\"\"Gower-Legendre similarity <NAME>., & <NAME>. (1986). Metric and Euclidean properties",
"* d) / (a + b + c + d) def gower_legendre( x:",
"d) / (a + 0.5 * (b + c) + d) def gower(",
"* (b + c) + d) def sokal_sneath2( x: BinaryFeatureVector, y: BinaryFeatureVector, mask:",
"austin_colwell( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Austin-Colwell",
"y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity (v2) <NAME>.,",
"float: \"\"\"Hamman similarity <NAME>. (1961). Merkmalsbestand und verwandtschaftsbeziehungen der farinosae: ein beitrag zum",
"Euclidean properties of dissimilarity coefficients. Journal of classification, 3(1), 5-48. Args: x (BinaryFeatureVector):",
"math.asin(math.sqrt((a + d) / (a + b + c + d))) def consonni_todeschini1(",
"= operational_taxonomic_units(x, y, mask) return (a + d) / math.sqrt((a + b) *",
"farinosae: ein beitrag zum system der monokotyledonen. Willdenowia, 639-768. Args: x (BinaryFeatureVector): binary",
"mask) return (a + d) / math.sqrt((a + b) * (a + c)",
"y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Consonni and Todeschini similarity",
") -> float: \"\"\"Gower similarity <NAME>. (1971). A general coefficient of similarity and",
"b + c + d) def gower_legendre( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector",
"c, d = operational_taxonomic_units(x, y, mask) return (a + d) / (b +",
"/ (a + 2 * (b + c) + d) def sokal_sneath2( x:",
"some of its properties. Biometrics, 857-871. Args: x (BinaryFeatureVector): binary feature vector y",
"(v1) <NAME>., & <NAME>. (2012). New similarity coefficients for binary data. Match-Communications in",
"+ 0.5 * (b + c) + d) def gower( x: BinaryFeatureVector, y:",
"* (a + d)) / (2 * (a + d) + b +",
"def gower( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float:",
"+ c + d) def hamman( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector =",
"mask) return (a + d - b - c) / (a + b",
"y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Faith similarity <NAME>. (1983).",
"operational_taxonomic_units(x, y, mask) return math.log(1 + a + d) / math.log(1 + a",
"return (a + d) / (b + c) def faith( x: BinaryFeatureVector, y:",
") -> float: \"\"\"Roges-Tanimoto similarity <NAME>., & <NAME>. (1960). A computer program for",
"ein beitrag zum system der monokotyledonen. Willdenowia, 639-768. Args: x (BinaryFeatureVector): binary feature",
"y, mask) return (a + d) / (a + 2 * (b +",
"\"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return (a + d",
"def smc( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float:",
"d) def sokal_sneath2( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) ->",
"similarity measures. Oecologia, 57(3), 287-290. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector):",
"Chemistry, 68(2), 581. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature",
"given vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return (2",
"d) + b + c) def sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector",
"y, mask) return (a + d) / (a + 0.5 * (b +",
"BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower similarity <NAME>.",
"def faith( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float:",
"* (b + c) + d) def gower( x: BinaryFeatureVector, y: BinaryFeatureVector, mask:",
"return (a + d) / (a + b + c + d) def",
"coefficient) <NAME>. (1958). A statistical method for evaluating systematic relationships. Univ. Kansas, Sci.",
") -> float: \"\"\"Faith similarity <NAME>. (1983). Asymmetric binary similarity measures. Oecologia, 57(3),",
"operational_taxonomic_units(x, y, mask) return (a + d) / (a + b + c",
"float: \"\"\"Austin-Colwell similarity <NAME>., & <NAME>. (1977). Evaluation of some coefficients for use",
"mask: BinaryFeatureVector = None ) -> float: \"\"\"Roges-Tanimoto similarity <NAME>., & <NAME>. (1960).",
"204-210. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns:",
"Journal of Systematic and Evolutionary Microbiology, 27(3), 204-210. Args: x (BinaryFeatureVector): binary feature",
"for binary data. Match-Communications in Mathematical and Computer Chemistry, 68(2), 581. Args: x",
"numerical classification. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector",
"Asymmetric binary similarity measures. Oecologia, 57(3), 287-290. Args: x (BinaryFeatureVector): binary feature vector",
"and Computer Chemistry, 68(2), 581. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector):",
"y, mask) return (a + d) / math.sqrt((a + b) * (a +",
"binary similarity measures. Oecologia, 57(3), 287-290. Args: x (BinaryFeatureVector): binary feature vector y",
"BinaryFeatureVector = None ) -> float: \"\"\"Austin-Colwell similarity <NAME>., & <NAME>. (1977). Evaluation",
"d) def gower( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) ->",
"/ math.pi * math.asin(math.sqrt((a + d) / (a + b + c +",
"Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns: float:",
"float: \"\"\"Sokal-Michener similarity (also called simple matching coefficient) <NAME>. (1958). A statistical method",
"d) / (b + c) def faith( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector",
"BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Roges-Tanimoto similarity <NAME>., & <NAME>.",
"+ d) def rogers_tanimoto( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None )",
"Biometrics, 857-871. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector",
"BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity (v3) <NAME>., &",
"mask) return (a + 0.5 * d) / (a + b + c",
"of some coefficients for use in numerical taxonomy of microorganisms. International Journal of",
"d)) / (2 * (a + d) + b + c) def sokal_sneath3(",
"mask) return (a + d) / (a + 2 * (b + c)",
"x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns: float: similarity",
"coefficients for binary data. Match-Communications in Mathematical and Computer Chemistry, 68(2), 581. Args:",
"math.pi * math.asin(math.sqrt((a + d) / (a + b + c + d)))",
"\"\"\"Consonni and Todeschini similarity (v1) <NAME>., & <NAME>. (2012). New similarity coefficients for",
"& <NAME>. (1960). A computer program for classifying plants. Science, 132(3434), 1115-1118. Args:",
"b + c + d))) def consonni_todeschini1( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector",
"+ a + d) / math.log(1 + a + b + c +",
"BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Michener similarity (also",
"None ) -> float: \"\"\"Faith similarity <NAME>. (1983). Asymmetric binary similarity measures. Oecologia,",
"similarity (also called simple matching coefficient) <NAME>. (1958). A statistical method for evaluating",
"+ c) def faith( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None )",
") -> float: \"\"\"Sokal-Sneath similarity (v3) <NAME>., & <NAME>. (1973). Numerical taxonomy. The",
"<NAME>. (1961). Merkmalsbestand und verwandtschaftsbeziehungen der farinosae: ein beitrag zum system der monokotyledonen.",
"similarity <NAME>., & <NAME>. (1977). Evaluation of some coefficients for use in numerical",
"+ d) * (c + d)) def austin_colwell( x: BinaryFeatureVector, y: BinaryFeatureVector, mask:",
"(a + b + c + d))) def consonni_todeschini1( x: BinaryFeatureVector, y: BinaryFeatureVector,",
"similarity <NAME>. (1971). A general coefficient of similarity and some of its properties.",
"def sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float:",
"numerical taxonomy of microorganisms. International Journal of Systematic and Evolutionary Microbiology, 27(3), 204-210.",
"similarity of given vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask)",
"(2 * (a + d) + b + c) def sokal_sneath3( x: BinaryFeatureVector,",
"= None ) -> float: \"\"\"Faith similarity <NAME>. (1983). Asymmetric binary similarity measures.",
"A general coefficient of similarity and some of its properties. Biometrics, 857-871. Args:",
"= operational_taxonomic_units(x, y, mask) return (2 * (a + d)) / (2 *",
"+ d)) def austin_colwell( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None )",
"vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return (a +",
"\"\"\"Sokal-Michener similarity (also called simple matching coefficient) <NAME>. (1958). A statistical method for",
"def consonni_todeschini1( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float:",
"BinaryFeatureVector = None ) -> float: \"\"\"Gower-Legendre similarity <NAME>., & <NAME>. (1986). Metric",
"coefficients. Journal of classification, 3(1), 5-48. Args: x (BinaryFeatureVector): binary feature vector y",
"\"\"\"Roges-Tanimoto similarity <NAME>., & <NAME>. (1960). A computer program for classifying plants. Science,",
"classification. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns:",
"operational_taxonomic_units(x, y, mask) return (2 * (a + d)) / (2 * (a",
"operational_taxonomic_units(x, y, mask) return (a + 0.5 * d) / (a + b",
"and Evolutionary Microbiology, 27(3), 204-210. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector):",
"(1977). Evaluation of some coefficients for use in numerical taxonomy of microorganisms. International",
"mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower-Legendre similarity <NAME>., & <NAME>. (1986).",
"(b + d) * (c + d)) def austin_colwell( x: BinaryFeatureVector, y: BinaryFeatureVector,",
"+ d) + b + c) def sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector, mask:",
"return (2 * (a + d)) / (2 * (a + d) +",
"+ a + b + c + d) def hamman( x: BinaryFeatureVector, y:",
"taxonomy. The principles and practice of numerical classification. Args: x (BinaryFeatureVector): binary feature",
"y, mask) return (a + d) / (b + c) def faith( x:",
"of microorganisms. International Journal of Systematic and Evolutionary Microbiology, 27(3), 204-210. Args: x",
"systematic relationships. Univ. Kansas, Sci. Bull., 38, 1409-1438. Args: x (BinaryFeatureVector): binary feature",
"of classification, 3(1), 5-48. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary",
"(a + d) / (a + 0.5 * (b + c) + d)",
"system der monokotyledonen. Willdenowia, 639-768. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector):",
"return (a + d) / math.sqrt((a + b) * (a + c) *",
"d) / (a + b + c + d) def rogers_tanimoto( x: BinaryFeatureVector,",
"= None ) -> float: \"\"\"Consonni and Todeschini similarity (v1) <NAME>., & <NAME>.",
"BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity (v2)",
"mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity (v3) <NAME>., & <NAME>.",
"def sokal_sneath2( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float:",
"(a + c) * (b + d) * (c + d)) def austin_colwell(",
"d) / (a + b + c + d))) def consonni_todeschini1( x: BinaryFeatureVector,",
"microorganisms. International Journal of Systematic and Evolutionary Microbiology, 27(3), 204-210. Args: x (BinaryFeatureVector):",
"3(1), 5-48. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector",
"general coefficient of similarity and some of its properties. Biometrics, 857-871. Args: x",
"mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Michener similarity (also called simple matching",
"= None ) -> float: \"\"\"Sokal-Michener similarity (also called simple matching coefficient) <NAME>.",
"b, c, d = operational_taxonomic_units(x, y, mask) return (a + d) / (b",
"x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Michener similarity",
"classification, 3(1), 5-48. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature",
"(v3) <NAME>., & <NAME>. (1973). Numerical taxonomy. The principles and practice of numerical",
"BinaryFeatureVector = None ) -> float: \"\"\"Consonni and Todeschini similarity (v1) <NAME>., &",
"math.log(1 + a + d) / math.log(1 + a + b + c",
"+ d) def hamman( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None )",
"A statistical method for evaluating systematic relationships. Univ. Kansas, Sci. Bull., 38, 1409-1438.",
"similarity (v3) <NAME>., & <NAME>. (1973). Numerical taxonomy. The principles and practice of",
"relationships. Univ. Kansas, Sci. Bull., 38, 1409-1438. Args: x (BinaryFeatureVector): binary feature vector",
"def gower_legendre( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float:",
"+ b + c + d))) def consonni_todeschini1( x: BinaryFeatureVector, y: BinaryFeatureVector, mask:",
"mask) return (2 * (a + d)) / (2 * (a + d)",
"of Systematic and Evolutionary Microbiology, 27(3), 204-210. Args: x (BinaryFeatureVector): binary feature vector",
"BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Faith similarity <NAME>.",
"BinaryFeatureVector = None ) -> float: \"\"\"Gower similarity <NAME>. (1971). A general coefficient",
"BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Hamman similarity <NAME>.",
"method for evaluating systematic relationships. Univ. Kansas, Sci. Bull., 38, 1409-1438. Args: x",
"x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower similarity",
"1409-1438. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns:",
"return (a + d - b - c) / (a + b +",
"* math.asin(math.sqrt((a + d) / (a + b + c + d))) def",
"consonni_todeschini1( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Consonni",
"BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Roges-Tanimoto similarity <NAME>.,",
"+ d) def sokal_sneath2( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None )",
"and Todeschini similarity (v1) <NAME>., & <NAME>. (2012). New similarity coefficients for binary",
"/ (2 * (a + d) + b + c) def sokal_sneath3( x:",
"given vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return (a",
"(a + d) / (b + c) def faith( x: BinaryFeatureVector, y: BinaryFeatureVector,",
"+ d) / math.sqrt((a + b) * (a + c) * (b +",
"binsdpy.utils import operational_taxonomic_units, BinaryFeatureVector def smc( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector =",
"d = operational_taxonomic_units(x, y, mask) return math.log(1 + a + d) / math.log(1",
"d) / math.sqrt((a + b) * (a + c) * (b + d)",
"+ d - b - c) / (a + b + c +",
"x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower-Legendre similarity",
"of its properties. Biometrics, 857-871. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector):",
"d) / (a + 2 * (b + c) + d) def sokal_sneath2(",
"c) * (b + d) * (c + d)) def austin_colwell( x: BinaryFeatureVector,",
"c, d = operational_taxonomic_units(x, y, mask) return 2 / math.pi * math.asin(math.sqrt((a +",
"Systematic and Evolutionary Microbiology, 27(3), 204-210. Args: x (BinaryFeatureVector): binary feature vector y",
"y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Austin-Colwell similarity <NAME>., &",
"+ c) * (b + d) * (c + d)) def austin_colwell( x:",
"= operational_taxonomic_units(x, y, mask) return 2 / math.pi * math.asin(math.sqrt((a + d) /",
"c + d))) def consonni_todeschini1( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None",
"= operational_taxonomic_units(x, y, mask) return (a + d) / (b + c) def",
"(a + 2 * (b + c) + d) def sokal_sneath2( x: BinaryFeatureVector,",
"BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Sneath similarity (v3)",
"c, d = operational_taxonomic_units(x, y, mask) return (a + d) / math.sqrt((a +",
"c + d) def rogers_tanimoto( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None",
"statistical method for evaluating systematic relationships. Univ. Kansas, Sci. Bull., 38, 1409-1438. Args:",
"None ) -> float: \"\"\"Sokal-Sneath similarity (v2) <NAME>., & <NAME>. (1973). Numerical taxonomy.",
"d) * (c + d)) def austin_colwell( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector",
"similarity <NAME>. (1983). Asymmetric binary similarity measures. Oecologia, 57(3), 287-290. Args: x (BinaryFeatureVector):",
"\"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return 2 / math.pi",
"taxonomy of microorganisms. International Journal of Systematic and Evolutionary Microbiology, 27(3), 204-210. Args:",
"c + d) def hamman( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None",
"\"\"\"Sokal-Sneath similarity (v3) <NAME>., & <NAME>. (1973). Numerical taxonomy. The principles and practice",
"d) / math.log(1 + a + b + c + d) def hamman(",
"vectors \"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return (2 *",
"New similarity coefficients for binary data. Match-Communications in Mathematical and Computer Chemistry, 68(2),",
"d = operational_taxonomic_units(x, y, mask) return (a + 0.5 * d) / (a",
"Computer Chemistry, 68(2), 581. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary",
"BinaryFeatureVector = None ) -> float: \"\"\"Hamman similarity <NAME>. (1961). Merkmalsbestand und verwandtschaftsbeziehungen",
"for classifying plants. Science, 132(3434), 1115-1118. Args: x (BinaryFeatureVector): binary feature vector y",
"d = operational_taxonomic_units(x, y, mask) return (2 * (a + d)) / (2",
"c, d = operational_taxonomic_units(x, y, mask) return (a + 0.5 * d) /",
"-> float: \"\"\"Gower similarity <NAME>. (1971). A general coefficient of similarity and some",
"/ math.log(1 + a + b + c + d) def hamman( x:",
"None ) -> float: \"\"\"Gower-Legendre similarity <NAME>., & <NAME>. (1986). Metric and Euclidean",
"Merkmalsbestand und verwandtschaftsbeziehungen der farinosae: ein beitrag zum system der monokotyledonen. Willdenowia, 639-768.",
"properties. Biometrics, 857-871. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature",
"BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Michener similarity (also called simple matching coefficient)",
"operational_taxonomic_units(x, y, mask) return (a + d) / (b + c) def faith(",
"gower_legendre( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Gower-Legendre",
"-> float: \"\"\"Hamman similarity <NAME>. (1961). Merkmalsbestand und verwandtschaftsbeziehungen der farinosae: ein beitrag",
"feature vector Returns: float: similarity of given vectors \"\"\" a, b, c, d",
"BinaryFeatureVector = None ) -> float: \"\"\"Faith similarity <NAME>. (1983). Asymmetric binary similarity",
"/ (a + 0.5 * (b + c) + d) def gower( x:",
"y, mask) return math.log(1 + a + d) / math.log(1 + a +",
"operational_taxonomic_units(x, y, mask) return (a + d) / (a + 0.5 * (b",
"a + d) / math.log(1 + a + b + c + d)",
"& <NAME>. (1977). Evaluation of some coefficients for use in numerical taxonomy of",
"similarity <NAME>. (1961). Merkmalsbestand und verwandtschaftsbeziehungen der farinosae: ein beitrag zum system der",
"y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Roges-Tanimoto similarity <NAME>., &",
"/ (b + c) def faith( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector =",
"smc( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Sokal-Michener",
"639-768. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature vector Returns:",
"= operational_taxonomic_units(x, y, mask) return (a + d) / (a + 0.5 *",
"+ c) + d) def gower( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector =",
"b, c, d = operational_taxonomic_units(x, y, mask) return (a + d) / math.sqrt((a",
"<NAME>. (1958). A statistical method for evaluating systematic relationships. Univ. Kansas, Sci. Bull.,",
") -> float: \"\"\"Consonni and Todeschini similarity (v1) <NAME>., & <NAME>. (2012). New",
"-> float: \"\"\"Gower-Legendre similarity <NAME>., & <NAME>. (1986). Metric and Euclidean properties of",
"(a + b + c + d) def rogers_tanimoto( x: BinaryFeatureVector, y: BinaryFeatureVector,",
"= operational_taxonomic_units(x, y, mask) return math.log(1 + a + d) / math.log(1 +",
"Microbiology, 27(3), 204-210. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary feature",
"coefficient of similarity and some of its properties. Biometrics, 857-871. Args: x (BinaryFeatureVector):",
"Sci. Bull., 38, 1409-1438. Args: x (BinaryFeatureVector): binary feature vector y (BinaryFeatureVector): binary",
"faith( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: \"\"\"Faith",
"/ (a + b + c + d) def rogers_tanimoto( x: BinaryFeatureVector, y:",
"(2012). New similarity coefficients for binary data. Match-Communications in Mathematical and Computer Chemistry,",
"\"\"\" a, b, c, d = operational_taxonomic_units(x, y, mask) return (2 * (a",
"binary data. Match-Communications in Mathematical and Computer Chemistry, 68(2), 581. Args: x (BinaryFeatureVector):"
] |
[
"Looping through key:value of the dictions for k, v in obj.items(): print('Key:Value', k,",
"'red', 'age': 42} # Using multiple assignments from the item tuple returned during",
"# Using multiple assignments from the item tuple returned during each iteration #",
"'age': 42} # Using multiple assignments from the item tuple returned during each",
"multiple assignments from the item tuple returned during each iteration for k, v",
"= {'color': 'red', 'age': 42} # Using multiple assignments from the item tuple",
"# Using multiple assignments from the item tuple returned during each iteration for",
"the item tuple returned during each iteration for k, v in obj.items(): print('Key:",
"k, v in obj.items(): print('Key: ' + k + ' Value: ' +",
"RESOURCES # obj = {'color': 'red', 'age': 42} # Using multiple assignments from",
"# HEAD # DataType - Dictionaries Multiple Assignments # DESCRIPTION # Describes the",
"returned during each iteration # Looping through key:value of the dictions for k,",
"iteration # Looping through key:value of the dictions for k, v in obj.items():",
"DataType - Dictionaries Multiple Assignments # DESCRIPTION # Describes the assigning, working, and",
"usages of dictionaries # RESOURCES # obj = {'color': 'red', 'age': 42} #",
"in obj.items(): print('Key: ' + k + ' Value: ' + str(v)) #",
"Dictionaries Multiple Assignments # DESCRIPTION # Describes the assigning, working, and method usages",
"method usages of dictionaries # RESOURCES # obj = {'color': 'red', 'age': 42}",
"each iteration for k, v in obj.items(): print('Key: ' + k + '",
"each iteration # Looping through key:value of the dictions for k, v in",
"' Value: ' + str(v)) # Using multiple assignments from the item tuple",
"Using multiple assignments from the item tuple returned during each iteration for k,",
"print('Key: ' + k + ' Value: ' + str(v)) # Using multiple",
"item tuple returned during each iteration # Looping through key:value of the dictions",
"HEAD # DataType - Dictionaries Multiple Assignments # DESCRIPTION # Describes the assigning,",
"+ k + ' Value: ' + str(v)) # Using multiple assignments from",
"Assignments # DESCRIPTION # Describes the assigning, working, and method usages of dictionaries",
"Multiple Assignments # DESCRIPTION # Describes the assigning, working, and method usages of",
"of dictionaries # RESOURCES # obj = {'color': 'red', 'age': 42} # Using",
"iteration for k, v in obj.items(): print('Key: ' + k + ' Value:",
"v in obj.items(): print('Key: ' + k + ' Value: ' + str(v))",
"through key:value of the dictions for k, v in obj.items(): print('Key:Value', k, v)",
"DESCRIPTION # Describes the assigning, working, and method usages of dictionaries # RESOURCES",
"Value: ' + str(v)) # Using multiple assignments from the item tuple returned",
"and method usages of dictionaries # RESOURCES # obj = {'color': 'red', 'age':",
"# DESCRIPTION # Describes the assigning, working, and method usages of dictionaries #",
"the assigning, working, and method usages of dictionaries # RESOURCES # obj =",
"+ ' Value: ' + str(v)) # Using multiple assignments from the item",
"from the item tuple returned during each iteration # Looping through key:value of",
"the item tuple returned during each iteration # Looping through key:value of the",
"for k, v in obj.items(): print('Key: ' + k + ' Value: '",
"working, and method usages of dictionaries # RESOURCES # obj = {'color': 'red',",
"assignments from the item tuple returned during each iteration # Looping through key:value",
"item tuple returned during each iteration for k, v in obj.items(): print('Key: '",
"obj.items(): print('Key: ' + k + ' Value: ' + str(v)) # Using",
"+ str(v)) # Using multiple assignments from the item tuple returned during each",
"{'color': 'red', 'age': 42} # Using multiple assignments from the item tuple returned",
"dictionaries # RESOURCES # obj = {'color': 'red', 'age': 42} # Using multiple",
"during each iteration for k, v in obj.items(): print('Key: ' + k +",
"multiple assignments from the item tuple returned during each iteration # Looping through",
"42} # Using multiple assignments from the item tuple returned during each iteration",
"returned during each iteration for k, v in obj.items(): print('Key: ' + k",
"tuple returned during each iteration # Looping through key:value of the dictions for",
"Describes the assigning, working, and method usages of dictionaries # RESOURCES # obj",
"# RESOURCES # obj = {'color': 'red', 'age': 42} # Using multiple assignments",
"# DataType - Dictionaries Multiple Assignments # DESCRIPTION # Describes the assigning, working,",
"during each iteration # Looping through key:value of the dictions for k, v",
"# obj = {'color': 'red', 'age': 42} # Using multiple assignments from the",
"obj = {'color': 'red', 'age': 42} # Using multiple assignments from the item",
"from the item tuple returned during each iteration for k, v in obj.items():",
"' + k + ' Value: ' + str(v)) # Using multiple assignments",
"# Looping through key:value of the dictions for k, v in obj.items(): print('Key:Value',",
"assignments from the item tuple returned during each iteration for k, v in",
"Using multiple assignments from the item tuple returned during each iteration # Looping",
"- Dictionaries Multiple Assignments # DESCRIPTION # Describes the assigning, working, and method",
"' + str(v)) # Using multiple assignments from the item tuple returned during",
"str(v)) # Using multiple assignments from the item tuple returned during each iteration",
"k + ' Value: ' + str(v)) # Using multiple assignments from the",
"# Describes the assigning, working, and method usages of dictionaries # RESOURCES #",
"tuple returned during each iteration for k, v in obj.items(): print('Key: ' +",
"assigning, working, and method usages of dictionaries # RESOURCES # obj = {'color':"
] |
[
"actions: dict): act = [] for action, value in actions.items(): act.append(Action(action, value)) self.__actions",
") self.actions = description['actions'] @property def actions(self): return self.__actions @actions.setter def actions(self, actions:",
"act = [] for action, value in actions.items(): act.append(Action(action, value)) self.__actions = act",
"self.actions = description['actions'] @property def actions(self): return self.__actions @actions.setter def actions(self, actions: dict):",
"import Action from utility_ai.traits.utility_score_trait import UtilityScoreTrait class Bucket(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name: str,",
"= description['actions'] @property def actions(self): return self.__actions @actions.setter def actions(self, actions: dict): act",
"name ) self.actions = description['actions'] @property def actions(self): return self.__actions @actions.setter def actions(self,",
"def actions(self, actions: dict): act = [] for action, value in actions.items(): act.append(Action(action,",
"from .action import Action from utility_ai.traits.utility_score_trait import UtilityScoreTrait class Bucket(ConfigurationEntry, UtilityScoreTrait): def __init__(self,",
"description) UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value, name ) self.actions = description['actions'] @property def actions(self):",
"actions(self): return self.__actions @actions.setter def actions(self, actions: dict): act = [] for action,",
"self.__actions @actions.setter def actions(self, actions: dict): act = [] for action, value in",
"ConfigurationEntry from .action import Action from utility_ai.traits.utility_score_trait import UtilityScoreTrait class Bucket(ConfigurationEntry, UtilityScoreTrait): def",
"from utility_ai.traits.utility_score_trait import UtilityScoreTrait class Bucket(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name: str, description: dict):",
"@property def actions(self): return self.__actions @actions.setter def actions(self, actions: dict): act = []",
"UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value, name ) self.actions = description['actions'] @property def actions(self): return",
"import ConfigurationEntry from .action import Action from utility_ai.traits.utility_score_trait import UtilityScoreTrait class Bucket(ConfigurationEntry, UtilityScoreTrait):",
"name: str, description: dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value, name )",
"UtilityScoreTrait): def __init__(self, name: str, description: dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__( self, description['utility_score_formula'],",
"import UtilityScoreTrait class Bucket(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name: str, description: dict): ConfigurationEntry.__init__(self, name,",
"class Bucket(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name: str, description: dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__(",
"dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value, name ) self.actions = description['actions']",
"name, description) UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value, name ) self.actions = description['actions'] @property def",
"description['actions'] @property def actions(self): return self.__actions @actions.setter def actions(self, actions: dict): act =",
"super().weight_value, name ) self.actions = description['actions'] @property def actions(self): return self.__actions @actions.setter def",
"description: dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value, name ) self.actions =",
"from .configuration_entry import ConfigurationEntry from .action import Action from utility_ai.traits.utility_score_trait import UtilityScoreTrait class",
"utility_ai.traits.utility_score_trait import UtilityScoreTrait class Bucket(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name: str, description: dict): ConfigurationEntry.__init__(self,",
"description['utility_score_formula'], super().weight_value, name ) self.actions = description['actions'] @property def actions(self): return self.__actions @actions.setter",
"return self.__actions @actions.setter def actions(self, actions: dict): act = [] for action, value",
"self, description['utility_score_formula'], super().weight_value, name ) self.actions = description['actions'] @property def actions(self): return self.__actions",
"def actions(self): return self.__actions @actions.setter def actions(self, actions: dict): act = [] for",
"str, description: dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value, name ) self.actions",
"ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value, name ) self.actions = description['actions'] @property",
".configuration_entry import ConfigurationEntry from .action import Action from utility_ai.traits.utility_score_trait import UtilityScoreTrait class Bucket(ConfigurationEntry,",
"dict): act = [] for action, value in actions.items(): act.append(Action(action, value)) self.__actions =",
"__init__(self, name: str, description: dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value, name",
"def __init__(self, name: str, description: dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value,",
"UtilityScoreTrait class Bucket(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name: str, description: dict): ConfigurationEntry.__init__(self, name, description)",
"actions(self, actions: dict): act = [] for action, value in actions.items(): act.append(Action(action, value))",
".action import Action from utility_ai.traits.utility_score_trait import UtilityScoreTrait class Bucket(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name:",
"@actions.setter def actions(self, actions: dict): act = [] for action, value in actions.items():",
"Action from utility_ai.traits.utility_score_trait import UtilityScoreTrait class Bucket(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name: str, description:",
"Bucket(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name: str, description: dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__( self,"
] |
[
"converted to upper case... self.assertEqual(category['name'], category_name.upper()) # Tough luck, categories do not have",
"# FUN FUN FUN. All categories have name converted to upper case... self.assertEqual(category['name'],",
"account is now full of unwanted categories... def test_product(self): c = self.client uuid1",
"self.client category_uuid = str(uuid.uuid1()) category_name = 'category name' c.create_category({ 'uuid': category_uuid, 'name': category_name",
"the for the sessino to expire, so it wil take a looooooong time",
"logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase): def __init__(self, *args, **kwargs):",
"= c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'], discount_percentage) new_name = 'new name' c.update_discount(discount_uuid, {'name': new_name})",
"c.create_product({ 'name': name, 'uuid': uuid1, }) product = c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'], name)",
"categories have name converted to upper case... self.assertEqual(category['name'], category_name.upper()) # Tough luck, categories",
"in c.get_product(uuid1)['variants']: if(variant['uuid'] == variant_uuid): variant_is_no_longer_in_product = False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with self.assertRaises(RequestException) as",
"discount_percentage = '10' c.create_discount({ 'uuid': discount_uuid, 'percentage': discount_percentage, }) self.assertGreater(len(c.get_all_discounts()), 0) discount =",
"= False for variant in product_with_updated_variant['variants']: if(variant['uuid'] != variant_uuid): continue self.assertEqual(variant['name'], variant_name) found_the_new_variant",
"'name': updated_name, }) updated_product = c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name) variant_uuid = str(uuid.uuid1()) variant_name =",
"404) uuid2 = str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2) current_product_amount = len(c.get_all_products()) c.create_product({'name': '1', 'uuid': uuid1})",
"make sure that you have environment variables set for the TestIzettle.__init__ method \"\"\"",
"len(c.get_all_products()) c.create_product({'name': '1', 'uuid': uuid1}) c.create_product({'name': '2', 'uuid': uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount + 2)",
"str(uuid.uuid1()) name = 'product1' with self.assertRaises(RequestException) as e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found',",
"environment variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD. \"\"\" super(TestIzettle, self).__init__(*args, **kwargs) self.client = Izettle(",
"name converted to upper case... self.assertEqual(category['name'], category_name.upper()) # Tough luck, categories do not",
"404) self.assertIn('not found', e.exception.developer_message) c.create_product({ 'name': name, 'uuid': uuid1, }) product = c.get_product(uuid1)",
"= self.client discount_uuid = str(uuid.uuid1()) discount_percentage = '10' c.create_discount({ 'uuid': discount_uuid, 'percentage': discount_percentage,",
"in the server, because we made up the uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not",
"self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase = c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This will take",
"luck, categories do not have delete method. # Your account is now full",
"Izettle(client_id='invalid') exception = re.exception self.assertEqual(exception.developer_message, \"Invalid client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code, 400) def test_discounts(self):",
"= 'category name' c.create_category({ 'uuid': category_uuid, 'name': category_name }) self.assertGreater(len(c.get_all_categroies()), 0) category =",
"= 'variant name 1' c.create_product_variant(uuid1, {'uuid': variant_uuid}) c.update_product_variant(uuid1, variant_uuid, {'name': variant_name}) product_with_updated_variant =",
"invalid parameters \"\"\" with self.assertRaises(RequestException) as re: Izettle(client_id='invalid') exception = re.exception self.assertEqual(exception.developer_message, \"Invalid",
"so it wil take a looooooong time \"\"\" self.client.__session_valid_until = time.time() + 9000",
"variables set for the TestIzettle.__init__ method \"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def",
"if(variant['uuid'] != variant_uuid): continue self.assertEqual(variant['name'], variant_name) found_the_new_variant = True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product",
"import unittest import logging import uuid import time from iZettle.iZettle import Izettle, RequestException",
"before we anticipate. This simply waits for the for the sessino to expire,",
"def test_invalid_client_id(self): \"\"\" Test client creation with invalid parameters \"\"\" with self.assertRaises(RequestException) as",
"have name converted to upper case... self.assertEqual(category['name'], category_name.upper()) # Tough luck, categories do",
"to upper case... self.assertEqual(category['name'], category_name.upper()) # Tough luck, categories do not have delete",
"c.create_product({'name': '2', 'uuid': uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount + 2) c.delete_product_list({'uuid': [uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount)",
"unwanted categories... def test_product(self): c = self.client uuid1 = str(uuid.uuid1()) name = 'product1'",
"single_purchase = c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This will take over 2 hours.') def test_session(self):",
"= logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase): def __init__(self, *args, **kwargs): \"\"\" Initialize iZettle client.",
"uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount + 2) c.delete_product_list({'uuid': [uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount) def test_purchases(self): c",
"self.assertEqual(updated_product['name'], updated_name) variant_uuid = str(uuid.uuid1()) variant_name = 'variant name 1' c.create_product_variant(uuid1, {'uuid': variant_uuid})",
"set for the TestIzettle.__init__ method \"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def test_auth(self):",
"variant_name = 'variant name 1' c.create_product_variant(uuid1, {'uuid': variant_uuid}) c.update_product_variant(uuid1, variant_uuid, {'name': variant_name}) product_with_updated_variant",
"course cannot be in the server, because we made up the uuid c.get_purchase(str(uuid.uuid1()))",
"in data dict c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError): # missing mandatory argument c.get_purchase() with self.assertRaises(RequestException)",
"def test_discounts(self): c = self.client discount_uuid = str(uuid.uuid1()) discount_percentage = '10' c.create_discount({ 'uuid':",
"'1', 'uuid': uuid1}) c.create_product({'name': '2', 'uuid': uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount + 2) c.delete_product_list({'uuid': [uuid1,",
"variant_is_no_longer_in_product = False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with self.assertRaises(RequestException) as re: c.get_product(uuid1) exception = re.exception",
"c.delete_product_list({'uuid': [uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount) def test_purchases(self): c = self.client with self.assertRaises(TypeError): #",
"iZettle.iZettle import Izettle, RequestException logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout)",
"'uuid': uuid1}) c.create_product({'name': '2', 'uuid': uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount + 2) c.delete_product_list({'uuid': [uuid1, uuid2]})",
"found_the_new_variant = False for variant in product_with_updated_variant['variants']: if(variant['uuid'] != variant_uuid): continue self.assertEqual(variant['name'], variant_name)",
"product_with_updated_variant['variants']: if(variant['uuid'] != variant_uuid): continue self.assertEqual(variant['name'], variant_name) found_the_new_variant = True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid)",
"with self.assertRaises(TypeError): # missing mandatory argument c.get_purchase() with self.assertRaises(RequestException) as e: # This",
"{ 'name': updated_name, }) updated_product = c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name) variant_uuid = str(uuid.uuid1()) variant_name",
"for the sessino to expire, so it wil take a looooooong time \"\"\"",
"uuid1 = str(uuid.uuid1()) name = 'product1' with self.assertRaises(RequestException) as e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404)",
"TestIzettle.__init__ method \"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def test_auth(self): \"\"\" Test that",
"str(uuid.uuid1()) discount_percentage = '10' c.create_discount({ 'uuid': discount_uuid, 'percentage': discount_percentage, }) self.assertGreater(len(c.get_all_discounts()), 0) discount",
"'variant name 1' c.create_product_variant(uuid1, {'uuid': variant_uuid}) c.update_product_variant(uuid1, variant_uuid, {'name': variant_name}) product_with_updated_variant = c.get_product(uuid1)",
"= re.exception self.assertEqual(exception.msg, \"request error 404\") self.assertEqual(exception.request.status_code, 404) uuid2 = str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2)",
"= 'product1' with self.assertRaises(RequestException) as e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) c.create_product({",
"\"Invalid client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code, 400) def test_discounts(self): c = self.client discount_uuid =",
"token from izettle API \"\"\" self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self): \"\"\" Test client creation with",
"for the for the sessino to expire, so it wil take a looooooong",
"logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase): def __init__(self, *args, **kwargs): \"\"\" Initialize iZettle client. Requires",
"you have environment variables set for the TestIzettle.__init__ method \"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret)",
"as re: c.get_discount(discount_uuid) exception = re.exception self.assertEqual(exception.request.status_code, 404) def test_categories(self): c = self.client",
"variant_uuid = str(uuid.uuid1()) variant_name = 'variant name 1' c.create_product_variant(uuid1, {'uuid': variant_uuid}) c.update_product_variant(uuid1, variant_uuid,",
"c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase = c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1",
"c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid) # FUN FUN FUN. All categories have name converted to",
"category_uuid, 'name': category_name }) self.assertGreater(len(c.get_all_categroies()), 0) category = c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid) # FUN",
"= c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'], name) updated_name = 'updated product name' c.update_product(uuid1, {",
"category_uuid = str(uuid.uuid1()) category_name = 'category name' c.create_category({ 'uuid': category_uuid, 'name': category_name })",
"self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def test_auth(self): \"\"\" Test that we got token",
"*args, **kwargs): \"\"\" Initialize iZettle client. Requires the following environment variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET,",
"c.get_product(uuid1) found_the_new_variant = False for variant in product_with_updated_variant['variants']: if(variant['uuid'] != variant_uuid): continue self.assertEqual(variant['name'],",
"current_product_amount) def test_purchases(self): c = self.client with self.assertRaises(TypeError): # Parameters need to be",
"Requires the following environment variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD. \"\"\" super(TestIzettle, self).__init__(*args, **kwargs)",
"= self.client category_uuid = str(uuid.uuid1()) category_name = 'category name' c.create_category({ 'uuid': category_uuid, 'name':",
"with self.assertRaises(RequestException) as e: # This order of course cannot be in the",
"# missing mandatory argument c.get_purchase() with self.assertRaises(RequestException) as e: # This order of",
"variant_uuid}) c.update_product_variant(uuid1, variant_uuid, {'name': variant_name}) product_with_updated_variant = c.get_product(uuid1) found_the_new_variant = False for variant",
"404) self.assertIn('not found', e.exception.developer_message) multiple_purchases = c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID']",
"take a looooooong time \"\"\" self.client.__session_valid_until = time.time() + 9000 time.sleep(8000) self.assertIsNotNone(self.client.get_all_products()) if",
"updated_name, }) updated_product = c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name) variant_uuid = str(uuid.uuid1()) variant_name = 'variant",
"following environment variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD. \"\"\" super(TestIzettle, self).__init__(*args, **kwargs) self.client =",
"\"invalid_client\") self.assertEqual(exception.request.status_code, 400) def test_discounts(self): c = self.client discount_uuid = str(uuid.uuid1()) discount_percentage =",
"self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def test_auth(self): \"\"\" Test that we got token from izettle API",
") def test_instance(self): \"\"\" Test that the client was initialized correctly. If this",
"found', e.exception.developer_message) c.create_product({ 'name': name, 'uuid': uuid1, }) product = c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1)",
"not have delete method. # Your account is now full of unwanted categories...",
"self.assertEqual(exception.msg, \"request error 404\") self.assertEqual(exception.request.status_code, 404) uuid2 = str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2) current_product_amount =",
"name, 'uuid': uuid1, }) product = c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'], name) updated_name =",
"self.assertGreater(len(c.get_all_discounts()), 0) discount = c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'], discount_percentage) new_name = 'new name'",
"= str(uuid.uuid1()) variant_name = 'variant name 1' c.create_product_variant(uuid1, {'uuid': variant_uuid}) c.update_product_variant(uuid1, variant_uuid, {'name':",
"import os import sys import unittest import logging import uuid import time from",
"to be in data dict c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError): # missing mandatory argument c.get_purchase()",
"purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase = c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase =",
"self.assertRaises(RequestException) as re: Izettle(client_id='invalid') exception = re.exception self.assertEqual(exception.developer_message, \"Invalid client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code,",
"tests if the integration works if the session expires before we anticipate. This",
"from izettle API \"\"\" self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self): \"\"\" Test client creation with invalid",
"e: # This order of course cannot be in the server, because we",
"name = 'product1' with self.assertRaises(RequestException) as e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message)",
"that you have environment variables set for the TestIzettle.__init__ method \"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id)",
"= re.exception self.assertEqual(exception.request.status_code, 404) def test_categories(self): c = self.client category_uuid = str(uuid.uuid1()) category_name",
"c.create_product_variant(uuid1, {'uuid': variant_uuid}) c.update_product_variant(uuid1, variant_uuid, {'name': variant_name}) product_with_updated_variant = c.get_product(uuid1) found_the_new_variant = False",
"Parameters need to be in data dict c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError): # missing mandatory",
"\"\"\" self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self): \"\"\" Test client creation with invalid parameters \"\"\" with",
"exception = re.exception self.assertEqual(exception.request.status_code, 404) def test_categories(self): c = self.client category_uuid = str(uuid.uuid1())",
"import time from iZettle.iZettle import Izettle, RequestException logger = logging.getLogger() logger.level = logging.DEBUG",
"self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This will take over 2 hours.') def test_session(self): \"\"\" This tests",
"logging import uuid import time from iZettle.iZettle import Izettle, RequestException logger = logging.getLogger()",
"= c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase = c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This",
"be in data dict c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError): # missing mandatory argument c.get_purchase() with",
"delete method. # Your account is now full of unwanted categories... def test_product(self):",
"c = self.client with self.assertRaises(TypeError): # Parameters need to be in data dict",
"404) def test_categories(self): c = self.client category_uuid = str(uuid.uuid1()) category_name = 'category name'",
"self.assertIsNotNone(self.client._Izettle__password) def test_auth(self): \"\"\" Test that we got token from izettle API \"\"\"",
"discount_percentage) new_name = 'new name' c.update_discount(discount_uuid, {'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid) with self.assertRaises(RequestException)",
"the session expires before we anticipate. This simply waits for the for the",
"multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase = c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase = c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid,",
"test_auth(self): \"\"\" Test that we got token from izettle API \"\"\" self.assertIsNotNone(self.client._Izettle__token) def",
"single_purchase['purchaseUUID']) @unittest.skip('This will take over 2 hours.') def test_session(self): \"\"\" This tests if",
"RequestException logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase):",
"self.assertEqual(exception.request.status_code, 400) def test_discounts(self): c = self.client discount_uuid = str(uuid.uuid1()) discount_percentage = '10'",
"self.assertEqual(category['name'], category_name.upper()) # Tough luck, categories do not have delete method. # Your",
"{'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid) with self.assertRaises(RequestException) as re: c.get_discount(discount_uuid) exception = re.exception",
"= str(uuid.uuid1()) category_name = 'category name' c.create_category({ 'uuid': category_uuid, 'name': category_name }) self.assertGreater(len(c.get_all_categroies()),",
"self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with self.assertRaises(RequestException) as re: c.get_product(uuid1) exception = re.exception self.assertEqual(exception.msg, \"request error",
"variant_uuid, {'name': variant_name}) product_with_updated_variant = c.get_product(uuid1) found_the_new_variant = False for variant in product_with_updated_variant['variants']:",
"simply waits for the for the sessino to expire, so it wil take",
"0) category = c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid) # FUN FUN FUN. All categories have",
"self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) c.create_product({ 'name': name, 'uuid': uuid1, }) product =",
"sessino to expire, so it wil take a looooooong time \"\"\" self.client.__session_valid_until =",
"uuid1) self.assertEqual(product['name'], name) updated_name = 'updated product name' c.update_product(uuid1, { 'name': updated_name, })",
"the TestIzettle.__init__ method \"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def test_auth(self): \"\"\" Test",
"{'name': variant_name}) product_with_updated_variant = c.get_product(uuid1) found_the_new_variant = False for variant in product_with_updated_variant['variants']: if(variant['uuid']",
"c.update_product_variant(uuid1, variant_uuid, {'name': variant_name}) product_with_updated_variant = c.get_product(uuid1) found_the_new_variant = False for variant in",
"= self.client with self.assertRaises(TypeError): # Parameters need to be in data dict c.get_multiple_purchases(limit=1)",
"stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase): def __init__(self, *args, **kwargs): \"\"\" Initialize iZettle",
"new_name) c.delete_discount(discount_uuid) with self.assertRaises(RequestException) as re: c.get_discount(discount_uuid) exception = re.exception self.assertEqual(exception.request.status_code, 404) def",
"variant in product_with_updated_variant['variants']: if(variant['uuid'] != variant_uuid): continue self.assertEqual(variant['name'], variant_name) found_the_new_variant = True self.assertTrue(found_the_new_variant)",
"client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], ) def test_instance(self): \"\"\" Test that the client was",
"c.get_purchase() with self.assertRaises(RequestException) as e: # This order of course cannot be in",
"test_invalid_client_id(self): \"\"\" Test client creation with invalid parameters \"\"\" with self.assertRaises(RequestException) as re:",
"Test that the client was initialized correctly. If this fails, make sure that",
"because we made up the uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) multiple_purchases",
"session expires before we anticipate. This simply waits for the for the sessino",
"was initialized correctly. If this fails, make sure that you have environment variables",
"of unwanted categories... def test_product(self): c = self.client uuid1 = str(uuid.uuid1()) name =",
"discount_uuid = str(uuid.uuid1()) discount_percentage = '10' c.create_discount({ 'uuid': discount_uuid, 'percentage': discount_percentage, }) self.assertGreater(len(c.get_all_discounts()),",
"dict c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError): # missing mandatory argument c.get_purchase() with self.assertRaises(RequestException) as e:",
"'10' c.create_discount({ 'uuid': discount_uuid, 'percentage': discount_percentage, }) self.assertGreater(len(c.get_all_discounts()), 0) discount = c.get_discount(discount_uuid) self.assertEqual(discount['uuid'],",
"discount_uuid, 'percentage': discount_percentage, }) self.assertGreater(len(c.get_all_discounts()), 0) discount = c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'], discount_percentage)",
"new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid) with self.assertRaises(RequestException) as re: c.get_discount(discount_uuid) exception = re.exception self.assertEqual(exception.request.status_code,",
"to expire, so it wil take a looooooong time \"\"\" self.client.__session_valid_until = time.time()",
"**kwargs) self.client = Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], ) def test_instance(self): \"\"\" Test",
"over 2 hours.') def test_session(self): \"\"\" This tests if the integration works if",
"the server, because we made up the uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found',",
"category_name }) self.assertGreater(len(c.get_all_categroies()), 0) category = c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid) # FUN FUN FUN.",
"name' c.create_category({ 'uuid': category_uuid, 'name': category_name }) self.assertGreater(len(c.get_all_categroies()), 0) category = c.get_category(category_uuid) self.assertEqual(category['uuid'],",
"creation with invalid parameters \"\"\" with self.assertRaises(RequestException) as re: Izettle(client_id='invalid') exception = re.exception",
"upper case... self.assertEqual(category['name'], category_name.upper()) # Tough luck, categories do not have delete method.",
"\"\"\" with self.assertRaises(RequestException) as re: Izettle(client_id='invalid') exception = re.exception self.assertEqual(exception.developer_message, \"Invalid client_id\") self.assertEqual(exception.request.json()['error'],",
"method \"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def test_auth(self): \"\"\" Test that we",
"'name': name, 'uuid': uuid1, }) product = c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'], name) updated_name",
"= c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This will take over 2 hours.') def test_session(self): \"\"\"",
"e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) c.create_product({ 'name': name, 'uuid': uuid1, })",
"c = self.client category_uuid = str(uuid.uuid1()) category_name = 'category name' c.create_category({ 'uuid': category_uuid,",
"c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError): # missing mandatory argument c.get_purchase() with self.assertRaises(RequestException) as e: #",
"be in the server, because we made up the uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404)",
"waits for the for the sessino to expire, so it wil take a",
"sys import unittest import logging import uuid import time from iZettle.iZettle import Izettle,",
"order of course cannot be in the server, because we made up the",
"the following environment variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD. \"\"\" super(TestIzettle, self).__init__(*args, **kwargs) self.client",
"e.exception.developer_message) c.create_product({ 'name': name, 'uuid': uuid1, }) product = c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'],",
"environment variables set for the TestIzettle.__init__ method \"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password)",
"the integration works if the session expires before we anticipate. This simply waits",
"= c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase = c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID'])",
"expires before we anticipate. This simply waits for the for the sessino to",
"user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], ) def test_instance(self): \"\"\" Test that the client was initialized correctly.",
"as e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) c.create_product({ 'name': name, 'uuid': uuid1,",
"test_product(self): c = self.client uuid1 = str(uuid.uuid1()) name = 'product1' with self.assertRaises(RequestException) as",
"continue self.assertEqual(variant['name'], variant_name) found_the_new_variant = True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product = True for",
"got token from izettle API \"\"\" self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self): \"\"\" Test client creation",
"\"\"\" Test client creation with invalid parameters \"\"\" with self.assertRaises(RequestException) as re: Izettle(client_id='invalid')",
"self.client uuid1 = str(uuid.uuid1()) name = 'product1' with self.assertRaises(RequestException) as e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code,",
"self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product = True for variant in c.get_product(uuid1)['variants']: if(variant['uuid'] == variant_uuid):",
"that we got token from izettle API \"\"\" self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self): \"\"\" Test",
"2) c.delete_product_list({'uuid': [uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount) def test_purchases(self): c = self.client with self.assertRaises(TypeError):",
"IZETTLE_PASSWORD. \"\"\" super(TestIzettle, self).__init__(*args, **kwargs) self.client = Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], )",
"This tests if the integration works if the session expires before we anticipate.",
"# Your account is now full of unwanted categories... def test_product(self): c =",
"data dict c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError): # missing mandatory argument c.get_purchase() with self.assertRaises(RequestException) as",
"re: Izettle(client_id='invalid') exception = re.exception self.assertEqual(exception.developer_message, \"Invalid client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code, 400) def",
"logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase): def __init__(self, *args, **kwargs): \"\"\" Initialize iZettle client. Requires the",
"c.get_product(uuid1) exception = re.exception self.assertEqual(exception.msg, \"request error 404\") self.assertEqual(exception.request.status_code, 404) uuid2 = str(uuid.uuid1())",
"self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def test_auth(self): \"\"\" Test that we got token from izettle",
"= c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name) variant_uuid = str(uuid.uuid1()) variant_name = 'variant name 1' c.create_product_variant(uuid1,",
"\"\"\" super(TestIzettle, self).__init__(*args, **kwargs) self.client = Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], ) def",
"= '10' c.create_discount({ 'uuid': discount_uuid, 'percentage': discount_percentage, }) self.assertGreater(len(c.get_all_discounts()), 0) discount = c.get_discount(discount_uuid)",
"the sessino to expire, so it wil take a looooooong time \"\"\" self.client.__session_valid_until",
"self.assertEqual(exception.request.status_code, 404) uuid2 = str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2) current_product_amount = len(c.get_all_products()) c.create_product({'name': '1', 'uuid':",
"variant_uuid): variant_is_no_longer_in_product = False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with self.assertRaises(RequestException) as re: c.get_product(uuid1) exception =",
"'name': category_name }) self.assertGreater(len(c.get_all_categroies()), 0) category = c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid) # FUN FUN",
"test_categories(self): c = self.client category_uuid = str(uuid.uuid1()) category_name = 'category name' c.create_category({ 'uuid':",
"exception = re.exception self.assertEqual(exception.msg, \"request error 404\") self.assertEqual(exception.request.status_code, 404) uuid2 = str(uuid.uuid1()) self.assertNotEqual(uuid1,",
"}) self.assertGreater(len(c.get_all_categroies()), 0) category = c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid) # FUN FUN FUN. All",
"'updated product name' c.update_product(uuid1, { 'name': updated_name, }) updated_product = c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name)",
"\"\"\" Test that we got token from izettle API \"\"\" self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self):",
"category_uuid) # FUN FUN FUN. All categories have name converted to upper case...",
"str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2) current_product_amount = len(c.get_all_products()) c.create_product({'name': '1', 'uuid': uuid1}) c.create_product({'name': '2', 'uuid':",
"!= variant_uuid): continue self.assertEqual(variant['name'], variant_name) found_the_new_variant = True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product =",
"of course cannot be in the server, because we made up the uuid",
"with invalid parameters \"\"\" with self.assertRaises(RequestException) as re: Izettle(client_id='invalid') exception = re.exception self.assertEqual(exception.developer_message,",
"with self.assertRaises(RequestException) as e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) c.create_product({ 'name': name,",
"uuid2 = str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2) current_product_amount = len(c.get_all_products()) c.create_product({'name': '1', 'uuid': uuid1}) c.create_product({'name':",
"discount_uuid) self.assertEqual(discount['percentage'], discount_percentage) new_name = 'new name' c.update_discount(discount_uuid, {'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid)",
"self).__init__(*args, **kwargs) self.client = Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], ) def test_instance(self): \"\"\"",
"that the client was initialized correctly. If this fails, make sure that you",
"= logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase): def __init__(self,",
"Initialize iZettle client. Requires the following environment variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD. \"\"\"",
"name) updated_name = 'updated product name' c.update_product(uuid1, { 'name': updated_name, }) updated_product =",
"c.get_discount(discount_uuid) exception = re.exception self.assertEqual(exception.request.status_code, 404) def test_categories(self): c = self.client category_uuid =",
"it wil take a looooooong time \"\"\" self.client.__session_valid_until = time.time() + 9000 time.sleep(8000)",
"\"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def test_auth(self): \"\"\" Test that we got",
"discount_percentage, }) self.assertGreater(len(c.get_all_discounts()), 0) discount = c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'], discount_percentage) new_name =",
"self.client with self.assertRaises(TypeError): # Parameters need to be in data dict c.get_multiple_purchases(limit=1) with",
"= re.exception self.assertEqual(exception.developer_message, \"Invalid client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code, 400) def test_discounts(self): c =",
"False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with self.assertRaises(RequestException) as re: c.get_product(uuid1) exception = re.exception self.assertEqual(exception.msg, \"request",
"def test_session(self): \"\"\" This tests if the integration works if the session expires",
"parameters \"\"\" with self.assertRaises(RequestException) as re: Izettle(client_id='invalid') exception = re.exception self.assertEqual(exception.developer_message, \"Invalid client_id\")",
"the client was initialized correctly. If this fails, make sure that you have",
"exception = re.exception self.assertEqual(exception.developer_message, \"Invalid client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code, 400) def test_discounts(self): c",
"as re: Izettle(client_id='invalid') exception = re.exception self.assertEqual(exception.developer_message, \"Invalid client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code, 400)",
"self.assertEqual(product['name'], name) updated_name = 'updated product name' c.update_product(uuid1, { 'name': updated_name, }) updated_product",
"name 1' c.create_product_variant(uuid1, {'uuid': variant_uuid}) c.update_product_variant(uuid1, variant_uuid, {'name': variant_name}) product_with_updated_variant = c.get_product(uuid1) found_the_new_variant",
"re.exception self.assertEqual(exception.msg, \"request error 404\") self.assertEqual(exception.request.status_code, 404) uuid2 = str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2) current_product_amount",
"product_with_updated_variant = c.get_product(uuid1) found_the_new_variant = False for variant in product_with_updated_variant['variants']: if(variant['uuid'] != variant_uuid):",
"fails, make sure that you have environment variables set for the TestIzettle.__init__ method",
"self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self): \"\"\" Test client creation with invalid parameters \"\"\" with self.assertRaises(RequestException)",
"\"\"\" self.client.__session_valid_until = time.time() + 9000 time.sleep(8000) self.assertIsNotNone(self.client.get_all_products()) if __name__ == '__main__': unittest.main(verbosity=2)",
"True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product = True for variant in c.get_product(uuid1)['variants']: if(variant['uuid'] ==",
"self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'], name) updated_name = 'updated product name' c.update_product(uuid1, { 'name': updated_name,",
"self.assertEqual(exception.developer_message, \"Invalid client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code, 400) def test_discounts(self): c = self.client discount_uuid",
"c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name) variant_uuid = str(uuid.uuid1()) variant_name = 'variant name 1' c.create_product_variant(uuid1, {'uuid':",
"= 'updated product name' c.update_product(uuid1, { 'name': updated_name, }) updated_product = c.get_product(uuid1) self.assertEqual(updated_product['name'],",
"os import sys import unittest import logging import uuid import time from iZettle.iZettle",
"missing mandatory argument c.get_purchase() with self.assertRaises(RequestException) as e: # This order of course",
"multiple_purchases = c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase = c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid,",
"logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase): def __init__(self, *args, **kwargs): \"\"\" Initialize",
"self.assertIn('not found', e.exception.developer_message) c.create_product({ 'name': name, 'uuid': uuid1, }) product = c.get_product(uuid1) self.assertEqual(product['uuid'],",
"now full of unwanted categories... def test_product(self): c = self.client uuid1 = str(uuid.uuid1())",
"def __init__(self, *args, **kwargs): \"\"\" Initialize iZettle client. Requires the following environment variables",
"re.exception self.assertEqual(exception.developer_message, \"Invalid client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code, 400) def test_discounts(self): c = self.client",
"have delete method. # Your account is now full of unwanted categories... def",
"self.assertRaises(RequestException) as re: c.get_product(uuid1) exception = re.exception self.assertEqual(exception.msg, \"request error 404\") self.assertEqual(exception.request.status_code, 404)",
"'uuid': uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount + 2) c.delete_product_list({'uuid': [uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount) def test_purchases(self):",
"self.assertEqual(category['uuid'], category_uuid) # FUN FUN FUN. All categories have name converted to upper",
"category_name.upper()) # Tough luck, categories do not have delete method. # Your account",
"= 'new name' c.update_discount(discount_uuid, {'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid) with self.assertRaises(RequestException) as re:",
"}) product = c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'], name) updated_name = 'updated product name'",
"product name' c.update_product(uuid1, { 'name': updated_name, }) updated_product = c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name) variant_uuid",
"= self.client uuid1 = str(uuid.uuid1()) name = 'product1' with self.assertRaises(RequestException) as e: c.get_product(uuid1)",
"logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase): def __init__(self, *args,",
"full of unwanted categories... def test_product(self): c = self.client uuid1 = str(uuid.uuid1()) name",
"c.create_product({'name': '1', 'uuid': uuid1}) c.create_product({'name': '2', 'uuid': uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount + 2) c.delete_product_list({'uuid':",
"**kwargs): \"\"\" Initialize iZettle client. Requires the following environment variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER,",
"self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase = c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1']",
"single_purchase['purchaseUUID']) purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase = c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This will take over",
"argument c.get_purchase() with self.assertRaises(RequestException) as e: # This order of course cannot be",
"c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) multiple_purchases = c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid",
"cannot be in the server, because we made up the uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code,",
"if(variant['uuid'] == variant_uuid): variant_is_no_longer_in_product = False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with self.assertRaises(RequestException) as re: c.get_product(uuid1)",
"= logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase): def __init__(self, *args, **kwargs): \"\"\"",
"c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'], name) updated_name = 'updated product name' c.update_product(uuid1, { 'name':",
"\"request error 404\") self.assertEqual(exception.request.status_code, 404) uuid2 = str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2) current_product_amount = len(c.get_all_products())",
"a looooooong time \"\"\" self.client.__session_valid_until = time.time() + 9000 time.sleep(8000) self.assertIsNotNone(self.client.get_all_products()) if __name__",
"super(TestIzettle, self).__init__(*args, **kwargs) self.client = Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], ) def test_instance(self):",
"name' c.update_product(uuid1, { 'name': updated_name, }) updated_product = c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name) variant_uuid =",
"c.delete_product(uuid1) with self.assertRaises(RequestException) as re: c.get_product(uuid1) exception = re.exception self.assertEqual(exception.msg, \"request error 404\")",
"c = self.client discount_uuid = str(uuid.uuid1()) discount_percentage = '10' c.create_discount({ 'uuid': discount_uuid, 'percentage':",
"str(uuid.uuid1()) category_name = 'category name' c.create_category({ 'uuid': category_uuid, 'name': category_name }) self.assertGreater(len(c.get_all_categroies()), 0)",
"variant_uuid) variant_is_no_longer_in_product = True for variant in c.get_product(uuid1)['variants']: if(variant['uuid'] == variant_uuid): variant_is_no_longer_in_product =",
"from iZettle.iZettle import Izettle, RequestException logger = logging.getLogger() logger.level = logging.DEBUG stream_handler =",
"c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product = True for variant in c.get_product(uuid1)['variants']: if(variant['uuid'] == variant_uuid): variant_is_no_longer_in_product",
"looooooong time \"\"\" self.client.__session_valid_until = time.time() + 9000 time.sleep(8000) self.assertIsNotNone(self.client.get_all_products()) if __name__ ==",
"= str(uuid.uuid1()) name = 'product1' with self.assertRaises(RequestException) as e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not",
"self.assertEqual(len(c.get_all_products()), current_product_amount + 2) c.delete_product_list({'uuid': [uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount) def test_purchases(self): c =",
"wil take a looooooong time \"\"\" self.client.__session_valid_until = time.time() + 9000 time.sleep(8000) self.assertIsNotNone(self.client.get_all_products())",
"with self.assertRaises(RequestException) as re: Izettle(client_id='invalid') exception = re.exception self.assertEqual(exception.developer_message, \"Invalid client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\")",
"self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'], discount_percentage) new_name = 'new name' c.update_discount(discount_uuid, {'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name)",
"c.update_discount(discount_uuid, {'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid) with self.assertRaises(RequestException) as re: c.get_discount(discount_uuid) exception =",
"True for variant in c.get_product(uuid1)['variants']: if(variant['uuid'] == variant_uuid): variant_is_no_longer_in_product = False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1)",
"test_purchases(self): c = self.client with self.assertRaises(TypeError): # Parameters need to be in data",
"If this fails, make sure that you have environment variables set for the",
"anticipate. This simply waits for the for the sessino to expire, so it",
"with self.assertRaises(TypeError): # Parameters need to be in data dict c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError):",
"def test_categories(self): c = self.client category_uuid = str(uuid.uuid1()) category_name = 'category name' c.create_category({",
"TestIzettle(unittest.TestCase): def __init__(self, *args, **kwargs): \"\"\" Initialize iZettle client. Requires the following environment",
"c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This will take over 2 hours.') def test_session(self): \"\"\" This",
"izettle API \"\"\" self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self): \"\"\" Test client creation with invalid parameters",
"def test_purchases(self): c = self.client with self.assertRaises(TypeError): # Parameters need to be in",
"c.delete_discount(discount_uuid) with self.assertRaises(RequestException) as re: c.get_discount(discount_uuid) exception = re.exception self.assertEqual(exception.request.status_code, 404) def test_categories(self):",
"c = self.client uuid1 = str(uuid.uuid1()) name = 'product1' with self.assertRaises(RequestException) as e:",
"category_name = 'category name' c.create_category({ 'uuid': category_uuid, 'name': category_name }) self.assertGreater(len(c.get_all_categroies()), 0) category",
"with self.assertRaises(RequestException) as re: c.get_discount(discount_uuid) exception = re.exception self.assertEqual(exception.request.status_code, 404) def test_categories(self): c",
"1' c.create_product_variant(uuid1, {'uuid': variant_uuid}) c.update_product_variant(uuid1, variant_uuid, {'name': variant_name}) product_with_updated_variant = c.get_product(uuid1) found_the_new_variant =",
"= c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid) # FUN FUN FUN. All categories have name converted",
"hours.') def test_session(self): \"\"\" This tests if the integration works if the session",
"c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'], discount_percentage) new_name = 'new name' c.update_discount(discount_uuid, {'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'],",
"time \"\"\" self.client.__session_valid_until = time.time() + 9000 time.sleep(8000) self.assertIsNotNone(self.client.get_all_products()) if __name__ == '__main__':",
"works if the session expires before we anticipate. This simply waits for the",
"Your account is now full of unwanted categories... def test_product(self): c = self.client",
"integration works if the session expires before we anticipate. This simply waits for",
"self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid) with self.assertRaises(RequestException) as re: c.get_discount(discount_uuid) exception = re.exception self.assertEqual(exception.request.status_code, 404)",
"product = c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'], name) updated_name = 'updated product name' c.update_product(uuid1,",
"as e: # This order of course cannot be in the server, because",
"# Parameters need to be in data dict c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError): # missing",
"self.assertNotEqual(uuid1, uuid2) current_product_amount = len(c.get_all_products()) c.create_product({'name': '1', 'uuid': uuid1}) c.create_product({'name': '2', 'uuid': uuid2})",
"c.create_category({ 'uuid': category_uuid, 'name': category_name }) self.assertGreater(len(c.get_all_categroies()), 0) category = c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid)",
"will take over 2 hours.') def test_session(self): \"\"\" This tests if the integration",
"uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount) def test_purchases(self): c = self.client with self.assertRaises(TypeError): # Parameters need",
"correctly. If this fails, make sure that you have environment variables set for",
"client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], ) def test_instance(self): \"\"\" Test that the client was initialized",
"= Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], ) def test_instance(self): \"\"\" Test that the",
"current_product_amount = len(c.get_all_products()) c.create_product({'name': '1', 'uuid': uuid1}) c.create_product({'name': '2', 'uuid': uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount",
"for variant in product_with_updated_variant['variants']: if(variant['uuid'] != variant_uuid): continue self.assertEqual(variant['name'], variant_name) found_the_new_variant = True",
"client. Requires the following environment variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD. \"\"\" super(TestIzettle, self).__init__(*args,",
"multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase = c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This will take over 2 hours.') def",
"Tough luck, categories do not have delete method. # Your account is now",
"for the TestIzettle.__init__ method \"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def test_auth(self): \"\"\"",
"name' c.update_discount(discount_uuid, {'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid) with self.assertRaises(RequestException) as re: c.get_discount(discount_uuid) exception",
"the uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) multiple_purchases = c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']),",
"have environment variables set for the TestIzettle.__init__ method \"\"\" self.assertIsNotNone(self.client) self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user)",
"case... self.assertEqual(category['name'], category_name.upper()) # Tough luck, categories do not have delete method. #",
"False for variant in product_with_updated_variant['variants']: if(variant['uuid'] != variant_uuid): continue self.assertEqual(variant['name'], variant_name) found_the_new_variant =",
"= True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product = True for variant in c.get_product(uuid1)['variants']: if(variant['uuid']",
"categories... def test_product(self): c = self.client uuid1 = str(uuid.uuid1()) name = 'product1' with",
"This simply waits for the for the sessino to expire, so it wil",
"import Izettle, RequestException logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler)",
"client_id\") self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code, 400) def test_discounts(self): c = self.client discount_uuid = str(uuid.uuid1())",
"}) self.assertGreater(len(c.get_all_discounts()), 0) discount = c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'], discount_percentage) new_name = 'new",
"initialized correctly. If this fails, make sure that you have environment variables set",
"c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase = c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This will",
"API \"\"\" self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self): \"\"\" Test client creation with invalid parameters \"\"\"",
"IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD. \"\"\" super(TestIzettle, self).__init__(*args, **kwargs) self.client = Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'],",
"import sys import unittest import logging import uuid import time from iZettle.iZettle import",
"variant_name) found_the_new_variant = True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product = True for variant in",
"time from iZettle.iZettle import Izettle, RequestException logger = logging.getLogger() logger.level = logging.DEBUG stream_handler",
"password=<PASSWORD>['<PASSWORD>'], ) def test_instance(self): \"\"\" Test that the client was initialized correctly. If",
"do not have delete method. # Your account is now full of unwanted",
"= multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase = c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase = c.get_purchase(purchase_uuid1)",
"self.assertRaises(RequestException) as e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) c.create_product({ 'name': name, 'uuid':",
"uuid2) current_product_amount = len(c.get_all_products()) c.create_product({'name': '1', 'uuid': uuid1}) c.create_product({'name': '2', 'uuid': uuid2}) self.assertEqual(len(c.get_all_products()),",
"def test_auth(self): \"\"\" Test that we got token from izettle API \"\"\" self.assertIsNotNone(self.client._Izettle__token)",
"{'uuid': variant_uuid}) c.update_product_variant(uuid1, variant_uuid, {'name': variant_name}) product_with_updated_variant = c.get_product(uuid1) found_the_new_variant = False for",
"FUN. All categories have name converted to upper case... self.assertEqual(category['name'], category_name.upper()) # Tough",
"'percentage': discount_percentage, }) self.assertGreater(len(c.get_all_discounts()), 0) discount = c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'], discount_percentage) new_name",
"= False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with self.assertRaises(RequestException) as re: c.get_product(uuid1) exception = re.exception self.assertEqual(exception.msg,",
"self.assertGreater(len(c.get_all_categroies()), 0) category = c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid) # FUN FUN FUN. All categories",
"404\") self.assertEqual(exception.request.status_code, 404) uuid2 = str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2) current_product_amount = len(c.get_all_products()) c.create_product({'name': '1',",
"== variant_uuid): variant_is_no_longer_in_product = False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with self.assertRaises(RequestException) as re: c.get_product(uuid1) exception",
"we made up the uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) multiple_purchases =",
"}) updated_product = c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name) variant_uuid = str(uuid.uuid1()) variant_name = 'variant name",
"found', e.exception.developer_message) multiple_purchases = c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase =",
"self.assertRaises(TypeError): # missing mandatory argument c.get_purchase() with self.assertRaises(RequestException) as e: # This order",
"2 hours.') def test_session(self): \"\"\" This tests if the integration works if the",
"as re: c.get_product(uuid1) exception = re.exception self.assertEqual(exception.msg, \"request error 404\") self.assertEqual(exception.request.status_code, 404) uuid2",
"= multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase = c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This will take over 2 hours.')",
"c.get_product(uuid1)['variants']: if(variant['uuid'] == variant_uuid): variant_is_no_longer_in_product = False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with self.assertRaises(RequestException) as re:",
"uuid1, }) product = c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'], name) updated_name = 'updated product",
"server, because we made up the uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message)",
"Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], ) def test_instance(self): \"\"\" Test that the client",
"updated_name) variant_uuid = str(uuid.uuid1()) variant_name = 'variant name 1' c.create_product_variant(uuid1, {'uuid': variant_uuid}) c.update_product_variant(uuid1,",
"found_the_new_variant = True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product = True for variant in c.get_product(uuid1)['variants']:",
"'category name' c.create_category({ 'uuid': category_uuid, 'name': category_name }) self.assertGreater(len(c.get_all_categroies()), 0) category = c.get_category(category_uuid)",
"category = c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid) # FUN FUN FUN. All categories have name",
"c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) c.create_product({ 'name': name, 'uuid': uuid1, }) product",
"import logging import uuid import time from iZettle.iZettle import Izettle, RequestException logger =",
"categories do not have delete method. # Your account is now full of",
"Test that we got token from izettle API \"\"\" self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self): \"\"\"",
"unittest import logging import uuid import time from iZettle.iZettle import Izettle, RequestException logger",
"\"\"\" Test that the client was initialized correctly. If this fails, make sure",
"current_product_amount + 2) c.delete_product_list({'uuid': [uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount) def test_purchases(self): c = self.client",
"self.client discount_uuid = str(uuid.uuid1()) discount_percentage = '10' c.create_discount({ 'uuid': discount_uuid, 'percentage': discount_percentage, })",
"error 404\") self.assertEqual(exception.request.status_code, 404) uuid2 = str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2) current_product_amount = len(c.get_all_products()) c.create_product({'name':",
"variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD. \"\"\" super(TestIzettle, self).__init__(*args, **kwargs) self.client = Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'],",
"up the uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) multiple_purchases = c.get_multiple_purchases({'limit': 1})",
"new_name = 'new name' c.update_discount(discount_uuid, {'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid) with self.assertRaises(RequestException) as",
"uuid import time from iZettle.iZettle import Izettle, RequestException logger = logging.getLogger() logger.level =",
"re: c.get_product(uuid1) exception = re.exception self.assertEqual(exception.msg, \"request error 404\") self.assertEqual(exception.request.status_code, 404) uuid2 =",
"'product1' with self.assertRaises(RequestException) as e: c.get_product(uuid1) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) c.create_product({ 'name':",
"updated_name = 'updated product name' c.update_product(uuid1, { 'name': updated_name, }) updated_product = c.get_product(uuid1)",
"self.assertRaises(RequestException) as re: c.get_discount(discount_uuid) exception = re.exception self.assertEqual(exception.request.status_code, 404) def test_categories(self): c =",
"logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class TestIzettle(unittest.TestCase): def",
"re: c.get_discount(discount_uuid) exception = re.exception self.assertEqual(exception.request.status_code, 404) def test_categories(self): c = self.client category_uuid",
"self.assertEqual(exception.request.json()['error'], \"invalid_client\") self.assertEqual(exception.request.status_code, 400) def test_discounts(self): c = self.client discount_uuid = str(uuid.uuid1()) discount_percentage",
"expire, so it wil take a looooooong time \"\"\" self.client.__session_valid_until = time.time() +",
"'new name' c.update_discount(discount_uuid, {'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid) with self.assertRaises(RequestException) as re: c.get_discount(discount_uuid)",
"Izettle, RequestException logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class",
"FUN FUN FUN. All categories have name converted to upper case... self.assertEqual(category['name'], category_name.upper())",
"def test_product(self): c = self.client uuid1 = str(uuid.uuid1()) name = 'product1' with self.assertRaises(RequestException)",
"self.assertEqual(len(c.get_all_products()), current_product_amount) def test_purchases(self): c = self.client with self.assertRaises(TypeError): # Parameters need to",
"test_discounts(self): c = self.client discount_uuid = str(uuid.uuid1()) discount_percentage = '10' c.create_discount({ 'uuid': discount_uuid,",
"in product_with_updated_variant['variants']: if(variant['uuid'] != variant_uuid): continue self.assertEqual(variant['name'], variant_name) found_the_new_variant = True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1,",
"class TestIzettle(unittest.TestCase): def __init__(self, *args, **kwargs): \"\"\" Initialize iZettle client. Requires the following",
"'uuid': uuid1, }) product = c.get_product(uuid1) self.assertEqual(product['uuid'], uuid1) self.assertEqual(product['name'], name) updated_name = 'updated",
"purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase = c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) @unittest.skip('This will take over 2",
"self.assertEqual(variant['name'], variant_name) found_the_new_variant = True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product = True for variant",
"1}) self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase = c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1 =",
"sure that you have environment variables set for the TestIzettle.__init__ method \"\"\" self.assertIsNotNone(self.client)",
"we anticipate. This simply waits for the for the sessino to expire, so",
"0) discount = c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'], discount_percentage) new_name = 'new name' c.update_discount(discount_uuid,",
"variant_uuid): continue self.assertEqual(variant['name'], variant_name) found_the_new_variant = True self.assertTrue(found_the_new_variant) c.delete_product_variant(uuid1, variant_uuid) variant_is_no_longer_in_product = True",
"'uuid': discount_uuid, 'percentage': discount_percentage, }) self.assertGreater(len(c.get_all_discounts()), 0) discount = c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'],",
"need to be in data dict c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError): # missing mandatory argument",
"def test_instance(self): \"\"\" Test that the client was initialized correctly. If this fails,",
"IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD. \"\"\" super(TestIzettle, self).__init__(*args, **kwargs) self.client = Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'],",
"single_purchase = c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase = c.get_purchase(purchase_uuid1) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID'])",
"self.client = Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'], ) def test_instance(self): \"\"\" Test that",
"self.assertRaises(RequestException) as e: # This order of course cannot be in the server,",
"client creation with invalid parameters \"\"\" with self.assertRaises(RequestException) as re: Izettle(client_id='invalid') exception =",
"'2', 'uuid': uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount + 2) c.delete_product_list({'uuid': [uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount) def",
"test_session(self): \"\"\" This tests if the integration works if the session expires before",
"client was initialized correctly. If this fails, make sure that you have environment",
"variant in c.get_product(uuid1)['variants']: if(variant['uuid'] == variant_uuid): variant_is_no_longer_in_product = False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with self.assertRaises(RequestException)",
"# This order of course cannot be in the server, because we made",
"Test client creation with invalid parameters \"\"\" with self.assertRaises(RequestException) as re: Izettle(client_id='invalid') exception",
"method. # Your account is now full of unwanted categories... def test_product(self): c",
"= len(c.get_all_products()) c.create_product({'name': '1', 'uuid': uuid1}) c.create_product({'name': '2', 'uuid': uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount +",
"400) def test_discounts(self): c = self.client discount_uuid = str(uuid.uuid1()) discount_percentage = '10' c.create_discount({",
"mandatory argument c.get_purchase() with self.assertRaises(RequestException) as e: # This order of course cannot",
"self.assertEqual(exception.request.status_code, 404) def test_categories(self): c = self.client category_uuid = str(uuid.uuid1()) category_name = 'category",
"[uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount) def test_purchases(self): c = self.client with self.assertRaises(TypeError): # Parameters",
"'uuid': category_uuid, 'name': category_name }) self.assertGreater(len(c.get_all_categroies()), 0) category = c.get_category(category_uuid) self.assertEqual(category['uuid'], category_uuid) #",
"if the integration works if the session expires before we anticipate. This simply",
"variant_name}) product_with_updated_variant = c.get_product(uuid1) found_the_new_variant = False for variant in product_with_updated_variant['variants']: if(variant['uuid'] !=",
"@unittest.skip('This will take over 2 hours.') def test_session(self): \"\"\" This tests if the",
"= str(uuid.uuid1()) discount_percentage = '10' c.create_discount({ 'uuid': discount_uuid, 'percentage': discount_percentage, }) self.assertGreater(len(c.get_all_discounts()), 0)",
"= c.get_product(uuid1) found_the_new_variant = False for variant in product_with_updated_variant['variants']: if(variant['uuid'] != variant_uuid): continue",
"self.assertIn('not found', e.exception.developer_message) multiple_purchases = c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase",
"= str(uuid.uuid1()) self.assertNotEqual(uuid1, uuid2) current_product_amount = len(c.get_all_products()) c.create_product({'name': '1', 'uuid': uuid1}) c.create_product({'name': '2',",
"c.update_product(uuid1, { 'name': updated_name, }) updated_product = c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name) variant_uuid = str(uuid.uuid1())",
"self.assertIsNotNone(self.client._Izettle__client_id) self.assertIsNotNone(self.client._Izettle__client_secret) self.assertIsNotNone(self.client._Izettle__user) self.assertIsNotNone(self.client._Izettle__password) def test_auth(self): \"\"\" Test that we got token from",
"is now full of unwanted categories... def test_product(self): c = self.client uuid1 =",
"1) purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase = c.get_purchase(purchase_uuid) self.assertEqual(purchase_uuid, single_purchase['purchaseUUID']) purchase_uuid1 = multiple_purchases['purchases'][0]['purchaseUUID1'] single_purchase",
"with self.assertRaises(RequestException) as re: c.get_product(uuid1) exception = re.exception self.assertEqual(exception.msg, \"request error 404\") self.assertEqual(exception.request.status_code,",
"All categories have name converted to upper case... self.assertEqual(category['name'], category_name.upper()) # Tough luck,",
"__init__(self, *args, **kwargs): \"\"\" Initialize iZettle client. Requires the following environment variables IZETTLE_CLIENT_ID,",
"e.exception.developer_message) multiple_purchases = c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid = multiple_purchases['purchases'][0]['purchaseUUID'] single_purchase = c.get_purchase(purchase_uuid)",
"c.create_discount({ 'uuid': discount_uuid, 'percentage': discount_percentage, }) self.assertGreater(len(c.get_all_discounts()), 0) discount = c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid)",
"take over 2 hours.') def test_session(self): \"\"\" This tests if the integration works",
"import uuid import time from iZettle.iZettle import Izettle, RequestException logger = logging.getLogger() logger.level",
"self.assertEqual(discount['percentage'], discount_percentage) new_name = 'new name' c.update_discount(discount_uuid, {'name': new_name}) self.assertEqual(c.get_discount(discount_uuid)['name'], new_name) c.delete_discount(discount_uuid) with",
"self.assertRaises(TypeError): # Parameters need to be in data dict c.get_multiple_purchases(limit=1) with self.assertRaises(TypeError): #",
"# Tough luck, categories do not have delete method. # Your account is",
"self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) multiple_purchases = c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']), 1) purchase_uuid =",
"\"\"\" Initialize iZettle client. Requires the following environment variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD.",
"this fails, make sure that you have environment variables set for the TestIzettle.__init__",
"uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) multiple_purchases = c.get_multiple_purchases({'limit': 1}) self.assertEqual(len(multiple_purchases['purchases']), 1)",
"made up the uuid c.get_purchase(str(uuid.uuid1())) self.assertEqual(e.exception.request.status_code, 404) self.assertIn('not found', e.exception.developer_message) multiple_purchases = c.get_multiple_purchases({'limit':",
"\"\"\" This tests if the integration works if the session expires before we",
"discount = c.get_discount(discount_uuid) self.assertEqual(discount['uuid'], discount_uuid) self.assertEqual(discount['percentage'], discount_percentage) new_name = 'new name' c.update_discount(discount_uuid, {'name':",
"= True for variant in c.get_product(uuid1)['variants']: if(variant['uuid'] == variant_uuid): variant_is_no_longer_in_product = False self.assertTrue(variant_is_no_longer_in_product)",
"for variant in c.get_product(uuid1)['variants']: if(variant['uuid'] == variant_uuid): variant_is_no_longer_in_product = False self.assertTrue(variant_is_no_longer_in_product) c.delete_product(uuid1) with",
"+ 2) c.delete_product_list({'uuid': [uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()), current_product_amount) def test_purchases(self): c = self.client with",
"IZETTLE_USER, IZETTLE_PASSWORD. \"\"\" super(TestIzettle, self).__init__(*args, **kwargs) self.client = Izettle( client_id=os.environ['IZETTLE_CLIENT_ID'], client_secret=os.environ['IZETTLE_CLIENT_SECRET'], user=os.environ['IZETTLE_USER'], password=<PASSWORD>['<PASSWORD>'],",
"we got token from izettle API \"\"\" self.assertIsNotNone(self.client._Izettle__token) def test_invalid_client_id(self): \"\"\" Test client",
"updated_product = c.get_product(uuid1) self.assertEqual(updated_product['name'], updated_name) variant_uuid = str(uuid.uuid1()) variant_name = 'variant name 1'",
"str(uuid.uuid1()) variant_name = 'variant name 1' c.create_product_variant(uuid1, {'uuid': variant_uuid}) c.update_product_variant(uuid1, variant_uuid, {'name': variant_name})",
"if the session expires before we anticipate. This simply waits for the for",
"This order of course cannot be in the server, because we made up",
"variant_is_no_longer_in_product = True for variant in c.get_product(uuid1)['variants']: if(variant['uuid'] == variant_uuid): variant_is_no_longer_in_product = False",
"uuid1}) c.create_product({'name': '2', 'uuid': uuid2}) self.assertEqual(len(c.get_all_products()), current_product_amount + 2) c.delete_product_list({'uuid': [uuid1, uuid2]}) self.assertEqual(len(c.get_all_products()),",
"re.exception self.assertEqual(exception.request.status_code, 404) def test_categories(self): c = self.client category_uuid = str(uuid.uuid1()) category_name =",
"FUN FUN. All categories have name converted to upper case... self.assertEqual(category['name'], category_name.upper()) #",
"test_instance(self): \"\"\" Test that the client was initialized correctly. If this fails, make",
"iZettle client. Requires the following environment variables IZETTLE_CLIENT_ID, IZETTLE_CLIENT_SECRET, IZETTLE_USER, IZETTLE_PASSWORD. \"\"\" super(TestIzettle,"
] |
[
"last or last < first < middle: pivot_index = 0 elif first <",
"return [array[1], array[0]], compare_count + 1 else: array, pivot_index = partition(array, pivot_location) if",
"== 1: return array, compare_count if len(array) == 2: if array[0] < array[1]:",
"<= len(array) - 3: array[pivot_index+1:], compare_count = quick_sort( array[pivot_index+1:], pivot_location, compare_count ) compare_count",
"pivot_location): pivot_index = get_pivot_index(array, pivot_location) # put the pivot index in the beginning",
"if pivot_location == 'first': pivot_index = 0 elif pivot_location == 'last': pivot_index =",
"== 'last': pivot_index = len(array) - 1 else: first = array[0] middle =",
"middle: pivot_index = 0 elif first < middle < last or last <",
"pivot_index = 0 elif first < middle < last or last < middle",
"middle < last or last < middle < first: pivot_index = (len(array) -",
"\"__main__\": f = open(\"QuickSort.txt\") array = [int(line) for line in f] sorted_array, compare_count",
"in f] sorted_array, compare_count = quick_sort(array, 'first') print(compare_count) f = open(\"QuickSort.txt\") array =",
"compare_count = quick_sort( array[pivot_index+1:], pivot_location, compare_count ) compare_count += len(array) - 1 return",
"beginning of the array if pivot_index != 0: array[0], array[pivot_index] = array[pivot_index], array[0]",
"= 1 # index of first element > array[0] for j in range(1,",
"'first': pivot_index = 0 elif pivot_location == 'last': pivot_index = len(array) - 1",
"- 1) // 2 else: pivot_index = len(array) - 1 return pivot_index if",
"array[1]: return [array[0], array[1]], compare_count + 1 else: return [array[1], array[0]], compare_count +",
"the beginning of the array if pivot_index != 0: array[0], array[pivot_index] = array[pivot_index],",
"pivot_index = 0 elif pivot_location == 'last': pivot_index = len(array) - 1 else:",
"array[0] # return the index of pivot return array, i - 1 def",
"quick_sort(array, 'last') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for line in f]",
"compare_count += len(array) - 1 return array, compare_count def partition(array, pivot_location): pivot_index =",
"= 0 elif first < middle < last or last < middle <",
"if array[0] < array[1]: return [array[0], array[1]], compare_count + 1 else: return [array[1],",
"= quick_sort( array[:pivot_index], pivot_location, compare_count ) if pivot_index <= len(array) - 3: array[pivot_index+1:],",
"array[0], array[pivot_index] = array[pivot_index], array[0] i = 1 # index of first element",
"compare_count = quick_sort( array[:pivot_index], pivot_location, compare_count ) if pivot_index <= len(array) - 3:",
"array = [int(line) for line in f] sorted_array, compare_count = quick_sort(array, 'first') print(compare_count)",
"2 else: pivot_index = len(array) - 1 return pivot_index if __name__ == \"__main__\":",
"<gh_stars>0 def quick_sort(array, pivot_location, compare_count=0): if len(array) == 1: return array, compare_count if",
") compare_count += len(array) - 1 return array, compare_count def partition(array, pivot_location): pivot_index",
"return pivot_index if __name__ == \"__main__\": f = open(\"QuickSort.txt\") array = [int(line) for",
"[array[0], array[1]], compare_count + 1 else: return [array[1], array[0]], compare_count + 1 else:",
"compare_count ) if pivot_index <= len(array) - 3: array[pivot_index+1:], compare_count = quick_sort( array[pivot_index+1:],",
"if pivot_index >= 2: array[:pivot_index], compare_count = quick_sort( array[:pivot_index], pivot_location, compare_count ) if",
"compare_count if len(array) == 2: if array[0] < array[1]: return [array[0], array[1]], compare_count",
"for line in f] sorted_array, compare_count = quick_sort(array, 'first') print(compare_count) f = open(\"QuickSort.txt\")",
"1 else: first = array[0] middle = array[(len(array) - 1) // 2] last",
"array[i-1], array[0] # return the index of pivot return array, i - 1",
"pivot_index = partition(array, pivot_location) if pivot_index >= 2: array[:pivot_index], compare_count = quick_sort( array[:pivot_index],",
"0 elif first < middle < last or last < middle < first:",
"pivot_location, compare_count ) if pivot_index <= len(array) - 3: array[pivot_index+1:], compare_count = quick_sort(",
"quick_sort( array[:pivot_index], pivot_location, compare_count ) if pivot_index <= len(array) - 3: array[pivot_index+1:], compare_count",
"__name__ == \"__main__\": f = open(\"QuickSort.txt\") array = [int(line) for line in f]",
"= open(\"QuickSort.txt\") array = [int(line) for line in f] sorted_array, compare_count = quick_sort(array,",
"compare_count=0): if len(array) == 1: return array, compare_count if len(array) == 2: if",
"i - 1 def get_pivot_index(array, pivot_location): if pivot_location == 'first': pivot_index = 0",
"= array[-1] if middle < first < last or last < first <",
"pivot_location, compare_count=0): if len(array) == 1: return array, compare_count if len(array) == 2:",
"middle < first < last or last < first < middle: pivot_index =",
"[array[1], array[0]], compare_count + 1 else: array, pivot_index = partition(array, pivot_location) if pivot_index",
"sorted_array, compare_count = quick_sort(array, 'first') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for",
"put the pivot index in the beginning of the array if pivot_index !=",
"- 1 else: first = array[0] middle = array[(len(array) - 1) // 2]",
"if middle < first < last or last < first < middle: pivot_index",
"pivot index in the beginning of the array if pivot_index != 0: array[0],",
"last or last < middle < first: pivot_index = (len(array) - 1) //",
"pivot_index = get_pivot_index(array, pivot_location) # put the pivot index in the beginning of",
"i = 1 # index of first element > array[0] for j in",
"< first < last or last < first < middle: pivot_index = 0",
"= array[(len(array) - 1) // 2] last = array[-1] if middle < first",
"= [int(line) for line in f] sorted_array, compare_count = quick_sort(array, 'last') print(compare_count) f",
"def quick_sort(array, pivot_location, compare_count=0): if len(array) == 1: return array, compare_count if len(array)",
"quick_sort(array, pivot_location, compare_count=0): if len(array) == 1: return array, compare_count if len(array) ==",
"2: array[:pivot_index], compare_count = quick_sort( array[:pivot_index], pivot_location, compare_count ) if pivot_index <= len(array)",
"= get_pivot_index(array, pivot_location) # put the pivot index in the beginning of the",
"index of first element > array[0] for j in range(1, len(array)): if array[j]",
"return the index of pivot return array, i - 1 def get_pivot_index(array, pivot_location):",
"0 elif pivot_location == 'last': pivot_index = len(array) - 1 else: first =",
"- 1 return pivot_index if __name__ == \"__main__\": f = open(\"QuickSort.txt\") array =",
"pivot_index = len(array) - 1 else: first = array[0] middle = array[(len(array) -",
"[int(line) for line in f] sorted_array, compare_count = quick_sort(array, 'last') print(compare_count) f =",
"compare_count def partition(array, pivot_location): pivot_index = get_pivot_index(array, pivot_location) # put the pivot index",
"if len(array) == 2: if array[0] < array[1]: return [array[0], array[1]], compare_count +",
"pivot_location): if pivot_location == 'first': pivot_index = 0 elif pivot_location == 'last': pivot_index",
"array[j] = array[j], array[i] i += 1 array[0], array[i-1] = array[i-1], array[0] #",
"if __name__ == \"__main__\": f = open(\"QuickSort.txt\") array = [int(line) for line in",
"array[:pivot_index], compare_count = quick_sort( array[:pivot_index], pivot_location, compare_count ) if pivot_index <= len(array) -",
"# index of first element > array[0] for j in range(1, len(array)): if",
"array, compare_count if len(array) == 2: if array[0] < array[1]: return [array[0], array[1]],",
"1 array[0], array[i-1] = array[i-1], array[0] # return the index of pivot return",
"first = array[0] middle = array[(len(array) - 1) // 2] last = array[-1]",
"j in range(1, len(array)): if array[j] < array[0]: array[i], array[j] = array[j], array[i]",
"> array[0] for j in range(1, len(array)): if array[j] < array[0]: array[i], array[j]",
"line in f] sorted_array, compare_count = quick_sort(array, 'last') print(compare_count) f = open(\"QuickSort.txt\") array",
"or last < first < middle: pivot_index = 0 elif first < middle",
"middle = array[(len(array) - 1) // 2] last = array[-1] if middle <",
"for j in range(1, len(array)): if array[j] < array[0]: array[i], array[j] = array[j],",
"'last': pivot_index = len(array) - 1 else: first = array[0] middle = array[(len(array)",
"array[0] middle = array[(len(array) - 1) // 2] last = array[-1] if middle",
"first < last or last < first < middle: pivot_index = 0 elif",
"compare_count = quick_sort(array, 'first') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for line",
"< first: pivot_index = (len(array) - 1) // 2 else: pivot_index = len(array)",
"// 2 else: pivot_index = len(array) - 1 return pivot_index if __name__ ==",
"the array if pivot_index != 0: array[0], array[pivot_index] = array[pivot_index], array[0] i =",
"(len(array) - 1) // 2 else: pivot_index = len(array) - 1 return pivot_index",
"the index of pivot return array, i - 1 def get_pivot_index(array, pivot_location): if",
"first: pivot_index = (len(array) - 1) // 2 else: pivot_index = len(array) -",
"pivot_location == 'first': pivot_index = 0 elif pivot_location == 'last': pivot_index = len(array)",
"last = array[-1] if middle < first < last or last < first",
"range(1, len(array)): if array[j] < array[0]: array[i], array[j] = array[j], array[i] i +=",
"- 1 def get_pivot_index(array, pivot_location): if pivot_location == 'first': pivot_index = 0 elif",
"array[1]], compare_count + 1 else: return [array[1], array[0]], compare_count + 1 else: array,",
"array, pivot_index = partition(array, pivot_location) if pivot_index >= 2: array[:pivot_index], compare_count = quick_sort(",
"else: pivot_index = len(array) - 1 return pivot_index if __name__ == \"__main__\": f",
"pivot_index >= 2: array[:pivot_index], compare_count = quick_sort( array[:pivot_index], pivot_location, compare_count ) if pivot_index",
"= len(array) - 1 return pivot_index if __name__ == \"__main__\": f = open(\"QuickSort.txt\")",
"pivot_location) # put the pivot index in the beginning of the array if",
"= partition(array, pivot_location) if pivot_index >= 2: array[:pivot_index], compare_count = quick_sort( array[:pivot_index], pivot_location,",
"compare_count + 1 else: array, pivot_index = partition(array, pivot_location) if pivot_index >= 2:",
"1) // 2] last = array[-1] if middle < first < last or",
"< last or last < middle < first: pivot_index = (len(array) - 1)",
"1: return array, compare_count if len(array) == 2: if array[0] < array[1]: return",
"return [array[0], array[1]], compare_count + 1 else: return [array[1], array[0]], compare_count + 1",
"the pivot index in the beginning of the array if pivot_index != 0:",
"array[(len(array) - 1) // 2] last = array[-1] if middle < first <",
"< last or last < first < middle: pivot_index = 0 elif first",
"pivot_index != 0: array[0], array[pivot_index] = array[pivot_index], array[0] i = 1 # index",
"last < first < middle: pivot_index = 0 elif first < middle <",
"= array[i-1], array[0] # return the index of pivot return array, i -",
"== \"__main__\": f = open(\"QuickSort.txt\") array = [int(line) for line in f] sorted_array,",
"line in f] sorted_array, compare_count = quick_sort(array, 'first') print(compare_count) f = open(\"QuickSort.txt\") array",
"array = [int(line) for line in f] sorted_array, compare_count = quick_sort(array, 'last') print(compare_count)",
"array if pivot_index != 0: array[0], array[pivot_index] = array[pivot_index], array[0] i = 1",
"array[i-1] = array[i-1], array[0] # return the index of pivot return array, i",
"partition(array, pivot_location) if pivot_index >= 2: array[:pivot_index], compare_count = quick_sort( array[:pivot_index], pivot_location, compare_count",
"i += 1 array[0], array[i-1] = array[i-1], array[0] # return the index of",
"# put the pivot index in the beginning of the array if pivot_index",
"pivot_index = (len(array) - 1) // 2 else: pivot_index = len(array) - 1",
"of first element > array[0] for j in range(1, len(array)): if array[j] <",
"get_pivot_index(array, pivot_location) # put the pivot index in the beginning of the array",
"def partition(array, pivot_location): pivot_index = get_pivot_index(array, pivot_location) # put the pivot index in",
"'first') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for line in f] sorted_array,",
"array[0] for j in range(1, len(array)): if array[j] < array[0]: array[i], array[j] =",
"len(array)): if array[j] < array[0]: array[i], array[j] = array[j], array[i] i += 1",
">= 2: array[:pivot_index], compare_count = quick_sort( array[:pivot_index], pivot_location, compare_count ) if pivot_index <=",
"< middle < first: pivot_index = (len(array) - 1) // 2 else: pivot_index",
"len(array) - 3: array[pivot_index+1:], compare_count = quick_sort( array[pivot_index+1:], pivot_location, compare_count ) compare_count +=",
"= array[pivot_index], array[0] i = 1 # index of first element > array[0]",
"partition(array, pivot_location): pivot_index = get_pivot_index(array, pivot_location) # put the pivot index in the",
"in f] sorted_array, compare_count = quick_sort(array, 'last') print(compare_count) f = open(\"QuickSort.txt\") array =",
"< middle < last or last < middle < first: pivot_index = (len(array)",
"< first < middle: pivot_index = 0 elif first < middle < last",
"else: return [array[1], array[0]], compare_count + 1 else: array, pivot_index = partition(array, pivot_location)",
"= quick_sort( array[pivot_index+1:], pivot_location, compare_count ) compare_count += len(array) - 1 return array,",
"compare_count + 1 else: return [array[1], array[0]], compare_count + 1 else: array, pivot_index",
"array[i], array[j] = array[j], array[i] i += 1 array[0], array[i-1] = array[i-1], array[0]",
"array[pivot_index+1:], pivot_location, compare_count ) compare_count += len(array) - 1 return array, compare_count def",
"for line in f] sorted_array, compare_count = quick_sort(array, 'last') print(compare_count) f = open(\"QuickSort.txt\")",
"array[0] i = 1 # index of first element > array[0] for j",
"array[pivot_index] = array[pivot_index], array[0] i = 1 # index of first element >",
"- 1) // 2] last = array[-1] if middle < first < last",
"last < middle < first: pivot_index = (len(array) - 1) // 2 else:",
"len(array) - 1 else: first = array[0] middle = array[(len(array) - 1) //",
"array[j] < array[0]: array[i], array[j] = array[j], array[i] i += 1 array[0], array[i-1]",
"1 def get_pivot_index(array, pivot_location): if pivot_location == 'first': pivot_index = 0 elif pivot_location",
"else: array, pivot_index = partition(array, pivot_location) if pivot_index >= 2: array[:pivot_index], compare_count =",
"quick_sort(array, 'first') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for line in f]",
"< array[0]: array[i], array[j] = array[j], array[i] i += 1 array[0], array[i-1] =",
"if len(array) == 1: return array, compare_count if len(array) == 2: if array[0]",
"+ 1 else: array, pivot_index = partition(array, pivot_location) if pivot_index >= 2: array[:pivot_index],",
"if pivot_index != 0: array[0], array[pivot_index] = array[pivot_index], array[0] i = 1 #",
"= array[j], array[i] i += 1 array[0], array[i-1] = array[i-1], array[0] # return",
"f] sorted_array, compare_count = quick_sort(array, 'first') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line)",
"array, compare_count def partition(array, pivot_location): pivot_index = get_pivot_index(array, pivot_location) # put the pivot",
"= quick_sort(array, 'last') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for line in",
"else: first = array[0] middle = array[(len(array) - 1) // 2] last =",
"< array[1]: return [array[0], array[1]], compare_count + 1 else: return [array[1], array[0]], compare_count",
"+= len(array) - 1 return array, compare_count def partition(array, pivot_location): pivot_index = get_pivot_index(array,",
"2] last = array[-1] if middle < first < last or last <",
"elif first < middle < last or last < middle < first: pivot_index",
"array[0], array[i-1] = array[i-1], array[0] # return the index of pivot return array,",
"# return the index of pivot return array, i - 1 def get_pivot_index(array,",
"of pivot return array, i - 1 def get_pivot_index(array, pivot_location): if pivot_location ==",
"'last') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for line in f] sorted_array,",
"== 'first': pivot_index = 0 elif pivot_location == 'last': pivot_index = len(array) -",
"+= 1 array[0], array[i-1] = array[i-1], array[0] # return the index of pivot",
"[int(line) for line in f] sorted_array, compare_count = quick_sort(array, 'first') print(compare_count) f =",
"1 else: array, pivot_index = partition(array, pivot_location) if pivot_index >= 2: array[:pivot_index], compare_count",
"index of pivot return array, i - 1 def get_pivot_index(array, pivot_location): if pivot_location",
"open(\"QuickSort.txt\") array = [int(line) for line in f] sorted_array, compare_count = quick_sort(array, 'last')",
"1 return array, compare_count def partition(array, pivot_location): pivot_index = get_pivot_index(array, pivot_location) # put",
"!= 0: array[0], array[pivot_index] = array[pivot_index], array[0] i = 1 # index of",
"array[pivot_index+1:], compare_count = quick_sort( array[pivot_index+1:], pivot_location, compare_count ) compare_count += len(array) - 1",
"1 else: return [array[1], array[0]], compare_count + 1 else: array, pivot_index = partition(array,",
"< middle: pivot_index = 0 elif first < middle < last or last",
"open(\"QuickSort.txt\") array = [int(line) for line in f] sorted_array, compare_count = quick_sort(array, 'median')",
"len(array) - 1 return array, compare_count def partition(array, pivot_location): pivot_index = get_pivot_index(array, pivot_location)",
"= 0 elif pivot_location == 'last': pivot_index = len(array) - 1 else: first",
"first < middle < last or last < middle < first: pivot_index =",
"== 2: if array[0] < array[1]: return [array[0], array[1]], compare_count + 1 else:",
"- 1 return array, compare_count def partition(array, pivot_location): pivot_index = get_pivot_index(array, pivot_location) #",
"array[0]], compare_count + 1 else: array, pivot_index = partition(array, pivot_location) if pivot_index >=",
"first element > array[0] for j in range(1, len(array)): if array[j] < array[0]:",
"in the beginning of the array if pivot_index != 0: array[0], array[pivot_index] =",
"return array, compare_count if len(array) == 2: if array[0] < array[1]: return [array[0],",
"def get_pivot_index(array, pivot_location): if pivot_location == 'first': pivot_index = 0 elif pivot_location ==",
"elif pivot_location == 'last': pivot_index = len(array) - 1 else: first = array[0]",
"sorted_array, compare_count = quick_sort(array, 'last') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for",
"0: array[0], array[pivot_index] = array[pivot_index], array[0] i = 1 # index of first",
"array, i - 1 def get_pivot_index(array, pivot_location): if pivot_location == 'first': pivot_index =",
"pivot_location, compare_count ) compare_count += len(array) - 1 return array, compare_count def partition(array,",
"if pivot_index <= len(array) - 3: array[pivot_index+1:], compare_count = quick_sort( array[pivot_index+1:], pivot_location, compare_count",
"return array, compare_count def partition(array, pivot_location): pivot_index = get_pivot_index(array, pivot_location) # put the",
"first < middle: pivot_index = 0 elif first < middle < last or",
"1 # index of first element > array[0] for j in range(1, len(array)):",
"array[0] < array[1]: return [array[0], array[1]], compare_count + 1 else: return [array[1], array[0]],",
"array[j], array[i] i += 1 array[0], array[i-1] = array[i-1], array[0] # return the",
"or last < middle < first: pivot_index = (len(array) - 1) // 2",
"- 3: array[pivot_index+1:], compare_count = quick_sort( array[pivot_index+1:], pivot_location, compare_count ) compare_count += len(array)",
"pivot_location) if pivot_index >= 2: array[:pivot_index], compare_count = quick_sort( array[:pivot_index], pivot_location, compare_count )",
"len(array) - 1 return pivot_index if __name__ == \"__main__\": f = open(\"QuickSort.txt\") array",
"compare_count ) compare_count += len(array) - 1 return array, compare_count def partition(array, pivot_location):",
"= len(array) - 1 else: first = array[0] middle = array[(len(array) - 1)",
"1) // 2 else: pivot_index = len(array) - 1 return pivot_index if __name__",
"f = open(\"QuickSort.txt\") array = [int(line) for line in f] sorted_array, compare_count =",
"print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for line in f] sorted_array, compare_count",
"pivot_index <= len(array) - 3: array[pivot_index+1:], compare_count = quick_sort( array[pivot_index+1:], pivot_location, compare_count )",
"in range(1, len(array)): if array[j] < array[0]: array[i], array[j] = array[j], array[i] i",
"len(array) == 1: return array, compare_count if len(array) == 2: if array[0] <",
"pivot return array, i - 1 def get_pivot_index(array, pivot_location): if pivot_location == 'first':",
"array[0]: array[i], array[j] = array[j], array[i] i += 1 array[0], array[i-1] = array[i-1],",
"element > array[0] for j in range(1, len(array)): if array[j] < array[0]: array[i],",
"pivot_index = len(array) - 1 return pivot_index if __name__ == \"__main__\": f =",
"return array, i - 1 def get_pivot_index(array, pivot_location): if pivot_location == 'first': pivot_index",
"3: array[pivot_index+1:], compare_count = quick_sort( array[pivot_index+1:], pivot_location, compare_count ) compare_count += len(array) -",
"middle < first: pivot_index = (len(array) - 1) // 2 else: pivot_index =",
"= (len(array) - 1) // 2 else: pivot_index = len(array) - 1 return",
"compare_count = quick_sort(array, 'last') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for line",
"array[pivot_index], array[0] i = 1 # index of first element > array[0] for",
"2: if array[0] < array[1]: return [array[0], array[1]], compare_count + 1 else: return",
"= [int(line) for line in f] sorted_array, compare_count = quick_sort(array, 'first') print(compare_count) f",
"array[:pivot_index], pivot_location, compare_count ) if pivot_index <= len(array) - 3: array[pivot_index+1:], compare_count =",
"= quick_sort(array, 'first') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line) for line in",
"pivot_index if __name__ == \"__main__\": f = open(\"QuickSort.txt\") array = [int(line) for line",
"+ 1 else: return [array[1], array[0]], compare_count + 1 else: array, pivot_index =",
"array[i] i += 1 array[0], array[i-1] = array[i-1], array[0] # return the index",
"len(array) == 2: if array[0] < array[1]: return [array[0], array[1]], compare_count + 1",
"get_pivot_index(array, pivot_location): if pivot_location == 'first': pivot_index = 0 elif pivot_location == 'last':",
") if pivot_index <= len(array) - 3: array[pivot_index+1:], compare_count = quick_sort( array[pivot_index+1:], pivot_location,",
"open(\"QuickSort.txt\") array = [int(line) for line in f] sorted_array, compare_count = quick_sort(array, 'first')",
"if array[j] < array[0]: array[i], array[j] = array[j], array[i] i += 1 array[0],",
"1 return pivot_index if __name__ == \"__main__\": f = open(\"QuickSort.txt\") array = [int(line)",
"quick_sort( array[pivot_index+1:], pivot_location, compare_count ) compare_count += len(array) - 1 return array, compare_count",
"f] sorted_array, compare_count = quick_sort(array, 'last') print(compare_count) f = open(\"QuickSort.txt\") array = [int(line)",
"array = [int(line) for line in f] sorted_array, compare_count = quick_sort(array, 'median') print(compare_count)",
"of the array if pivot_index != 0: array[0], array[pivot_index] = array[pivot_index], array[0] i",
"array[-1] if middle < first < last or last < first < middle:",
"index in the beginning of the array if pivot_index != 0: array[0], array[pivot_index]",
"= array[0] middle = array[(len(array) - 1) // 2] last = array[-1] if",
"pivot_location == 'last': pivot_index = len(array) - 1 else: first = array[0] middle",
"// 2] last = array[-1] if middle < first < last or last"
] |
[
"datetime.datetime.now() second = str(time.second).strip(\" \") minute = str(time.minute).strip(\" \") hour = str(time.hour).strip(\" \")",
"open(\"data/commands.cfg\", \"r\") cr = c.read().split(\"\\n\") for line in cr: cmdline = line.split(\": \",",
"else: irc.send(chan, \"You don't have the permissions to perform this command!!\") elif data.startswith(\"!\"):",
"= text.replace(\":\", \"\") user = buffer.split(\"!\", 1)[0] buffer.replace(buffer, \"\") buffer = text data",
"f.reset() else: irc.send(chan, \"You don't have the Permissions to perform this command!!\") f.reset()",
"str(time.hour).strip(\" \") timestamp = \"[\" + hour.zfill(2) + \":\" + minute.zfill(2) + \":\"",
"info = cmdline[1] if data.strip(\" \") == cmd: irc.send(chan, info) print(BOTID + \":",
"= cmdline[1] if data.strip(\" \") == cmd: irc.send(chan, info) print(BOTID + \": \"",
"f.addcmd(irc, chan, data) f.reset() else: irc.send(chan, \"You don't have the Permissions to perform",
"+ user + \"!\" + user + \"@\" + user + \".\" +",
"def main(chan, Main, irc, VIP, f): print(\"finished Loading\") print(\"executing main section\") while Main:",
"section\") while Main: text = irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer = text.replace(\":\", \"\") user",
"sys.exit(0) f.reset() else: irc.send(chan, \"You don't have the permissions to perform this command!!\")",
"data.strip(\" \") == cmd: irc.send(chan, info) print(BOTID + \": \" + info) cmdline.clear()",
"\"]\" f.chatlog(user, data, timestamp) print(timestamp, user, \":\", data) if \"PING :tmi.twitch.tv\" == text:",
"f.reset() elif data.startswith(\"!cmdadd\"): if user in VIP: f.addcmd(irc, chan, data) f.reset() else: irc.send(chan,",
"user in VIP: f.addcmd(irc, chan, data) f.reset() else: irc.send(chan, \"You don't have the",
"data, timestamp) print(timestamp, user, \":\", data) if \"PING :tmi.twitch.tv\" == text: irc.pong() f.reset()",
"elif data == \"!quote\": q = open(\"data/quotes.ccfg\", \"r\") quotes = q.read().split(\"\\n\") quote =",
"line.split(\": \", 1) cmd = cmdline[0] info = cmdline[1] if data.strip(\" \") ==",
"= text data = buffer.replace(\":\" + user + \"!\" + user + \"@\"",
"have the Permissions to perform this command!!\") f.reset() elif data.startswith(\"!quoteadd\"): if user in",
"1)[0] buffer.replace(buffer, \"\") buffer = text data = buffer.replace(\":\" + user + \"!\"",
"== text: irc.pong() f.reset() elif data.startswith(\"!cmdadd\"): if user in VIP: f.addcmd(irc, chan, data)",
"\"!stop\": if user == CHANNEL: sys.exit(0) f.reset() else: irc.send(chan, \"You don't have the",
"print(timestamp, user, \":\", data) if \"PING :tmi.twitch.tv\" == text: irc.pong() f.reset() elif data.startswith(\"!cmdadd\"):",
"+ \": \" + info) cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\") f.reset() c.close() break",
"f): print(\"finished Loading\") print(\"executing main section\") while Main: text = irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\")",
"\"PRIVMSG \" + \"#\", \"\").split(\" :\", 1)[1] time = datetime.datetime.now() second = str(time.second).strip(\"",
"FUNCTIONS import * import datetime def main(chan, Main, irc, VIP, f): print(\"finished Loading\")",
"if \"PING :tmi.twitch.tv\" == text: irc.pong() f.reset() elif data.startswith(\"!cmdadd\"): if user in VIP:",
"buffer.replace(buffer, \"\") buffer = text data = buffer.replace(\":\" + user + \"!\" +",
"\"[\" + hour.zfill(2) + \":\" + minute.zfill(2) + \":\" + second.zfill(2) + \"]\"",
"+ \"]\" f.chatlog(user, data, timestamp) print(timestamp, user, \":\", data) if \"PING :tmi.twitch.tv\" ==",
"hour.zfill(2) + \":\" + minute.zfill(2) + \":\" + second.zfill(2) + \"]\" f.chatlog(user, data,",
"= open(\"data/commands.cfg\", \"r\") cr = c.read().split(\"\\n\") for line in cr: cmdline = line.split(\":",
"\"tmi.twitch.tv \" + \"PRIVMSG \" + \"#\", \"\").split(\" :\", 1)[1] time = datetime.datetime.now()",
"print(BOTID + \": \" + info) cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\") f.reset() c.close()",
"+ user + \".\" + \"tmi.twitch.tv \" + \"PRIVMSG \" + \"#\", \"\").split(\"",
"+ second.zfill(2) + \"]\" f.chatlog(user, data, timestamp) print(timestamp, user, \":\", data) if \"PING",
"irc, VIP, f): print(\"finished Loading\") print(\"executing main section\") while Main: text = irc.get_text().strip(bytes(\"\\r\\n\",",
"else: irc.send(chan, \"You don't have the Permissions to perform this command!!\") irc.reset() elif",
"\" + quote) f.reset() q.close() elif data == \"!stop\": if user == CHANNEL:",
"user + \".\" + \"tmi.twitch.tv \" + \"PRIVMSG \" + \"#\", \"\").split(\" :\",",
"= datetime.datetime.now() second = str(time.second).strip(\" \") minute = str(time.minute).strip(\" \") hour = str(time.hour).strip(\"",
"this command!!\") irc.reset() elif data == \"!quote\": q = open(\"data/quotes.ccfg\", \"r\") quotes =",
"line in cr: cmdline = line.split(\": \", 1) cmd = cmdline[0] info =",
"buffer.replace(\":\" + user + \"!\" + user + \"@\" + user + \".\"",
"irc.send(chan, \"You don't have the Permissions to perform this command!!\") irc.reset() elif data",
"info.replace(info, \"\") f.reset() c.close() break else: cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\") else: f.reset()",
"Loading\") print(\"executing main section\") while Main: text = irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer =",
"Main: text = irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer = text.replace(\":\", \"\") user = buffer.split(\"!\",",
"chan, data) f.reset() else: irc.send(chan, \"You don't have the Permissions to perform this",
"data == \"!quote\": q = open(\"data/quotes.ccfg\", \"r\") quotes = q.read().split(\"\\n\") quote = random.choice(quotes)",
"f.chatlog(user, data, timestamp) print(timestamp, user, \":\", data) if \"PING :tmi.twitch.tv\" == text: irc.pong()",
"buffer = text.replace(\":\", \"\") user = buffer.split(\"!\", 1)[0] buffer.replace(buffer, \"\") buffer = text",
"this command!!\") elif data.startswith(\"!\"): c = open(\"data/commands.cfg\", \"r\") cr = c.read().split(\"\\n\") for line",
"== cmd: irc.send(chan, info) print(BOTID + \": \" + info) cmdline.clear() cmd.replace(cmd, \"\")",
"\"\") buffer = text data = buffer.replace(\":\" + user + \"!\" + user",
"== \"!quote\": q = open(\"data/quotes.ccfg\", \"r\") quotes = q.read().split(\"\\n\") quote = random.choice(quotes) irc.send(chan,",
"cr = c.read().split(\"\\n\") for line in cr: cmdline = line.split(\": \", 1) cmd",
"cr: cmdline = line.split(\": \", 1) cmd = cmdline[0] info = cmdline[1] if",
"\"\") info.replace(info, \"\") f.reset() c.close() break else: cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\") else:",
"+ user + \"@\" + user + \".\" + \"tmi.twitch.tv \" + \"PRIVMSG",
"user in VIP: f.addQuote(irc, chan, data) f.reset() else: irc.send(chan, \"You don't have the",
"Permissions to perform this command!!\") irc.reset() elif data == \"!quote\": q = open(\"data/quotes.ccfg\",",
"\" + \"#\", \"\").split(\" :\", 1)[1] time = datetime.datetime.now() second = str(time.second).strip(\" \")",
"quote = random.choice(quotes) irc.send(chan, quote) print(BOTID + \": \" + quote) f.reset() q.close()",
"have the permissions to perform this command!!\") elif data.startswith(\"!\"): c = open(\"data/commands.cfg\", \"r\")",
"user, \":\", data) if \"PING :tmi.twitch.tv\" == text: irc.pong() f.reset() elif data.startswith(\"!cmdadd\"): if",
":tmi.twitch.tv\" == text: irc.pong() f.reset() elif data.startswith(\"!cmdadd\"): if user in VIP: f.addcmd(irc, chan,",
"+ \":\" + minute.zfill(2) + \":\" + second.zfill(2) + \"]\" f.chatlog(user, data, timestamp)",
"= open(\"data/quotes.ccfg\", \"r\") quotes = q.read().split(\"\\n\") quote = random.choice(quotes) irc.send(chan, quote) print(BOTID +",
"cmdline = line.split(\": \", 1) cmd = cmdline[0] info = cmdline[1] if data.strip(\"",
"irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer = text.replace(\":\", \"\") user = buffer.split(\"!\", 1)[0] buffer.replace(buffer, \"\")",
"perform this command!!\") f.reset() elif data.startswith(\"!quoteadd\"): if user in VIP: f.addQuote(irc, chan, data)",
"\"!quote\": q = open(\"data/quotes.ccfg\", \"r\") quotes = q.read().split(\"\\n\") quote = random.choice(quotes) irc.send(chan, quote)",
"irc.send(chan, info) print(BOTID + \": \" + info) cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\")",
"* import datetime def main(chan, Main, irc, VIP, f): print(\"finished Loading\") print(\"executing main",
"irc.pong() f.reset() elif data.startswith(\"!cmdadd\"): if user in VIP: f.addcmd(irc, chan, data) f.reset() else:",
"if user in VIP: f.addQuote(irc, chan, data) f.reset() else: irc.send(chan, \"You don't have",
"command!!\") f.reset() elif data.startswith(\"!quoteadd\"): if user in VIP: f.addQuote(irc, chan, data) f.reset() else:",
"don't have the Permissions to perform this command!!\") irc.reset() elif data == \"!quote\":",
"\": \" + quote) f.reset() q.close() elif data == \"!stop\": if user ==",
"the Permissions to perform this command!!\") f.reset() elif data.startswith(\"!quoteadd\"): if user in VIP:",
"+ \".\" + \"tmi.twitch.tv \" + \"PRIVMSG \" + \"#\", \"\").split(\" :\", 1)[1]",
"data.startswith(\"!\"): c = open(\"data/commands.cfg\", \"r\") cr = c.read().split(\"\\n\") for line in cr: cmdline",
"\" + info) cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\") f.reset() c.close() break else: cmdline.clear()",
"irc.send(chan, \"You don't have the permissions to perform this command!!\") elif data.startswith(\"!\"): c",
"time = datetime.datetime.now() second = str(time.second).strip(\" \") minute = str(time.minute).strip(\" \") hour =",
"\") == cmd: irc.send(chan, info) print(BOTID + \": \" + info) cmdline.clear() cmd.replace(cmd,",
"\", 1) cmd = cmdline[0] info = cmdline[1] if data.strip(\" \") == cmd:",
"+ info) cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\") f.reset() c.close() break else: cmdline.clear() cmd.replace(cmd,",
"while Main: text = irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer = text.replace(\":\", \"\") user =",
"data) if \"PING :tmi.twitch.tv\" == text: irc.pong() f.reset() elif data.startswith(\"!cmdadd\"): if user in",
"cmdline[0] info = cmdline[1] if data.strip(\" \") == cmd: irc.send(chan, info) print(BOTID +",
"data) f.reset() else: irc.send(chan, \"You don't have the Permissions to perform this command!!\")",
"print(\"executing main section\") while Main: text = irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer = text.replace(\":\",",
"from FUNCTIONS import * import datetime def main(chan, Main, irc, VIP, f): print(\"finished",
"+ \": \" + quote) f.reset() q.close() elif data == \"!stop\": if user",
"\":\" + second.zfill(2) + \"]\" f.chatlog(user, data, timestamp) print(timestamp, user, \":\", data) if",
"= buffer.split(\"!\", 1)[0] buffer.replace(buffer, \"\") buffer = text data = buffer.replace(\":\" + user",
"= cmdline[0] info = cmdline[1] if data.strip(\" \") == cmd: irc.send(chan, info) print(BOTID",
"f.reset() else: irc.send(chan, \"You don't have the Permissions to perform this command!!\") irc.reset()",
"info) print(BOTID + \": \" + info) cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\") f.reset()",
"f.reset() elif data.startswith(\"!quoteadd\"): if user in VIP: f.addQuote(irc, chan, data) f.reset() else: irc.send(chan,",
"== CHANNEL: sys.exit(0) f.reset() else: irc.send(chan, \"You don't have the permissions to perform",
"user = buffer.split(\"!\", 1)[0] buffer.replace(buffer, \"\") buffer = text data = buffer.replace(\":\" +",
"buffer = text data = buffer.replace(\":\" + user + \"!\" + user +",
"\"You don't have the Permissions to perform this command!!\") f.reset() elif data.startswith(\"!quoteadd\"): if",
"to perform this command!!\") f.reset() elif data.startswith(\"!quoteadd\"): if user in VIP: f.addQuote(irc, chan,",
"minute.zfill(2) + \":\" + second.zfill(2) + \"]\" f.chatlog(user, data, timestamp) print(timestamp, user, \":\",",
"VIP: f.addQuote(irc, chan, data) f.reset() else: irc.send(chan, \"You don't have the Permissions to",
"+ \"!\" + user + \"@\" + user + \".\" + \"tmi.twitch.tv \"",
"irc.send(chan, quote) print(BOTID + \": \" + quote) f.reset() q.close() elif data ==",
"= str(time.second).strip(\" \") minute = str(time.minute).strip(\" \") hour = str(time.hour).strip(\" \") timestamp =",
"cmd = cmdline[0] info = cmdline[1] if data.strip(\" \") == cmd: irc.send(chan, info)",
"text = irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer = text.replace(\":\", \"\") user = buffer.split(\"!\", 1)[0]",
"info) cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\") f.reset() c.close() break else: cmdline.clear() cmd.replace(cmd, \"\")",
"f.addQuote(irc, chan, data) f.reset() else: irc.send(chan, \"You don't have the Permissions to perform",
"\"!\" + user + \"@\" + user + \".\" + \"tmi.twitch.tv \" +",
"if data.strip(\" \") == cmd: irc.send(chan, info) print(BOTID + \": \" + info)",
"the permissions to perform this command!!\") elif data.startswith(\"!\"): c = open(\"data/commands.cfg\", \"r\") cr",
"cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\") f.reset() c.close() break else: cmdline.clear() cmd.replace(cmd, \"\") info.replace(info,",
"import datetime def main(chan, Main, irc, VIP, f): print(\"finished Loading\") print(\"executing main section\")",
"buffer.split(\"!\", 1)[0] buffer.replace(buffer, \"\") buffer = text data = buffer.replace(\":\" + user +",
"\") timestamp = \"[\" + hour.zfill(2) + \":\" + minute.zfill(2) + \":\" +",
"= q.read().split(\"\\n\") quote = random.choice(quotes) irc.send(chan, quote) print(BOTID + \": \" + quote)",
"the Permissions to perform this command!!\") irc.reset() elif data == \"!quote\": q =",
"+ minute.zfill(2) + \":\" + second.zfill(2) + \"]\" f.chatlog(user, data, timestamp) print(timestamp, user,",
"q = open(\"data/quotes.ccfg\", \"r\") quotes = q.read().split(\"\\n\") quote = random.choice(quotes) irc.send(chan, quote) print(BOTID",
"quote) f.reset() q.close() elif data == \"!stop\": if user == CHANNEL: sys.exit(0) f.reset()",
"cmdline[1] if data.strip(\" \") == cmd: irc.send(chan, info) print(BOTID + \": \" +",
"data = buffer.replace(\":\" + user + \"!\" + user + \"@\" + user",
"\"@\" + user + \".\" + \"tmi.twitch.tv \" + \"PRIVMSG \" + \"#\",",
"quote) print(BOTID + \": \" + quote) f.reset() q.close() elif data == \"!stop\":",
"import * import datetime def main(chan, Main, irc, VIP, f): print(\"finished Loading\") print(\"executing",
"str(time.minute).strip(\" \") hour = str(time.hour).strip(\" \") timestamp = \"[\" + hour.zfill(2) + \":\"",
"= c.read().split(\"\\n\") for line in cr: cmdline = line.split(\": \", 1) cmd =",
"f.reset() else: irc.send(chan, \"You don't have the permissions to perform this command!!\") elif",
"to perform this command!!\") irc.reset() elif data == \"!quote\": q = open(\"data/quotes.ccfg\", \"r\")",
"if user == CHANNEL: sys.exit(0) f.reset() else: irc.send(chan, \"You don't have the permissions",
"\":\" + minute.zfill(2) + \":\" + second.zfill(2) + \"]\" f.chatlog(user, data, timestamp) print(timestamp,",
"perform this command!!\") irc.reset() elif data == \"!quote\": q = open(\"data/quotes.ccfg\", \"r\") quotes",
"user + \"@\" + user + \".\" + \"tmi.twitch.tv \" + \"PRIVMSG \"",
"don't have the permissions to perform this command!!\") elif data.startswith(\"!\"): c = open(\"data/commands.cfg\",",
"text: irc.pong() f.reset() elif data.startswith(\"!cmdadd\"): if user in VIP: f.addcmd(irc, chan, data) f.reset()",
"perform this command!!\") elif data.startswith(\"!\"): c = open(\"data/commands.cfg\", \"r\") cr = c.read().split(\"\\n\") for",
"don't have the Permissions to perform this command!!\") f.reset() elif data.startswith(\"!quoteadd\"): if user",
"c = open(\"data/commands.cfg\", \"r\") cr = c.read().split(\"\\n\") for line in cr: cmdline =",
"= line.split(\": \", 1) cmd = cmdline[0] info = cmdline[1] if data.strip(\" \")",
"if user in VIP: f.addcmd(irc, chan, data) f.reset() else: irc.send(chan, \"You don't have",
"= random.choice(quotes) irc.send(chan, quote) print(BOTID + \": \" + quote) f.reset() q.close() elif",
"str(time.second).strip(\" \") minute = str(time.minute).strip(\" \") hour = str(time.hour).strip(\" \") timestamp = \"[\"",
"= str(time.minute).strip(\" \") hour = str(time.hour).strip(\" \") timestamp = \"[\" + hour.zfill(2) +",
"\"r\") quotes = q.read().split(\"\\n\") quote = random.choice(quotes) irc.send(chan, quote) print(BOTID + \": \"",
"+ quote) f.reset() q.close() elif data == \"!stop\": if user == CHANNEL: sys.exit(0)",
"\"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer = text.replace(\":\", \"\") user = buffer.split(\"!\", 1)[0] buffer.replace(buffer, \"\") buffer",
"for line in cr: cmdline = line.split(\": \", 1) cmd = cmdline[0] info",
"elif data.startswith(\"!\"): c = open(\"data/commands.cfg\", \"r\") cr = c.read().split(\"\\n\") for line in cr:",
"permissions to perform this command!!\") elif data.startswith(\"!\"): c = open(\"data/commands.cfg\", \"r\") cr =",
"\" + \"PRIVMSG \" + \"#\", \"\").split(\" :\", 1)[1] time = datetime.datetime.now() second",
"\"ignore\") buffer = text.replace(\":\", \"\") user = buffer.split(\"!\", 1)[0] buffer.replace(buffer, \"\") buffer =",
"print(\"finished Loading\") print(\"executing main section\") while Main: text = irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer",
"VIP, f): print(\"finished Loading\") print(\"executing main section\") while Main: text = irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\",",
"second.zfill(2) + \"]\" f.chatlog(user, data, timestamp) print(timestamp, user, \":\", data) if \"PING :tmi.twitch.tv\"",
"cmd.replace(cmd, \"\") info.replace(info, \"\") f.reset() c.close() break else: cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\")",
"= str(time.hour).strip(\" \") timestamp = \"[\" + hour.zfill(2) + \":\" + minute.zfill(2) +",
"data.startswith(\"!quoteadd\"): if user in VIP: f.addQuote(irc, chan, data) f.reset() else: irc.send(chan, \"You don't",
"\"You don't have the Permissions to perform this command!!\") irc.reset() elif data ==",
"in cr: cmdline = line.split(\": \", 1) cmd = cmdline[0] info = cmdline[1]",
"c.read().split(\"\\n\") for line in cr: cmdline = line.split(\": \", 1) cmd = cmdline[0]",
"user + \"!\" + user + \"@\" + user + \".\" + \"tmi.twitch.tv",
"1) cmd = cmdline[0] info = cmdline[1] if data.strip(\" \") == cmd: irc.send(chan,",
"+ \"@\" + user + \".\" + \"tmi.twitch.tv \" + \"PRIVMSG \" +",
"+ \":\" + second.zfill(2) + \"]\" f.chatlog(user, data, timestamp) print(timestamp, user, \":\", data)",
"minute = str(time.minute).strip(\" \") hour = str(time.hour).strip(\" \") timestamp = \"[\" + hour.zfill(2)",
"= \"[\" + hour.zfill(2) + \":\" + minute.zfill(2) + \":\" + second.zfill(2) +",
"\"r\") cr = c.read().split(\"\\n\") for line in cr: cmdline = line.split(\": \", 1)",
"+ \"PRIVMSG \" + \"#\", \"\").split(\" :\", 1)[1] time = datetime.datetime.now() second =",
"data == \"!stop\": if user == CHANNEL: sys.exit(0) f.reset() else: irc.send(chan, \"You don't",
"hour = str(time.hour).strip(\" \") timestamp = \"[\" + hour.zfill(2) + \":\" + minute.zfill(2)",
"irc.send(chan, \"You don't have the Permissions to perform this command!!\") f.reset() elif data.startswith(\"!quoteadd\"):",
"have the Permissions to perform this command!!\") irc.reset() elif data == \"!quote\": q",
"irc.reset() elif data == \"!quote\": q = open(\"data/quotes.ccfg\", \"r\") quotes = q.read().split(\"\\n\") quote",
"quotes = q.read().split(\"\\n\") quote = random.choice(quotes) irc.send(chan, quote) print(BOTID + \": \" +",
"user == CHANNEL: sys.exit(0) f.reset() else: irc.send(chan, \"You don't have the permissions to",
"CHANNEL: sys.exit(0) f.reset() else: irc.send(chan, \"You don't have the permissions to perform this",
"command!!\") elif data.startswith(\"!\"): c = open(\"data/commands.cfg\", \"r\") cr = c.read().split(\"\\n\") for line in",
"in VIP: f.addcmd(irc, chan, data) f.reset() else: irc.send(chan, \"You don't have the Permissions",
"open(\"data/quotes.ccfg\", \"r\") quotes = q.read().split(\"\\n\") quote = random.choice(quotes) irc.send(chan, quote) print(BOTID + \":",
"== \"!stop\": if user == CHANNEL: sys.exit(0) f.reset() else: irc.send(chan, \"You don't have",
"main(chan, Main, irc, VIP, f): print(\"finished Loading\") print(\"executing main section\") while Main: text",
"\"You don't have the permissions to perform this command!!\") elif data.startswith(\"!\"): c =",
"timestamp = \"[\" + hour.zfill(2) + \":\" + minute.zfill(2) + \":\" + second.zfill(2)",
"\".\" + \"tmi.twitch.tv \" + \"PRIVMSG \" + \"#\", \"\").split(\" :\", 1)[1] time",
"second = str(time.second).strip(\" \") minute = str(time.minute).strip(\" \") hour = str(time.hour).strip(\" \") timestamp",
"\":\", data) if \"PING :tmi.twitch.tv\" == text: irc.pong() f.reset() elif data.startswith(\"!cmdadd\"): if user",
"else: irc.send(chan, \"You don't have the Permissions to perform this command!!\") f.reset() elif",
"\") minute = str(time.minute).strip(\" \") hour = str(time.hour).strip(\" \") timestamp = \"[\" +",
"Main, irc, VIP, f): print(\"finished Loading\") print(\"executing main section\") while Main: text =",
"= buffer.replace(\":\" + user + \"!\" + user + \"@\" + user +",
"command!!\") irc.reset() elif data == \"!quote\": q = open(\"data/quotes.ccfg\", \"r\") quotes = q.read().split(\"\\n\")",
"Permissions to perform this command!!\") f.reset() elif data.startswith(\"!quoteadd\"): if user in VIP: f.addQuote(irc,",
"elif data.startswith(\"!quoteadd\"): if user in VIP: f.addQuote(irc, chan, data) f.reset() else: irc.send(chan, \"You",
"in VIP: f.addQuote(irc, chan, data) f.reset() else: irc.send(chan, \"You don't have the Permissions",
"to perform this command!!\") elif data.startswith(\"!\"): c = open(\"data/commands.cfg\", \"r\") cr = c.read().split(\"\\n\")",
"\"PING :tmi.twitch.tv\" == text: irc.pong() f.reset() elif data.startswith(\"!cmdadd\"): if user in VIP: f.addcmd(irc,",
":\", 1)[1] time = datetime.datetime.now() second = str(time.second).strip(\" \") minute = str(time.minute).strip(\" \")",
"\"#\", \"\").split(\" :\", 1)[1] time = datetime.datetime.now() second = str(time.second).strip(\" \") minute =",
"data.startswith(\"!cmdadd\"): if user in VIP: f.addcmd(irc, chan, data) f.reset() else: irc.send(chan, \"You don't",
"elif data == \"!stop\": if user == CHANNEL: sys.exit(0) f.reset() else: irc.send(chan, \"You",
"random.choice(quotes) irc.send(chan, quote) print(BOTID + \": \" + quote) f.reset() q.close() elif data",
"<filename>MAIN.py from FUNCTIONS import * import datetime def main(chan, Main, irc, VIP, f):",
"text.replace(\":\", \"\") user = buffer.split(\"!\", 1)[0] buffer.replace(buffer, \"\") buffer = text data =",
"+ \"#\", \"\").split(\" :\", 1)[1] time = datetime.datetime.now() second = str(time.second).strip(\" \") minute",
"elif data.startswith(\"!cmdadd\"): if user in VIP: f.addcmd(irc, chan, data) f.reset() else: irc.send(chan, \"You",
"+ \"tmi.twitch.tv \" + \"PRIVMSG \" + \"#\", \"\").split(\" :\", 1)[1] time =",
"q.close() elif data == \"!stop\": if user == CHANNEL: sys.exit(0) f.reset() else: irc.send(chan,",
"datetime def main(chan, Main, irc, VIP, f): print(\"finished Loading\") print(\"executing main section\") while",
"timestamp) print(timestamp, user, \":\", data) if \"PING :tmi.twitch.tv\" == text: irc.pong() f.reset() elif",
"f.reset() q.close() elif data == \"!stop\": if user == CHANNEL: sys.exit(0) f.reset() else:",
"\": \" + info) cmdline.clear() cmd.replace(cmd, \"\") info.replace(info, \"\") f.reset() c.close() break else:",
"\"\") user = buffer.split(\"!\", 1)[0] buffer.replace(buffer, \"\") buffer = text data = buffer.replace(\":\"",
"= irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer = text.replace(\":\", \"\") user = buffer.split(\"!\", 1)[0] buffer.replace(buffer,",
"this command!!\") f.reset() elif data.startswith(\"!quoteadd\"): if user in VIP: f.addQuote(irc, chan, data) f.reset()",
"cmd: irc.send(chan, info) print(BOTID + \": \" + info) cmdline.clear() cmd.replace(cmd, \"\") info.replace(info,",
"main section\") while Main: text = irc.get_text().strip(bytes(\"\\r\\n\", \"UTF-8\")).decode(\"UTF-8\", \"ignore\") buffer = text.replace(\":\", \"\")",
"q.read().split(\"\\n\") quote = random.choice(quotes) irc.send(chan, quote) print(BOTID + \": \" + quote) f.reset()",
"print(BOTID + \": \" + quote) f.reset() q.close() elif data == \"!stop\": if",
"text data = buffer.replace(\":\" + user + \"!\" + user + \"@\" +",
"\") hour = str(time.hour).strip(\" \") timestamp = \"[\" + hour.zfill(2) + \":\" +",
"\"\").split(\" :\", 1)[1] time = datetime.datetime.now() second = str(time.second).strip(\" \") minute = str(time.minute).strip(\"",
"+ hour.zfill(2) + \":\" + minute.zfill(2) + \":\" + second.zfill(2) + \"]\" f.chatlog(user,",
"VIP: f.addcmd(irc, chan, data) f.reset() else: irc.send(chan, \"You don't have the Permissions to",
"1)[1] time = datetime.datetime.now() second = str(time.second).strip(\" \") minute = str(time.minute).strip(\" \") hour"
] |
[
"tf.reshape(scaled_img, [x.shape[0], h ** 2]) def quantize(x): phi = tf.concat( [tf.expand_dims(tf.cos(x) * np.pi/2,",
"scale, 1], strides=[1, scale, scale, 1], padding='VALID') h //= scale return tf.reshape(scaled_img, [x.shape[0],",
"tf.concat( [tf.expand_dims(tf.cos(x) * np.pi/2, 2), tf.expand_dims(tf.sin(x) * np.pi/2, 2)], 2) return phi def",
"scale return tf.reshape(scaled_img, [x.shape[0], h ** 2]) def quantize(x): phi = tf.concat( [tf.expand_dims(tf.cos(x)",
"* np.pi/2, 2)], 2) return phi def load_mnist(one_hot=True, random_state=42): mnist = input_data.read_data_sets('MNIST_data/', one_hot=one_hot)",
"h, h, 1) scaled_img = tf.nn.avg_pool(img, ksize=[1, scale, scale, 1], strides=[1, scale, scale,",
"return tf.reshape(scaled_img, [x.shape[0], h ** 2]) def quantize(x): phi = tf.concat( [tf.expand_dims(tf.cos(x) *",
"tf.expand_dims(tf.sin(x) * np.pi/2, 2)], 2) return phi def load_mnist(one_hot=True, random_state=42): mnist = input_data.read_data_sets('MNIST_data/',",
"[x.shape[0], h ** 2]) def quantize(x): phi = tf.concat( [tf.expand_dims(tf.cos(x) * np.pi/2, 2),",
"h //= scale return tf.reshape(scaled_img, [x.shape[0], h ** 2]) def quantize(x): phi =",
"def load_mnist(one_hot=True, random_state=42): mnist = input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X = np.concatenate((mnist.train.images, mnist.test.images), axis=0) mnist_y",
"2)], 2) return phi def load_mnist(one_hot=True, random_state=42): mnist = input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X =",
"1) scaled_img = tf.nn.avg_pool(img, ksize=[1, scale, scale, 1], strides=[1, scale, scale, 1], padding='VALID')",
"* np.pi/2, 2), tf.expand_dims(tf.sin(x) * np.pi/2, 2)], 2) return phi def load_mnist(one_hot=True, random_state=42):",
"= int(np.sqrt(x.shape[1])) img = x.astype(\"float32\").reshape(x.shape[0], h, h, 1) scaled_img = tf.nn.avg_pool(img, ksize=[1, scale,",
"random_state=42): mnist = input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X = np.concatenate((mnist.train.images, mnist.test.images), axis=0) mnist_y = np.concatenate((mnist.train.labels,",
"1], strides=[1, scale, scale, 1], padding='VALID') h //= scale return tf.reshape(scaled_img, [x.shape[0], h",
"[tf.expand_dims(tf.cos(x) * np.pi/2, 2), tf.expand_dims(tf.sin(x) * np.pi/2, 2)], 2) return phi def load_mnist(one_hot=True,",
"-> order 4 h = int(np.sqrt(x.shape[1])) img = x.astype(\"float32\").reshape(x.shape[0], h, h, 1) scaled_img",
"= x.astype(\"float32\").reshape(x.shape[0], h, h, 1) scaled_img = tf.nn.avg_pool(img, ksize=[1, scale, scale, 1], strides=[1,",
"tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from sklearn.model_selection import train_test_split def down_scale(x,",
"tensorflow.examples.tutorials.mnist import input_data from sklearn.model_selection import train_test_split def down_scale(x, scale=2): # order 2",
"//= scale return tf.reshape(scaled_img, [x.shape[0], h ** 2]) def quantize(x): phi = tf.concat(",
"scale=2): # order 2 -> order 4 h = int(np.sqrt(x.shape[1])) img = x.astype(\"float32\").reshape(x.shape[0],",
"= np.concatenate((mnist.train.images, mnist.test.images), axis=0) mnist_y = np.concatenate((mnist.train.labels, mnist.test.labels), axis=0) return train_test_split(mnist_X, mnist_y, test_size=0.2,",
"quantize(x): phi = tf.concat( [tf.expand_dims(tf.cos(x) * np.pi/2, 2), tf.expand_dims(tf.sin(x) * np.pi/2, 2)], 2)",
"ksize=[1, scale, scale, 1], strides=[1, scale, scale, 1], padding='VALID') h //= scale return",
"= tf.nn.avg_pool(img, ksize=[1, scale, scale, 1], strides=[1, scale, scale, 1], padding='VALID') h //=",
"def down_scale(x, scale=2): # order 2 -> order 4 h = int(np.sqrt(x.shape[1])) img",
"load_mnist(one_hot=True, random_state=42): mnist = input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X = np.concatenate((mnist.train.images, mnist.test.images), axis=0) mnist_y =",
"mnist_X = np.concatenate((mnist.train.images, mnist.test.images), axis=0) mnist_y = np.concatenate((mnist.train.labels, mnist.test.labels), axis=0) return train_test_split(mnist_X, mnist_y,",
"2), tf.expand_dims(tf.sin(x) * np.pi/2, 2)], 2) return phi def load_mnist(one_hot=True, random_state=42): mnist =",
"order 2 -> order 4 h = int(np.sqrt(x.shape[1])) img = x.astype(\"float32\").reshape(x.shape[0], h, h,",
"np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from sklearn.model_selection import train_test_split",
"import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from sklearn.model_selection import train_test_split def",
"def quantize(x): phi = tf.concat( [tf.expand_dims(tf.cos(x) * np.pi/2, 2), tf.expand_dims(tf.sin(x) * np.pi/2, 2)],",
"order 4 h = int(np.sqrt(x.shape[1])) img = x.astype(\"float32\").reshape(x.shape[0], h, h, 1) scaled_img =",
"from sklearn.model_selection import train_test_split def down_scale(x, scale=2): # order 2 -> order 4",
"# order 2 -> order 4 h = int(np.sqrt(x.shape[1])) img = x.astype(\"float32\").reshape(x.shape[0], h,",
"strides=[1, scale, scale, 1], padding='VALID') h //= scale return tf.reshape(scaled_img, [x.shape[0], h **",
"scale, 1], padding='VALID') h //= scale return tf.reshape(scaled_img, [x.shape[0], h ** 2]) def",
"numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from sklearn.model_selection",
"tf from tensorflow.examples.tutorials.mnist import input_data from sklearn.model_selection import train_test_split def down_scale(x, scale=2): #",
"img = x.astype(\"float32\").reshape(x.shape[0], h, h, 1) scaled_img = tf.nn.avg_pool(img, ksize=[1, scale, scale, 1],",
"as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from sklearn.model_selection import",
"h = int(np.sqrt(x.shape[1])) img = x.astype(\"float32\").reshape(x.shape[0], h, h, 1) scaled_img = tf.nn.avg_pool(img, ksize=[1,",
"scale, scale, 1], strides=[1, scale, scale, 1], padding='VALID') h //= scale return tf.reshape(scaled_img,",
"2]) def quantize(x): phi = tf.concat( [tf.expand_dims(tf.cos(x) * np.pi/2, 2), tf.expand_dims(tf.sin(x) * np.pi/2,",
"np.pi/2, 2), tf.expand_dims(tf.sin(x) * np.pi/2, 2)], 2) return phi def load_mnist(one_hot=True, random_state=42): mnist",
"sklearn.model_selection import train_test_split def down_scale(x, scale=2): # order 2 -> order 4 h",
"mnist = input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X = np.concatenate((mnist.train.images, mnist.test.images), axis=0) mnist_y = np.concatenate((mnist.train.labels, mnist.test.labels),",
"4 h = int(np.sqrt(x.shape[1])) img = x.astype(\"float32\").reshape(x.shape[0], h, h, 1) scaled_img = tf.nn.avg_pool(img,",
"import train_test_split def down_scale(x, scale=2): # order 2 -> order 4 h =",
"from tensorflow.examples.tutorials.mnist import input_data from sklearn.model_selection import train_test_split def down_scale(x, scale=2): # order",
"scaled_img = tf.nn.avg_pool(img, ksize=[1, scale, scale, 1], strides=[1, scale, scale, 1], padding='VALID') h",
"= input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X = np.concatenate((mnist.train.images, mnist.test.images), axis=0) mnist_y = np.concatenate((mnist.train.labels, mnist.test.labels), axis=0)",
"np.pi/2, 2)], 2) return phi def load_mnist(one_hot=True, random_state=42): mnist = input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X",
"down_scale(x, scale=2): # order 2 -> order 4 h = int(np.sqrt(x.shape[1])) img =",
"padding='VALID') h //= scale return tf.reshape(scaled_img, [x.shape[0], h ** 2]) def quantize(x): phi",
"phi = tf.concat( [tf.expand_dims(tf.cos(x) * np.pi/2, 2), tf.expand_dims(tf.sin(x) * np.pi/2, 2)], 2) return",
"train_test_split def down_scale(x, scale=2): # order 2 -> order 4 h = int(np.sqrt(x.shape[1]))",
"return phi def load_mnist(one_hot=True, random_state=42): mnist = input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X = np.concatenate((mnist.train.images, mnist.test.images),",
"h, 1) scaled_img = tf.nn.avg_pool(img, ksize=[1, scale, scale, 1], strides=[1, scale, scale, 1],",
"** 2]) def quantize(x): phi = tf.concat( [tf.expand_dims(tf.cos(x) * np.pi/2, 2), tf.expand_dims(tf.sin(x) *",
"x.astype(\"float32\").reshape(x.shape[0], h, h, 1) scaled_img = tf.nn.avg_pool(img, ksize=[1, scale, scale, 1], strides=[1, scale,",
"input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X = np.concatenate((mnist.train.images, mnist.test.images), axis=0) mnist_y = np.concatenate((mnist.train.labels, mnist.test.labels), axis=0) return",
"import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from",
"import input_data from sklearn.model_selection import train_test_split def down_scale(x, scale=2): # order 2 ->",
"phi def load_mnist(one_hot=True, random_state=42): mnist = input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X = np.concatenate((mnist.train.images, mnist.test.images), axis=0)",
"np.concatenate((mnist.train.images, mnist.test.images), axis=0) mnist_y = np.concatenate((mnist.train.labels, mnist.test.labels), axis=0) return train_test_split(mnist_X, mnist_y, test_size=0.2, random_state=random_state)",
"2 -> order 4 h = int(np.sqrt(x.shape[1])) img = x.astype(\"float32\").reshape(x.shape[0], h, h, 1)",
"one_hot=one_hot) mnist_X = np.concatenate((mnist.train.images, mnist.test.images), axis=0) mnist_y = np.concatenate((mnist.train.labels, mnist.test.labels), axis=0) return train_test_split(mnist_X,",
"h ** 2]) def quantize(x): phi = tf.concat( [tf.expand_dims(tf.cos(x) * np.pi/2, 2), tf.expand_dims(tf.sin(x)",
"as tf from tensorflow.examples.tutorials.mnist import input_data from sklearn.model_selection import train_test_split def down_scale(x, scale=2):",
"tf.nn.avg_pool(img, ksize=[1, scale, scale, 1], strides=[1, scale, scale, 1], padding='VALID') h //= scale",
"1], padding='VALID') h //= scale return tf.reshape(scaled_img, [x.shape[0], h ** 2]) def quantize(x):",
"input_data from sklearn.model_selection import train_test_split def down_scale(x, scale=2): # order 2 -> order",
"scale, scale, 1], padding='VALID') h //= scale return tf.reshape(scaled_img, [x.shape[0], h ** 2])",
"2) return phi def load_mnist(one_hot=True, random_state=42): mnist = input_data.read_data_sets('MNIST_data/', one_hot=one_hot) mnist_X = np.concatenate((mnist.train.images,",
"= tf.concat( [tf.expand_dims(tf.cos(x) * np.pi/2, 2), tf.expand_dims(tf.sin(x) * np.pi/2, 2)], 2) return phi",
"int(np.sqrt(x.shape[1])) img = x.astype(\"float32\").reshape(x.shape[0], h, h, 1) scaled_img = tf.nn.avg_pool(img, ksize=[1, scale, scale,"
] |
[
"> AutoCAD DXF\", \"description\": \"The script exports Blender geometry to DXF format r12",
"by the Free Software Foundation; either version 2 # of the License, or",
"distributed in the hope that it will be useful, # but WITHOUT ANY",
"Foundation; either version 2 # of the License, or (at your option) any",
"# along with this program; if not, write to the Free Software Foundation,",
"Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # #####",
"script exports Blender geometry to DXF format r12 version.\", \"warning\": \"Under construction! Visit",
"PURPOSE. See the # GNU General Public License for more details. # #",
"the Free Software Foundation; either version 2 # of the License, or (at",
"program; if not, write to the Free Software Foundation, # Inc., 51 Franklin",
". import operator def menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\") classes = ( operator.DXFExporter,",
"# as published by the Free Software Foundation; either version 2 # of",
"migius), <NAME>\", \"version\": (2, 2, 3), \"blender\": (2, 80, 0), \"location\": \"File >",
"of the GNU General Public License # as published by the Free Software",
"if \"bpy\" in locals(): from importlib import reload reload(operator) del reload import bpy",
"LICENSE BLOCK ##### # # This program is free software; you can redistribute",
"2 # of the License, or (at your option) any later version. #",
"the License, or (at your option) any later version. # # This program",
"any later version. # # This program is distributed in the hope that",
"menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\") classes = ( operator.DXFExporter, ) def register(): from",
"if not, write to the Free Software Foundation, # Inc., 51 Franklin Street,",
"51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END",
"modify it under the terms of the GNU General Public License # as",
"bl_info = { \"name\": \"Export Autocad DXF Format (.dxf)\", \"author\": \"<NAME> (AKA migius),",
"##### # # This program is free software; you can redistribute it and/or",
"# # This program is free software; you can redistribute it and/or #",
"General Public License # as published by the Free Software Foundation; either version",
"DXF\", \"description\": \"The script exports Blender geometry to DXF format r12 version.\", \"warning\":",
"of the License, or (at your option) any later version. # # This",
"published by the Free Software Foundation; either version 2 # of the License,",
"# ##### END GPL LICENSE BLOCK ##### bl_info = { \"name\": \"Export Autocad",
"License for more details. # # You should have received a copy of",
"# modify it under the terms of the GNU General Public License #",
"write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor,",
"Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL",
"register(): from bpy.utils import register_class for cls in classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister():",
"\"<NAME> (AKA migius), <NAME>\", \"version\": (2, 2, 3), \"blender\": (2, 80, 0), \"location\":",
"from bpy.utils import unregister_class for cls in reversed(classes): unregister_class(cls) bpy.types.TOPBAR_MT_file_export.remove(menu_func) if __name__ ==",
"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General",
"classes = ( operator.DXFExporter, ) def register(): from bpy.utils import register_class for cls",
"in classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): from bpy.utils import unregister_class for cls in",
"This program is free software; you can redistribute it and/or # modify it",
"02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### bl_info = {",
"BLOCK ##### # # This program is free software; you can redistribute it",
"Wiki for details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\", } if \"bpy\" in locals(): from",
"\"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\", } if \"bpy\" in locals(): from importlib import reload reload(operator)",
"# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free",
"should have received a copy of the GNU General Public License # along",
"PARTICULAR PURPOSE. See the # GNU General Public License for more details. #",
"operator def menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\") classes = ( operator.DXFExporter, ) def",
"import operator def menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\") classes = ( operator.DXFExporter, )",
"del reload import bpy from . import operator def menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD",
"Public License # along with this program; if not, write to the Free",
"either version 2 # of the License, or (at your option) any later",
"Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE",
"BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you",
"( operator.DXFExporter, ) def register(): from bpy.utils import register_class for cls in classes:",
"without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"DXF Format (.dxf)\", \"author\": \"<NAME> (AKA migius), <NAME>\", \"version\": (2, 2, 3), \"blender\":",
"(AKA migius), <NAME>\", \"version\": (2, 2, 3), \"blender\": (2, 80, 0), \"location\": \"File",
"DXF\") classes = ( operator.DXFExporter, ) def register(): from bpy.utils import register_class for",
"from . import operator def menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\") classes = (",
"from importlib import reload reload(operator) del reload import bpy from . import operator",
"{ \"name\": \"Export Autocad DXF Format (.dxf)\", \"author\": \"<NAME> (AKA migius), <NAME>\", \"version\":",
"hope that it will be useful, # but WITHOUT ANY WARRANTY; without even",
"free software; you can redistribute it and/or # modify it under the terms",
"2, 3), \"blender\": (2, 80, 0), \"location\": \"File > Export > AutoCAD DXF\",",
"# # ##### END GPL LICENSE BLOCK ##### bl_info = { \"name\": \"Export",
"this program; if not, write to the Free Software Foundation, # Inc., 51",
"3), \"blender\": (2, 80, 0), \"location\": \"File > Export > AutoCAD DXF\", \"description\":",
"a copy of the GNU General Public License # along with this program;",
"is free software; you can redistribute it and/or # modify it under the",
"\"Import-Export\", } if \"bpy\" in locals(): from importlib import reload reload(operator) del reload",
"and/or # modify it under the terms of the GNU General Public License",
"not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth",
"(.dxf)\", \"author\": \"<NAME> (AKA migius), <NAME>\", \"version\": (2, 2, 3), \"blender\": (2, 80,",
"\"blender\": (2, 80, 0), \"location\": \"File > Export > AutoCAD DXF\", \"description\": \"The",
"from bpy.utils import register_class for cls in classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): from",
"importlib import reload reload(operator) del reload import bpy from . import operator def",
"Public License # as published by the Free Software Foundation; either version 2",
"License # as published by the Free Software Foundation; either version 2 #",
"warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #",
"You should have received a copy of the GNU General Public License #",
"terms of the GNU General Public License # as published by the Free",
"Autocad DXF Format (.dxf)\", \"author\": \"<NAME> (AKA migius), <NAME>\", \"version\": (2, 2, 3),",
"(2, 80, 0), \"location\": \"File > Export > AutoCAD DXF\", \"description\": \"The script",
"See the # GNU General Public License for more details. # # You",
"Visit Wiki for details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\", } if \"bpy\" in locals():",
"reload reload(operator) del reload import bpy from . import operator def menu_func(self, context):",
"def menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\") classes = ( operator.DXFExporter, ) def register():",
"Free Software Foundation; either version 2 # of the License, or (at your",
"\"author\": \"<NAME> (AKA migius), <NAME>\", \"version\": (2, 2, 3), \"blender\": (2, 80, 0),",
"(at your option) any later version. # # This program is distributed in",
"This program is distributed in the hope that it will be useful, #",
"details. # # You should have received a copy of the GNU General",
"WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A",
"\"Export Autocad DXF Format (.dxf)\", \"author\": \"<NAME> (AKA migius), <NAME>\", \"version\": (2, 2,",
"bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): from bpy.utils import unregister_class for cls in reversed(classes): unregister_class(cls) bpy.types.TOPBAR_MT_file_export.remove(menu_func)",
"useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #",
"that it will be useful, # but WITHOUT ANY WARRANTY; without even the",
"##### bl_info = { \"name\": \"Export Autocad DXF Format (.dxf)\", \"author\": \"<NAME> (AKA",
"of the GNU General Public License # along with this program; if not,",
"the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA",
"GNU General Public License # along with this program; if not, write to",
"your option) any later version. # # This program is distributed in the",
"Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK",
"def register(): from bpy.utils import register_class for cls in classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def",
"as published by the Free Software Foundation; either version 2 # of the",
"received a copy of the GNU General Public License # along with this",
"to DXF format r12 version.\", \"warning\": \"Under construction! Visit Wiki for details.\", \"doc_url\":",
"Format (.dxf)\", \"author\": \"<NAME> (AKA migius), <NAME>\", \"version\": (2, 2, 3), \"blender\": (2,",
"(2, 2, 3), \"blender\": (2, 80, 0), \"location\": \"File > Export > AutoCAD",
"LICENSE BLOCK ##### bl_info = { \"name\": \"Export Autocad DXF Format (.dxf)\", \"author\":",
"for cls in classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): from bpy.utils import unregister_class for",
"GPL LICENSE BLOCK ##### # # This program is free software; you can",
"Blender geometry to DXF format r12 version.\", \"warning\": \"Under construction! Visit Wiki for",
"program is free software; you can redistribute it and/or # modify it under",
"0), \"location\": \"File > Export > AutoCAD DXF\", \"description\": \"The script exports Blender",
"geometry to DXF format r12 version.\", \"warning\": \"Under construction! Visit Wiki for details.\",",
"even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"def unregister(): from bpy.utils import unregister_class for cls in reversed(classes): unregister_class(cls) bpy.types.TOPBAR_MT_file_export.remove(menu_func) if",
"classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): from bpy.utils import unregister_class for cls in reversed(classes):",
"BLOCK ##### bl_info = { \"name\": \"Export Autocad DXF Format (.dxf)\", \"author\": \"<NAME>",
"in locals(): from importlib import reload reload(operator) del reload import bpy from .",
"implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR",
"later version. # # This program is distributed in the hope that it",
"Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### bl_info",
"= ( operator.DXFExporter, ) def register(): from bpy.utils import register_class for cls in",
"you can redistribute it and/or # modify it under the terms of the",
"\"name\": \"Export Autocad DXF Format (.dxf)\", \"author\": \"<NAME> (AKA migius), <NAME>\", \"version\": (2,",
"it and/or # modify it under the terms of the GNU General Public",
"along with this program; if not, write to the Free Software Foundation, #",
"it will be useful, # but WITHOUT ANY WARRANTY; without even the implied",
"# of the License, or (at your option) any later version. # #",
"# # This program is distributed in the hope that it will be",
"WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS",
"\"The script exports Blender geometry to DXF format r12 version.\", \"warning\": \"Under construction!",
"the hope that it will be useful, # but WITHOUT ANY WARRANTY; without",
"# # You should have received a copy of the GNU General Public",
"register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): from bpy.utils import unregister_class for cls in reversed(classes): unregister_class(cls)",
"r12 version.\", \"warning\": \"Under construction! Visit Wiki for details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\",",
"version 2 # of the License, or (at your option) any later version.",
"License # along with this program; if not, write to the Free Software",
"General Public License for more details. # # You should have received a",
"import unregister_class for cls in reversed(classes): unregister_class(cls) bpy.types.TOPBAR_MT_file_export.remove(menu_func) if __name__ == \"__main__\": register()",
"END GPL LICENSE BLOCK ##### bl_info = { \"name\": \"Export Autocad DXF Format",
"FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more",
"reload(operator) del reload import bpy from . import operator def menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname,",
"MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### bl_info =",
"be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of",
"have received a copy of the GNU General Public License # along with",
"the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"can redistribute it and/or # modify it under the terms of the GNU",
"# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # #",
"# You should have received a copy of the GNU General Public License",
"Public License for more details. # # You should have received a copy",
"Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK #####",
"\"location\": \"File > Export > AutoCAD DXF\", \"description\": \"The script exports Blender geometry",
"DXF format r12 version.\", \"warning\": \"Under construction! Visit Wiki for details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\",",
"it under the terms of the GNU General Public License # as published",
"is distributed in the hope that it will be useful, # but WITHOUT",
"USA. # # ##### END GPL LICENSE BLOCK ##### bl_info = { \"name\":",
"License, or (at your option) any later version. # # This program is",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public",
"\"version\": (2, 2, 3), \"blender\": (2, 80, 0), \"location\": \"File > Export >",
"for details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\", } if \"bpy\" in locals(): from importlib",
"locals(): from importlib import reload reload(operator) del reload import bpy from . import",
"in the hope that it will be useful, # but WITHOUT ANY WARRANTY;",
"version. # # This program is distributed in the hope that it will",
"FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for",
"Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.",
"text=\"AutoCAD DXF\") classes = ( operator.DXFExporter, ) def register(): from bpy.utils import register_class",
"unregister(): from bpy.utils import unregister_class for cls in reversed(classes): unregister_class(cls) bpy.types.TOPBAR_MT_file_export.remove(menu_func) if __name__",
"} if \"bpy\" in locals(): from importlib import reload reload(operator) del reload import",
"construction! Visit Wiki for details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\", } if \"bpy\" in",
"operator.DXFExporter, ) def register(): from bpy.utils import register_class for cls in classes: register_class(cls)",
"Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,",
"bpy.utils import register_class for cls in classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): from bpy.utils",
"##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software;",
"GNU General Public License # as published by the Free Software Foundation; either",
") def register(): from bpy.utils import register_class for cls in classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func)",
"\"bpy\" in locals(): from importlib import reload reload(operator) del reload import bpy from",
"Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #",
"the # GNU General Public License for more details. # # You should",
"\"category\": \"Import-Export\", } if \"bpy\" in locals(): from importlib import reload reload(operator) del",
"copy of the GNU General Public License # along with this program; if",
"General Public License # along with this program; if not, write to the",
"self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\") classes = ( operator.DXFExporter, ) def register(): from bpy.utils import",
"\"File > Export > AutoCAD DXF\", \"description\": \"The script exports Blender geometry to",
"AutoCAD DXF\", \"description\": \"The script exports Blender geometry to DXF format r12 version.\",",
"A PARTICULAR PURPOSE. See the # GNU General Public License for more details.",
"> Export > AutoCAD DXF\", \"description\": \"The script exports Blender geometry to DXF",
"or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License",
"register_class for cls in classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): from bpy.utils import unregister_class",
"the GNU General Public License # along with this program; if not, write",
"for more details. # # You should have received a copy of the",
"Software Foundation; either version 2 # of the License, or (at your option)",
"the terms of the GNU General Public License # as published by the",
"under the terms of the GNU General Public License # as published by",
"reload import bpy from . import operator def menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\")",
"or (at your option) any later version. # # This program is distributed",
"bpy from . import operator def menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\") classes =",
"with this program; if not, write to the Free Software Foundation, # Inc.,",
"<NAME>\", \"version\": (2, 2, 3), \"blender\": (2, 80, 0), \"location\": \"File > Export",
"80, 0), \"location\": \"File > Export > AutoCAD DXF\", \"description\": \"The script exports",
"\"Under construction! Visit Wiki for details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\", } if \"bpy\"",
"will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty",
"exports Blender geometry to DXF format r12 version.\", \"warning\": \"Under construction! Visit Wiki",
"# This program is free software; you can redistribute it and/or # modify",
"\"warning\": \"Under construction! Visit Wiki for details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\", } if",
"##### END GPL LICENSE BLOCK ##### bl_info = { \"name\": \"Export Autocad DXF",
"\"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\", } if \"bpy\" in locals(): from importlib import reload",
"import bpy from . import operator def menu_func(self, context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\") classes",
"software; you can redistribute it and/or # modify it under the terms of",
"cls in classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): from bpy.utils import unregister_class for cls",
"more details. # # You should have received a copy of the GNU",
"details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\", } if \"bpy\" in locals(): from importlib import",
"of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU",
"import register_class for cls in classes: register_class(cls) bpy.types.TOPBAR_MT_file_export.append(menu_func) def unregister(): from bpy.utils import",
"GNU General Public License for more details. # # You should have received",
"GPL LICENSE BLOCK ##### bl_info = { \"name\": \"Export Autocad DXF Format (.dxf)\",",
"context): self.layout.operator(operator.DXFExporter.bl_idname, text=\"AutoCAD DXF\") classes = ( operator.DXFExporter, ) def register(): from bpy.utils",
"\"description\": \"The script exports Blender geometry to DXF format r12 version.\", \"warning\": \"Under",
"option) any later version. # # This program is distributed in the hope",
"# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY",
"to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston,",
"# GNU General Public License for more details. # # You should have",
"Export > AutoCAD DXF\", \"description\": \"The script exports Blender geometry to DXF format",
"format r12 version.\", \"warning\": \"Under construction! Visit Wiki for details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\":",
"version.\", \"warning\": \"Under construction! Visit Wiki for details.\", \"doc_url\": \"{BLENDER_MANUAL_URL}/addons/import_export/scene_dxf.html\", \"category\": \"Import-Export\", }",
"= { \"name\": \"Export Autocad DXF Format (.dxf)\", \"author\": \"<NAME> (AKA migius), <NAME>\",",
"bpy.utils import unregister_class for cls in reversed(classes): unregister_class(cls) bpy.types.TOPBAR_MT_file_export.remove(menu_func) if __name__ == \"__main__\":",
"redistribute it and/or # modify it under the terms of the GNU General",
"import reload reload(operator) del reload import bpy from . import operator def menu_func(self,",
"program is distributed in the hope that it will be useful, # but",
"# This program is distributed in the hope that it will be useful,",
"the GNU General Public License # as published by the Free Software Foundation;",
"but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or"
] |
[
"= 'lastmention(ed)/lastsaid <text> - checks the log for the last time someone mentioned",
"'/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mentionnottoday\"], stdout=subprocess.PIPE) output =",
"class Command(CommandInterface): triggers = ['lastsaid', 'lastmention', 'lastmentioned'] help = 'lastmention(ed)/lastsaid <text> - checks",
"\"lastmentioned\"): proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo,",
"proc.stdout.read() return IRCResponse(ResponseType.Say, output, message.ReplyTo) if len(message.MessageList) > 1 and message.Command == \"lastsaid\":",
"if len(message.MessageList) > 1 and (message.Command == \"lastmention\" or message.Command == \"lastmentioned\"): proc",
"message.ReplyTo) if len(message.MessageList) > 1 and message.Command == \"lastsaid\": proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php',",
"and message.Command == \"lastsaid\": proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\")",
"subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mentionnottoday\"], stdout=subprocess.PIPE) output",
"\"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mention\"], stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say, output,",
"a given word or phrase' def execute(self, message): \"\"\" @type message: IRCMessage \"\"\"",
"utf-8 -*- from IRCMessage import IRCMessage from IRCResponse import IRCResponse, ResponseType from CommandInterface",
"CommandInterface import subprocess class Command(CommandInterface): triggers = ['lastsaid', 'lastmention', 'lastmentioned'] help = 'lastmention(ed)/lastsaid",
"message): \"\"\" @type message: IRCMessage \"\"\" if len(message.MessageList) > 1 and (message.Command ==",
"return IRCResponse(ResponseType.Say, output, message.ReplyTo) if len(message.MessageList) > 1 and message.Command == \"lastsaid\": proc",
"the last time someone mentioned a given word or phrase' def execute(self, message):",
"someone mentioned a given word or phrase' def execute(self, message): \"\"\" @type message:",
"from IRCMessage import IRCMessage from IRCResponse import IRCResponse, ResponseType from CommandInterface import CommandInterface",
"> 1 and (message.Command == \"lastmention\" or message.Command == \"lastmentioned\"): proc = subprocess.Popen(['/usr/bin/php',",
"execute(self, message): \"\"\" @type message: IRCMessage \"\"\" if len(message.MessageList) > 1 and (message.Command",
"help = 'lastmention(ed)/lastsaid <text> - checks the log for the last time someone",
"IRCResponse import IRCResponse, ResponseType from CommandInterface import CommandInterface import subprocess class Command(CommandInterface): triggers",
"= subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mentionnottoday\"], stdout=subprocess.PIPE)",
"message.Command == \"lastsaid\": proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") +",
"['lastsaid', 'lastmention', 'lastmentioned'] help = 'lastmention(ed)/lastsaid <text> - checks the log for the",
"mentioned a given word or phrase' def execute(self, message): \"\"\" @type message: IRCMessage",
"message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mentionnottoday\"], stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say,",
"message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mention\"], stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say,",
"1 and message.Command == \"lastsaid\": proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\",",
"= ['lastsaid', 'lastmention', 'lastmentioned'] help = 'lastmention(ed)/lastsaid <text> - checks the log for",
"\"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mentionnottoday\"], stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say, output,",
"-*- from IRCMessage import IRCMessage from IRCResponse import IRCResponse, ResponseType from CommandInterface import",
"subprocess class Command(CommandInterface): triggers = ['lastsaid', 'lastmention', 'lastmentioned'] help = 'lastmention(ed)/lastsaid <text> -",
"1 and (message.Command == \"lastmention\" or message.Command == \"lastmentioned\"): proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php',",
"from CommandInterface import CommandInterface import subprocess class Command(CommandInterface): triggers = ['lastsaid', 'lastmention', 'lastmentioned']",
"\"\\\"\", message.ReplyTo, \"mention\"], stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say, output, message.ReplyTo) if len(message.MessageList)",
"import CommandInterface import subprocess class Command(CommandInterface): triggers = ['lastsaid', 'lastmention', 'lastmentioned'] help =",
"-*- coding: utf-8 -*- from IRCMessage import IRCMessage from IRCResponse import IRCResponse, ResponseType",
"proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mentionnottoday\"],",
"= subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mention\"], stdout=subprocess.PIPE)",
"IRCMessage from IRCResponse import IRCResponse, ResponseType from CommandInterface import CommandInterface import subprocess class",
"len(message.MessageList) > 1 and message.Command == \"lastsaid\": proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" +",
"\"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mentionnottoday\"], stdout=subprocess.PIPE) output = proc.stdout.read()",
"@type message: IRCMessage \"\"\" if len(message.MessageList) > 1 and (message.Command == \"lastmention\" or",
"'lastmentioned'] help = 'lastmention(ed)/lastsaid <text> - checks the log for the last time",
"IRCMessage \"\"\" if len(message.MessageList) > 1 and (message.Command == \"lastmention\" or message.Command ==",
"Command(CommandInterface): triggers = ['lastsaid', 'lastmention', 'lastmentioned'] help = 'lastmention(ed)/lastsaid <text> - checks the",
"== \"lastsaid\": proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\",",
"checks the log for the last time someone mentioned a given word or",
"import IRCResponse, ResponseType from CommandInterface import CommandInterface import subprocess class Command(CommandInterface): triggers =",
"\"\"\" @type message: IRCMessage \"\"\" if len(message.MessageList) > 1 and (message.Command == \"lastmention\"",
"> 1 and message.Command == \"lastsaid\": proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\",",
"or message.Command == \"lastmentioned\"): proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\")",
"== \"lastmention\" or message.Command == \"lastmentioned\"): proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\",",
"+ message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mention\"], stdout=subprocess.PIPE) output = proc.stdout.read() return",
"phrase' def execute(self, message): \"\"\" @type message: IRCMessage \"\"\" if len(message.MessageList) > 1",
"'lastmention', 'lastmentioned'] help = 'lastmention(ed)/lastsaid <text> - checks the log for the last",
"'lastmention(ed)/lastsaid <text> - checks the log for the last time someone mentioned a",
"word or phrase' def execute(self, message): \"\"\" @type message: IRCMessage \"\"\" if len(message.MessageList)",
"ResponseType from CommandInterface import CommandInterface import subprocess class Command(CommandInterface): triggers = ['lastsaid', 'lastmention',",
"= proc.stdout.read() return IRCResponse(ResponseType.Say, output, message.ReplyTo) if len(message.MessageList) > 1 and message.Command ==",
"<text> - checks the log for the last time someone mentioned a given",
"stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say, output, message.ReplyTo) if len(message.MessageList) > 1 and",
"triggers = ['lastsaid', 'lastmention', 'lastmentioned'] help = 'lastmention(ed)/lastsaid <text> - checks the log",
"(message.Command == \"lastmention\" or message.Command == \"lastmentioned\"): proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" +",
"\"\"\" if len(message.MessageList) > 1 and (message.Command == \"lastmention\" or message.Command == \"lastmentioned\"):",
"log for the last time someone mentioned a given word or phrase' def",
"the log for the last time someone mentioned a given word or phrase'",
"import subprocess class Command(CommandInterface): triggers = ['lastsaid', 'lastmention', 'lastmentioned'] help = 'lastmention(ed)/lastsaid <text>",
"coding: utf-8 -*- from IRCMessage import IRCMessage from IRCResponse import IRCResponse, ResponseType from",
"message.Command == \"lastmentioned\"): proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") +",
"\"lastsaid\": proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo,",
"proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mention\"],",
"output, message.ReplyTo) if len(message.MessageList) > 1 and message.Command == \"lastsaid\": proc = subprocess.Popen(['/usr/bin/php',",
"== \"lastmentioned\"): proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\",",
"\"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mention\"], stdout=subprocess.PIPE) output = proc.stdout.read()",
"message.ReplyTo, \"mention\"], stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say, output, message.ReplyTo) if len(message.MessageList) >",
"from IRCResponse import IRCResponse, ResponseType from CommandInterface import CommandInterface import subprocess class Command(CommandInterface):",
"+ \"\\\"\", message.ReplyTo, \"mention\"], stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say, output, message.ReplyTo) if",
"import IRCMessage from IRCResponse import IRCResponse, ResponseType from CommandInterface import CommandInterface import subprocess",
"or phrase' def execute(self, message): \"\"\" @type message: IRCMessage \"\"\" if len(message.MessageList) >",
"def execute(self, message): \"\"\" @type message: IRCMessage \"\"\" if len(message.MessageList) > 1 and",
"\"lastmention\" or message.Command == \"lastmentioned\"): proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\",",
"time someone mentioned a given word or phrase' def execute(self, message): \"\"\" @type",
"IRCResponse, ResponseType from CommandInterface import CommandInterface import subprocess class Command(CommandInterface): triggers = ['lastsaid',",
"message: IRCMessage \"\"\" if len(message.MessageList) > 1 and (message.Command == \"lastmention\" or message.Command",
"IRCMessage import IRCMessage from IRCResponse import IRCResponse, ResponseType from CommandInterface import CommandInterface import",
"\"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mention\"], stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say, output, message.ReplyTo)",
"if len(message.MessageList) > 1 and message.Command == \"lastsaid\": proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\"",
"CommandInterface import CommandInterface import subprocess class Command(CommandInterface): triggers = ['lastsaid', 'lastmention', 'lastmentioned'] help",
"+ message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mentionnottoday\"], stdout=subprocess.PIPE) output = proc.stdout.read() return",
"last time someone mentioned a given word or phrase' def execute(self, message): \"\"\"",
"len(message.MessageList) > 1 and (message.Command == \"lastmention\" or message.Command == \"lastmentioned\"): proc =",
"for the last time someone mentioned a given word or phrase' def execute(self,",
"- checks the log for the last time someone mentioned a given word",
"# -*- coding: utf-8 -*- from IRCMessage import IRCMessage from IRCResponse import IRCResponse,",
"'/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mention\"], stdout=subprocess.PIPE) output =",
"output = proc.stdout.read() return IRCResponse(ResponseType.Say, output, message.ReplyTo) if len(message.MessageList) > 1 and message.Command",
"subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\" + message.Parameters.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mention\"], stdout=subprocess.PIPE) output",
"\"mention\"], stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say, output, message.ReplyTo) if len(message.MessageList) > 1",
"IRCResponse(ResponseType.Say, output, message.ReplyTo) if len(message.MessageList) > 1 and message.Command == \"lastsaid\": proc =",
"\"\\\\\\n\") + \"\\\"\", message.ReplyTo, \"mentionnottoday\"], stdout=subprocess.PIPE) output = proc.stdout.read() return IRCResponse(ResponseType.Say, output, message.ReplyTo)",
"given word or phrase' def execute(self, message): \"\"\" @type message: IRCMessage \"\"\" if",
"and (message.Command == \"lastmention\" or message.Command == \"lastmentioned\"): proc = subprocess.Popen(['/usr/bin/php', '/opt/moronbot/loggrep.php', \"\\\"\""
] |
[
"list[Index], consolidate: bool = True, ) -> BlockManager: # Assertions disabled for performance",
"_form_blocks(arrays, names, axes, consolidate) mgr = BlockManager(blocks, axes) except ValueError as e: raise",
"provided, infer it from placment and values. \"\"\" if ndim is None: #",
") blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks = multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate ) blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]):",
"API for downstream libraries. We ask that downstream authors 1) Try to avoid",
"-1: extra_locs.append(i) continue v = arrays[name_idx] block_type = get_block_type(v) items_dict[block_type.__name__].append((i, v)) blocks: list[Block]",
"pandas_dtype, ) from pandas.core.arrays import DatetimeArray from pandas.core.construction import extract_array from pandas.core.indexes.api import",
"len(items_dict[\"ExtensionBlock\"]): external_blocks = [ ExtensionBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"ExtensionBlock\"] ]",
"None: dtype = pandas_dtype(dtype) values, dtype = extract_pandas_array(values, dtype, ndim) if klass is",
"else: ndim = 2 else: ndim = values.ndim return ndim def create_block_manager_from_arrays( arrays,",
"klass=None, ndim=None, dtype: Dtype | None = None ) -> Block: \"\"\" This",
"we can pass 1D dt64tz values values = extract_array(values, extract_numpy=True) values = ensure_block_shape(values,",
"construction_error, multi_blockify, simple_blockify, ) def make_block( values, placement, klass=None, ndim=None, dtype: Dtype |",
"consolidate: bool ) -> list[Block]: # put \"leftover\" items in float bucket, where",
"is not provided, infer it from placment and values. \"\"\" if ndim is",
"[ DatetimeTZBlock( ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i), ndim=2, ) for i, array in items_dict[\"DatetimeTZBlock\"] ]",
"list) # assert all(isinstance(x, Index) for x in axes) arrays = [extract_array(x, extract_numpy=True)",
"not None if not isinstance(values.dtype, np.dtype): if len(placement) != 1: ndim = 1",
"ExtensionBlock, check_ndim, ensure_block_shape, extract_pandas_array, get_block_type, maybe_coerce_values, new_block, ) from pandas.core.internals.managers import ( BlockManager,",
"analogue to blocks.new_block. We ask that downstream libraries use this rather than any",
"v = arrays[name_idx] block_type = get_block_type(v) items_dict[block_type.__name__].append((i, v)) blocks: list[Block] = [] if",
"# empty items -> dtype object block_values = np.empty(shape, dtype=object) block_values.fill(np.nan) na_block =",
") -> list[Block]: # put \"leftover\" items in float bucket, where else? #",
"names_idx.get_indexer_for(axes[0]) for i, name_idx in enumerate(names_indexer): if name_idx == -1: extra_locs.append(i) continue v",
"= names if names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx)) else: # Assertion disabled for performance",
"import ( is_datetime64tz_dtype, pandas_dtype, ) from pandas.core.arrays import DatetimeArray from pandas.core.construction import extract_array",
"extra_locs = [] names_idx = names if names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx)) else: #",
"in float bucket, where else? # generalize? items_dict: DefaultDict[str, list] = defaultdict(list) extra_locs",
"exposed here (or in core.internals) \"\"\" from __future__ import annotations from collections import",
"items_dict[block_type.__name__].append((i, v)) blocks: list[Block] = [] if len(items_dict[\"NumericBlock\"]): numeric_blocks = multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate",
"np from pandas._libs.internals import BlockPlacement from pandas._typing import ( ArrayLike, Dtype, ) from",
"construction_error(len(arrays), arrays[0].shape, axes, e) if consolidate: mgr._consolidate_inplace() return mgr def _form_blocks( arrays: list[ArrayLike],",
"for downstream libraries. We ask that downstream authors 1) Try to avoid using",
"return mgr def _form_blocks( arrays: list[ArrayLike], names: Index, axes: list[Index], consolidate: bool )",
"raise construction_error(len(arrays), arrays[0].shape, axes, e) if consolidate: mgr._consolidate_inplace() return mgr def _form_blocks( arrays:",
"= [] if len(items_dict[\"NumericBlock\"]): numeric_blocks = multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate ) blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]):",
"for performance # assert names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0]) for i, name_idx in enumerate(names_indexer):",
"array in items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]): external_blocks = [ ExtensionBlock(array, placement=BlockPlacement(i), ndim=2)",
"import BlockPlacement from pandas._typing import ( ArrayLike, Dtype, ) from pandas.core.dtypes.common import (",
"pseudo-public API for downstream libraries. We ask that downstream authors 1) Try to",
") blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks = [ DatetimeTZBlock( ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i), ndim=2, )",
"= names_idx.get_indexer_for(axes[0]) for i, name_idx in enumerate(names_indexer): if name_idx == -1: extra_locs.append(i) continue",
"ndim=2) for i, array in items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]): external_blocks = [",
"placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks) if len(extra_locs): shape =",
"names_indexer = np.arange(len(names_idx)) else: # Assertion disabled for performance # assert names_idx.intersection(axes[0]).is_unique names_indexer",
"block_values = np.empty(shape, dtype=object) block_values.fill(np.nan) na_block = new_block(block_values, placement=extra_locs, ndim=2) blocks.append(na_block) return blocks",
"for i, array in items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks) if len(extra_locs): shape = (len(extra_locs),) +",
"arrays: list[ArrayLike], names: Index, axes: list[Index], consolidate: bool ) -> list[Block]: # put",
"placement=placement) def maybe_infer_ndim(values, placement: BlockPlacement, ndim: int | None) -> int: \"\"\" If",
"import Index from pandas.core.internals.blocks import ( Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock, check_ndim, ensure_block_shape, extract_pandas_array,",
"try: blocks = _form_blocks(arrays, names, axes, consolidate) mgr = BlockManager(blocks, axes) except ValueError",
"constructor now assumes ndim is not None if not isinstance(values.dtype, np.dtype): if len(placement)",
"simple_blockify( items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate ) blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"]) > 0: cat_blocks = [",
"DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype): # pyarrow calls get here values = DatetimeArray._simple_new(values, dtype=dtype)",
"= ensure_block_shape(values, ndim) check_ndim(values, placement, ndim) values = maybe_coerce_values(values) return klass(values, ndim=ndim, placement=placement)",
"_form_blocks( arrays: list[ArrayLike], names: Index, axes: list[Index], consolidate: bool ) -> list[Block]: #",
"1) Try to avoid using internals directly altogether, and failing that, 2) Use",
"if len(items_dict[\"ObjectBlock\"]) > 0: object_blocks = simple_blockify( items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate ) blocks.extend(object_blocks) if",
"= [ ExtensionBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks) if",
"arrays = [extract_array(x, extract_numpy=True) for x in arrays] try: blocks = _form_blocks(arrays, names,",
"only functions exposed here (or in core.internals) \"\"\" from __future__ import annotations from",
"placment and values. \"\"\" if ndim is None: # GH#38134 Block constructor now",
"elif klass is DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype): # pyarrow calls get here values",
"maybe_coerce_values(values) return klass(values, ndim=ndim, placement=placement) def maybe_infer_ndim(values, placement: BlockPlacement, ndim: int | None)",
"names_indexer = names_idx.get_indexer_for(axes[0]) for i, name_idx in enumerate(names_indexer): if name_idx == -1: extra_locs.append(i)",
"def maybe_infer_ndim(values, placement: BlockPlacement, ndim: int | None) -> int: \"\"\" If `ndim`",
"= arrays[name_idx] block_type = get_block_type(v) items_dict[block_type.__name__].append((i, v)) blocks: list[Block] = [] if len(items_dict[\"NumericBlock\"]):",
"CategoricalBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]): external_blocks",
"ExtensionBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks) if len(extra_locs): shape",
"new_block, ) from pandas.core.internals.managers import ( BlockManager, construction_error, multi_blockify, simple_blockify, ) def make_block(",
"float bucket, where else? # generalize? items_dict: DefaultDict[str, list] = defaultdict(list) extra_locs =",
"to avoid using internals directly altogether, and failing that, 2) Use only functions",
"| None) -> int: \"\"\" If `ndim` is not provided, infer it from",
"e) if consolidate: mgr._consolidate_inplace() return mgr def _form_blocks( arrays: list[ArrayLike], names: Index, axes:",
"ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i), ndim=2, ) for i, array in items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks) if",
"2 else: ndim = values.ndim return ndim def create_block_manager_from_arrays( arrays, names: Index, axes:",
"extract_numpy=True) for x in arrays] try: blocks = _form_blocks(arrays, names, axes, consolidate) mgr",
"[ CategoricalBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]):",
"and not is_datetime64tz_dtype(values.dtype): # pyarrow calls get here values = DatetimeArray._simple_new(values, dtype=dtype) if",
"pass 1D dt64tz values values = extract_array(values, extract_numpy=True) values = ensure_block_shape(values, ndim) check_ndim(values,",
"in enumerate(names_indexer): if name_idx == -1: extra_locs.append(i) continue v = arrays[name_idx] block_type =",
"= maybe_infer_ndim(values, placement, ndim) if is_datetime64tz_dtype(values.dtype): # GH#41168 ensure we can pass 1D",
"for x in arrays] try: blocks = _form_blocks(arrays, names, axes, consolidate) mgr =",
"multi_blockify, simple_blockify, ) def make_block( values, placement, klass=None, ndim=None, dtype: Dtype | None",
") -> Block: \"\"\" This is a pseudo-public analogue to blocks.new_block. We ask",
"If `ndim` is not provided, infer it from placment and values. \"\"\" if",
"is not None if not isinstance(values.dtype, np.dtype): if len(placement) != 1: ndim =",
"blocks = _form_blocks(arrays, names, axes, consolidate) mgr = BlockManager(blocks, axes) except ValueError as",
"DatetimeTZBlock, ExtensionBlock, check_ndim, ensure_block_shape, extract_pandas_array, get_block_type, maybe_coerce_values, new_block, ) from pandas.core.internals.managers import (",
"values.dtype klass = get_block_type(values, dtype) elif klass is DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype): #",
"arrays[name_idx] block_type = get_block_type(v) items_dict[block_type.__name__].append((i, v)) blocks: list[Block] = [] if len(items_dict[\"NumericBlock\"]): numeric_blocks",
"using internals directly altogether, and failing that, 2) Use only functions exposed here",
"for i, name_idx in enumerate(names_indexer): if name_idx == -1: extra_locs.append(i) continue v =",
"array in items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks) if len(extra_locs): shape = (len(extra_locs),) + tuple(len(x) for",
"from pandas.core.arrays import DatetimeArray from pandas.core.construction import extract_array from pandas.core.indexes.api import Index from",
"extract_array from pandas.core.indexes.api import Index from pandas.core.internals.blocks import ( Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock,",
"libraries use this rather than any fully-internal APIs, including but not limited to:",
"this rather than any fully-internal APIs, including but not limited to: - core.internals.blocks.make_block",
"axes, e) if consolidate: mgr._consolidate_inplace() return mgr def _form_blocks( arrays: list[ArrayLike], names: Index,",
") -> BlockManager: # Assertions disabled for performance # assert isinstance(names, Index) #",
"not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) ndim = maybe_infer_ndim(values, placement, ndim) if is_datetime64tz_dtype(values.dtype):",
"directly altogether, and failing that, 2) Use only functions exposed here (or in",
"pyarrow calls get here values = DatetimeArray._simple_new(values, dtype=dtype) if not isinstance(placement, BlockPlacement): placement",
"i, array in items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]): external_blocks = [ ExtensionBlock(array, placement=BlockPlacement(i),",
"items_dict[\"NumericBlock\"], consolidate=consolidate ) blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks = multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate ) blocks.extend(dtlike_blocks)",
"that downstream libraries use this rather than any fully-internal APIs, including but not",
"Index from pandas.core.internals.blocks import ( Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock, check_ndim, ensure_block_shape, extract_pandas_array, get_block_type,",
"values, dtype = extract_pandas_array(values, dtype, ndim) if klass is None: dtype = dtype",
"else: ndim = values.ndim return ndim def create_block_manager_from_arrays( arrays, names: Index, axes: list[Index],",
"dtype) elif klass is DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype): # pyarrow calls get here",
"ensure we can pass 1D dt64tz values values = extract_array(values, extract_numpy=True) values =",
"from placment and values. \"\"\" if ndim is None: # GH#38134 Block constructor",
") from pandas.core.dtypes.common import ( is_datetime64tz_dtype, pandas_dtype, ) from pandas.core.arrays import DatetimeArray from",
"isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) ndim = maybe_infer_ndim(values, placement, ndim) if is_datetime64tz_dtype(values.dtype): #",
"We ask that downstream libraries use this rather than any fully-internal APIs, including",
"dtype is not None: dtype = pandas_dtype(dtype) values, dtype = extract_pandas_array(values, dtype, ndim)",
"extract_numpy=True) values = ensure_block_shape(values, ndim) check_ndim(values, placement, ndim) values = maybe_coerce_values(values) return klass(values,",
"continue v = arrays[name_idx] block_type = get_block_type(v) items_dict[block_type.__name__].append((i, v)) blocks: list[Block] = []",
"BlockPlacement, ndim: int | None) -> int: \"\"\" If `ndim` is not provided,",
"pandas.core.construction import extract_array from pandas.core.indexes.api import Index from pandas.core.internals.blocks import ( Block, CategoricalBlock,",
"list[Index], consolidate: bool ) -> list[Block]: # put \"leftover\" items in float bucket,",
"ndim is None: # GH#38134 Block constructor now assumes ndim is not None",
"else? # generalize? items_dict: DefaultDict[str, list] = defaultdict(list) extra_locs = [] names_idx =",
"BlockPlacement): placement = BlockPlacement(placement) ndim = maybe_infer_ndim(values, placement, ndim) if is_datetime64tz_dtype(values.dtype): # GH#41168",
"> 0: object_blocks = simple_blockify( items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate ) blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"]) >",
"for i, array in items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"]) > 0: object_blocks =",
"in items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks) if len(extra_locs): shape = (len(extra_locs),) + tuple(len(x) for x",
"from collections import defaultdict from typing import DefaultDict import numpy as np from",
"values = DatetimeArray._simple_new(values, dtype=dtype) if not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) ndim =",
"altogether, and failing that, 2) Use only functions exposed here (or in core.internals)",
"items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate ) blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"]) > 0: cat_blocks = [ CategoricalBlock(array,",
"for x in axes) arrays = [extract_array(x, extract_numpy=True) for x in arrays] try:",
"np.arange(len(names_idx)) else: # Assertion disabled for performance # assert names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0])",
"pseudo-public analogue to blocks.new_block. We ask that downstream libraries use this rather than",
"DatetimeTZBlock( ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i), ndim=2, ) for i, array in items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks)",
"# pyarrow calls get here values = DatetimeArray._simple_new(values, dtype=dtype) if not isinstance(placement, BlockPlacement):",
") from pandas.core.arrays import DatetimeArray from pandas.core.construction import extract_array from pandas.core.indexes.api import Index",
"get_block_type(v) items_dict[block_type.__name__].append((i, v)) blocks: list[Block] = [] if len(items_dict[\"NumericBlock\"]): numeric_blocks = multi_blockify( items_dict[\"NumericBlock\"],",
"0: cat_blocks = [ CategoricalBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"CategoricalBlock\"] ]",
"assert isinstance(names, Index) # assert isinstance(axes, list) # assert all(isinstance(x, Index) for x",
"and failing that, 2) Use only functions exposed here (or in core.internals) \"\"\"",
"placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]): external_blocks =",
"object block_values = np.empty(shape, dtype=object) block_values.fill(np.nan) na_block = new_block(block_values, placement=extra_locs, ndim=2) blocks.append(na_block) return",
"pandas.core.internals.blocks import ( Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock, check_ndim, ensure_block_shape, extract_pandas_array, get_block_type, maybe_coerce_values, new_block,",
"Block constructor now assumes ndim is not None if not isinstance(values.dtype, np.dtype): if",
"placement, klass=None, ndim=None, dtype: Dtype | None = None ) -> Block: \"\"\"",
"extract_pandas_array(values, dtype, ndim) if klass is None: dtype = dtype or values.dtype klass",
"True, ) -> BlockManager: # Assertions disabled for performance # assert isinstance(names, Index)",
"# put \"leftover\" items in float bucket, where else? # generalize? items_dict: DefaultDict[str,",
"placement: BlockPlacement, ndim: int | None) -> int: \"\"\" If `ndim` is not",
"name_idx in enumerate(names_indexer): if name_idx == -1: extra_locs.append(i) continue v = arrays[name_idx] block_type",
"axes) except ValueError as e: raise construction_error(len(arrays), arrays[0].shape, axes, e) if consolidate: mgr._consolidate_inplace()",
"Block.__init__ \"\"\" if dtype is not None: dtype = pandas_dtype(dtype) values, dtype =",
"isinstance(axes, list) # assert all(isinstance(x, Index) for x in axes) arrays = [extract_array(x,",
"dtype=dtype) if not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) ndim = maybe_infer_ndim(values, placement, ndim)",
"Index, axes: list[Index], consolidate: bool ) -> list[Block]: # put \"leftover\" items in",
"i, array in items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"]) > 0: object_blocks = simple_blockify(",
"from pandas.core.internals.blocks import ( Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock, check_ndim, ensure_block_shape, extract_pandas_array, get_block_type, maybe_coerce_values,",
"Assertion disabled for performance # assert names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0]) for i, name_idx",
"( BlockManager, construction_error, multi_blockify, simple_blockify, ) def make_block( values, placement, klass=None, ndim=None, dtype:",
"(len(extra_locs),) + tuple(len(x) for x in axes[1:]) # empty items -> dtype object",
"( ArrayLike, Dtype, ) from pandas.core.dtypes.common import ( is_datetime64tz_dtype, pandas_dtype, ) from pandas.core.arrays",
"Dtype, ) from pandas.core.dtypes.common import ( is_datetime64tz_dtype, pandas_dtype, ) from pandas.core.arrays import DatetimeArray",
"from pandas.core.indexes.api import Index from pandas.core.internals.blocks import ( Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock, check_ndim,",
"- Block.__init__ \"\"\" if dtype is not None: dtype = pandas_dtype(dtype) values, dtype",
"rather than any fully-internal APIs, including but not limited to: - core.internals.blocks.make_block -",
"assert isinstance(axes, list) # assert all(isinstance(x, Index) for x in axes) arrays =",
"fully-internal APIs, including but not limited to: - core.internals.blocks.make_block - Block.make_block - Block.make_block_same_class",
"than any fully-internal APIs, including but not limited to: - core.internals.blocks.make_block - Block.make_block",
"= dtype or values.dtype klass = get_block_type(values, dtype) elif klass is DatetimeTZBlock and",
"if name_idx == -1: extra_locs.append(i) continue v = arrays[name_idx] block_type = get_block_type(v) items_dict[block_type.__name__].append((i,",
"that downstream authors 1) Try to avoid using internals directly altogether, and failing",
"Assertions disabled for performance # assert isinstance(names, Index) # assert isinstance(axes, list) #",
"import DefaultDict import numpy as np from pandas._libs.internals import BlockPlacement from pandas._typing import",
"None if not isinstance(values.dtype, np.dtype): if len(placement) != 1: ndim = 1 else:",
"in items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"]) > 0: object_blocks = simple_blockify( items_dict[\"ObjectBlock\"], np.object_,",
"-> Block: \"\"\" This is a pseudo-public analogue to blocks.new_block. We ask that",
"pandas.core.arrays import DatetimeArray from pandas.core.construction import extract_array from pandas.core.indexes.api import Index from pandas.core.internals.blocks",
"or values.dtype klass = get_block_type(values, dtype) elif klass is DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype):",
"from pandas.core.dtypes.common import ( is_datetime64tz_dtype, pandas_dtype, ) from pandas.core.arrays import DatetimeArray from pandas.core.construction",
"pandas._typing import ( ArrayLike, Dtype, ) from pandas.core.dtypes.common import ( is_datetime64tz_dtype, pandas_dtype, )",
"= multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate ) blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks = [ DatetimeTZBlock( ensure_block_shape(extract_array(array),",
"if len(items_dict[\"CategoricalBlock\"]) > 0: cat_blocks = [ CategoricalBlock(array, placement=BlockPlacement(i), ndim=2) for i, array",
"if not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) ndim = maybe_infer_ndim(values, placement, ndim) if",
"| None = None ) -> Block: \"\"\" This is a pseudo-public analogue",
"names: Index, axes: list[Index], consolidate: bool = True, ) -> BlockManager: # Assertions",
"# assert names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0]) for i, name_idx in enumerate(names_indexer): if name_idx",
"import ( Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock, check_ndim, ensure_block_shape, extract_pandas_array, get_block_type, maybe_coerce_values, new_block, )",
"\"\"\" If `ndim` is not provided, infer it from placment and values. \"\"\"",
"[extract_array(x, extract_numpy=True) for x in arrays] try: blocks = _form_blocks(arrays, names, axes, consolidate)",
"len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks = [ DatetimeTZBlock( ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i), ndim=2, ) for i, array",
"including but not limited to: - core.internals.blocks.make_block - Block.make_block - Block.make_block_same_class - Block.__init__",
"as e: raise construction_error(len(arrays), arrays[0].shape, axes, e) if consolidate: mgr._consolidate_inplace() return mgr def",
"e: raise construction_error(len(arrays), arrays[0].shape, axes, e) if consolidate: mgr._consolidate_inplace() return mgr def _form_blocks(",
"consolidate=consolidate ) blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"]) > 0: cat_blocks = [ CategoricalBlock(array, placement=BlockPlacement(i), ndim=2)",
"\"leftover\" items in float bucket, where else? # generalize? items_dict: DefaultDict[str, list] =",
"that, 2) Use only functions exposed here (or in core.internals) \"\"\" from __future__",
"- core.internals.blocks.make_block - Block.make_block - Block.make_block_same_class - Block.__init__ \"\"\" if dtype is not",
"= pandas_dtype(dtype) values, dtype = extract_pandas_array(values, dtype, ndim) if klass is None: dtype",
"import DatetimeArray from pandas.core.construction import extract_array from pandas.core.indexes.api import Index from pandas.core.internals.blocks import",
"list] = defaultdict(list) extra_locs = [] names_idx = names if names_idx.equals(axes[0]): names_indexer =",
"names if names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx)) else: # Assertion disabled for performance #",
"= 1 else: ndim = 2 else: ndim = values.ndim return ndim def",
"klass = get_block_type(values, dtype) elif klass is DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype): # pyarrow",
") from pandas.core.internals.managers import ( BlockManager, construction_error, multi_blockify, simple_blockify, ) def make_block( values,",
"if len(extra_locs): shape = (len(extra_locs),) + tuple(len(x) for x in axes[1:]) # empty",
"= extract_pandas_array(values, dtype, ndim) if klass is None: dtype = dtype or values.dtype",
"\"\"\" if ndim is None: # GH#38134 Block constructor now assumes ndim is",
"axes, consolidate) mgr = BlockManager(blocks, axes) except ValueError as e: raise construction_error(len(arrays), arrays[0].shape,",
"external_blocks = [ ExtensionBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks)",
"= [extract_array(x, extract_numpy=True) for x in arrays] try: blocks = _form_blocks(arrays, names, axes,",
"get_block_type, maybe_coerce_values, new_block, ) from pandas.core.internals.managers import ( BlockManager, construction_error, multi_blockify, simple_blockify, )",
"items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate ) blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks = [ DatetimeTZBlock( ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i),",
"ensure_block_shape(values, ndim) check_ndim(values, placement, ndim) values = maybe_coerce_values(values) return klass(values, ndim=ndim, placement=placement) def",
"Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock, check_ndim, ensure_block_shape, extract_pandas_array, get_block_type, maybe_coerce_values, new_block, ) from pandas.core.internals.managers",
"Try to avoid using internals directly altogether, and failing that, 2) Use only",
"0: object_blocks = simple_blockify( items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate ) blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"]) > 0:",
"= maybe_coerce_values(values) return klass(values, ndim=ndim, placement=placement) def maybe_infer_ndim(values, placement: BlockPlacement, ndim: int |",
"where else? # generalize? items_dict: DefaultDict[str, list] = defaultdict(list) extra_locs = [] names_idx",
"# generalize? items_dict: DefaultDict[str, list] = defaultdict(list) extra_locs = [] names_idx = names",
"klass is None: dtype = dtype or values.dtype klass = get_block_type(values, dtype) elif",
"ndim = maybe_infer_ndim(values, placement, ndim) if is_datetime64tz_dtype(values.dtype): # GH#41168 ensure we can pass",
"1: ndim = 1 else: ndim = 2 else: ndim = values.ndim return",
"blocks: list[Block] = [] if len(items_dict[\"NumericBlock\"]): numeric_blocks = multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate ) blocks.extend(numeric_blocks)",
"(or in core.internals) \"\"\" from __future__ import annotations from collections import defaultdict from",
"This is a pseudo-public analogue to blocks.new_block. We ask that downstream libraries use",
"placement, ndim) if is_datetime64tz_dtype(values.dtype): # GH#41168 ensure we can pass 1D dt64tz values",
"placement=BlockPlacement(i), ndim=2, ) for i, array in items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"]) >",
"is None: # GH#38134 Block constructor now assumes ndim is not None if",
"list[ArrayLike], names: Index, axes: list[Index], consolidate: bool ) -> list[Block]: # put \"leftover\"",
"not limited to: - core.internals.blocks.make_block - Block.make_block - Block.make_block_same_class - Block.__init__ \"\"\" if",
"] blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"]) > 0: object_blocks = simple_blockify( items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate )",
"x in axes[1:]) # empty items -> dtype object block_values = np.empty(shape, dtype=object)",
"simple_blockify, ) def make_block( values, placement, klass=None, ndim=None, dtype: Dtype | None =",
"klass is DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype): # pyarrow calls get here values =",
"= BlockPlacement(placement) ndim = maybe_infer_ndim(values, placement, ndim) if is_datetime64tz_dtype(values.dtype): # GH#41168 ensure we",
"pandas.core.indexes.api import Index from pandas.core.internals.blocks import ( Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock, check_ndim, ensure_block_shape,",
"2) Use only functions exposed here (or in core.internals) \"\"\" from __future__ import",
"dtype = pandas_dtype(dtype) values, dtype = extract_pandas_array(values, dtype, ndim) if klass is None:",
"else: # Assertion disabled for performance # assert names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0]) for",
"-> dtype object block_values = np.empty(shape, dtype=object) block_values.fill(np.nan) na_block = new_block(block_values, placement=extra_locs, ndim=2)",
"libraries. We ask that downstream authors 1) Try to avoid using internals directly",
"None: dtype = dtype or values.dtype klass = get_block_type(values, dtype) elif klass is",
"np.object_, consolidate=consolidate ) blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"]) > 0: cat_blocks = [ CategoricalBlock(array, placement=BlockPlacement(i),",
"items_dict: DefaultDict[str, list] = defaultdict(list) extra_locs = [] names_idx = names if names_idx.equals(axes[0]):",
"arrays[0].shape, axes, e) if consolidate: mgr._consolidate_inplace() return mgr def _form_blocks( arrays: list[ArrayLike], names:",
"internals directly altogether, and failing that, 2) Use only functions exposed here (or",
"= BlockManager(blocks, axes) except ValueError as e: raise construction_error(len(arrays), arrays[0].shape, axes, e) if",
"!= 1: ndim = 1 else: ndim = 2 else: ndim = values.ndim",
"to blocks.new_block. We ask that downstream libraries use this rather than any fully-internal",
"placement, ndim) values = maybe_coerce_values(values) return klass(values, ndim=ndim, placement=placement) def maybe_infer_ndim(values, placement: BlockPlacement,",
"names, axes, consolidate) mgr = BlockManager(blocks, axes) except ValueError as e: raise construction_error(len(arrays),",
"i, name_idx in enumerate(names_indexer): if name_idx == -1: extra_locs.append(i) continue v = arrays[name_idx]",
"items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]): external_blocks = [ ExtensionBlock(array, placement=BlockPlacement(i), ndim=2) for i,",
"len(placement) != 1: ndim = 1 else: ndim = 2 else: ndim =",
"if klass is None: dtype = dtype or values.dtype klass = get_block_type(values, dtype)",
"= np.arange(len(names_idx)) else: # Assertion disabled for performance # assert names_idx.intersection(axes[0]).is_unique names_indexer =",
"[] if len(items_dict[\"NumericBlock\"]): numeric_blocks = multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate ) blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks",
"2), placement=BlockPlacement(i), ndim=2, ) for i, array in items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"])",
"performance # assert names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0]) for i, name_idx in enumerate(names_indexer): if",
"ndim = 1 else: ndim = 2 else: ndim = values.ndim return ndim",
"ndim is not None if not isinstance(values.dtype, np.dtype): if len(placement) != 1: ndim",
"\"\"\" if dtype is not None: dtype = pandas_dtype(dtype) values, dtype = extract_pandas_array(values,",
"BlockPlacement(placement) ndim = maybe_infer_ndim(values, placement, ndim) if is_datetime64tz_dtype(values.dtype): # GH#41168 ensure we can",
"-> BlockManager: # Assertions disabled for performance # assert isinstance(names, Index) # assert",
"names_idx = names if names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx)) else: # Assertion disabled for",
"ndim=2, ) for i, array in items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"]) > 0:",
"Index) for x in axes) arrays = [extract_array(x, extract_numpy=True) for x in arrays]",
"= [ CategoricalBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks) if",
"if len(placement) != 1: ndim = 1 else: ndim = 2 else: ndim",
"isinstance(values.dtype, np.dtype): if len(placement) != 1: ndim = 1 else: ndim = 2",
"for i, array in items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]): external_blocks = [ ExtensionBlock(array,",
"names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx)) else: # Assertion disabled for performance # assert names_idx.intersection(axes[0]).is_unique",
"performance # assert isinstance(names, Index) # assert isinstance(axes, list) # assert all(isinstance(x, Index)",
"] blocks.extend(external_blocks) if len(extra_locs): shape = (len(extra_locs),) + tuple(len(x) for x in axes[1:])",
"] blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]): external_blocks = [ ExtensionBlock(array, placement=BlockPlacement(i), ndim=2) for i, array",
"\"\"\" This is a pseudo-public analogue to blocks.new_block. We ask that downstream libraries",
"ValueError as e: raise construction_error(len(arrays), arrays[0].shape, axes, e) if consolidate: mgr._consolidate_inplace() return mgr",
"cat_blocks = [ CategoricalBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks)",
"disabled for performance # assert isinstance(names, Index) # assert isinstance(axes, list) # assert",
"names: Index, axes: list[Index], consolidate: bool ) -> list[Block]: # put \"leftover\" items",
"if not isinstance(values.dtype, np.dtype): if len(placement) != 1: ndim = 1 else: ndim",
"items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"]) > 0: object_blocks = simple_blockify( items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate",
"ask that downstream libraries use this rather than any fully-internal APIs, including but",
"any fully-internal APIs, including but not limited to: - core.internals.blocks.make_block - Block.make_block -",
"klass(values, ndim=ndim, placement=placement) def maybe_infer_ndim(values, placement: BlockPlacement, ndim: int | None) -> int:",
"create_block_manager_from_arrays( arrays, names: Index, axes: list[Index], consolidate: bool = True, ) -> BlockManager:",
"= multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate ) blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks = multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate",
"maybe_coerce_values, new_block, ) from pandas.core.internals.managers import ( BlockManager, construction_error, multi_blockify, simple_blockify, ) def",
"downstream libraries use this rather than any fully-internal APIs, including but not limited",
"dtype object block_values = np.empty(shape, dtype=object) block_values.fill(np.nan) na_block = new_block(block_values, placement=extra_locs, ndim=2) blocks.append(na_block)",
"None ) -> Block: \"\"\" This is a pseudo-public analogue to blocks.new_block. We",
"items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks) if len(extra_locs): shape = (len(extra_locs),) + tuple(len(x) for x in",
"from __future__ import annotations from collections import defaultdict from typing import DefaultDict import",
"numeric_blocks = multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate ) blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks = multi_blockify( items_dict[\"DatetimeLikeBlock\"],",
"def make_block( values, placement, klass=None, ndim=None, dtype: Dtype | None = None )",
"maybe_infer_ndim(values, placement, ndim) if is_datetime64tz_dtype(values.dtype): # GH#41168 ensure we can pass 1D dt64tz",
"get here values = DatetimeArray._simple_new(values, dtype=dtype) if not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement)",
"APIs, including but not limited to: - core.internals.blocks.make_block - Block.make_block - Block.make_block_same_class -",
"= get_block_type(v) items_dict[block_type.__name__].append((i, v)) blocks: list[Block] = [] if len(items_dict[\"NumericBlock\"]): numeric_blocks = multi_blockify(",
"( Block, CategoricalBlock, DatetimeTZBlock, ExtensionBlock, check_ndim, ensure_block_shape, extract_pandas_array, get_block_type, maybe_coerce_values, new_block, ) from",
"consolidate) mgr = BlockManager(blocks, axes) except ValueError as e: raise construction_error(len(arrays), arrays[0].shape, axes,",
"from pandas._typing import ( ArrayLike, Dtype, ) from pandas.core.dtypes.common import ( is_datetime64tz_dtype, pandas_dtype,",
"ndim) if is_datetime64tz_dtype(values.dtype): # GH#41168 ensure we can pass 1D dt64tz values values",
"limited to: - core.internals.blocks.make_block - Block.make_block - Block.make_block_same_class - Block.__init__ \"\"\" if dtype",
"DatetimeArray._simple_new(values, dtype=dtype) if not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) ndim = maybe_infer_ndim(values, placement,",
"here values = DatetimeArray._simple_new(values, dtype=dtype) if not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) ndim",
"return klass(values, ndim=ndim, placement=placement) def maybe_infer_ndim(values, placement: BlockPlacement, ndim: int | None) ->",
"not is_datetime64tz_dtype(values.dtype): # pyarrow calls get here values = DatetimeArray._simple_new(values, dtype=dtype) if not",
"axes: list[Index], consolidate: bool = True, ) -> BlockManager: # Assertions disabled for",
"def _form_blocks( arrays: list[ArrayLike], names: Index, axes: list[Index], consolidate: bool ) -> list[Block]:",
"items -> dtype object block_values = np.empty(shape, dtype=object) block_values.fill(np.nan) na_block = new_block(block_values, placement=extra_locs,",
"# GH#41168 ensure we can pass 1D dt64tz values values = extract_array(values, extract_numpy=True)",
"= defaultdict(list) extra_locs = [] names_idx = names if names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx))",
"if len(items_dict[\"NumericBlock\"]): numeric_blocks = multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate ) blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks =",
"__future__ import annotations from collections import defaultdict from typing import DefaultDict import numpy",
"collections import defaultdict from typing import DefaultDict import numpy as np from pandas._libs.internals",
"bucket, where else? # generalize? items_dict: DefaultDict[str, list] = defaultdict(list) extra_locs = []",
"dtype = extract_pandas_array(values, dtype, ndim) if klass is None: dtype = dtype or",
"blocks.extend(external_blocks) if len(extra_locs): shape = (len(extra_locs),) + tuple(len(x) for x in axes[1:]) #",
"to: - core.internals.blocks.make_block - Block.make_block - Block.make_block_same_class - Block.__init__ \"\"\" if dtype is",
"from pandas._libs.internals import BlockPlacement from pandas._typing import ( ArrayLike, Dtype, ) from pandas.core.dtypes.common",
"import extract_array from pandas.core.indexes.api import Index from pandas.core.internals.blocks import ( Block, CategoricalBlock, DatetimeTZBlock,",
"len(items_dict[\"CategoricalBlock\"]) > 0: cat_blocks = [ CategoricalBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in",
"list[Block] = [] if len(items_dict[\"NumericBlock\"]): numeric_blocks = multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate ) blocks.extend(numeric_blocks) if",
"name_idx == -1: extra_locs.append(i) continue v = arrays[name_idx] block_type = get_block_type(v) items_dict[block_type.__name__].append((i, v))",
"axes) arrays = [extract_array(x, extract_numpy=True) for x in arrays] try: blocks = _form_blocks(arrays,",
"blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"]) > 0: cat_blocks = [ CategoricalBlock(array, placement=BlockPlacement(i), ndim=2) for i,",
"DatetimeArray from pandas.core.construction import extract_array from pandas.core.indexes.api import Index from pandas.core.internals.blocks import (",
"block_type = get_block_type(v) items_dict[block_type.__name__].append((i, v)) blocks: list[Block] = [] if len(items_dict[\"NumericBlock\"]): numeric_blocks =",
"consolidate: bool = True, ) -> BlockManager: # Assertions disabled for performance #",
"BlockManager, construction_error, multi_blockify, simple_blockify, ) def make_block( values, placement, klass=None, ndim=None, dtype: Dtype",
"a pseudo-public API for downstream libraries. We ask that downstream authors 1) Try",
"GH#38134 Block constructor now assumes ndim is not None if not isinstance(values.dtype, np.dtype):",
"is_datetime64tz_dtype(values.dtype): # GH#41168 ensure we can pass 1D dt64tz values values = extract_array(values,",
"extract_pandas_array, get_block_type, maybe_coerce_values, new_block, ) from pandas.core.internals.managers import ( BlockManager, construction_error, multi_blockify, simple_blockify,",
"values = maybe_coerce_values(values) return klass(values, ndim=ndim, placement=placement) def maybe_infer_ndim(values, placement: BlockPlacement, ndim: int",
"blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks = [ DatetimeTZBlock( ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i), ndim=2, ) for",
"= values.ndim return ndim def create_block_manager_from_arrays( arrays, names: Index, axes: list[Index], consolidate: bool",
"numpy as np from pandas._libs.internals import BlockPlacement from pandas._typing import ( ArrayLike, Dtype,",
"all(isinstance(x, Index) for x in axes) arrays = [extract_array(x, extract_numpy=True) for x in",
"import numpy as np from pandas._libs.internals import BlockPlacement from pandas._typing import ( ArrayLike,",
"items in float bucket, where else? # generalize? items_dict: DefaultDict[str, list] = defaultdict(list)",
"disabled for performance # assert names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0]) for i, name_idx in",
"BlockManager: # Assertions disabled for performance # assert isinstance(names, Index) # assert isinstance(axes,",
"dtype or values.dtype klass = get_block_type(values, dtype) elif klass is DatetimeTZBlock and not",
"len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks = multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate ) blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks = [",
"ndim) values = maybe_coerce_values(values) return klass(values, ndim=ndim, placement=placement) def maybe_infer_ndim(values, placement: BlockPlacement, ndim:",
"import ( ArrayLike, Dtype, ) from pandas.core.dtypes.common import ( is_datetime64tz_dtype, pandas_dtype, ) from",
"+ tuple(len(x) for x in axes[1:]) # empty items -> dtype object block_values",
"-> int: \"\"\" If `ndim` is not provided, infer it from placment and",
"int | None) -> int: \"\"\" If `ndim` is not provided, infer it",
"> 0: cat_blocks = [ CategoricalBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"CategoricalBlock\"]",
"here (or in core.internals) \"\"\" from __future__ import annotations from collections import defaultdict",
"core.internals) \"\"\" from __future__ import annotations from collections import defaultdict from typing import",
"= True, ) -> BlockManager: # Assertions disabled for performance # assert isinstance(names,",
"ensure_block_shape, extract_pandas_array, get_block_type, maybe_coerce_values, new_block, ) from pandas.core.internals.managers import ( BlockManager, construction_error, multi_blockify,",
"calls get here values = DatetimeArray._simple_new(values, dtype=dtype) if not isinstance(placement, BlockPlacement): placement =",
"assert all(isinstance(x, Index) for x in axes) arrays = [extract_array(x, extract_numpy=True) for x",
"= [] names_idx = names if names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx)) else: # Assertion",
"names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0]) for i, name_idx in enumerate(names_indexer): if name_idx == -1:",
"enumerate(names_indexer): if name_idx == -1: extra_locs.append(i) continue v = arrays[name_idx] block_type = get_block_type(v)",
"if is_datetime64tz_dtype(values.dtype): # GH#41168 ensure we can pass 1D dt64tz values values =",
"if consolidate: mgr._consolidate_inplace() return mgr def _form_blocks( arrays: list[ArrayLike], names: Index, axes: list[Index],",
"GH#41168 ensure we can pass 1D dt64tz values values = extract_array(values, extract_numpy=True) values",
"not provided, infer it from placment and values. \"\"\" if ndim is None:",
"= 2 else: ndim = values.ndim return ndim def create_block_manager_from_arrays( arrays, names: Index,",
"None: # GH#38134 Block constructor now assumes ndim is not None if not",
"We ask that downstream authors 1) Try to avoid using internals directly altogether,",
"failing that, 2) Use only functions exposed here (or in core.internals) \"\"\" from",
"is DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype): # pyarrow calls get here values = DatetimeArray._simple_new(values,",
"len(items_dict[\"ObjectBlock\"]) > 0: object_blocks = simple_blockify( items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate ) blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"])",
"shape = (len(extra_locs),) + tuple(len(x) for x in axes[1:]) # empty items ->",
"= (len(extra_locs),) + tuple(len(x) for x in axes[1:]) # empty items -> dtype",
"mgr._consolidate_inplace() return mgr def _form_blocks( arrays: list[ArrayLike], names: Index, axes: list[Index], consolidate: bool",
"# Assertions disabled for performance # assert isinstance(names, Index) # assert isinstance(axes, list)",
"tuple(len(x) for x in axes[1:]) # empty items -> dtype object block_values =",
"import defaultdict from typing import DefaultDict import numpy as np from pandas._libs.internals import",
"v)) blocks: list[Block] = [] if len(items_dict[\"NumericBlock\"]): numeric_blocks = multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate )",
"values. \"\"\" if ndim is None: # GH#38134 Block constructor now assumes ndim",
"authors 1) Try to avoid using internals directly altogether, and failing that, 2)",
"except ValueError as e: raise construction_error(len(arrays), arrays[0].shape, axes, e) if consolidate: mgr._consolidate_inplace() return",
"if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks = [ DatetimeTZBlock( ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i), ndim=2, ) for i,",
"= [ DatetimeTZBlock( ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i), ndim=2, ) for i, array in items_dict[\"DatetimeTZBlock\"]",
"make_block( values, placement, klass=None, ndim=None, dtype: Dtype | None = None ) ->",
"BlockManager(blocks, axes) except ValueError as e: raise construction_error(len(arrays), arrays[0].shape, axes, e) if consolidate:",
"import annotations from collections import defaultdict from typing import DefaultDict import numpy as",
"Use only functions exposed here (or in core.internals) \"\"\" from __future__ import annotations",
"assert names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0]) for i, name_idx in enumerate(names_indexer): if name_idx ==",
"consolidate: mgr._consolidate_inplace() return mgr def _form_blocks( arrays: list[ArrayLike], names: Index, axes: list[Index], consolidate:",
"list[Block]: # put \"leftover\" items in float bucket, where else? # generalize? items_dict:",
"dtype = dtype or values.dtype klass = get_block_type(values, dtype) elif klass is DatetimeTZBlock",
"CategoricalBlock, DatetimeTZBlock, ExtensionBlock, check_ndim, ensure_block_shape, extract_pandas_array, get_block_type, maybe_coerce_values, new_block, ) from pandas.core.internals.managers import",
"if names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx)) else: # Assertion disabled for performance # assert",
"dttz_blocks = [ DatetimeTZBlock( ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i), ndim=2, ) for i, array in",
"ndim) check_ndim(values, placement, ndim) values = maybe_coerce_values(values) return klass(values, ndim=ndim, placement=placement) def maybe_infer_ndim(values,",
"dtype: Dtype | None = None ) -> Block: \"\"\" This is a",
"= DatetimeArray._simple_new(values, dtype=dtype) if not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) ndim = maybe_infer_ndim(values,",
"blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"]) > 0: object_blocks = simple_blockify( items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate ) blocks.extend(object_blocks)",
"\"\"\" This is a pseudo-public API for downstream libraries. We ask that downstream",
"use this rather than any fully-internal APIs, including but not limited to: -",
"from pandas.core.internals.managers import ( BlockManager, construction_error, multi_blockify, simple_blockify, ) def make_block( values, placement,",
"= extract_array(values, extract_numpy=True) values = ensure_block_shape(values, ndim) check_ndim(values, placement, ndim) values = maybe_coerce_values(values)",
"-> list[Block]: # put \"leftover\" items in float bucket, where else? # generalize?",
"= _form_blocks(arrays, names, axes, consolidate) mgr = BlockManager(blocks, axes) except ValueError as e:",
"None = None ) -> Block: \"\"\" This is a pseudo-public analogue to",
"This is a pseudo-public API for downstream libraries. We ask that downstream authors",
"if len(items_dict[\"ExtensionBlock\"]): external_blocks = [ ExtensionBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"ExtensionBlock\"]",
"pandas_dtype(dtype) values, dtype = extract_pandas_array(values, dtype, ndim) if klass is None: dtype =",
"values, placement, klass=None, ndim=None, dtype: Dtype | None = None ) -> Block:",
"ndim = values.ndim return ndim def create_block_manager_from_arrays( arrays, names: Index, axes: list[Index], consolidate:",
"axes: list[Index], consolidate: bool ) -> list[Block]: # put \"leftover\" items in float",
"typing import DefaultDict import numpy as np from pandas._libs.internals import BlockPlacement from pandas._typing",
"dt64tz values values = extract_array(values, extract_numpy=True) values = ensure_block_shape(values, ndim) check_ndim(values, placement, ndim)",
"and values. \"\"\" if ndim is None: # GH#38134 Block constructor now assumes",
"functions exposed here (or in core.internals) \"\"\" from __future__ import annotations from collections",
"is_datetime64tz_dtype(values.dtype): # pyarrow calls get here values = DatetimeArray._simple_new(values, dtype=dtype) if not isinstance(placement,",
"from typing import DefaultDict import numpy as np from pandas._libs.internals import BlockPlacement from",
"as np from pandas._libs.internals import BlockPlacement from pandas._typing import ( ArrayLike, Dtype, )",
"infer it from placment and values. \"\"\" if ndim is None: # GH#38134",
"ndim def create_block_manager_from_arrays( arrays, names: Index, axes: list[Index], consolidate: bool = True, )",
"for x in axes[1:]) # empty items -> dtype object block_values = np.empty(shape,",
"ndim: int | None) -> int: \"\"\" If `ndim` is not provided, infer",
"None) -> int: \"\"\" If `ndim` is not provided, infer it from placment",
"DefaultDict[str, list] = defaultdict(list) extra_locs = [] names_idx = names if names_idx.equals(axes[0]): names_indexer",
"1 else: ndim = 2 else: ndim = values.ndim return ndim def create_block_manager_from_arrays(",
"in arrays] try: blocks = _form_blocks(arrays, names, axes, consolidate) mgr = BlockManager(blocks, axes)",
"BlockPlacement from pandas._typing import ( ArrayLike, Dtype, ) from pandas.core.dtypes.common import ( is_datetime64tz_dtype,",
"values values = extract_array(values, extract_numpy=True) values = ensure_block_shape(values, ndim) check_ndim(values, placement, ndim) values",
"import ( BlockManager, construction_error, multi_blockify, simple_blockify, ) def make_block( values, placement, klass=None, ndim=None,",
"put \"leftover\" items in float bucket, where else? # generalize? items_dict: DefaultDict[str, list]",
"not None: dtype = pandas_dtype(dtype) values, dtype = extract_pandas_array(values, dtype, ndim) if klass",
"if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks = multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate ) blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks =",
"- Block.make_block_same_class - Block.__init__ \"\"\" if dtype is not None: dtype = pandas_dtype(dtype)",
"# assert all(isinstance(x, Index) for x in axes) arrays = [extract_array(x, extract_numpy=True) for",
"DefaultDict import numpy as np from pandas._libs.internals import BlockPlacement from pandas._typing import (",
"get_block_type(values, dtype) elif klass is DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype): # pyarrow calls get",
") for i, array in items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"]) > 0: object_blocks",
"empty items -> dtype object block_values = np.empty(shape, dtype=object) block_values.fill(np.nan) na_block = new_block(block_values,",
"# GH#38134 Block constructor now assumes ndim is not None if not isinstance(values.dtype,",
") def make_block( values, placement, klass=None, ndim=None, dtype: Dtype | None = None",
"ask that downstream authors 1) Try to avoid using internals directly altogether, and",
"blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks = multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate ) blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks",
"extra_locs.append(i) continue v = arrays[name_idx] block_type = get_block_type(v) items_dict[block_type.__name__].append((i, v)) blocks: list[Block] =",
") blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"]) > 0: cat_blocks = [ CategoricalBlock(array, placement=BlockPlacement(i), ndim=2) for",
"annotations from collections import defaultdict from typing import DefaultDict import numpy as np",
"= None ) -> Block: \"\"\" This is a pseudo-public analogue to blocks.new_block.",
"Block.make_block_same_class - Block.__init__ \"\"\" if dtype is not None: dtype = pandas_dtype(dtype) values,",
"array in items_dict[\"DatetimeTZBlock\"] ] blocks.extend(dttz_blocks) if len(items_dict[\"ObjectBlock\"]) > 0: object_blocks = simple_blockify( items_dict[\"ObjectBlock\"],",
"np.dtype): if len(placement) != 1: ndim = 1 else: ndim = 2 else:",
"downstream authors 1) Try to avoid using internals directly altogether, and failing that,",
"maybe_infer_ndim(values, placement: BlockPlacement, ndim: int | None) -> int: \"\"\" If `ndim` is",
"is a pseudo-public analogue to blocks.new_block. We ask that downstream libraries use this",
"ndim) if klass is None: dtype = dtype or values.dtype klass = get_block_type(values,",
"def create_block_manager_from_arrays( arrays, names: Index, axes: list[Index], consolidate: bool = True, ) ->",
"# assert isinstance(axes, list) # assert all(isinstance(x, Index) for x in axes) arrays",
"is None: dtype = dtype or values.dtype klass = get_block_type(values, dtype) elif klass",
"ndim=2) for i, array in items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks) if len(extra_locs): shape = (len(extra_locs),)",
"len(extra_locs): shape = (len(extra_locs),) + tuple(len(x) for x in axes[1:]) # empty items",
"( is_datetime64tz_dtype, pandas_dtype, ) from pandas.core.arrays import DatetimeArray from pandas.core.construction import extract_array from",
"assumes ndim is not None if not isinstance(values.dtype, np.dtype): if len(placement) != 1:",
"ndim=None, dtype: Dtype | None = None ) -> Block: \"\"\" This is",
"# assert isinstance(names, Index) # assert isinstance(axes, list) # assert all(isinstance(x, Index) for",
"Index, axes: list[Index], consolidate: bool = True, ) -> BlockManager: # Assertions disabled",
"dtlike_blocks = multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate ) blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks = [ DatetimeTZBlock(",
"extract_array(values, extract_numpy=True) values = ensure_block_shape(values, ndim) check_ndim(values, placement, ndim) values = maybe_coerce_values(values) return",
"avoid using internals directly altogether, and failing that, 2) Use only functions exposed",
"in axes) arrays = [extract_array(x, extract_numpy=True) for x in arrays] try: blocks =",
"i, array in items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks) if len(extra_locs): shape = (len(extra_locs),) + tuple(len(x)",
"not isinstance(values.dtype, np.dtype): if len(placement) != 1: ndim = 1 else: ndim =",
"blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]): external_blocks = [ ExtensionBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in",
"dtype, ndim) if klass is None: dtype = dtype or values.dtype klass =",
"consolidate=consolidate ) blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks = multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate ) blocks.extend(dtlike_blocks) if",
"axes[1:]) # empty items -> dtype object block_values = np.empty(shape, dtype=object) block_values.fill(np.nan) na_block",
"ndim=ndim, placement=placement) def maybe_infer_ndim(values, placement: BlockPlacement, ndim: int | None) -> int: \"\"\"",
"[] names_idx = names if names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx)) else: # Assertion disabled",
"return ndim def create_block_manager_from_arrays( arrays, names: Index, axes: list[Index], consolidate: bool = True,",
"but not limited to: - core.internals.blocks.make_block - Block.make_block - Block.make_block_same_class - Block.__init__ \"\"\"",
"check_ndim(values, placement, ndim) values = maybe_coerce_values(values) return klass(values, ndim=ndim, placement=placement) def maybe_infer_ndim(values, placement:",
"pandas._libs.internals import BlockPlacement from pandas._typing import ( ArrayLike, Dtype, ) from pandas.core.dtypes.common import",
"1D dt64tz values values = extract_array(values, extract_numpy=True) values = ensure_block_shape(values, ndim) check_ndim(values, placement,",
"pandas.core.dtypes.common import ( is_datetime64tz_dtype, pandas_dtype, ) from pandas.core.arrays import DatetimeArray from pandas.core.construction import",
"for performance # assert isinstance(names, Index) # assert isinstance(axes, list) # assert all(isinstance(x,",
"blocks.new_block. We ask that downstream libraries use this rather than any fully-internal APIs,",
"arrays, names: Index, axes: list[Index], consolidate: bool = True, ) -> BlockManager: #",
"[ ExtensionBlock(array, placement=BlockPlacement(i), ndim=2) for i, array in items_dict[\"ExtensionBlock\"] ] blocks.extend(external_blocks) if len(extra_locs):",
"== -1: extra_locs.append(i) continue v = arrays[name_idx] block_type = get_block_type(v) items_dict[block_type.__name__].append((i, v)) blocks:",
"\"\"\" from __future__ import annotations from collections import defaultdict from typing import DefaultDict",
"ndim = 2 else: ndim = values.ndim return ndim def create_block_manager_from_arrays( arrays, names:",
"defaultdict from typing import DefaultDict import numpy as np from pandas._libs.internals import BlockPlacement",
"a pseudo-public analogue to blocks.new_block. We ask that downstream libraries use this rather",
"defaultdict(list) extra_locs = [] names_idx = names if names_idx.equals(axes[0]): names_indexer = np.arange(len(names_idx)) else:",
"values = extract_array(values, extract_numpy=True) values = ensure_block_shape(values, ndim) check_ndim(values, placement, ndim) values =",
"int: \"\"\" If `ndim` is not provided, infer it from placment and values.",
"arrays] try: blocks = _form_blocks(arrays, names, axes, consolidate) mgr = BlockManager(blocks, axes) except",
"values.ndim return ndim def create_block_manager_from_arrays( arrays, names: Index, axes: list[Index], consolidate: bool =",
"mgr = BlockManager(blocks, axes) except ValueError as e: raise construction_error(len(arrays), arrays[0].shape, axes, e)",
"ArrayLike, Dtype, ) from pandas.core.dtypes.common import ( is_datetime64tz_dtype, pandas_dtype, ) from pandas.core.arrays import",
"if dtype is not None: dtype = pandas_dtype(dtype) values, dtype = extract_pandas_array(values, dtype,",
"if ndim is None: # GH#38134 Block constructor now assumes ndim is not",
"Dtype | None = None ) -> Block: \"\"\" This is a pseudo-public",
"x in axes) arrays = [extract_array(x, extract_numpy=True) for x in arrays] try: blocks",
"core.internals.blocks.make_block - Block.make_block - Block.make_block_same_class - Block.__init__ \"\"\" if dtype is not None:",
"bool ) -> list[Block]: # put \"leftover\" items in float bucket, where else?",
"it from placment and values. \"\"\" if ndim is None: # GH#38134 Block",
"- Block.make_block - Block.make_block_same_class - Block.__init__ \"\"\" if dtype is not None: dtype",
"object_blocks = simple_blockify( items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate ) blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"]) > 0: cat_blocks",
"values = ensure_block_shape(values, ndim) check_ndim(values, placement, ndim) values = maybe_coerce_values(values) return klass(values, ndim=ndim,",
"generalize? items_dict: DefaultDict[str, list] = defaultdict(list) extra_locs = [] names_idx = names if",
"# Assertion disabled for performance # assert names_idx.intersection(axes[0]).is_unique names_indexer = names_idx.get_indexer_for(axes[0]) for i,",
"x in arrays] try: blocks = _form_blocks(arrays, names, axes, consolidate) mgr = BlockManager(blocks,",
"`ndim` is not provided, infer it from placment and values. \"\"\" if ndim",
"= get_block_type(values, dtype) elif klass is DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype): # pyarrow calls",
"Index) # assert isinstance(axes, list) # assert all(isinstance(x, Index) for x in axes)",
"pandas.core.internals.managers import ( BlockManager, construction_error, multi_blockify, simple_blockify, ) def make_block( values, placement, klass=None,",
"in axes[1:]) # empty items -> dtype object block_values = np.empty(shape, dtype=object) block_values.fill(np.nan)",
"check_ndim, ensure_block_shape, extract_pandas_array, get_block_type, maybe_coerce_values, new_block, ) from pandas.core.internals.managers import ( BlockManager, construction_error,",
"Block: \"\"\" This is a pseudo-public analogue to blocks.new_block. We ask that downstream",
"from pandas.core.construction import extract_array from pandas.core.indexes.api import Index from pandas.core.internals.blocks import ( Block,",
"isinstance(names, Index) # assert isinstance(axes, list) # assert all(isinstance(x, Index) for x in",
"placement = BlockPlacement(placement) ndim = maybe_infer_ndim(values, placement, ndim) if is_datetime64tz_dtype(values.dtype): # GH#41168 ensure",
"is not None: dtype = pandas_dtype(dtype) values, dtype = extract_pandas_array(values, dtype, ndim) if",
"multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate ) blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks = [ DatetimeTZBlock( ensure_block_shape(extract_array(array), 2),",
"consolidate=consolidate ) blocks.extend(dtlike_blocks) if len(items_dict[\"DatetimeTZBlock\"]): dttz_blocks = [ DatetimeTZBlock( ensure_block_shape(extract_array(array), 2), placement=BlockPlacement(i), ndim=2,",
"bool = True, ) -> BlockManager: # Assertions disabled for performance # assert",
"in items_dict[\"CategoricalBlock\"] ] blocks.extend(cat_blocks) if len(items_dict[\"ExtensionBlock\"]): external_blocks = [ ExtensionBlock(array, placement=BlockPlacement(i), ndim=2) for",
"len(items_dict[\"NumericBlock\"]): numeric_blocks = multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate ) blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks = multi_blockify(",
"can pass 1D dt64tz values values = extract_array(values, extract_numpy=True) values = ensure_block_shape(values, ndim)",
"downstream libraries. We ask that downstream authors 1) Try to avoid using internals",
"multi_blockify( items_dict[\"NumericBlock\"], consolidate=consolidate ) blocks.extend(numeric_blocks) if len(items_dict[\"DatetimeLikeBlock\"]): dtlike_blocks = multi_blockify( items_dict[\"DatetimeLikeBlock\"], consolidate=consolidate )",
"is a pseudo-public API for downstream libraries. We ask that downstream authors 1)",
"Block.make_block - Block.make_block_same_class - Block.__init__ \"\"\" if dtype is not None: dtype =",
"is_datetime64tz_dtype, pandas_dtype, ) from pandas.core.arrays import DatetimeArray from pandas.core.construction import extract_array from pandas.core.indexes.api",
"now assumes ndim is not None if not isinstance(values.dtype, np.dtype): if len(placement) !=",
"= simple_blockify( items_dict[\"ObjectBlock\"], np.object_, consolidate=consolidate ) blocks.extend(object_blocks) if len(items_dict[\"CategoricalBlock\"]) > 0: cat_blocks =",
"mgr def _form_blocks( arrays: list[ArrayLike], names: Index, axes: list[Index], consolidate: bool ) ->",
"in core.internals) \"\"\" from __future__ import annotations from collections import defaultdict from typing"
] |
[
"shell=True) Libraries.time.sleep(15) def wifi_unsuccessful(): print('Sir, connection establishment to internet was unsuccessful!') #check network",
"filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi', shell=True) Libraries.time.sleep(15) def wifi_unsuccessful(): print('Sir, connection establishment",
"Libraries #function definitions def add_wlan_profile(): Libraries.subprocess.run('netsh wlan add profile filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def open_wifi():",
"Libraries.subprocess.run('start ms-settings:network-wifi', shell=True) Libraries.time.sleep(15) def wifi_unsuccessful(): print('Sir, connection establishment to internet was unsuccessful!')",
"Libraries.subprocess.run('netsh wlan add profile filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi', shell=True) Libraries.time.sleep(15) def",
"def add_wlan_profile(): Libraries.subprocess.run('netsh wlan add profile filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi', shell=True)",
"internet was unsuccessful!') #check network connection def check_wifi(): try: Libraries.urllib.request.urlopen('https://www.google.com/') return True except:",
"Libraries.time.sleep(15) def wifi_unsuccessful(): print('Sir, connection establishment to internet was unsuccessful!') #check network connection",
"shell=True) def open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi', shell=True) Libraries.time.sleep(15) def wifi_unsuccessful(): print('Sir, connection establishment to",
"add profile filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi', shell=True) Libraries.time.sleep(15) def wifi_unsuccessful(): print('Sir,",
"#function definitions def add_wlan_profile(): Libraries.subprocess.run('netsh wlan add profile filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def open_wifi(): Libraries.subprocess.run('start",
"print('Sir, connection establishment to internet was unsuccessful!') #check network connection def check_wifi(): try:",
"def wifi_unsuccessful(): print('Sir, connection establishment to internet was unsuccessful!') #check network connection def",
"wifi_unsuccessful(): print('Sir, connection establishment to internet was unsuccessful!') #check network connection def check_wifi():",
"unsuccessful!') #check network connection def check_wifi(): try: Libraries.urllib.request.urlopen('https://www.google.com/') return True except: return False",
"wlan add profile filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi', shell=True) Libraries.time.sleep(15) def wifi_unsuccessful():",
"open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi', shell=True) Libraries.time.sleep(15) def wifi_unsuccessful(): print('Sir, connection establishment to internet was",
"ms-settings:network-wifi', shell=True) Libraries.time.sleep(15) def wifi_unsuccessful(): print('Sir, connection establishment to internet was unsuccessful!') #check",
"def open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi', shell=True) Libraries.time.sleep(15) def wifi_unsuccessful(): print('Sir, connection establishment to internet",
"to internet was unsuccessful!') #check network connection def check_wifi(): try: Libraries.urllib.request.urlopen('https://www.google.com/') return True",
"add_wlan_profile(): Libraries.subprocess.run('netsh wlan add profile filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi', shell=True) Libraries.time.sleep(15)",
"was unsuccessful!') #check network connection def check_wifi(): try: Libraries.urllib.request.urlopen('https://www.google.com/') return True except: return",
"import Libraries #function definitions def add_wlan_profile(): Libraries.subprocess.run('netsh wlan add profile filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def",
"profile filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi', shell=True) Libraries.time.sleep(15) def wifi_unsuccessful(): print('Sir, connection",
"definitions def add_wlan_profile(): Libraries.subprocess.run('netsh wlan add profile filename=\"../Credentials/G5s_Hotspot.xml\"', shell=True) def open_wifi(): Libraries.subprocess.run('start ms-settings:network-wifi',",
"establishment to internet was unsuccessful!') #check network connection def check_wifi(): try: Libraries.urllib.request.urlopen('https://www.google.com/') return",
"connection establishment to internet was unsuccessful!') #check network connection def check_wifi(): try: Libraries.urllib.request.urlopen('https://www.google.com/')"
] |
[
"datetime for absolute time and timedelta for relative time.\"\"\" def __init__(self, initial_clock: Optional[datetime]",
"<gh_stars>0 from datetime import datetime from typing import Optional from .scheduler import UTC_ZERO",
"import UTC_ZERO from .virtualtimescheduler import VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a virtual time scheduler",
"None) -> None: \"\"\"Creates a new historical scheduler with the specified initial clock",
"historical scheduler with the specified initial clock value. Args: initial_clock: Initial value for",
"None: \"\"\"Creates a new historical scheduler with the specified initial clock value. Args:",
"\"\"\"Creates a new historical scheduler with the specified initial clock value. Args: initial_clock:",
"new historical scheduler with the specified initial clock value. Args: initial_clock: Initial value",
"time scheduler that uses datetime for absolute time and timedelta for relative time.\"\"\"",
".scheduler import UTC_ZERO from .virtualtimescheduler import VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a virtual time",
"virtual time scheduler that uses datetime for absolute time and timedelta for relative",
"the specified initial clock value. Args: initial_clock: Initial value for the clock. \"\"\"",
"Optional from .scheduler import UTC_ZERO from .virtualtimescheduler import VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a",
"that uses datetime for absolute time and timedelta for relative time.\"\"\" def __init__(self,",
"import VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a virtual time scheduler that uses datetime for",
"a virtual time scheduler that uses datetime for absolute time and timedelta for",
"def __init__(self, initial_clock: Optional[datetime] = None) -> None: \"\"\"Creates a new historical scheduler",
".virtualtimescheduler import VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a virtual time scheduler that uses datetime",
"a new historical scheduler with the specified initial clock value. Args: initial_clock: Initial",
"import Optional from .scheduler import UTC_ZERO from .virtualtimescheduler import VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides",
"absolute time and timedelta for relative time.\"\"\" def __init__(self, initial_clock: Optional[datetime] = None)",
"scheduler with the specified initial clock value. Args: initial_clock: Initial value for the",
"\"\"\"Provides a virtual time scheduler that uses datetime for absolute time and timedelta",
"typing import Optional from .scheduler import UTC_ZERO from .virtualtimescheduler import VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler):",
"__init__(self, initial_clock: Optional[datetime] = None) -> None: \"\"\"Creates a new historical scheduler with",
"datetime from typing import Optional from .scheduler import UTC_ZERO from .virtualtimescheduler import VirtualTimeScheduler",
"for relative time.\"\"\" def __init__(self, initial_clock: Optional[datetime] = None) -> None: \"\"\"Creates a",
"from .virtualtimescheduler import VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a virtual time scheduler that uses",
"timedelta for relative time.\"\"\" def __init__(self, initial_clock: Optional[datetime] = None) -> None: \"\"\"Creates",
"Optional[datetime] = None) -> None: \"\"\"Creates a new historical scheduler with the specified",
"datetime import datetime from typing import Optional from .scheduler import UTC_ZERO from .virtualtimescheduler",
"import datetime from typing import Optional from .scheduler import UTC_ZERO from .virtualtimescheduler import",
"uses datetime for absolute time and timedelta for relative time.\"\"\" def __init__(self, initial_clock:",
"UTC_ZERO from .virtualtimescheduler import VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a virtual time scheduler that",
"from datetime import datetime from typing import Optional from .scheduler import UTC_ZERO from",
"HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a virtual time scheduler that uses datetime for absolute time and",
"VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a virtual time scheduler that uses datetime for absolute",
"initial clock value. Args: initial_clock: Initial value for the clock. \"\"\" super().__init__(initial_clock or",
"time and timedelta for relative time.\"\"\" def __init__(self, initial_clock: Optional[datetime] = None) ->",
"scheduler that uses datetime for absolute time and timedelta for relative time.\"\"\" def",
"initial_clock: Optional[datetime] = None) -> None: \"\"\"Creates a new historical scheduler with the",
"for absolute time and timedelta for relative time.\"\"\" def __init__(self, initial_clock: Optional[datetime] =",
"-> None: \"\"\"Creates a new historical scheduler with the specified initial clock value.",
"relative time.\"\"\" def __init__(self, initial_clock: Optional[datetime] = None) -> None: \"\"\"Creates a new",
"with the specified initial clock value. Args: initial_clock: Initial value for the clock.",
"clock value. Args: initial_clock: Initial value for the clock. \"\"\" super().__init__(initial_clock or UTC_ZERO)",
"class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a virtual time scheduler that uses datetime for absolute time",
"from typing import Optional from .scheduler import UTC_ZERO from .virtualtimescheduler import VirtualTimeScheduler class",
"= None) -> None: \"\"\"Creates a new historical scheduler with the specified initial",
"time.\"\"\" def __init__(self, initial_clock: Optional[datetime] = None) -> None: \"\"\"Creates a new historical",
"and timedelta for relative time.\"\"\" def __init__(self, initial_clock: Optional[datetime] = None) -> None:",
"from .scheduler import UTC_ZERO from .virtualtimescheduler import VirtualTimeScheduler class HistoricalScheduler(VirtualTimeScheduler): \"\"\"Provides a virtual",
"specified initial clock value. Args: initial_clock: Initial value for the clock. \"\"\" super().__init__(initial_clock"
] |
[
"count_substring(string, sub_string): count=0 i=0 while(i!=len(string)-len(sub_string)+1): z=string[i:].find(sub_string) if(z!=-1): count+=1 i=i+z+1 else: break return count",
"def count_substring(string, sub_string): count=0 i=0 while(i!=len(string)-len(sub_string)+1): z=string[i:].find(sub_string) if(z!=-1): count+=1 i=i+z+1 else: break return"
] |
[
"lista_tareas): self.lista_tareas = lista_tareas def bubbleSort(self): for i in range(len(self.lista-1)): for j in",
"__init__(self, lista_tareas): self.lista_tareas = lista_tareas def bubbleSort(self): for i in range(len(self.lista-1)): for j",
"Tareas: def __init__(self, lista_tareas): self.lista_tareas = lista_tareas def bubbleSort(self): for i in range(len(self.lista-1)):",
"self.lista_tareas = lista_tareas def bubbleSort(self): for i in range(len(self.lista-1)): for j in range(len(self.lista-1)):",
"in range(len(self.lista-1)): for j in range(len(self.lista-1)): if self.lista[j] > self.lista[j+1]: self.lista[j], self.lista[j+1] =",
"i in range(len(self.lista-1)): for j in range(len(self.lista-1)): if self.lista[j] > self.lista[j+1]: self.lista[j], self.lista[j+1]",
"bubbleSort(self): for i in range(len(self.lista-1)): for j in range(len(self.lista-1)): if self.lista[j] > self.lista[j+1]:",
"= lista_tareas def bubbleSort(self): for i in range(len(self.lista-1)): for j in range(len(self.lista-1)): if",
"if self.lista[j] > self.lista[j+1]: self.lista[j], self.lista[j+1] = self.lista[j+1], self.lista[j] lista= [8,13,5,6,13] bubbleSort(lista) print(lista)",
"for j in range(len(self.lista-1)): if self.lista[j] > self.lista[j+1]: self.lista[j], self.lista[j+1] = self.lista[j+1], self.lista[j]",
"range(len(self.lista-1)): if self.lista[j] > self.lista[j+1]: self.lista[j], self.lista[j+1] = self.lista[j+1], self.lista[j] lista= [8,13,5,6,13] bubbleSort(lista)",
"range(len(self.lista-1)): for j in range(len(self.lista-1)): if self.lista[j] > self.lista[j+1]: self.lista[j], self.lista[j+1] = self.lista[j+1],",
"for i in range(len(self.lista-1)): for j in range(len(self.lista-1)): if self.lista[j] > self.lista[j+1]: self.lista[j],",
"def __init__(self, lista_tareas): self.lista_tareas = lista_tareas def bubbleSort(self): for i in range(len(self.lista-1)): for",
"lista_tareas def bubbleSort(self): for i in range(len(self.lista-1)): for j in range(len(self.lista-1)): if self.lista[j]",
"class Tareas: def __init__(self, lista_tareas): self.lista_tareas = lista_tareas def bubbleSort(self): for i in",
"in range(len(self.lista-1)): if self.lista[j] > self.lista[j+1]: self.lista[j], self.lista[j+1] = self.lista[j+1], self.lista[j] lista= [8,13,5,6,13]",
"j in range(len(self.lista-1)): if self.lista[j] > self.lista[j+1]: self.lista[j], self.lista[j+1] = self.lista[j+1], self.lista[j] lista=",
"def bubbleSort(self): for i in range(len(self.lista-1)): for j in range(len(self.lista-1)): if self.lista[j] >"
] |
[
") model.save('./model/model.h5') test_loss, test_acc = model.evaluate(test_data, test_labels) print(\"Model Accuracy: \", test_acc, \"Model Loss:",
"# summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'],",
"dir = \"./data/\" for category in categories: path = os.path.join(dir, category) class_num =",
"SIZE = 120 def getData(): rawdata = [] data = [] dir =",
"\" \", len(test_labels)) model = createModel(train_data) checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss', mode='min') opt",
"train_labels, epochs=10, validation_data=(val_data, val_labels) ) model.save('./model/model.h5') test_loss, test_acc = model.evaluate(test_data, test_labels) print(\"Model Accuracy:",
"for category in categories: path = os.path.join(dir, category) class_num = categories.index(category) for img",
"1) img_data = img_data / 255.0 img_labels = np.array(img_labels) return img_data, img_labels data,",
"model.fit(train_data, train_labels, epochs=10, validation_data=(val_data, val_labels) ) model.save('./model/model.h5') test_loss, test_acc = model.evaluate(test_data, test_labels) print(\"Model",
"try: rawdata = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_data = cv2.resize(rawdata, (SIZE, SIZE)) data.append([new_data, class_num])",
"import keras import matplotlib.pyplot as plt import os import cv2 import random import",
"metrics=[\"accuracy\"], ) history = model.fit(train_data, train_labels, epochs=10, validation_data=(val_data, val_labels) ) model.save('./model/model.h5') test_loss, test_acc",
"plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss'])",
"plt import os import cv2 import random import sklearn.model_selection as model_selection import datetime",
"= \"./data/\" for category in categories: path = os.path.join(dir, category) class_num = categories.index(category)",
"for features, label in data: img_data.append(features) img_labels.append(label) img_data = np.array(img_data).reshape(-1, SIZE, SIZE, 1)",
"features, label in data: img_data.append(features) img_labels.append(label) img_data = np.array(img_data).reshape(-1, SIZE, SIZE, 1) img_data",
"import datetime from model import createModel from contextlib import redirect_stdout categories = [\"NonDemented\",",
"class_num = categories.index(category) for img in os.listdir(path): try: rawdata = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)",
"plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history",
"img in os.listdir(path): try: rawdata = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_data = cv2.resize(rawdata, (SIZE,",
"\" \", len(train_labels), len(test_data), \" \", len(test_labels)) model = createModel(train_data) checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5',",
"category) class_num = categories.index(category) for img in os.listdir(path): try: rawdata = cv2.imread(os.path.join(path, img),",
"[] for features, label in data: img_data.append(features) img_labels.append(label) img_data = np.array(img_data).reshape(-1, SIZE, SIZE,",
"cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_data = cv2.resize(rawdata, (SIZE, SIZE)) data.append([new_data, class_num]) except Exception as",
"plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model",
"= model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data), \" \", len(train_labels), len(test_data), \" \", len(test_labels)) model =",
"import numpy as np from tensorflow import keras import matplotlib.pyplot as plt import",
"import random import sklearn.model_selection as model_selection import datetime from model import createModel from",
"= np.array(img_data).reshape(-1, SIZE, SIZE, 1) img_data = img_data / 255.0 img_labels = np.array(img_labels)",
"import matplotlib.pyplot as plt import os import cv2 import random import sklearn.model_selection as",
"in categories: path = os.path.join(dir, category) class_num = categories.index(category) for img in os.listdir(path):",
"img_data, img_labels data, labels = getData() train_data, test_data, train_labels, test_labels = model_selection.train_test_split(data, labels,",
"data.append([new_data, class_num]) except Exception as e: pass random.shuffle(data) img_data = [] img_labels =",
"img_data = [] img_labels = [] for features, label in data: img_data.append(features) img_labels.append(label)",
"\"ModerateDemented\", \"VeryMildDemented\"] SIZE = 120 def getData(): rawdata = [] data = []",
"as np from tensorflow import keras import matplotlib.pyplot as plt import os import",
"= cv2.resize(rawdata, (SIZE, SIZE)) data.append([new_data, class_num]) except Exception as e: pass random.shuffle(data) img_data",
"test_labels = model_selection.train_test_split(data, labels, test_size=0.20) train_data, val_data, train_labels, val_labels = model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data),",
"labels, test_size=0.20) train_data, val_data, train_labels, val_labels = model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data), \" \", len(train_labels),",
"= [] img_labels = [] for features, label in data: img_data.append(features) img_labels.append(label) img_data",
"\"Model Loss: \", test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper",
"getData(): rawdata = [] data = [] dir = \"./data/\" for category in",
"cv2.resize(rawdata, (SIZE, SIZE)) data.append([new_data, class_num]) except Exception as e: pass random.shuffle(data) img_data =",
"= keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], ) history = model.fit(train_data, train_labels, epochs=10, validation_data=(val_data, val_labels)",
"label in data: img_data.append(features) img_labels.append(label) img_data = np.array(img_data).reshape(-1, SIZE, SIZE, 1) img_data =",
"test_loss, test_acc = model.evaluate(test_data, test_labels) print(\"Model Accuracy: \", test_acc, \"Model Loss: \", test_loss)",
"model.evaluate(test_data, test_labels) print(\"Model Accuracy: \", test_acc, \"Model Loss: \", test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model",
"test_acc, \"Model Loss: \", test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'],",
"'test'], loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss')",
"np.array(img_data).reshape(-1, SIZE, SIZE, 1) img_data = img_data / 255.0 img_labels = np.array(img_labels) return",
"import sklearn.model_selection as model_selection import datetime from model import createModel from contextlib import",
") history = model.fit(train_data, train_labels, epochs=10, validation_data=(val_data, val_labels) ) model.save('./model/model.h5') test_loss, test_acc =",
"as e: pass random.shuffle(data) img_data = [] img_labels = [] for features, label",
"os.path.join(dir, category) class_num = categories.index(category) for img in os.listdir(path): try: rawdata = cv2.imread(os.path.join(path,",
"= np.array(img_labels) return img_data, img_labels data, labels = getData() train_data, test_data, train_labels, test_labels",
"model_selection import datetime from model import createModel from contextlib import redirect_stdout categories =",
"from contextlib import redirect_stdout categories = [\"NonDemented\", \"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"] SIZE = 120",
"def getData(): rawdata = [] data = [] dir = \"./data/\" for category",
"class_num]) except Exception as e: pass random.shuffle(data) img_data = [] img_labels = []",
"print(len(train_data), \" \", len(train_labels), len(test_data), \" \", len(test_labels)) model = createModel(train_data) checkpoint =",
"model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], ) history = model.fit(train_data, train_labels, epochs=10, validation_data=(val_data, val_labels) ) model.save('./model/model.h5')",
"plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize",
"model import createModel from contextlib import redirect_stdout categories = [\"NonDemented\", \"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"]",
"for img in os.listdir(path): try: rawdata = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_data = cv2.resize(rawdata,",
"cv2.IMREAD_GRAYSCALE) new_data = cv2.resize(rawdata, (SIZE, SIZE)) data.append([new_data, class_num]) except Exception as e: pass",
"new_data = cv2.resize(rawdata, (SIZE, SIZE)) data.append([new_data, class_num]) except Exception as e: pass random.shuffle(data)",
"labels = getData() train_data, test_data, train_labels, test_labels = model_selection.train_test_split(data, labels, test_size=0.20) train_data, val_data,",
"epochs=10, validation_data=(val_data, val_labels) ) model.save('./model/model.h5') test_loss, test_acc = model.evaluate(test_data, test_labels) print(\"Model Accuracy: \",",
"= getData() train_data, test_data, train_labels, test_labels = model_selection.train_test_split(data, labels, test_size=0.20) train_data, val_data, train_labels,",
"Accuracy: \", test_acc, \"Model Loss: \", test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch')",
"img_data = np.array(img_data).reshape(-1, SIZE, SIZE, 1) img_data = img_data / 255.0 img_labels =",
"train_data, val_data, train_labels, val_labels = model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data), \" \", len(train_labels), len(test_data), \"",
"numpy as np from tensorflow import keras import matplotlib.pyplot as plt import os",
"contextlib import redirect_stdout categories = [\"NonDemented\", \"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"] SIZE = 120 def",
"train_labels, test_labels = model_selection.train_test_split(data, labels, test_size=0.20) train_data, val_data, train_labels, val_labels = model_selection.train_test_split(train_data, train_labels,test_size=0.10)",
"val_data, train_labels, val_labels = model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data), \" \", len(train_labels), len(test_data), \" \",",
"os import cv2 import random import sklearn.model_selection as model_selection import datetime from model",
"in data: img_data.append(features) img_labels.append(label) img_data = np.array(img_data).reshape(-1, SIZE, SIZE, 1) img_data = img_data",
"categories.index(category) for img in os.listdir(path): try: rawdata = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_data =",
"summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper",
"img_labels.append(label) img_data = np.array(img_data).reshape(-1, SIZE, SIZE, 1) img_data = img_data / 255.0 img_labels",
"val_labels) ) model.save('./model/model.h5') test_loss, test_acc = model.evaluate(test_data, test_labels) print(\"Model Accuracy: \", test_acc, \"Model",
"model_selection.train_test_split(data, labels, test_size=0.20) train_data, val_data, train_labels, val_labels = model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data), \" \",",
"train_data, test_data, train_labels, test_labels = model_selection.train_test_split(data, labels, test_size=0.20) train_data, val_data, train_labels, val_labels =",
"\"./data/\" for category in categories: path = os.path.join(dir, category) class_num = categories.index(category) for",
"= createModel(train_data) checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss', mode='min') opt = keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\",",
"in os.listdir(path): try: rawdata = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_data = cv2.resize(rawdata, (SIZE, SIZE))",
"import cv2 import random import sklearn.model_selection as model_selection import datetime from model import",
"[] data = [] dir = \"./data/\" for category in categories: path =",
"import redirect_stdout categories = [\"NonDemented\", \"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"] SIZE = 120 def getData():",
"accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss",
"redirect_stdout categories = [\"NonDemented\", \"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"] SIZE = 120 def getData(): rawdata",
"= [\"NonDemented\", \"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"] SIZE = 120 def getData(): rawdata = []",
"opt = keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], ) history = model.fit(train_data, train_labels, epochs=10, validation_data=(val_data,",
"\", test_acc, \"Model Loss: \", test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train',",
"history = model.fit(train_data, train_labels, epochs=10, validation_data=(val_data, val_labels) ) model.save('./model/model.h5') test_loss, test_acc = model.evaluate(test_data,",
"cv2 import random import sklearn.model_selection as model_selection import datetime from model import createModel",
"save_best_only=True, monitor='val_loss', mode='min') opt = keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], ) history = model.fit(train_data,",
"path = os.path.join(dir, category) class_num = categories.index(category) for img in os.listdir(path): try: rawdata",
"train_labels, val_labels = model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data), \" \", len(train_labels), len(test_data), \" \", len(test_labels))",
"test_labels) print(\"Model Accuracy: \", test_acc, \"Model Loss: \", test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy')",
"rawdata = [] data = [] dir = \"./data/\" for category in categories:",
"return img_data, img_labels data, labels = getData() train_data, test_data, train_labels, test_labels = model_selection.train_test_split(data,",
"test_acc = model.evaluate(test_data, test_labels) print(\"Model Accuracy: \", test_acc, \"Model Loss: \", test_loss) plt.plot(history.history['accuracy'])",
"= model.evaluate(test_data, test_labels) print(\"Model Accuracy: \", test_acc, \"Model Loss: \", test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy'])",
"test_data, train_labels, test_labels = model_selection.train_test_split(data, labels, test_size=0.20) train_data, val_data, train_labels, val_labels = model_selection.train_test_split(train_data,",
"\", len(test_labels)) model = createModel(train_data) checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss', mode='min') opt =",
"plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train',",
"= os.path.join(dir, category) class_num = categories.index(category) for img in os.listdir(path): try: rawdata =",
"Loss: \", test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left')",
"createModel from contextlib import redirect_stdout categories = [\"NonDemented\", \"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"] SIZE =",
"plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss'])",
"train_labels,test_size=0.10) print(len(train_data), \" \", len(train_labels), len(test_data), \" \", len(test_labels)) model = createModel(train_data) checkpoint",
"= [] dir = \"./data/\" for category in categories: path = os.path.join(dir, category)",
"category in categories: path = os.path.join(dir, category) class_num = categories.index(category) for img in",
"img_data.append(features) img_labels.append(label) img_data = np.array(img_data).reshape(-1, SIZE, SIZE, 1) img_data = img_data / 255.0",
"np.array(img_labels) return img_data, img_labels data, labels = getData() train_data, test_data, train_labels, test_labels =",
"= [] data = [] dir = \"./data/\" for category in categories: path",
"random.shuffle(data) img_data = [] img_labels = [] for features, label in data: img_data.append(features)",
"img_labels = np.array(img_labels) return img_data, img_labels data, labels = getData() train_data, test_data, train_labels,",
"createModel(train_data) checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss', mode='min') opt = keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"],",
"checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss', mode='min') opt = keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], )",
"validation_data=(val_data, val_labels) ) model.save('./model/model.h5') test_loss, test_acc = model.evaluate(test_data, test_labels) print(\"Model Accuracy: \", test_acc,",
"data = [] dir = \"./data/\" for category in categories: path = os.path.join(dir,",
"from model import createModel from contextlib import redirect_stdout categories = [\"NonDemented\", \"MildDemented\", \"ModerateDemented\",",
"categories: path = os.path.join(dir, category) class_num = categories.index(category) for img in os.listdir(path): try:",
"model.save('./model/model.h5') test_loss, test_acc = model.evaluate(test_data, test_labels) print(\"Model Accuracy: \", test_acc, \"Model Loss: \",",
"\", test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show()",
"print(\"Model Accuracy: \", test_acc, \"Model Loss: \", test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy')",
"datetime from model import createModel from contextlib import redirect_stdout categories = [\"NonDemented\", \"MildDemented\",",
"[] dir = \"./data/\" for category in categories: path = os.path.join(dir, category) class_num",
"except Exception as e: pass random.shuffle(data) img_data = [] img_labels = [] for",
"data, labels = getData() train_data, test_data, train_labels, test_labels = model_selection.train_test_split(data, labels, test_size=0.20) train_data,",
"[] img_labels = [] for features, label in data: img_data.append(features) img_labels.append(label) img_data =",
"loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], ) history = model.fit(train_data, train_labels, epochs=10, validation_data=(val_data, val_labels) ) model.save('./model/model.h5') test_loss,",
"matplotlib.pyplot as plt import os import cv2 import random import sklearn.model_selection as model_selection",
"import os import cv2 import random import sklearn.model_selection as model_selection import datetime from",
"sklearn.model_selection as model_selection import datetime from model import createModel from contextlib import redirect_stdout",
"len(test_labels)) model = createModel(train_data) checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss', mode='min') opt = keras.optimizers.Adam(learning_rate=0.001)",
"= model.fit(train_data, train_labels, epochs=10, validation_data=(val_data, val_labels) ) model.save('./model/model.h5') test_loss, test_acc = model.evaluate(test_data, test_labels)",
"keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss', mode='min') opt = keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], ) history =",
"from tensorflow import keras import matplotlib.pyplot as plt import os import cv2 import",
"img_data = img_data / 255.0 img_labels = np.array(img_labels) return img_data, img_labels data, labels",
"pass random.shuffle(data) img_data = [] img_labels = [] for features, label in data:",
"mode='min') opt = keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], ) history = model.fit(train_data, train_labels, epochs=10,",
"= keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss', mode='min') opt = keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], ) history",
"255.0 img_labels = np.array(img_labels) return img_data, img_labels data, labels = getData() train_data, test_data,",
"history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left')",
"SIZE, SIZE, 1) img_data = img_data / 255.0 img_labels = np.array(img_labels) return img_data,",
"np from tensorflow import keras import matplotlib.pyplot as plt import os import cv2",
"\"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"] SIZE = 120 def getData(): rawdata = [] data =",
"os.listdir(path): try: rawdata = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_data = cv2.resize(rawdata, (SIZE, SIZE)) data.append([new_data,",
"random import sklearn.model_selection as model_selection import datetime from model import createModel from contextlib",
"len(test_data), \" \", len(test_labels)) model = createModel(train_data) checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss', mode='min')",
"keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], ) history = model.fit(train_data, train_labels, epochs=10, validation_data=(val_data, val_labels) )",
"Exception as e: pass random.shuffle(data) img_data = [] img_labels = [] for features,",
"= cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_data = cv2.resize(rawdata, (SIZE, SIZE)) data.append([new_data, class_num]) except Exception",
"(SIZE, SIZE)) data.append([new_data, class_num]) except Exception as e: pass random.shuffle(data) img_data = []",
"model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data), \" \", len(train_labels), len(test_data), \" \", len(test_labels)) model = createModel(train_data)",
"monitor='val_loss', mode='min') opt = keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"], ) history = model.fit(train_data, train_labels,",
"SIZE)) data.append([new_data, class_num]) except Exception as e: pass random.shuffle(data) img_data = [] img_labels",
"loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('loss')",
"[\"NonDemented\", \"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"] SIZE = 120 def getData(): rawdata = [] data",
"= [] for features, label in data: img_data.append(features) img_labels.append(label) img_data = np.array(img_data).reshape(-1, SIZE,",
"= model_selection.train_test_split(data, labels, test_size=0.20) train_data, val_data, train_labels, val_labels = model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data), \"",
"rawdata = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_data = cv2.resize(rawdata, (SIZE, SIZE)) data.append([new_data, class_num]) except",
"for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show()",
"as plt import os import cv2 import random import sklearn.model_selection as model_selection import",
"= categories.index(category) for img in os.listdir(path): try: rawdata = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_data",
"\", len(train_labels), len(test_data), \" \", len(test_labels)) model = createModel(train_data) checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True,",
"categories = [\"NonDemented\", \"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"] SIZE = 120 def getData(): rawdata =",
"/ 255.0 img_labels = np.array(img_labels) return img_data, img_labels data, labels = getData() train_data,",
"img_data / 255.0 img_labels = np.array(img_labels) return img_data, img_labels data, labels = getData()",
"data: img_data.append(features) img_labels.append(label) img_data = np.array(img_data).reshape(-1, SIZE, SIZE, 1) img_data = img_data /",
"img), cv2.IMREAD_GRAYSCALE) new_data = cv2.resize(rawdata, (SIZE, SIZE)) data.append([new_data, class_num]) except Exception as e:",
"plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for",
"tensorflow import keras import matplotlib.pyplot as plt import os import cv2 import random",
"120 def getData(): rawdata = [] data = [] dir = \"./data/\" for",
"val_labels = model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data), \" \", len(train_labels), len(test_data), \" \", len(test_labels)) model",
"left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('loss') plt.xlabel('epoch')",
"test_loss) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() #",
"import createModel from contextlib import redirect_stdout categories = [\"NonDemented\", \"MildDemented\", \"ModerateDemented\", \"VeryMildDemented\"] SIZE",
"= 120 def getData(): rawdata = [] data = [] dir = \"./data/\"",
"test_size=0.20) train_data, val_data, train_labels, val_labels = model_selection.train_test_split(train_data, train_labels,test_size=0.10) print(len(train_data), \" \", len(train_labels), len(test_data),",
"keras import matplotlib.pyplot as plt import os import cv2 import random import sklearn.model_selection",
"as model_selection import datetime from model import createModel from contextlib import redirect_stdout categories",
"img_labels = [] for features, label in data: img_data.append(features) img_labels.append(label) img_data = np.array(img_data).reshape(-1,",
"getData() train_data, test_data, train_labels, test_labels = model_selection.train_test_split(data, labels, test_size=0.20) train_data, val_data, train_labels, val_labels",
"model = createModel(train_data) checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss', mode='min') opt = keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=opt,",
"e: pass random.shuffle(data) img_data = [] img_labels = [] for features, label in",
"= img_data / 255.0 img_labels = np.array(img_labels) return img_data, img_labels data, labels =",
"\"VeryMildDemented\"] SIZE = 120 def getData(): rawdata = [] data = [] dir",
"img_labels data, labels = getData() train_data, test_data, train_labels, test_labels = model_selection.train_test_split(data, labels, test_size=0.20)",
"SIZE, 1) img_data = img_data / 255.0 img_labels = np.array(img_labels) return img_data, img_labels",
"len(train_labels), len(test_data), \" \", len(test_labels)) model = createModel(train_data) checkpoint = keras.callbacks.ModelCheckpoint(filepath='./model/model.h5', save_best_only=True, monitor='val_loss',"
] |
[
"= False ) register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover', max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic",
"Heli, HeliHover, HeliForwardFlight register( id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic",
"register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover', max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic = False )",
"heligym.envs import Heli, HeliHover, HeliForwardFlight register( id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps = 5000, reward_threshold =",
"register( id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic = False )",
"gym.envs.registration import register from heligym.envs import Heli, HeliHover, HeliForwardFlight register( id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps",
"max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic = False ) register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover',",
"register from heligym.envs import Heli, HeliHover, HeliForwardFlight register( id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps = 5000,",
"= 5000, reward_threshold = 0.95, nondeterministic = False ) register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover', max_episode_steps",
"id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic = False ) register(",
"import register from heligym.envs import Heli, HeliHover, HeliForwardFlight register( id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps =",
"0.95, nondeterministic = False ) register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover', max_episode_steps = 5000, reward_threshold =",
"reward_threshold = 0.95, nondeterministic = False ) register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover', max_episode_steps = 5000,",
"import Heli, HeliHover, HeliForwardFlight register( id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps = 5000, reward_threshold = 0.95,",
"False ) register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover', max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic =",
"from gym.envs.registration import register from heligym.envs import Heli, HeliHover, HeliForwardFlight register( id='Heli-v0', entry_point='heligym.envs:Heli',",
"entry_point='heligym.envs:Heli', max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic = False ) register( id='HeliHover-v0',",
"HeliForwardFlight register( id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic = False",
"5000, reward_threshold = 0.95, nondeterministic = False ) register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover', max_episode_steps =",
") register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover', max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic = False",
"from heligym.envs import Heli, HeliHover, HeliForwardFlight register( id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps = 5000, reward_threshold",
"HeliHover, HeliForwardFlight register( id='Heli-v0', entry_point='heligym.envs:Heli', max_episode_steps = 5000, reward_threshold = 0.95, nondeterministic =",
"= 0.95, nondeterministic = False ) register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover', max_episode_steps = 5000, reward_threshold",
"nondeterministic = False ) register( id='HeliHover-v0', entry_point='heligym.envs:HeliHover', max_episode_steps = 5000, reward_threshold = 0.95,"
] |
[
"ImageFolder from tqdm import tqdm from model.encoder import Encoder from util.data_set import TestDataSet",
"from tqdm import tqdm from model.encoder import Encoder from util.data_set import TestDataSet from",
"in processor: data = data.to(device=device) label = label.to(device=device) optimizer.zero_grad() with amp.autocast(): cla_output =",
"= 3097 embedding_features = 3097 aug_norm_mean = [123.68, 116.779, 103.939] aug_norm_std = [58.393,",
"cosine_distance = torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10 = torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy() query_res = {} for",
"epoch_idx in range(epoch): loss_arr = [] processor = tqdm(data_loader) for data, label in",
"csv.writer(f) for query_key in query_res.keys(): csv_writer.writerow([query_key] + query_res[query_key]) if __name__ == '__main__': init()",
"224)), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean], std=[s / 255. for",
"import ImageFolder from tqdm import tqdm from model.encoder import Encoder from util.data_set import",
"device = torch.device('cuda:0') num_classes = 3097 embedding_features = 3097 aug_norm_mean = [123.68, 116.779,",
"Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available(): model = nn.DataParallel(model).to(device=device) model.eval() return model def encode(model, test_dataset):",
"p=2, dim=-1)) embedding_block = torch.cat(embedding_block, dim=0) return embedding_block.float() # matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train():",
"3097 embedding_features = 3097 aug_norm_mean = [123.68, 116.779, 103.939] aug_norm_std = [58.393, 57.12,",
"= f.read().splitlines() with open(gallery_names_path, 'r') as f: gallery_names = f.read().splitlines() cosine_distance = torch.matmul(query_embedding_block,",
"for s in aug_norm_std]), ]) query_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'query'), './saved-output/query_images.txt', transforms=test_transforms) gallery_dataset",
"len(loss_arr) processor.set_description(' Epoch=%d/%d; mLoss=%.4f; loss=%.4f' % (epoch_idx + 1, epoch, mean_loss, float(loss))) torch.save(model.module.state_dict(),",
"num_workers=32) processor = tqdm(data_loader) embedding_block = [] for img in processor: with torch.no_grad():",
"match_names.append(gallery_names[match_idx]) query_res[query_name] = match_names query_res[query_name][0] = '{' + query_res[query_name][0] query_res[query_name][-1] += '}' with",
"match_idx in match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name] = match_names query_res[query_name][0] = '{' + query_res[query_name][0] query_res[query_name][-1]",
"embedding_features = 3097 aug_norm_mean = [123.68, 116.779, 103.939] aug_norm_std = [58.393, 57.12, 57.375]",
"57.12, 57.375] name = 'r50-mlp-3097-amp' output_base_path = os.path.join('./saved-output', name) if not os.path.exists(output_base_path): os.mkdir(output_base_path)",
"torch.save(model.module.state_dict(), param_name) def query(query_embedding_block, gallery_embedding_block, query_names_path, gallery_names_path): with open(query_names_path, 'r') as f: query_names",
"torch.cuda.amp as amp import torch.nn as nn import torch.nn.functional as fun import torchvision.transforms",
"= query_names[idx] match_names = [] for match_idx in match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name] = match_names",
"model = nn.DataParallel(model) model.to(device=device).train() train_transforms = transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0), ratio=(3. / 4.,",
"import tqdm from model.encoder import Encoder from util.data_set import TestDataSet from util.lr_scheduler import",
"+ query_res[query_key]) if __name__ == '__main__': init() train() test_model = get_test_model() test_transforms =",
"200 iter_per_epoch = len(data_loader) warm_epoch = 2 optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0001)",
"data_loader = DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=32) processor = tqdm(data_loader) embedding_block = [] for",
"transforms=test_transforms) gallery_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block = encode(test_model, query_dataset) gallery_embedding_block",
"'../../DataSet/digital-device-dataset' train_path = os.path.join(data_set_path, 'train') device = torch.device('cuda:0') num_classes = 3097 embedding_features =",
"transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean], std=[s / 255. for",
"= csv.writer(f) for query_key in query_res.keys(): csv_writer.writerow([query_key] + query_res[query_key]) if __name__ == '__main__':",
"name = 'r50-mlp-3097-amp' output_base_path = os.path.join('./saved-output', name) if not os.path.exists(output_base_path): os.mkdir(output_base_path) model_name =",
"for m in aug_norm_mean], std=[s / 255. for s in aug_norm_std]), ]) cla_dataset",
"import torch.nn.functional as fun import torchvision.transforms as transforms from torch.optim import SGD from",
"processor = tqdm(data_loader) embedding_block = [] for img in processor: with torch.no_grad(): embedded_feature",
"dim=-1).indices.cpu().numpy() query_res = {} for idx, match_indices in enumerate(indices_top_10): query_name = query_names[idx] match_names",
"in range(epoch): loss_arr = [] processor = tqdm(data_loader) for data, label in processor:",
"= transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean], std=[s",
"shuffle=False, num_workers=32) processor = tqdm(data_loader) embedding_block = [] for img in processor: with",
"= '{' + query_res[query_name][0] query_res[query_name][-1] += '}' with open(os.path.join(output_base_path, 'submission.csv'), 'w', encoding='utf-8') as",
"= [58.393, 57.12, 57.375] name = 'r50-mlp-3097-amp' output_base_path = os.path.join('./saved-output', name) if not",
"processor = tqdm(data_loader) for data, label in processor: data = data.to(device=device) label =",
"import torch.nn as nn import torch.nn.functional as fun import torchvision.transforms as transforms from",
"std=[s / 255. for s in aug_norm_std]), ]) cla_dataset = ImageFolder(train_path, transform=train_transforms) data_loader",
"epoch * iter_per_epoch, max_lr=0.1) # arc_margin_product = ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler = amp.GradScaler() for",
"= SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0001) scheduler = LinearCosineScheduler(optimizer, warm_epoch * iter_per_epoch, epoch *",
"model.eval() return model def encode(model, test_dataset): data_loader = DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=32) processor",
"query_res.keys(): csv_writer.writerow([query_key] + query_res[query_key]) if __name__ == '__main__': init() train() test_model = get_test_model()",
"label in processor: data = data.to(device=device) label = label.to(device=device) optimizer.zero_grad() with amp.autocast(): cla_output",
"test_model = get_test_model() test_transforms = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for",
"'./saved-output/query_images.txt', transforms=test_transforms) gallery_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block = encode(test_model, query_dataset)",
"# arc_margin_product = ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler = amp.GradScaler() for epoch_idx in range(epoch): loss_arr",
"query_names[idx] match_names = [] for match_idx in match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name] = match_names query_res[query_name][0]",
"/ 255. for s in aug_norm_std]), ]) query_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'query'), './saved-output/query_images.txt',",
"1, epoch, mean_loss, float(loss))) torch.save(model.module.state_dict(), param_name) def query(query_embedding_block, gallery_embedding_block, query_names_path, gallery_names_path): with open(query_names_path,",
"open(query_names_path, 'r') as f: query_names = f.read().splitlines() with open(gallery_names_path, 'r') as f: gallery_names",
"'r') as f: query_names = f.read().splitlines() with open(gallery_names_path, 'r') as f: gallery_names =",
"= 3097 aug_norm_mean = [123.68, 116.779, 103.939] aug_norm_std = [58.393, 57.12, 57.375] name",
"2 optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0001) scheduler = LinearCosineScheduler(optimizer, warm_epoch * iter_per_epoch,",
"= {} for idx, match_indices in enumerate(indices_top_10): query_name = query_names[idx] match_names = []",
"'./saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block = encode(test_model, query_dataset) gallery_embedding_block = encode(test_model, gallery_dataset) query(query_embedding_block, gallery_embedding_block, './saved-output/query_images.txt',",
"in aug_norm_std]), ]) cla_dataset = ImageFolder(train_path, transform=train_transforms) data_loader = DataLoader(cla_dataset, batch_size=256, shuffle=True, num_workers=32)",
"== '__main__': init() train() test_model = get_test_model() test_transforms = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(),",
"torch.utils.data import DataLoader from torchvision.datasets import ImageFolder from tqdm import tqdm from model.encoder",
"= arc_margin_product(cla_output, label) loss = fun.cross_entropy(cla_output, label) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() scheduler.step() loss_arr.append(float(loss)) mean_loss",
"as np import torch import torch.backends.cudnn import torch.cuda.amp as amp import torch.nn as",
"= torch.device('cuda:0') num_classes = 3097 embedding_features = 3097 aug_norm_mean = [123.68, 116.779, 103.939]",
"LinearCosineScheduler(optimizer, warm_epoch * iter_per_epoch, epoch * iter_per_epoch, max_lr=0.1) # arc_margin_product = ArcMarginProduct(in_features=embedding_feature, out_features=num_classes)",
"torchvision.transforms as transforms from torch.optim import SGD from torch.utils.data import DataLoader from torchvision.datasets",
"import * data_set_path = '../../DataSet/digital-device-dataset' train_path = os.path.join(data_set_path, 'train') device = torch.device('cuda:0') num_classes",
"f: csv_writer = csv.writer(f) for query_key in query_res.keys(): csv_writer.writerow([query_key] + query_res[query_key]) if __name__",
"data, label in processor: data = data.to(device=device) label = label.to(device=device) optimizer.zero_grad() with amp.autocast():",
"from util.tools import * data_set_path = '../../DataSet/digital-device-dataset' train_path = os.path.join(data_set_path, 'train') device =",
"= label.to(device=device) optimizer.zero_grad() with amp.autocast(): cla_output = model(data) # loss = arc_margin_product(cla_output, label)",
"f.read().splitlines() with open(gallery_names_path, 'r') as f: gallery_names = f.read().splitlines() cosine_distance = torch.matmul(query_embedding_block, gallery_embedding_block.t())",
"'}' with open(os.path.join(output_base_path, 'submission.csv'), 'w', encoding='utf-8') as f: csv_writer = csv.writer(f) for query_key",
"aug_norm_std = [58.393, 57.12, 57.375] name = 'r50-mlp-3097-amp' output_base_path = os.path.join('./saved-output', name) if",
"'query-embedding-block') def get_test_model(): model = Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available(): model = nn.DataParallel(model).to(device=device) model.eval()",
"= os.path.join(data_set_path, 'train') device = torch.device('cuda:0') num_classes = 3097 embedding_features = 3097 aug_norm_mean",
"with torch.no_grad(): embedded_feature = model(img) embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1)) embedding_block = torch.cat(embedding_block, dim=0) return",
"csv_writer.writerow([query_key] + query_res[query_key]) if __name__ == '__main__': init() train() test_model = get_test_model() test_transforms",
"in match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name] = match_names query_res[query_name][0] = '{' + query_res[query_name][0] query_res[query_name][-1] +=",
"arc_margin_product = ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler = amp.GradScaler() for epoch_idx in range(epoch): loss_arr =",
"tqdm import tqdm from model.encoder import Encoder from util.data_set import TestDataSet from util.lr_scheduler",
"epoch = 200 iter_per_epoch = len(data_loader) warm_epoch = 2 optimizer = SGD(model.parameters(), lr=0.1,",
"sum(loss_arr) / len(loss_arr) processor.set_description(' Epoch=%d/%d; mLoss=%.4f; loss=%.4f' % (epoch_idx + 1, epoch, mean_loss,",
"transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean], std=[s / 255.",
"query_name = query_names[idx] match_names = [] for match_idx in match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name] =",
"embedded_feature = model(img) embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1)) embedding_block = torch.cat(embedding_block, dim=0) return embedding_block.float() #",
"aug_norm_mean = [123.68, 116.779, 103.939] aug_norm_std = [58.393, 57.12, 57.375] name = 'r50-mlp-3097-amp'",
"matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train(): model = Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name) model = nn.DataParallel(model) model.to(device=device).train()",
"ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler = amp.GradScaler() for epoch_idx in range(epoch): loss_arr = [] processor",
"nn import torch.nn.functional as fun import torchvision.transforms as transforms from torch.optim import SGD",
"saturation=0.4, contrast=0.4), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean], std=[s",
"data = data.to(device=device) label = label.to(device=device) optimizer.zero_grad() with amp.autocast(): cla_output = model(data) #",
"os.path.join('./saved-output', name) if not os.path.exists(output_base_path): os.mkdir(output_base_path) model_name = os.path.join(output_base_path, 'model.pkl') param_name = os.path.join(output_base_path,",
"import DataLoader from torchvision.datasets import ImageFolder from tqdm import tqdm from model.encoder import",
"output_base_path = os.path.join('./saved-output', name) if not os.path.exists(output_base_path): os.mkdir(output_base_path) model_name = os.path.join(output_base_path, 'model.pkl') param_name",
"in query_res.keys(): csv_writer.writerow([query_key] + query_res[query_key]) if __name__ == '__main__': init() train() test_model =",
"torch.cat(embedding_block, dim=0) return embedding_block.float() # matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train(): model = Encoder(feature_num=embedding_features) torch.save(model.state_dict(),",
"os.mkdir(output_base_path) model_name = os.path.join(output_base_path, 'model.pkl') param_name = os.path.join(output_base_path, 'param.pth') # gallery_embedding_block_name = os.path.join(output_base_path,",
"scaler = amp.GradScaler() for epoch_idx in range(epoch): loss_arr = [] processor = tqdm(data_loader)",
"in enumerate(indices_top_10): query_name = query_names[idx] match_names = [] for match_idx in match_indices: match_names.append(gallery_names[match_idx])",
"scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4), transforms.Resize((224,",
"for s in aug_norm_std]), ]) cla_dataset = ImageFolder(train_path, transform=train_transforms) data_loader = DataLoader(cla_dataset, batch_size=256,",
"= 200 iter_per_epoch = len(data_loader) warm_epoch = 2 optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9,",
"torch.save(model.state_dict(), model_name) model = nn.DataParallel(model) model.to(device=device).train() train_transforms = transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0), ratio=(3.",
"= torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy() query_res = {} for idx, match_indices in enumerate(indices_top_10): query_name",
"iter_per_epoch = len(data_loader) warm_epoch = 2 optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0001) scheduler",
"= len(data_loader) warm_epoch = 2 optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0001) scheduler =",
"img in processor: with torch.no_grad(): embedded_feature = model(img) embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1)) embedding_block =",
"loss = arc_margin_product(cla_output, label) loss = fun.cross_entropy(cla_output, label) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() scheduler.step() loss_arr.append(float(loss))",
"from torchvision.datasets import ImageFolder from tqdm import tqdm from model.encoder import Encoder from",
"from util.data_set import TestDataSet from util.lr_scheduler import LinearCosineScheduler from util.tools import * data_set_path",
"scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() scheduler.step() loss_arr.append(float(loss)) mean_loss = sum(loss_arr) / len(loss_arr) processor.set_description(' Epoch=%d/%d; mLoss=%.4f;",
"torch.optim import SGD from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder from tqdm",
"os.path.join(output_base_path, 'query-embedding-block') def get_test_model(): model = Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available(): model = nn.DataParallel(model).to(device=device)",
"= model(data) # loss = arc_margin_product(cla_output, label) loss = fun.cross_entropy(cla_output, label) scaler.scale(loss).backward() scaler.step(optimizer)",
"match_indices in enumerate(indices_top_10): query_name = query_names[idx] match_names = [] for match_idx in match_indices:",
"57.375] name = 'r50-mlp-3097-amp' output_base_path = os.path.join('./saved-output', name) if not os.path.exists(output_base_path): os.mkdir(output_base_path) model_name",
"103.939] aug_norm_std = [58.393, 57.12, 57.375] name = 'r50-mlp-3097-amp' output_base_path = os.path.join('./saved-output', name)",
"train(): model = Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name) model = nn.DataParallel(model) model.to(device=device).train() train_transforms = transforms.Compose([",
"if torch.cuda.is_available(): model = nn.DataParallel(model).to(device=device) model.eval() return model def encode(model, test_dataset): data_loader =",
"open(os.path.join(output_base_path, 'submission.csv'), 'w', encoding='utf-8') as f: csv_writer = csv.writer(f) for query_key in query_res.keys():",
"data_loader = DataLoader(cla_dataset, batch_size=256, shuffle=True, num_workers=32) epoch = 200 iter_per_epoch = len(data_loader) warm_epoch",
"gallery_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block = encode(test_model, query_dataset) gallery_embedding_block =",
"model = nn.DataParallel(model).to(device=device) model.eval() return model def encode(model, test_dataset): data_loader = DataLoader(test_dataset, batch_size=256,",
"DataLoader(cla_dataset, batch_size=256, shuffle=True, num_workers=32) epoch = 200 iter_per_epoch = len(data_loader) warm_epoch = 2",
"= 2 optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0001) scheduler = LinearCosineScheduler(optimizer, warm_epoch *",
"torch.device('cuda:0') num_classes = 3097 embedding_features = 3097 aug_norm_mean = [123.68, 116.779, 103.939] aug_norm_std",
"query_res[query_name][-1] += '}' with open(os.path.join(output_base_path, 'submission.csv'), 'w', encoding='utf-8') as f: csv_writer = csv.writer(f)",
"torchvision.datasets import ImageFolder from tqdm import tqdm from model.encoder import Encoder from util.data_set",
"np import torch import torch.backends.cudnn import torch.cuda.amp as amp import torch.nn as nn",
"255. for s in aug_norm_std]), ]) cla_dataset = ImageFolder(train_path, transform=train_transforms) data_loader = DataLoader(cla_dataset,",
"label) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() scheduler.step() loss_arr.append(float(loss)) mean_loss = sum(loss_arr) / len(loss_arr) processor.set_description(' Epoch=%d/%d;",
"= torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10 = torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy() query_res = {} for idx,",
"range(epoch): loss_arr = [] processor = tqdm(data_loader) for data, label in processor: data",
"csv_writer = csv.writer(f) for query_key in query_res.keys(): csv_writer.writerow([query_key] + query_res[query_key]) if __name__ ==",
"/ 3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for",
"model def encode(model, test_dataset): data_loader = DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=32) processor = tqdm(data_loader)",
"import csv import os import numpy as np import torch import torch.backends.cudnn import",
"epoch, mean_loss, float(loss))) torch.save(model.module.state_dict(), param_name) def query(query_embedding_block, gallery_embedding_block, query_names_path, gallery_names_path): with open(query_names_path, 'r')",
"{} for idx, match_indices in enumerate(indices_top_10): query_name = query_names[idx] match_names = [] for",
"1.0), ratio=(3. / 4., 4. / 3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4), transforms.Resize((224, 224)),",
"momentum=0.9, weight_decay=0.0001) scheduler = LinearCosineScheduler(optimizer, warm_epoch * iter_per_epoch, epoch * iter_per_epoch, max_lr=0.1) #",
"query_names = f.read().splitlines() with open(gallery_names_path, 'r') as f: gallery_names = f.read().splitlines() cosine_distance =",
"amp.autocast(): cla_output = model(data) # loss = arc_margin_product(cla_output, label) loss = fun.cross_entropy(cla_output, label)",
"SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0001) scheduler = LinearCosineScheduler(optimizer, warm_epoch * iter_per_epoch, epoch * iter_per_epoch,",
"import TestDataSet from util.lr_scheduler import LinearCosineScheduler from util.tools import * data_set_path = '../../DataSet/digital-device-dataset'",
"ImageFolder(train_path, transform=train_transforms) data_loader = DataLoader(cla_dataset, batch_size=256, shuffle=True, num_workers=32) epoch = 200 iter_per_epoch =",
"len(data_loader) warm_epoch = 2 optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0001) scheduler = LinearCosineScheduler(optimizer,",
"= get_test_model() test_transforms = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m",
"= amp.GradScaler() for epoch_idx in range(epoch): loss_arr = [] processor = tqdm(data_loader) for",
"scaler.update() scheduler.step() loss_arr.append(float(loss)) mean_loss = sum(loss_arr) / len(loss_arr) processor.set_description(' Epoch=%d/%d; mLoss=%.4f; loss=%.4f' %",
"label) loss = fun.cross_entropy(cla_output, label) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() scheduler.step() loss_arr.append(float(loss)) mean_loss = sum(loss_arr)",
"max_lr=0.1) # arc_margin_product = ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler = amp.GradScaler() for epoch_idx in range(epoch):",
"'model.pkl') param_name = os.path.join(output_base_path, 'param.pth') # gallery_embedding_block_name = os.path.join(output_base_path, 'gallery-embedding-block') # query_embedding_block_name =",
"__name__ == '__main__': init() train() test_model = get_test_model() test_transforms = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224),",
"= Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available(): model = nn.DataParallel(model).to(device=device) model.eval() return model def encode(model,",
"transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4),",
"model = Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name) model = nn.DataParallel(model) model.to(device=device).train() train_transforms = transforms.Compose([ transforms.RandomResizedCrop(size=224,",
"std=[s / 255. for s in aug_norm_std]), ]) query_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'query'),",
"'r') as f: gallery_names = f.read().splitlines() cosine_distance = torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10 = torch.topk(cosine_distance,",
"from model.encoder import Encoder from util.data_set import TestDataSet from util.lr_scheduler import LinearCosineScheduler from",
"transforms from torch.optim import SGD from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder",
"4. / 3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[m / 255.",
"函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train(): model = Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name) model = nn.DataParallel(model) model.to(device=device).train() train_transforms",
"cla_output = model(data) # loss = arc_margin_product(cla_output, label) loss = fun.cross_entropy(cla_output, label) scaler.scale(loss).backward()",
"open(gallery_names_path, 'r') as f: gallery_names = f.read().splitlines() cosine_distance = torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10 =",
"aug_norm_mean], std=[s / 255. for s in aug_norm_std]), ]) query_dataset = TestDataSet(os.path.join(data_set_path, 'test',",
"/ 4., 4. / 3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[m",
"loss = fun.cross_entropy(cla_output, label) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() scheduler.step() loss_arr.append(float(loss)) mean_loss = sum(loss_arr) /",
"data.to(device=device) label = label.to(device=device) optimizer.zero_grad() with amp.autocast(): cla_output = model(data) # loss =",
"4., 4. / 3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[m /",
"transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean], std=[s / 255.",
"query_embedding_block_name = os.path.join(output_base_path, 'query-embedding-block') def get_test_model(): model = Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available(): model",
"init() train() test_model = get_test_model() test_transforms = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m /",
"116.779, 103.939] aug_norm_std = [58.393, 57.12, 57.375] name = 'r50-mlp-3097-amp' output_base_path = os.path.join('./saved-output',",
"optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0001) scheduler = LinearCosineScheduler(optimizer, warm_epoch * iter_per_epoch, epoch",
"with open(gallery_names_path, 'r') as f: gallery_names = f.read().splitlines() cosine_distance = torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10",
"mean_loss, float(loss))) torch.save(model.module.state_dict(), param_name) def query(query_embedding_block, gallery_embedding_block, query_names_path, gallery_names_path): with open(query_names_path, 'r') as",
"/ len(loss_arr) processor.set_description(' Epoch=%d/%d; mLoss=%.4f; loss=%.4f' % (epoch_idx + 1, epoch, mean_loss, float(loss)))",
"mLoss=%.4f; loss=%.4f' % (epoch_idx + 1, epoch, mean_loss, float(loss))) torch.save(model.module.state_dict(), param_name) def query(query_embedding_block,",
"= f.read().splitlines() cosine_distance = torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10 = torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy() query_res =",
"os.path.exists(output_base_path): os.mkdir(output_base_path) model_name = os.path.join(output_base_path, 'model.pkl') param_name = os.path.join(output_base_path, 'param.pth') # gallery_embedding_block_name =",
"query_key in query_res.keys(): csv_writer.writerow([query_key] + query_res[query_key]) if __name__ == '__main__': init() train() test_model",
"with open(query_names_path, 'r') as f: query_names = f.read().splitlines() with open(gallery_names_path, 'r') as f:",
"= os.path.join(output_base_path, 'model.pkl') param_name = os.path.join(output_base_path, 'param.pth') # gallery_embedding_block_name = os.path.join(output_base_path, 'gallery-embedding-block') #",
"nn.DataParallel(model).to(device=device) model.eval() return model def encode(model, test_dataset): data_loader = DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=32)",
"return model def encode(model, test_dataset): data_loader = DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=32) processor =",
"tqdm(data_loader) embedding_block = [] for img in processor: with torch.no_grad(): embedded_feature = model(img)",
"scheduler.step() loss_arr.append(float(loss)) mean_loss = sum(loss_arr) / len(loss_arr) processor.set_description(' Epoch=%d/%d; mLoss=%.4f; loss=%.4f' % (epoch_idx",
"in aug_norm_mean], std=[s / 255. for s in aug_norm_std]), ]) cla_dataset = ImageFolder(train_path,",
"TestDataSet(os.path.join(data_set_path, 'test', 'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block = encode(test_model, query_dataset) gallery_embedding_block = encode(test_model, gallery_dataset)",
"+= '}' with open(os.path.join(output_base_path, 'submission.csv'), 'w', encoding='utf-8') as f: csv_writer = csv.writer(f) for",
"for query_key in query_res.keys(): csv_writer.writerow([query_key] + query_res[query_key]) if __name__ == '__main__': init() train()",
"transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean], std=[s /",
"query_res[query_key]) if __name__ == '__main__': init() train() test_model = get_test_model() test_transforms = transforms.Compose([",
"encoding='utf-8') as f: csv_writer = csv.writer(f) for query_key in query_res.keys(): csv_writer.writerow([query_key] + query_res[query_key])",
"= os.path.join(output_base_path, 'gallery-embedding-block') # query_embedding_block_name = os.path.join(output_base_path, 'query-embedding-block') def get_test_model(): model = Encoder(feature_num=embedding_features)",
"255. for s in aug_norm_std]), ]) query_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'query'), './saved-output/query_images.txt', transforms=test_transforms)",
"3097 aug_norm_mean = [123.68, 116.779, 103.939] aug_norm_std = [58.393, 57.12, 57.375] name =",
"indices_top_10 = torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy() query_res = {} for idx, match_indices in enumerate(indices_top_10):",
"= TestDataSet(os.path.join(data_set_path, 'test', 'query'), './saved-output/query_images.txt', transforms=test_transforms) gallery_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms)",
"loss=%.4f' % (epoch_idx + 1, epoch, mean_loss, float(loss))) torch.save(model.module.state_dict(), param_name) def query(query_embedding_block, gallery_embedding_block,",
"f: query_names = f.read().splitlines() with open(gallery_names_path, 'r') as f: gallery_names = f.read().splitlines() cosine_distance",
"+ query_res[query_name][0] query_res[query_name][-1] += '}' with open(os.path.join(output_base_path, 'submission.csv'), 'w', encoding='utf-8') as f: csv_writer",
"with amp.autocast(): cla_output = model(data) # loss = arc_margin_product(cla_output, label) loss = fun.cross_entropy(cla_output,",
"DataLoader from torchvision.datasets import ImageFolder from tqdm import tqdm from model.encoder import Encoder",
"transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean], std=[s / 255. for s",
"ratio=(3. / 4., 4. / 3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4), transforms.Resize((224, 224)), transforms.ToTensor(),",
"= os.path.join(output_base_path, 'query-embedding-block') def get_test_model(): model = Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available(): model =",
"match_names = [] for match_idx in match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name] = match_names query_res[query_name][0] =",
"processor.set_description(' Epoch=%d/%d; mLoss=%.4f; loss=%.4f' % (epoch_idx + 1, epoch, mean_loss, float(loss))) torch.save(model.module.state_dict(), param_name)",
"util.tools import * data_set_path = '../../DataSet/digital-device-dataset' train_path = os.path.join(data_set_path, 'train') device = torch.device('cuda:0')",
"import LinearCosineScheduler from util.tools import * data_set_path = '../../DataSet/digital-device-dataset' train_path = os.path.join(data_set_path, 'train')",
"aug_norm_mean], std=[s / 255. for s in aug_norm_std]), ]) cla_dataset = ImageFolder(train_path, transform=train_transforms)",
"not os.path.exists(output_base_path): os.mkdir(output_base_path) model_name = os.path.join(output_base_path, 'model.pkl') param_name = os.path.join(output_base_path, 'param.pth') # gallery_embedding_block_name",
"label = label.to(device=device) optimizer.zero_grad() with amp.autocast(): cla_output = model(data) # loss = arc_margin_product(cla_output,",
"gallery_embedding_block_name = os.path.join(output_base_path, 'gallery-embedding-block') # query_embedding_block_name = os.path.join(output_base_path, 'query-embedding-block') def get_test_model(): model =",
"import Encoder from util.data_set import TestDataSet from util.lr_scheduler import LinearCosineScheduler from util.tools import",
"= os.path.join(output_base_path, 'param.pth') # gallery_embedding_block_name = os.path.join(output_base_path, 'gallery-embedding-block') # query_embedding_block_name = os.path.join(output_base_path, 'query-embedding-block')",
"query_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'query'), './saved-output/query_images.txt', transforms=test_transforms) gallery_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'gallery'), './saved-output/gallery_images.txt',",
"embedding_block = torch.cat(embedding_block, dim=0) return embedding_block.float() # matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train(): model =",
"out_features=num_classes) scaler = amp.GradScaler() for epoch_idx in range(epoch): loss_arr = [] processor =",
"= os.path.join('./saved-output', name) if not os.path.exists(output_base_path): os.mkdir(output_base_path) model_name = os.path.join(output_base_path, 'model.pkl') param_name =",
"'test', 'query'), './saved-output/query_images.txt', transforms=test_transforms) gallery_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block =",
"query(query_embedding_block, gallery_embedding_block, query_names_path, gallery_names_path): with open(query_names_path, 'r') as f: query_names = f.read().splitlines() with",
"train_path = os.path.join(data_set_path, 'train') device = torch.device('cuda:0') num_classes = 3097 embedding_features = 3097",
"model = Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available(): model = nn.DataParallel(model).to(device=device) model.eval() return model def",
"transforms=test_transforms) query_embedding_block = encode(test_model, query_dataset) gallery_embedding_block = encode(test_model, gallery_dataset) query(query_embedding_block, gallery_embedding_block, './saved-output/query_images.txt', './saved-output/gallery_images.txt')",
"loss_arr.append(float(loss)) mean_loss = sum(loss_arr) / len(loss_arr) processor.set_description(' Epoch=%d/%d; mLoss=%.4f; loss=%.4f' % (epoch_idx +",
"[] for match_idx in match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name] = match_names query_res[query_name][0] = '{' +",
"num_classes = 3097 embedding_features = 3097 aug_norm_mean = [123.68, 116.779, 103.939] aug_norm_std =",
"aug_norm_std]), ]) query_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'query'), './saved-output/query_images.txt', transforms=test_transforms) gallery_dataset = TestDataSet(os.path.join(data_set_path, 'test',",
"[] processor = tqdm(data_loader) for data, label in processor: data = data.to(device=device) label",
"= TestDataSet(os.path.join(data_set_path, 'test', 'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block = encode(test_model, query_dataset) gallery_embedding_block = encode(test_model,",
"tqdm from model.encoder import Encoder from util.data_set import TestDataSet from util.lr_scheduler import LinearCosineScheduler",
"amp.GradScaler() for epoch_idx in range(epoch): loss_arr = [] processor = tqdm(data_loader) for data,",
"scaler.step(optimizer) scaler.update() scheduler.step() loss_arr.append(float(loss)) mean_loss = sum(loss_arr) / len(loss_arr) processor.set_description(' Epoch=%d/%d; mLoss=%.4f; loss=%.4f'",
"mean_loss = sum(loss_arr) / len(loss_arr) processor.set_description(' Epoch=%d/%d; mLoss=%.4f; loss=%.4f' % (epoch_idx + 1,",
"match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name] = match_names query_res[query_name][0] = '{' + query_res[query_name][0] query_res[query_name][-1] += '}'",
"def encode(model, test_dataset): data_loader = DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=32) processor = tqdm(data_loader) embedding_block",
"= torch.cat(embedding_block, dim=0) return embedding_block.float() # matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train(): model = Encoder(feature_num=embedding_features)",
"as nn import torch.nn.functional as fun import torchvision.transforms as transforms from torch.optim import",
"as transforms from torch.optim import SGD from torch.utils.data import DataLoader from torchvision.datasets import",
"arc_margin_product(cla_output, label) loss = fun.cross_entropy(cla_output, label) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() scheduler.step() loss_arr.append(float(loss)) mean_loss =",
"Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name) model = nn.DataParallel(model) model.to(device=device).train() train_transforms = transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0),",
"'query'), './saved-output/query_images.txt', transforms=test_transforms) gallery_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block = encode(test_model,",
"* iter_per_epoch, max_lr=0.1) # arc_margin_product = ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler = amp.GradScaler() for epoch_idx",
"shuffle=True, num_workers=32) epoch = 200 iter_per_epoch = len(data_loader) warm_epoch = 2 optimizer =",
"'{' + query_res[query_name][0] query_res[query_name][-1] += '}' with open(os.path.join(output_base_path, 'submission.csv'), 'w', encoding='utf-8') as f:",
"processor: data = data.to(device=device) label = label.to(device=device) optimizer.zero_grad() with amp.autocast(): cla_output = model(data)",
"in aug_norm_mean], std=[s / 255. for s in aug_norm_std]), ]) query_dataset = TestDataSet(os.path.join(data_set_path,",
"torch import torch.backends.cudnn import torch.cuda.amp as amp import torch.nn as nn import torch.nn.functional",
"encode(model, test_dataset): data_loader = DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=32) processor = tqdm(data_loader) embedding_block =",
"= ImageFolder(train_path, transform=train_transforms) data_loader = DataLoader(cla_dataset, batch_size=256, shuffle=True, num_workers=32) epoch = 200 iter_per_epoch",
"data_set_path = '../../DataSet/digital-device-dataset' train_path = os.path.join(data_set_path, 'train') device = torch.device('cuda:0') num_classes = 3097",
"get_test_model() test_transforms = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in",
"'w', encoding='utf-8') as f: csv_writer = csv.writer(f) for query_key in query_res.keys(): csv_writer.writerow([query_key] +",
"as f: query_names = f.read().splitlines() with open(gallery_names_path, 'r') as f: gallery_names = f.read().splitlines()",
"= fun.cross_entropy(cla_output, label) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() scheduler.step() loss_arr.append(float(loss)) mean_loss = sum(loss_arr) / len(loss_arr)",
"= ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler = amp.GradScaler() for epoch_idx in range(epoch): loss_arr = []",
"/ 255. for m in aug_norm_mean], std=[s / 255. for s in aug_norm_std]),",
"from util.lr_scheduler import LinearCosineScheduler from util.tools import * data_set_path = '../../DataSet/digital-device-dataset' train_path =",
"gallery_embedding_block.t()) indices_top_10 = torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy() query_res = {} for idx, match_indices in",
"# matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train(): model = Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name) model = nn.DataParallel(model)",
"model(img) embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1)) embedding_block = torch.cat(embedding_block, dim=0) return embedding_block.float() # matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor)",
"name) if not os.path.exists(output_base_path): os.mkdir(output_base_path) model_name = os.path.join(output_base_path, 'model.pkl') param_name = os.path.join(output_base_path, 'param.pth')",
"torch.no_grad(): embedded_feature = model(img) embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1)) embedding_block = torch.cat(embedding_block, dim=0) return embedding_block.float()",
"import torch.cuda.amp as amp import torch.nn as nn import torch.nn.functional as fun import",
"processor: with torch.no_grad(): embedded_feature = model(img) embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1)) embedding_block = torch.cat(embedding_block, dim=0)",
"= [123.68, 116.779, 103.939] aug_norm_std = [58.393, 57.12, 57.375] name = 'r50-mlp-3097-amp' output_base_path",
"return embedding_block.float() # matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train(): model = Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name) model",
"# query_embedding_block_name = os.path.join(output_base_path, 'query-embedding-block') def get_test_model(): model = Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available():",
"os.path.join(output_base_path, 'param.pth') # gallery_embedding_block_name = os.path.join(output_base_path, 'gallery-embedding-block') # query_embedding_block_name = os.path.join(output_base_path, 'query-embedding-block') def",
"SGD from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder from tqdm import tqdm",
"model.to(device=device).train() train_transforms = transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)),",
"fun import torchvision.transforms as transforms from torch.optim import SGD from torch.utils.data import DataLoader",
"num_workers=32) epoch = 200 iter_per_epoch = len(data_loader) warm_epoch = 2 optimizer = SGD(model.parameters(),",
"as fun import torchvision.transforms as transforms from torch.optim import SGD from torch.utils.data import",
"'gallery-embedding-block') # query_embedding_block_name = os.path.join(output_base_path, 'query-embedding-block') def get_test_model(): model = Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if",
"import SGD from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder from tqdm import",
"= sum(loss_arr) / len(loss_arr) processor.set_description(' Epoch=%d/%d; mLoss=%.4f; loss=%.4f' % (epoch_idx + 1, epoch,",
"torch.nn as nn import torch.nn.functional as fun import torchvision.transforms as transforms from torch.optim",
"'train') device = torch.device('cuda:0') num_classes = 3097 embedding_features = 3097 aug_norm_mean = [123.68,",
"Epoch=%d/%d; mLoss=%.4f; loss=%.4f' % (epoch_idx + 1, epoch, mean_loss, float(loss))) torch.save(model.module.state_dict(), param_name) def",
"warm_epoch * iter_per_epoch, epoch * iter_per_epoch, max_lr=0.1) # arc_margin_product = ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler",
"batch_size=256, shuffle=True, num_workers=32) epoch = 200 iter_per_epoch = len(data_loader) warm_epoch = 2 optimizer",
"transform=train_transforms) data_loader = DataLoader(cla_dataset, batch_size=256, shuffle=True, num_workers=32) epoch = 200 iter_per_epoch = len(data_loader)",
"test_dataset): data_loader = DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=32) processor = tqdm(data_loader) embedding_block = []",
"'test', 'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block = encode(test_model, query_dataset) gallery_embedding_block = encode(test_model, gallery_dataset) query(query_embedding_block,",
"query_res[query_name][0] query_res[query_name][-1] += '}' with open(os.path.join(output_base_path, 'submission.csv'), 'w', encoding='utf-8') as f: csv_writer =",
"transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in",
"as amp import torch.nn as nn import torch.nn.functional as fun import torchvision.transforms as",
"amp import torch.nn as nn import torch.nn.functional as fun import torchvision.transforms as transforms",
"transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean],",
"tqdm(data_loader) for data, label in processor: data = data.to(device=device) label = label.to(device=device) optimizer.zero_grad()",
"csv import os import numpy as np import torch import torch.backends.cudnn import torch.cuda.amp",
"Encoder from util.data_set import TestDataSet from util.lr_scheduler import LinearCosineScheduler from util.tools import *",
"TestDataSet(os.path.join(data_set_path, 'test', 'query'), './saved-output/query_images.txt', transforms=test_transforms) gallery_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block",
"iter_per_epoch, epoch * iter_per_epoch, max_lr=0.1) # arc_margin_product = ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler = amp.GradScaler()",
"= tqdm(data_loader) embedding_block = [] for img in processor: with torch.no_grad(): embedded_feature =",
"= nn.DataParallel(model) model.to(device=device).train() train_transforms = transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0), ratio=(3. / 4., 4.",
"label.to(device=device) optimizer.zero_grad() with amp.autocast(): cla_output = model(data) # loss = arc_margin_product(cla_output, label) loss",
"f: gallery_names = f.read().splitlines() cosine_distance = torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10 = torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy()",
"= match_names query_res[query_name][0] = '{' + query_res[query_name][0] query_res[query_name][-1] += '}' with open(os.path.join(output_base_path, 'submission.csv'),",
"cla_dataset = ImageFolder(train_path, transform=train_transforms) data_loader = DataLoader(cla_dataset, batch_size=256, shuffle=True, num_workers=32) epoch = 200",
"def get_test_model(): model = Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available(): model = nn.DataParallel(model).to(device=device) model.eval() return",
"util.data_set import TestDataSet from util.lr_scheduler import LinearCosineScheduler from util.tools import * data_set_path =",
"from torch.optim import SGD from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder from",
"os.path.join(output_base_path, 'model.pkl') param_name = os.path.join(output_base_path, 'param.pth') # gallery_embedding_block_name = os.path.join(output_base_path, 'gallery-embedding-block') # query_embedding_block_name",
"contrast=0.4), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean], std=[s /",
"if not os.path.exists(output_base_path): os.mkdir(output_base_path) model_name = os.path.join(output_base_path, 'model.pkl') param_name = os.path.join(output_base_path, 'param.pth') #",
"test_transforms = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m in aug_norm_mean],",
"255. for m in aug_norm_mean], std=[s / 255. for s in aug_norm_std]), ])",
"'__main__': init() train() test_model = get_test_model() test_transforms = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m",
"os import numpy as np import torch import torch.backends.cudnn import torch.cuda.amp as amp",
"get_test_model(): model = Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available(): model = nn.DataParallel(model).to(device=device) model.eval() return model",
"import torch.backends.cudnn import torch.cuda.amp as amp import torch.nn as nn import torch.nn.functional as",
"embedding_block.float() # matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train(): model = Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name) model =",
"TestDataSet from util.lr_scheduler import LinearCosineScheduler from util.tools import * data_set_path = '../../DataSet/digital-device-dataset' train_path",
"as f: csv_writer = csv.writer(f) for query_key in query_res.keys(): csv_writer.writerow([query_key] + query_res[query_key]) if",
"model.encoder import Encoder from util.data_set import TestDataSet from util.lr_scheduler import LinearCosineScheduler from util.tools",
"for img in processor: with torch.no_grad(): embedded_feature = model(img) embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1)) embedding_block",
"def query(query_embedding_block, gallery_embedding_block, query_names_path, gallery_names_path): with open(query_names_path, 'r') as f: query_names = f.read().splitlines()",
"model(data) # loss = arc_margin_product(cla_output, label) loss = fun.cross_entropy(cla_output, label) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update()",
"(epoch_idx + 1, epoch, mean_loss, float(loss))) torch.save(model.module.state_dict(), param_name) def query(query_embedding_block, gallery_embedding_block, query_names_path, gallery_names_path):",
"nn.DataParallel(model) model.to(device=device).train() train_transforms = transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0), ratio=(3. / 4., 4. /",
"]) cla_dataset = ImageFolder(train_path, transform=train_transforms) data_loader = DataLoader(cla_dataset, batch_size=256, shuffle=True, num_workers=32) epoch =",
"= data.to(device=device) label = label.to(device=device) optimizer.zero_grad() with amp.autocast(): cla_output = model(data) # loss",
"query_res = {} for idx, match_indices in enumerate(indices_top_10): query_name = query_names[idx] match_names =",
"from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder from tqdm import tqdm from",
"= LinearCosineScheduler(optimizer, warm_epoch * iter_per_epoch, epoch * iter_per_epoch, max_lr=0.1) # arc_margin_product = ArcMarginProduct(in_features=embedding_feature,",
"fun.cross_entropy(cla_output, label) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() scheduler.step() loss_arr.append(float(loss)) mean_loss = sum(loss_arr) / len(loss_arr) processor.set_description('",
"= '../../DataSet/digital-device-dataset' train_path = os.path.join(data_set_path, 'train') device = torch.device('cuda:0') num_classes = 3097 embedding_features",
"m in aug_norm_mean], std=[s / 255. for s in aug_norm_std]), ]) cla_dataset =",
"# loss = arc_margin_product(cla_output, label) loss = fun.cross_entropy(cla_output, label) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() scheduler.step()",
"query_res[query_name] = match_names query_res[query_name][0] = '{' + query_res[query_name][0] query_res[query_name][-1] += '}' with open(os.path.join(output_base_path,",
"LinearCosineScheduler from util.tools import * data_set_path = '../../DataSet/digital-device-dataset' train_path = os.path.join(data_set_path, 'train') device",
"= DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=32) processor = tqdm(data_loader) embedding_block = [] for img",
"+ 1, epoch, mean_loss, float(loss))) torch.save(model.module.state_dict(), param_name) def query(query_embedding_block, gallery_embedding_block, query_names_path, gallery_names_path): with",
"numpy as np import torch import torch.backends.cudnn import torch.cuda.amp as amp import torch.nn",
"s in aug_norm_std]), ]) query_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'query'), './saved-output/query_images.txt', transforms=test_transforms) gallery_dataset =",
"s in aug_norm_std]), ]) cla_dataset = ImageFolder(train_path, transform=train_transforms) data_loader = DataLoader(cla_dataset, batch_size=256, shuffle=True,",
"% (epoch_idx + 1, epoch, mean_loss, float(loss))) torch.save(model.module.state_dict(), param_name) def query(query_embedding_block, gallery_embedding_block, query_names_path,",
"m in aug_norm_mean], std=[s / 255. for s in aug_norm_std]), ]) query_dataset =",
"[58.393, 57.12, 57.375] name = 'r50-mlp-3097-amp' output_base_path = os.path.join('./saved-output', name) if not os.path.exists(output_base_path):",
"scheduler = LinearCosineScheduler(optimizer, warm_epoch * iter_per_epoch, epoch * iter_per_epoch, max_lr=0.1) # arc_margin_product =",
"train_transforms = transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)), transforms.RandomHorizontalFlip(p=0.5),",
"lr=0.1, momentum=0.9, weight_decay=0.0001) scheduler = LinearCosineScheduler(optimizer, warm_epoch * iter_per_epoch, epoch * iter_per_epoch, max_lr=0.1)",
"query_res[query_name][0] = '{' + query_res[query_name][0] query_res[query_name][-1] += '}' with open(os.path.join(output_base_path, 'submission.csv'), 'w', encoding='utf-8')",
"model.load_state_dict(torch.load(param_name)) if torch.cuda.is_available(): model = nn.DataParallel(model).to(device=device) model.eval() return model def encode(model, test_dataset): data_loader",
"# gallery_embedding_block_name = os.path.join(output_base_path, 'gallery-embedding-block') # query_embedding_block_name = os.path.join(output_base_path, 'query-embedding-block') def get_test_model(): model",
"for epoch_idx in range(epoch): loss_arr = [] processor = tqdm(data_loader) for data, label",
"with open(os.path.join(output_base_path, 'submission.csv'), 'w', encoding='utf-8') as f: csv_writer = csv.writer(f) for query_key in",
"dim=0) return embedding_block.float() # matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train(): model = Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name)",
"3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4, contrast=0.4), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[m / 255. for m",
"def train(): model = Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name) model = nn.DataParallel(model) model.to(device=device).train() train_transforms =",
"= [] for match_idx in match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name] = match_names query_res[query_name][0] = '{'",
"for match_idx in match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name] = match_names query_res[query_name][0] = '{' + query_res[query_name][0]",
"weight_decay=0.0001) scheduler = LinearCosineScheduler(optimizer, warm_epoch * iter_per_epoch, epoch * iter_per_epoch, max_lr=0.1) # arc_margin_product",
"[] for img in processor: with torch.no_grad(): embedded_feature = model(img) embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1))",
"gallery_names_path): with open(query_names_path, 'r') as f: query_names = f.read().splitlines() with open(gallery_names_path, 'r') as",
"<gh_stars>0 import csv import os import numpy as np import torch import torch.backends.cudnn",
"aug_norm_std]), ]) cla_dataset = ImageFolder(train_path, transform=train_transforms) data_loader = DataLoader(cla_dataset, batch_size=256, shuffle=True, num_workers=32) epoch",
"iter_per_epoch, max_lr=0.1) # arc_margin_product = ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler = amp.GradScaler() for epoch_idx in",
"for m in aug_norm_mean], std=[s / 255. for s in aug_norm_std]), ]) query_dataset",
"'param.pth') # gallery_embedding_block_name = os.path.join(output_base_path, 'gallery-embedding-block') # query_embedding_block_name = os.path.join(output_base_path, 'query-embedding-block') def get_test_model():",
"= [] for img in processor: with torch.no_grad(): embedded_feature = model(img) embedding_block.append(fun.normalize(embedded_feature, p=2,",
"train() test_model = get_test_model() test_transforms = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[m / 255.",
"embedding_block = [] for img in processor: with torch.no_grad(): embedded_feature = model(img) embedding_block.append(fun.normalize(embedded_feature,",
"'gallery'), './saved-output/gallery_images.txt', transforms=test_transforms) query_embedding_block = encode(test_model, query_dataset) gallery_embedding_block = encode(test_model, gallery_dataset) query(query_embedding_block, gallery_embedding_block,",
"import numpy as np import torch import torch.backends.cudnn import torch.cuda.amp as amp import",
"= model(img) embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1)) embedding_block = torch.cat(embedding_block, dim=0) return embedding_block.float() # matmul",
"= Encoder(feature_num=embedding_features) torch.save(model.state_dict(), model_name) model = nn.DataParallel(model) model.to(device=device).train() train_transforms = transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08,",
"= DataLoader(cla_dataset, batch_size=256, shuffle=True, num_workers=32) epoch = 200 iter_per_epoch = len(data_loader) warm_epoch =",
"import torch import torch.backends.cudnn import torch.cuda.amp as amp import torch.nn as nn import",
"param_name) def query(query_embedding_block, gallery_embedding_block, query_names_path, gallery_names_path): with open(query_names_path, 'r') as f: query_names =",
"as f: gallery_names = f.read().splitlines() cosine_distance = torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10 = torch.topk(cosine_distance, k=10,",
"gallery_embedding_block, query_names_path, gallery_names_path): with open(query_names_path, 'r') as f: query_names = f.read().splitlines() with open(gallery_names_path,",
"model_name = os.path.join(output_base_path, 'model.pkl') param_name = os.path.join(output_base_path, 'param.pth') # gallery_embedding_block_name = os.path.join(output_base_path, 'gallery-embedding-block')",
"k=10, dim=-1).indices.cpu().numpy() query_res = {} for idx, match_indices in enumerate(indices_top_10): query_name = query_names[idx]",
"torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10 = torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy() query_res = {} for idx, match_indices",
"transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4, saturation=0.4,",
"optimizer.zero_grad() with amp.autocast(): cla_output = model(data) # loss = arc_margin_product(cla_output, label) loss =",
"'submission.csv'), 'w', encoding='utf-8') as f: csv_writer = csv.writer(f) for query_key in query_res.keys(): csv_writer.writerow([query_key]",
"torch.cuda.is_available(): model = nn.DataParallel(model).to(device=device) model.eval() return model def encode(model, test_dataset): data_loader = DataLoader(test_dataset,",
"= 'r50-mlp-3097-amp' output_base_path = os.path.join('./saved-output', name) if not os.path.exists(output_base_path): os.mkdir(output_base_path) model_name = os.path.join(output_base_path,",
"torch.backends.cudnn import torch.cuda.amp as amp import torch.nn as nn import torch.nn.functional as fun",
"import torchvision.transforms as transforms from torch.optim import SGD from torch.utils.data import DataLoader from",
"import os import numpy as np import torch import torch.backends.cudnn import torch.cuda.amp as",
"in processor: with torch.no_grad(): embedded_feature = model(img) embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1)) embedding_block = torch.cat(embedding_block,",
"loss_arr = [] processor = tqdm(data_loader) for data, label in processor: data =",
"util.lr_scheduler import LinearCosineScheduler from util.tools import * data_set_path = '../../DataSet/digital-device-dataset' train_path = os.path.join(data_set_path,",
"in aug_norm_std]), ]) query_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'query'), './saved-output/query_images.txt', transforms=test_transforms) gallery_dataset = TestDataSet(os.path.join(data_set_path,",
"= transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)), transforms.RandomHorizontalFlip(p=0.5), transforms.ColorJitter(brightness=0.4,",
"* iter_per_epoch, epoch * iter_per_epoch, max_lr=0.1) # arc_margin_product = ArcMarginProduct(in_features=embedding_feature, out_features=num_classes) scaler =",
"idx, match_indices in enumerate(indices_top_10): query_name = query_names[idx] match_names = [] for match_idx in",
"warm_epoch = 2 optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0001) scheduler = LinearCosineScheduler(optimizer, warm_epoch",
"os.path.join(data_set_path, 'train') device = torch.device('cuda:0') num_classes = 3097 embedding_features = 3097 aug_norm_mean =",
"torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy() query_res = {} for idx, match_indices in enumerate(indices_top_10): query_name =",
"batch_size=256, shuffle=False, num_workers=32) processor = tqdm(data_loader) embedding_block = [] for img in processor:",
"embedding_block.append(fun.normalize(embedded_feature, p=2, dim=-1)) embedding_block = torch.cat(embedding_block, dim=0) return embedding_block.float() # matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def",
"param_name = os.path.join(output_base_path, 'param.pth') # gallery_embedding_block_name = os.path.join(output_base_path, 'gallery-embedding-block') # query_embedding_block_name = os.path.join(output_base_path,",
"DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=32) processor = tqdm(data_loader) embedding_block = [] for img in",
"/ 255. for s in aug_norm_std]), ]) cla_dataset = ImageFolder(train_path, transform=train_transforms) data_loader =",
"match_names query_res[query_name][0] = '{' + query_res[query_name][0] query_res[query_name][-1] += '}' with open(os.path.join(output_base_path, 'submission.csv'), 'w',",
"= tqdm(data_loader) for data, label in processor: data = data.to(device=device) label = label.to(device=device)",
"f.read().splitlines() cosine_distance = torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10 = torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy() query_res = {}",
"torch.nn.functional as fun import torchvision.transforms as transforms from torch.optim import SGD from torch.utils.data",
"= nn.DataParallel(model).to(device=device) model.eval() return model def encode(model, test_dataset): data_loader = DataLoader(test_dataset, batch_size=256, shuffle=False,",
"= [] processor = tqdm(data_loader) for data, label in processor: data = data.to(device=device)",
"[123.68, 116.779, 103.939] aug_norm_std = [58.393, 57.12, 57.375] name = 'r50-mlp-3097-amp' output_base_path =",
"for data, label in processor: data = data.to(device=device) label = label.to(device=device) optimizer.zero_grad() with",
"enumerate(indices_top_10): query_name = query_names[idx] match_names = [] for match_idx in match_indices: match_names.append(gallery_names[match_idx]) query_res[query_name]",
"os.path.join(output_base_path, 'gallery-embedding-block') # query_embedding_block_name = os.path.join(output_base_path, 'query-embedding-block') def get_test_model(): model = Encoder(feature_num=embedding_features) model.load_state_dict(torch.load(param_name))",
"if __name__ == '__main__': init() train() test_model = get_test_model() test_transforms = transforms.Compose([ transforms.Resize(256),",
"model_name) model = nn.DataParallel(model) model.to(device=device).train() train_transforms = transforms.Compose([ transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0), ratio=(3. /",
"'r50-mlp-3097-amp' output_base_path = os.path.join('./saved-output', name) if not os.path.exists(output_base_path): os.mkdir(output_base_path) model_name = os.path.join(output_base_path, 'model.pkl')",
"for idx, match_indices in enumerate(indices_top_10): query_name = query_names[idx] match_names = [] for match_idx",
"transforms.Normalize(mean=[m / 255. for m in aug_norm_mean], std=[s / 255. for s in",
"* data_set_path = '../../DataSet/digital-device-dataset' train_path = os.path.join(data_set_path, 'train') device = torch.device('cuda:0') num_classes =",
"dim=-1)) embedding_block = torch.cat(embedding_block, dim=0) return embedding_block.float() # matmul 函数不支持fp16(HalfTensor),将其转换为fp32(FloatTensor) def train(): model",
"float(loss))) torch.save(model.module.state_dict(), param_name) def query(query_embedding_block, gallery_embedding_block, query_names_path, gallery_names_path): with open(query_names_path, 'r') as f:",
"gallery_names = f.read().splitlines() cosine_distance = torch.matmul(query_embedding_block, gallery_embedding_block.t()) indices_top_10 = torch.topk(cosine_distance, k=10, dim=-1).indices.cpu().numpy() query_res",
"query_names_path, gallery_names_path): with open(query_names_path, 'r') as f: query_names = f.read().splitlines() with open(gallery_names_path, 'r')",
"]) query_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'query'), './saved-output/query_images.txt', transforms=test_transforms) gallery_dataset = TestDataSet(os.path.join(data_set_path, 'test', 'gallery'),"
] |
[
"Created by yifei on 2018/2/5. \"\"\" import control_center if __name__ == \"__main__\": root_url",
"# -*- coding: UTF-8 -*- \"\"\" Description [] Created by yifei on 2018/2/5.",
"yifei on 2018/2/5. \"\"\" import control_center if __name__ == \"__main__\": root_url = \"http://blog.csdn.net/hustqb/article/list\"",
"Description [] Created by yifei on 2018/2/5. \"\"\" import control_center if __name__ ==",
"#!/usr/bin/python # -*- coding: UTF-8 -*- \"\"\" Description [] Created by yifei on",
"\"\"\" import control_center if __name__ == \"__main__\": root_url = \"http://blog.csdn.net/hustqb/article/list\" spider = control_center.SpiderMain()",
"coding: UTF-8 -*- \"\"\" Description [] Created by yifei on 2018/2/5. \"\"\" import",
"by yifei on 2018/2/5. \"\"\" import control_center if __name__ == \"__main__\": root_url =",
"UTF-8 -*- \"\"\" Description [] Created by yifei on 2018/2/5. \"\"\" import control_center",
"2018/2/5. \"\"\" import control_center if __name__ == \"__main__\": root_url = \"http://blog.csdn.net/hustqb/article/list\" spider =",
"[] Created by yifei on 2018/2/5. \"\"\" import control_center if __name__ == \"__main__\":",
"-*- \"\"\" Description [] Created by yifei on 2018/2/5. \"\"\" import control_center if",
"on 2018/2/5. \"\"\" import control_center if __name__ == \"__main__\": root_url = \"http://blog.csdn.net/hustqb/article/list\" spider",
"-*- coding: UTF-8 -*- \"\"\" Description [] Created by yifei on 2018/2/5. \"\"\"",
"\"\"\" Description [] Created by yifei on 2018/2/5. \"\"\" import control_center if __name__",
"import control_center if __name__ == \"__main__\": root_url = \"http://blog.csdn.net/hustqb/article/list\" spider = control_center.SpiderMain() spider.start_crawling(root_url)"
] |
[
"= 90 if(\"richClubPercentage\" in config): richClubPercentage = config[\"richClubPercentage\"]; networks = jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks",
": calcMatchIndex, \"BetweenessCentrality\" : calcBetweenessCentrality, \"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted, \"BetweennessCentralization\" : calcBetweennessCentralization, \"RichClubCoefficient\" :",
"else: return None, g.modularity(Ci, weights=None); def calcDegree(g): results = np.array(g.degree(mode=\"ALL\")) return results, np.average(results)",
"\"retain-weights\":false, # \"threshold\": \"none\" richClubPercentage = 90 if(\"richClubPercentage\" in config): richClubPercentage = config[\"richClubPercentage\"];",
"\"transform\":\"absolute\", //\"absolute\" or \"signed\" # \"retain-weights\":false, # \"threshold\": \"none\" richClubPercentage = 90 if(\"richClubPercentage\"",
"results, np.average(results) def calcInDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.indegree()) return results,",
"= int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): ret = float(obj) elif isinstance(obj,",
"range(g.vcount())] else: return [[(e.target,1) if e.target!=i else (e.source,1) for e in g.es[g.incident(i,mode=mode)]] for",
"def warning(msg): global results results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\", \"msg\": msg}) print(msg) def error(msg): global",
"= float(obj) elif isinstance(obj, (np.ndarray,)): ret = obj.tolist() else: ret = json.JSONEncoder.default(self, obj)",
": calcClusteringCoefficient, \"Coreness\" : calcCoreness, \"MatchIndex\" : calcMatchIndex, \"BetweenessCentrality\" : calcBetweenessCentrality, \"BetweenessCentralityWeighted\" :",
"global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) exitApp() configFilename = \"config.json\" argCount",
"= np.array(g.outdegree()) return results, np.average(results) def calcStrength(g): if(\"weight\" not in g.edge_attributes()): return (None,None)",
"return numbers def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in g.edge_attributes()): return [[(e.target,e[\"weight\"]) if e.target!=i else (e.source,e[\"weight\"])",
"fp, cls=NumpyEncoder) if len(results[\"errors\"]) > 0: sys.exit(1) else: sys.exit() def exitAppWithError(msg): global results",
"= \"weight\")) return results, np.average(results) def calcClusteringCoefficient(g): # if(\"weight\" in g.edge_attributes()): results =",
"for i in range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else:",
"measurements = { \"Degree\" : calcDegree, \"InDegree\" : calcInDegree, \"OutDegree\" : calcOutDegree, \"Strength\"",
"not in g.edge_attributes() or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"IN\", weights =",
"neigh] for neigh in neighs] kappa = np.zeros(g.vcount()) kappaSi = [[] for _",
"{\"errors\": [], \"warnings\": [], \"brainlife\": [], \"datatype_tags\": [], \"tags\": []} def warning(msg): global",
"None, meanMatchIndex def calcBetweenessCentrality(g): result = np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result) def calcBetweenessCentralityWeighted(g): if(\"weight\" not",
"= np.zeros(g.ecount()) for id,e in enumerate(g.es): node1,node2 = e.tuple viz1 = g.neighbors(node1) viz2",
"= jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks = [] for network in tqdm(networks): weighted = \"weight\"",
"global results with open(\"product.json\", \"w\") as fp: json.dump(results, fp, cls=NumpyEncoder) if len(results[\"errors\"]) >",
"or \"signed\" # \"retain-weights\":false, # \"threshold\": \"none\" richClubPercentage = 90 if(\"richClubPercentage\" in config):",
"= np.nonzero(degree>=dT)[0] indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1): RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC =",
"g.edge_attributes()): return (None,None) results = np.array(g.strength(mode=\"ALL\", weights = \"weight\")) return results, np.average(results) def",
"not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"OUT\", weights = \"weight\")) return results, np.average(results)",
"outputNetworks = [] for network in tqdm(networks): weighted = \"weight\" in network.edge_attributes() hasCommunities",
"network.vs[measurement] = nodePropData if(networkPropData is not None): if(nodePropData is not None): #Average measurement",
"cneighs[i]]) communityDegrees = {community:0 for community in nodeCommunities} for community,weight in cneighs[i]: communityDegrees[community]+=weight",
"= [d[ni] for ni in names] if(returnDict): return numbers,d else: return numbers def",
"d = {ni: indi for indi, ni in enumerate(set(names))} numbers = [d[ni] for",
"in range(max(Ci)+1)] for i in range(g.vcount()): kappa[i] = np.sum([weight for community,weight in cneighs[i]",
"#results['brainlife'].append({\"type\": \"warning\", \"msg\": msg}) print(msg) def error(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\":",
"np.array(g.outdegree()) return results, np.average(results) def calcStrength(g): if(\"weight\" not in g.edge_attributes()): return (None,None) results",
"in g.edge_attributes() or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"OUT\", weights = \"weight\"))",
"is not None): network.vs[measurement] = nodePropData if(networkPropData is not None): if(nodePropData is not",
"else (e.source,1) for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\"",
"in neigh] for neigh in neighs] if(\"weight\" in g.edge_attributes()): degrees = np.array(g.strength(mode=mode,weights=\"weight\")) else:",
"def calcOutStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return (None,None) results =",
"= None if isinstance(ret, (bytes, bytearray)): ret = ret.decode(\"utf-8\") return ret results =",
"np.average(results) def calcInDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.indegree()) return results, np.average(results)",
"= measurementFunction(network) if(nodePropData is not None): network.vs[measurement] = nodePropData if(networkPropData is not None):",
"np.nanmean(results) def calcCoreness(g): results = np.array(g.coreness(mode=\"ALL\")) return results, None def calcMatchIndex(g): degree =",
"msg}) print(msg) exitApp() configFilename = \"config.json\" argCount = len(sys.argv) if(argCount > 1): configFilename",
"g.transitivity_local_undirected(weights=None) # else: # results = g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0), np.nanmean(results) def calcCoreness(g): results",
"measurement,measurementFunction in measurements.items(): nodePropData,networkPropData = measurementFunction(network) if(nodePropData is not None): network.vs[measurement] = nodePropData",
"outputDirectory = \"output\" outputFile = PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with open(configFilename, \"r\") as",
"= {ni: indi for indi, ni in enumerate(set(names))} numbers = [d[ni] for ni",
"def reindexList(names,returnDict=False): d = {ni: indi for indi, ni in enumerate(set(names))} numbers =",
"if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) neighs = getNeighborhoods(g,mode=mode) cneighs",
"return (None,None) results = np.array(g.strength(mode=\"OUT\", weights = \"weight\")) return results, np.average(results) def calcClusteringCoefficient(g):",
"[[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh in neighs] kappa = np.zeros(g.vcount()) kappaSi",
"return False try: numericValue = float(value) return np.isfinite(numericValue) except ValueError: return False class",
"np.sum([weight for community,weight in cneighs[i] if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi = np.zeros(max(Ci)+1) stdKappaSi =",
"= len(sys.argv) if(argCount > 1): configFilename = sys.argv[1] outputDirectory = \"output\" outputFile =",
"set(viz2) if ((degree[node1]+degree[node2]) > 2): matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id] = 0 meanMatchIndex",
"is not None): if(nodePropData is not None): #Average measurement network[\"Avg. \"+measurement] = networkPropData",
"#results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) def exitApp(): global results with open(\"product.json\", \"w\") as",
"python import sys import os.path from os.path import join as PJ import re",
"g.edge_attributes()): results = g.transitivity_local_undirected(weights=None) # else: # results = g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0), np.nanmean(results)",
"else: return numbers def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in g.edge_attributes()): return [[(e.target,e[\"weight\"]) if e.target!=i else",
"def calcStrength(g): if(\"weight\" not in g.edge_attributes()): return (None,None) results = np.array(g.strength(mode=\"ALL\", weights =",
"results = np.array(g.coreness(mode=\"ALL\")) return results, None def calcMatchIndex(g): degree = np.array(g.degree()) matchIndex =",
"return numbers,d else: return numbers def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in g.edge_attributes()): return [[(e.target,e[\"weight\"]) if",
"None,0 denom = (vnum-1)*(vnum-2) temparr = [2*i/denom for i in G.betweenness()] max_temparr =",
"if e.target!=i else (e.source,e[\"weight\"]) for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] else:",
"(None,None) results = np.array(g.indegree()) return results, np.average(results) def calcOutDegree(g): if(not g.is_directed()): return (None,None)",
"getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh in neighs] if(\"weight\"",
"set([community for community,weight in cneighs[i]]) communityDegrees = {community:0 for community in nodeCommunities} for",
"\"output\" outputFile = PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with open(configFilename, \"r\") as fd: config",
"igraph as ig import jgf import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as",
"network[\"Avg. \"+measurement] = networkPropData else: network[measurement] = networkPropData outputNetworks.append(network) jgf.igraph.save(outputNetworks, outputFile, compressed=True) exitApp()",
"[], \"datatype_tags\": [], \"tags\": []} def warning(msg): global results results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\", \"msg\":",
"calcBetweenessCentralityWeighted(g): if(\"weight\" not in g.edge_attributes()): return (None,None) result = np.array(g.betweenness(weights=\"weight\")) return result,np.average(result) def",
"= ret.decode(\"utf-8\") return ret results = {\"errors\": [], \"warnings\": [], \"brainlife\": [], \"datatype_tags\":",
"for neigh in neighs] kappa = np.zeros(g.vcount()) kappaSi = [[] for _ in",
"g.edge_attributes()): return (None,None) result = np.array(g.betweenness(weights=\"weight\")) return result,np.average(result) def calcBetweennessCentralization(G): vnum = G.vcount()",
"calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) neighs = getNeighborhoods(g,mode=mode)",
"#results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) exitApp() configFilename = \"config.json\" argCount = len(sys.argv) if(argCount",
"dT = int(np.percentile(degree,Trc)) indNodes = np.nonzero(degree>=dT)[0] indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1): RC =",
"matplotlib.pyplot as plt def calcModularity(g): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return",
"avgKappaSi[ci] = np.average(kappaSi[ci]) stdKappaSi[ci] = np.std(kappaSi[ci]) zmodule = np.zeros(g.vcount()) for i in range(g.vcount()):",
"results = g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0), np.nanmean(results) def calcCoreness(g): results = np.array(g.coreness(mode=\"ALL\")) return results,",
"else: return (None,None) neighs = getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth in neigh]",
"Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) neighs = getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth) for",
"if(\"weight\" not in g.edge_attributes()): return (None,None) result = np.array(g.betweenness(weights=\"weight\")) return result,np.average(result) def calcBetweennessCentralization(G):",
"calcBetweenessCentralityWeighted, \"BetweennessCentralization\" : calcBetweennessCentralization, \"RichClubCoefficient\" : calcRichClubCoefficient, \"DegreeAssortativity\" : calcDegreeAssortativity, \"Diameter\" : calcDiameter,",
"if math.isnan(ret): ret = None if isinstance(ret, (bytes, bytearray)): ret = ret.decode(\"utf-8\") return",
"tqdm import tqdm import igraph as ig import jgf import matplotlib as mpl",
"in g.edge_attributes()): return [[(e.target,e[\"weight\"]) if e.target!=i else (e.source,e[\"weight\"]) for e in g.es[g.incident(i,mode=mode)]] for",
"g.edge_attributes()): return [[(e.target,e[\"weight\"]) if e.target!=i else (e.source,e[\"weight\"]) for e in g.es[g.incident(i,mode=mode)]] for i",
"for i in G.betweenness()] max_temparr = max(temparr) return None,sum(max_temparr-i for i in temparr)/(vnum-1)",
"in range(g.vcount()): nodeCommunities = set([community for community,weight in cneighs[i]]) communityDegrees = {community:0 for",
"def calcClusteringCoefficient(g): # if(\"weight\" in g.edge_attributes()): results = g.transitivity_local_undirected(weights=None) # else: # results",
"sys import os.path from os.path import join as PJ import re import json",
"[] for network in tqdm(networks): weighted = \"weight\" in network.edge_attributes() hasCommunities = \"Community\"",
"None): if(nodePropData is not None): #Average measurement network[\"Avg. \"+measurement] = networkPropData else: network[measurement]",
"network.edge_attributes() hasCommunities = \"Community\" in network.vertex_attributes() for measurement,measurementFunction in measurements.items(): nodePropData,networkPropData = measurementFunction(network)",
"if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) if(\"weight\" in g.edge_attributes()): return",
"import tqdm import igraph as ig import jgf import matplotlib as mpl mpl.use('Agg')",
"ret = ret.decode(\"utf-8\") return ret results = {\"errors\": [], \"warnings\": [], \"brainlife\": [],",
"measurementFunction(network) if(nodePropData is not None): network.vs[measurement] = nodePropData if(networkPropData is not None): if(nodePropData",
"\"tags\": []} def warning(msg): global results results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\", \"msg\": msg}) print(msg) def",
"calcDegreeAssortativity, \"Diameter\" : calcDiameter, \"ModuleDegreeZScore\" : calcModuleDegreeZScore, \"ParticipationCoeff\" : calcParticipationCoeff, \"Modularity\" : calcModularity,",
"exitApp(): global results with open(\"product.json\", \"w\") as fp: json.dump(results, fp, cls=NumpyEncoder) if len(results[\"errors\"])",
"< 3: return None,0 denom = (vnum-1)*(vnum-2) temparr = [2*i/denom for i in",
"g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"OUT\", weights = \"weight\")) return results, np.average(results) def",
"np.zeros(g.ecount()) for id,e in enumerate(g.es): node1,node2 = e.tuple viz1 = g.neighbors(node1) viz2 =",
"calcDiameter(g): if(\"weight\" in g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False): d =",
"np.array(g.strength(mode=\"ALL\", weights = \"weight\")) return results, np.average(results) def calcInStrength(g): if(\"weight\" not in g.edge_attributes()",
"jgf import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt def calcModularity(g): if(\"Community\"",
"node1,node2 = e.tuple viz1 = g.neighbors(node1) viz2 = g.neighbors(node2) sharedNei = set(viz1) &",
"obj.tolist() else: ret = json.JSONEncoder.default(self, obj) if isinstance(ret, (float)): if math.isnan(ret): ret =",
"if(\"richClubPercentage\" in config): richClubPercentage = config[\"richClubPercentage\"]; networks = jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks = []",
"np.uint8, np.uint16, np.uint32, np.uint64)): ret = int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):",
"sys.argv[1] outputDirectory = \"output\" outputFile = PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with open(configFilename, \"r\")",
"= np.average(kappaSi[ci]) stdKappaSi[ci] = np.std(kappaSi[ci]) zmodule = np.zeros(g.vcount()) for i in range(g.vcount()): ci",
"ret = int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): ret = float(obj) elif",
"def calcRichClubCoefficient(g, highest=True, scores=None, indices_only=False): Trc = richClubPercentage degree = np.array(g.degree()) edges =",
"calcBetweennessCentralization, \"RichClubCoefficient\" : calcRichClubCoefficient, \"DegreeAssortativity\" : calcDegreeAssortativity, \"Diameter\" : calcDiameter, \"ModuleDegreeZScore\" : calcModuleDegreeZScore,",
"3: return None,0 denom = (vnum-1)*(vnum-2) temparr = [2*i/denom for i in G.betweenness()]",
"if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"OUT\", weights",
"in g.edge_attributes()): return (None,None) result = np.array(g.betweenness(weights=\"weight\")) return result,np.average(result) def calcBetweennessCentralization(G): vnum =",
"\"Diameter\" : calcDiameter, \"ModuleDegreeZScore\" : calcModuleDegreeZScore, \"ParticipationCoeff\" : calcParticipationCoeff, \"Modularity\" : calcModularity, }",
"community,weight in cneighs[i]: communityDegrees[community]+=weight kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2)) result = 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] = 0",
"mpl.use('Agg') import matplotlib.pyplot as plt def calcModularity(g): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"])",
"names] if(returnDict): return numbers,d else: return numbers def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in g.edge_attributes()): return",
"NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64,",
"in nodeCommunities} for community,weight in cneighs[i]: communityDegrees[community]+=weight kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2)) result = 1.0-kappasi/np.power(degrees,2.0)",
"np.uint64)): ret = int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): ret = float(obj)",
"os.path import join as PJ import re import json import numpy as np",
"if(not g.is_directed()): return (None,None) results = np.array(g.outdegree()) return results, np.average(results) def calcStrength(g): if(\"weight\"",
"if(\"weight\" in g.edge_attributes()): return None, g.modularity(Ci, weights=\"weight\"); else: return None, g.modularity(Ci, weights=None); def",
": calcBetweennessCentralization, \"RichClubCoefficient\" : calcRichClubCoefficient, \"DegreeAssortativity\" : calcDegreeAssortativity, \"Diameter\" : calcDiameter, \"ModuleDegreeZScore\" :",
"((degree[node1]+degree[node2]) > 2): matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id] = 0 meanMatchIndex = np.mean(matchIndex)",
"is not None): #Average measurement network[\"Avg. \"+measurement] = networkPropData else: network[measurement] = networkPropData",
"\"threshold\": \"none\" richClubPercentage = 90 if(\"richClubPercentage\" in config): richClubPercentage = config[\"richClubPercentage\"]; networks =",
"np.uint32, np.uint64)): ret = int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): ret =",
"int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): ret = float(obj) elif isinstance(obj, (np.ndarray,)):",
"g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"IN\", weights = \"weight\")) return results, np.average(results) def",
"np.array(g.get_edgelist()) sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]] dT = int(np.percentile(degree,Trc)) indNodes = np.nonzero(degree>=dT)[0] indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0]",
"= np.sum(np.power(list(communityDegrees.values()),2)) result = 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] = 0 return result,None measurements = {",
"calcStrength(g): if(\"weight\" not in g.edge_attributes()): return (None,None) results = np.array(g.strength(mode=\"ALL\", weights = \"weight\"))",
"np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1): RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC = 0 return None,RC def",
"(e.source,e[\"weight\"]) for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] else: return [[(e.target,1) if",
"nodePropData if(networkPropData is not None): if(nodePropData is not None): #Average measurement network[\"Avg. \"+measurement]",
"isFloat(value): if(value is None): return False try: numericValue = float(value) return np.isfinite(numericValue) except",
"calcDegree(g): results = np.array(g.degree(mode=\"ALL\")) return results, np.average(results) def calcInDegree(g): if(not g.is_directed()): return (None,None)",
"json.JSONEncoder.default(self, obj) if isinstance(ret, (float)): if math.isnan(ret): ret = None if isinstance(ret, (bytes,",
"np.array(g.degree(mode=\"ALL\")) return results, np.average(results) def calcInDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.indegree())",
"msg}) print(msg) def exitApp(): global results with open(\"product.json\", \"w\") as fp: json.dump(results, fp,",
"PJ import re import json import numpy as np from tqdm import tqdm",
"_ in range(max(Ci)+1)] for i in range(g.vcount()): kappa[i] = np.sum([weight for community,weight in",
"plt def calcModularity(g): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) if(\"weight\"",
"in g.edge_attributes()): return None, g.modularity(Ci, weights=\"weight\"); else: return None, g.modularity(Ci, weights=None); def calcDegree(g):",
"G.vcount() if vnum < 3: return None,0 denom = (vnum-1)*(vnum-2) temparr = [2*i/denom",
"np.array(g.strength(mode=\"IN\", weights = \"weight\")) return results, np.average(results) def calcOutStrength(g): if(\"weight\" not in g.edge_attributes()",
"import json import numpy as np from tqdm import tqdm import igraph as",
"def calcDiameter(g): if(\"weight\" in g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False): d",
"results with open(\"product.json\", \"w\") as fp: json.dump(results, fp, cls=NumpyEncoder) if len(results[\"errors\"]) > 0:",
"None def calcMatchIndex(g): degree = np.array(g.degree()) matchIndex = np.zeros(g.ecount()) for id,e in enumerate(g.es):",
"= G.vcount() if vnum < 3: return None,0 denom = (vnum-1)*(vnum-2) temparr =",
"kappa = np.zeros(g.vcount()) kappaSi = [[] for _ in range(max(Ci)+1)] for i in",
"return results, np.average(results) def calcClusteringCoefficient(g): # if(\"weight\" in g.edge_attributes()): results = g.transitivity_local_undirected(weights=None) #",
"result = 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] = 0 return result,None measurements = { \"Degree\" :",
"calcOutDegree, \"Strength\" : calcStrength, \"InStrength\" : calcInStrength, \"OutStrength\" : calcOutStrength, \"ClusteringCoefficient\" : calcClusteringCoefficient,",
"as fd: config = json.load(fd) # \"transform\":\"absolute\", //\"absolute\" or \"signed\" # \"retain-weights\":false, #",
"> 2): matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id] = 0 meanMatchIndex = np.mean(matchIndex) return",
"reindexList(names,returnDict=False): d = {ni: indi for indi, ni in enumerate(set(names))} numbers = [d[ni]",
"= 0 return None,RC def calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g): if(\"weight\" in g.edge_attributes()):",
"max(temparr) return None,sum(max_temparr-i for i in temparr)/(vnum-1) def calcRichClubCoefficient(g, highest=True, scores=None, indices_only=False): Trc",
"calcBetweenessCentrality, \"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted, \"BetweennessCentralization\" : calcBetweennessCentralization, \"RichClubCoefficient\" : calcRichClubCoefficient, \"DegreeAssortativity\" : calcDegreeAssortativity,",
"= \"Community\" in network.vertex_attributes() for measurement,measurementFunction in measurements.items(): nodePropData,networkPropData = measurementFunction(network) if(nodePropData is",
"(None,None) neighs = getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh",
"(None,None) if(\"weight\" in g.edge_attributes()): return None, g.modularity(Ci, weights=\"weight\"); else: return None, g.modularity(Ci, weights=None);",
"matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt def calcModularity(g): if(\"Community\" in g.vertex_attributes()):",
"\"r\") as fd: config = json.load(fd) # \"transform\":\"absolute\", //\"absolute\" or \"signed\" # \"retain-weights\":false,",
"= 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC = 0 return None,RC def calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed()) def",
"return results, np.average(results) def calcStrength(g): if(\"weight\" not in g.edge_attributes()): return (None,None) results =",
"np.array(g.degree()) matchIndex = np.zeros(g.ecount()) for id,e in enumerate(g.es): node1,node2 = e.tuple viz1 =",
"g.edge_attributes() or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"OUT\", weights = \"weight\")) return",
"np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result) def calcBetweenessCentralityWeighted(g): if(\"weight\" not in g.edge_attributes()): return (None,None) result =",
"range(g.vcount()): ci = Ci[i] if(stdKappaSi[ci]>0): zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\"",
"\"Modularity\" : calcModularity, } def isFloat(value): if(value is None): return False try: numericValue",
"= degree[edges[:,0]],degree[edges[:,1]] dT = int(np.percentile(degree,Trc)) indNodes = np.nonzero(degree>=dT)[0] indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1):",
"i in range(g.vcount()): kappa[i] = np.sum([weight for community,weight in cneighs[i] if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i])",
"in G.betweenness()] max_temparr = max(temparr) return None,sum(max_temparr-i for i in temparr)/(vnum-1) def calcRichClubCoefficient(g,",
"matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id] = 0 meanMatchIndex = np.mean(matchIndex) return None, meanMatchIndex",
"matchIndex[id] = 0 meanMatchIndex = np.mean(matchIndex) return None, meanMatchIndex def calcBetweenessCentrality(g): result =",
"calcModularity(g): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) if(\"weight\" in g.edge_attributes()):",
"np.zeros(g.vcount()) kappaSi = [[] for _ in range(max(Ci)+1)] for i in range(g.vcount()): kappa[i]",
"if(value is None): return False try: numericValue = float(value) return np.isfinite(numericValue) except ValueError:",
"(np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): ret =",
"edges = np.array(g.get_edgelist()) sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]] dT = int(np.percentile(degree,Trc)) indNodes = np.nonzero(degree>=dT)[0] indEdges",
"ret results = {\"errors\": [], \"warnings\": [], \"brainlife\": [], \"datatype_tags\": [], \"tags\": []}",
"#Average measurement network[\"Avg. \"+measurement] = networkPropData else: network[measurement] = networkPropData outputNetworks.append(network) jgf.igraph.save(outputNetworks, outputFile,",
"richClubPercentage = 90 if(\"richClubPercentage\" in config): richClubPercentage = config[\"richClubPercentage\"]; networks = jgf.igraph.load(config[\"network\"], compressed=True)",
"= np.sum([weight for community,weight in cneighs[i] if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi = np.zeros(max(Ci)+1) stdKappaSi",
"kappa[i] = np.sum([weight for community,weight in cneighs[i] if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi = np.zeros(max(Ci)+1)",
"g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] else: return [[(e.target,1) if e.target!=i else (e.source,1) for",
"if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"IN\", weights",
"np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees = np.array(g.degree(mode=mode)) kappasi = np.zeros(g.vcount()) for i in range(g.vcount()): nodeCommunities",
"\"DegreeAssortativity\" : calcDegreeAssortativity, \"Diameter\" : calcDiameter, \"ModuleDegreeZScore\" : calcModuleDegreeZScore, \"ParticipationCoeff\" : calcParticipationCoeff, \"Modularity\"",
": calcBetweenessCentrality, \"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted, \"BetweennessCentralization\" : calcBetweennessCentralization, \"RichClubCoefficient\" : calcRichClubCoefficient, \"DegreeAssortativity\" :",
"highest=True, scores=None, indices_only=False): Trc = richClubPercentage degree = np.array(g.degree()) edges = np.array(g.get_edgelist()) sourceDegree,targetDegree",
"np.array(g.indegree()) return results, np.average(results) def calcOutDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.outdegree())",
"communityDegrees[community]+=weight kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2)) result = 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] = 0 return result,None measurements",
"cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh in neighs] kappa =",
"def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8,",
"None): network.vs[measurement] = nodePropData if(networkPropData is not None): if(nodePropData is not None): #Average",
"numericValue = float(value) return np.isfinite(numericValue) except ValueError: return False class NumpyEncoder(json.JSONEncoder): def default(self,",
"cneighs[i]: communityDegrees[community]+=weight kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2)) result = 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] = 0 return result,None",
"getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh in neighs] kappa",
"return zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None)",
"calcParticipationCoeff, \"Modularity\" : calcModularity, } def isFloat(value): if(value is None): return False try:",
"np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): ret = int(obj) elif isinstance(obj, (np.float_,",
"= np.zeros(g.vcount()) kappaSi = [[] for _ in range(max(Ci)+1)] for i in range(g.vcount()):",
"os.makedirs(outputDirectory) with open(configFilename, \"r\") as fd: config = json.load(fd) # \"transform\":\"absolute\", //\"absolute\" or",
"return results, np.average(results) def calcOutDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.outdegree()) return",
"e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci",
"id,e in enumerate(g.es): node1,node2 = e.tuple viz1 = g.neighbors(node1) viz2 = g.neighbors(node2) sharedNei",
"if ((degree[node1]+degree[node2]) > 2): matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id] = 0 meanMatchIndex =",
"= \"weight\")) return results, np.average(results) def calcInStrength(g): if(\"weight\" not in g.edge_attributes() or not",
"= np.zeros(g.vcount()) for i in range(g.vcount()): nodeCommunities = set([community for community,weight in cneighs[i]])",
"isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): ret = float(obj) elif isinstance(obj, (np.ndarray,)): ret =",
"PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with open(configFilename, \"r\") as fd: config = json.load(fd) #",
"= np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1): RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC = 0 return None,RC",
"for i in range(g.vcount()): kappa[i] = np.sum([weight for community,weight in cneighs[i] if community==Ci[i]])",
"g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) if(\"weight\" in g.edge_attributes()): return None, g.modularity(Ci,",
"as np from tqdm import tqdm import igraph as ig import jgf import",
"[[] for _ in range(max(Ci)+1)] for i in range(g.vcount()): kappa[i] = np.sum([weight for",
"\"msg\": msg}) print(msg) def error(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg)",
"sys.exit(1) else: sys.exit() def exitAppWithError(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg)",
"= {community:0 for community in nodeCommunities} for community,weight in cneighs[i]: communityDegrees[community]+=weight kappasi[i] =",
"np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): ret = int(obj) elif",
"calcInStrength, \"OutStrength\" : calcOutStrength, \"ClusteringCoefficient\" : calcClusteringCoefficient, \"Coreness\" : calcCoreness, \"MatchIndex\" : calcMatchIndex,",
"not in g.edge_attributes()): return (None,None) result = np.array(g.betweenness(weights=\"weight\")) return result,np.average(result) def calcBetweennessCentralization(G): vnum",
"return None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g): if(\"weight\" in g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return None,g.diameter(directed=g.is_directed()) def",
"return ret results = {\"errors\": [], \"warnings\": [], \"brainlife\": [], \"datatype_tags\": [], \"tags\":",
"\"BetweennessCentralization\" : calcBetweennessCentralization, \"RichClubCoefficient\" : calcRichClubCoefficient, \"DegreeAssortativity\" : calcDegreeAssortativity, \"Diameter\" : calcDiameter, \"ModuleDegreeZScore\"",
"\"msg\": msg}) print(msg) def exitApp(): global results with open(\"product.json\", \"w\") as fp: json.dump(results,",
"return None,0 denom = (vnum-1)*(vnum-2) temparr = [2*i/denom for i in G.betweenness()] max_temparr",
": calcOutDegree, \"Strength\" : calcStrength, \"InStrength\" : calcInStrength, \"OutStrength\" : calcOutStrength, \"ClusteringCoefficient\" :",
"} def isFloat(value): if(value is None): return False try: numericValue = float(value) return",
"as PJ import re import json import numpy as np from tqdm import",
"def calcBetweennessCentralization(G): vnum = G.vcount() if vnum < 3: return None,0 denom =",
"# else: # results = g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0), np.nanmean(results) def calcCoreness(g): results =",
"(None,None) results = np.array(g.strength(mode=\"IN\", weights = \"weight\")) return results, np.average(results) def calcOutStrength(g): if(\"weight\"",
"(indNodes.size>1): RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC = 0 return None,RC def calcDegreeAssortativity(g): return",
"np.average(results) def calcOutStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return (None,None) results",
"degree = np.array(g.degree()) matchIndex = np.zeros(g.ecount()) for id,e in enumerate(g.es): node1,node2 = e.tuple",
"def calcBetweenessCentrality(g): result = np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result) def calcBetweenessCentralityWeighted(g): if(\"weight\" not in g.edge_attributes()):",
"richClubPercentage degree = np.array(g.degree()) edges = np.array(g.get_edgelist()) sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]] dT = int(np.percentile(degree,Trc))",
"configFilename = \"config.json\" argCount = len(sys.argv) if(argCount > 1): configFilename = sys.argv[1] outputDirectory",
"weights = \"weight\")) return results, np.average(results) def calcInStrength(g): if(\"weight\" not in g.edge_attributes() or",
"= np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result) def calcBetweenessCentralityWeighted(g): if(\"weight\" not in g.edge_attributes()): return (None,None) result",
"else: matchIndex[id] = 0 meanMatchIndex = np.mean(matchIndex) return None, meanMatchIndex def calcBetweenessCentrality(g): result",
"viz2 = g.neighbors(node2) sharedNei = set(viz1) & set(viz2) if ((degree[node1]+degree[node2]) > 2): matchIndex[id]",
"set(viz1) & set(viz2) if ((degree[node1]+degree[node2]) > 2): matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id] =",
"= reindexList(g.vs[\"Community\"]) else: return (None,None) if(\"weight\" in g.edge_attributes()): return None, g.modularity(Ci, weights=\"weight\"); else:",
"in range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None)",
"neigh in neighs] kappa = np.zeros(g.vcount()) kappaSi = [[] for _ in range(max(Ci)+1)]",
"degrees = np.array(g.degree(mode=mode)) kappasi = np.zeros(g.vcount()) for i in range(g.vcount()): nodeCommunities = set([community",
"measurements.items(): nodePropData,networkPropData = measurementFunction(network) if(nodePropData is not None): network.vs[measurement] = nodePropData if(networkPropData is",
"g.edge_attributes()): degrees = np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees = np.array(g.degree(mode=mode)) kappasi = np.zeros(g.vcount()) for i",
"= g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0), np.nanmean(results) def calcCoreness(g): results = np.array(g.coreness(mode=\"ALL\")) return results, None",
"np.average(results) def calcStrength(g): if(\"weight\" not in g.edge_attributes()): return (None,None) results = np.array(g.strength(mode=\"ALL\", weights",
"None, g.modularity(Ci, weights=None); def calcDegree(g): results = np.array(g.degree(mode=\"ALL\")) return results, np.average(results) def calcInDegree(g):",
"json import numpy as np from tqdm import tqdm import igraph as ig",
"else: return [[(e.target,1) if e.target!=i else (e.source,1) for e in g.es[g.incident(i,mode=mode)]] for i",
"False try: numericValue = float(value) return np.isfinite(numericValue) except ValueError: return False class NumpyEncoder(json.JSONEncoder):",
"if(networkPropData is not None): if(nodePropData is not None): #Average measurement network[\"Avg. \"+measurement] =",
"import jgf import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt def calcModularity(g):",
"in config): richClubPercentage = config[\"richClubPercentage\"]; networks = jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks = [] for",
"\"weight\")) return results, np.average(results) def calcClusteringCoefficient(g): # if(\"weight\" in g.edge_attributes()): results = g.transitivity_local_undirected(weights=None)",
"is None): return False try: numericValue = float(value) return np.isfinite(numericValue) except ValueError: return",
"def calcInDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.indegree()) return results, np.average(results) def",
"np.array(g.coreness(mode=\"ALL\")) return results, None def calcMatchIndex(g): degree = np.array(g.degree()) matchIndex = np.zeros(g.ecount()) for",
"from os.path import join as PJ import re import json import numpy as",
"zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"])",
"g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"])",
"try: numericValue = float(value) return np.isfinite(numericValue) except ValueError: return False class NumpyEncoder(json.JSONEncoder): def",
"for network in tqdm(networks): weighted = \"weight\" in network.edge_attributes() hasCommunities = \"Community\" in",
"for measurement,measurementFunction in measurements.items(): nodePropData,networkPropData = measurementFunction(network) if(nodePropData is not None): network.vs[measurement] =",
"RC = 0 return None,RC def calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g): if(\"weight\" in",
": calcOutStrength, \"ClusteringCoefficient\" : calcClusteringCoefficient, \"Coreness\" : calcCoreness, \"MatchIndex\" : calcMatchIndex, \"BetweenessCentrality\" :",
"os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with open(configFilename, \"r\") as fd: config = json.load(fd) # \"transform\":\"absolute\", //\"absolute\"",
"in g.edge_attributes()): return (None,None) results = np.array(g.strength(mode=\"ALL\", weights = \"weight\")) return results, np.average(results)",
"= config[\"richClubPercentage\"]; networks = jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks = [] for network in tqdm(networks):",
"calcOutStrength, \"ClusteringCoefficient\" : calcClusteringCoefficient, \"Coreness\" : calcCoreness, \"MatchIndex\" : calcMatchIndex, \"BetweenessCentrality\" : calcBetweenessCentrality,",
"indices_only=False): Trc = richClubPercentage degree = np.array(g.degree()) edges = np.array(g.get_edgelist()) sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]]",
"g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) neighs = getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth)",
"= reindexList(g.vs[\"Community\"]) else: return (None,None) neighs = getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth",
"def exitApp(): global results with open(\"product.json\", \"w\") as fp: json.dump(results, fp, cls=NumpyEncoder) if",
"result = np.array(g.betweenness(weights=\"weight\")) return result,np.average(result) def calcBetweennessCentralization(G): vnum = G.vcount() if vnum <",
"for ci in range(len(kappaSi)): avgKappaSi[ci] = np.average(kappaSi[ci]) stdKappaSi[ci] = np.std(kappaSi[ci]) zmodule = np.zeros(g.vcount())",
"jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks = [] for network in tqdm(networks): weighted = \"weight\" in",
"from tqdm import tqdm import igraph as ig import jgf import matplotlib as",
": calcInStrength, \"OutStrength\" : calcOutStrength, \"ClusteringCoefficient\" : calcClusteringCoefficient, \"Coreness\" : calcCoreness, \"MatchIndex\" :",
"= 0 meanMatchIndex = np.mean(matchIndex) return None, meanMatchIndex def calcBetweenessCentrality(g): result = np.array(g.betweenness(directed=g.is_directed()))",
"results = np.array(g.indegree()) return results, np.average(results) def calcOutDegree(g): if(not g.is_directed()): return (None,None) results",
"argCount = len(sys.argv) if(argCount > 1): configFilename = sys.argv[1] outputDirectory = \"output\" outputFile",
": calcModuleDegreeZScore, \"ParticipationCoeff\" : calcParticipationCoeff, \"Modularity\" : calcModularity, } def isFloat(value): if(value is",
"richClubPercentage = config[\"richClubPercentage\"]; networks = jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks = [] for network in",
"else: return None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False): d = {ni: indi for indi, ni in",
"for indi, ni in enumerate(set(names))} numbers = [d[ni] for ni in names] if(returnDict):",
"result,None measurements = { \"Degree\" : calcDegree, \"InDegree\" : calcInDegree, \"OutDegree\" : calcOutDegree,",
"hasCommunities = \"Community\" in network.vertex_attributes() for measurement,measurementFunction in measurements.items(): nodePropData,networkPropData = measurementFunction(network) if(nodePropData",
"def calcBetweenessCentralityWeighted(g): if(\"weight\" not in g.edge_attributes()): return (None,None) result = np.array(g.betweenness(weights=\"weight\")) return result,np.average(result)",
"[], \"brainlife\": [], \"datatype_tags\": [], \"tags\": []} def warning(msg): global results results['warnings'].append(msg) #results['brainlife'].append({\"type\":",
"None if isinstance(ret, (bytes, bytearray)): ret = ret.decode(\"utf-8\") return ret results = {\"errors\":",
"return (None,None) results = np.array(g.strength(mode=\"ALL\", weights = \"weight\")) return results, np.average(results) def calcInStrength(g):",
"\"ClusteringCoefficient\" : calcClusteringCoefficient, \"Coreness\" : calcCoreness, \"MatchIndex\" : calcMatchIndex, \"BetweenessCentrality\" : calcBetweenessCentrality, \"BetweenessCentralityWeighted\"",
": calcModularity, } def isFloat(value): if(value is None): return False try: numericValue =",
"[], \"warnings\": [], \"brainlife\": [], \"datatype_tags\": [], \"tags\": []} def warning(msg): global results",
"2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC = 0 return None,RC def calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g):",
"np.float16, np.float32, np.float64)): ret = float(obj) elif isinstance(obj, (np.ndarray,)): ret = obj.tolist() else:",
"meanMatchIndex def calcBetweenessCentrality(g): result = np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result) def calcBetweenessCentralityWeighted(g): if(\"weight\" not in",
"isinstance(obj, (np.ndarray,)): ret = obj.tolist() else: ret = json.JSONEncoder.default(self, obj) if isinstance(ret, (float)):",
"\"OutDegree\" : calcOutDegree, \"Strength\" : calcStrength, \"InStrength\" : calcInStrength, \"OutStrength\" : calcOutStrength, \"ClusteringCoefficient\"",
"default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16,",
"import igraph as ig import jgf import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot",
"tqdm(networks): weighted = \"weight\" in network.edge_attributes() hasCommunities = \"Community\" in network.vertex_attributes() for measurement,measurementFunction",
"for community,weight in cneighs[i]]) communityDegrees = {community:0 for community in nodeCommunities} for community,weight",
"in cneighs[i]: communityDegrees[community]+=weight kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2)) result = 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] = 0 return",
"numbers,d else: return numbers def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in g.edge_attributes()): return [[(e.target,e[\"weight\"]) if e.target!=i",
"\"ModuleDegreeZScore\" : calcModuleDegreeZScore, \"ParticipationCoeff\" : calcParticipationCoeff, \"Modularity\" : calcModularity, } def isFloat(value): if(value",
"np.array(g.strength(mode=\"OUT\", weights = \"weight\")) return results, np.average(results) def calcClusteringCoefficient(g): # if(\"weight\" in g.edge_attributes()):",
"neigh in neighs] if(\"weight\" in g.edge_attributes()): degrees = np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees = np.array(g.degree(mode=mode))",
"in range(g.vcount()): ci = Ci[i] if(stdKappaSi[ci]>0): zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"):",
": calcDiameter, \"ModuleDegreeZScore\" : calcModuleDegreeZScore, \"ParticipationCoeff\" : calcParticipationCoeff, \"Modularity\" : calcModularity, } def",
"\"signed\" # \"retain-weights\":false, # \"threshold\": \"none\" richClubPercentage = 90 if(\"richClubPercentage\" in config): richClubPercentage",
"as plt def calcModularity(g): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None)",
"global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) def exitApp(): global results with",
"None): #Average measurement network[\"Avg. \"+measurement] = networkPropData else: network[measurement] = networkPropData outputNetworks.append(network) jgf.igraph.save(outputNetworks,",
"return False class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,",
"np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): ret = int(obj) elif isinstance(obj, (np.float_, np.float16,",
"= np.array(g.degree()) edges = np.array(g.get_edgelist()) sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]] dT = int(np.percentile(degree,Trc)) indNodes =",
"g.modularity(Ci, weights=\"weight\"); else: return None, g.modularity(Ci, weights=None); def calcDegree(g): results = np.array(g.degree(mode=\"ALL\")) return",
"= np.array(g.indegree()) return results, np.average(results) def calcOutDegree(g): if(not g.is_directed()): return (None,None) results =",
"results = np.array(g.strength(mode=\"IN\", weights = \"weight\")) return results, np.average(results) def calcOutStrength(g): if(\"weight\" not",
"= np.array(g.betweenness(weights=\"weight\")) return result,np.average(result) def calcBetweennessCentralization(G): vnum = G.vcount() if vnum < 3:",
"calcRichClubCoefficient(g, highest=True, scores=None, indices_only=False): Trc = richClubPercentage degree = np.array(g.degree()) edges = np.array(g.get_edgelist())",
"range(g.vcount()): kappa[i] = np.sum([weight for community,weight in cneighs[i] if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi =",
"elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): ret = float(obj) elif isinstance(obj, (np.ndarray,)): ret",
"in network.edge_attributes() hasCommunities = \"Community\" in network.vertex_attributes() for measurement,measurementFunction in measurements.items(): nodePropData,networkPropData =",
"obj) if isinstance(ret, (float)): if math.isnan(ret): ret = None if isinstance(ret, (bytes, bytearray)):",
"= 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] = 0 return result,None measurements = { \"Degree\" : calcDegree,",
"np.nan_to_num(results,0), np.nanmean(results) def calcCoreness(g): results = np.array(g.coreness(mode=\"ALL\")) return results, None def calcMatchIndex(g): degree",
"def calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g): if(\"weight\" in g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return",
"import sys import os.path from os.path import join as PJ import re import",
"indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1): RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC = 0 return",
"= set(viz1) & set(viz2) if ((degree[node1]+degree[node2]) > 2): matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id]",
"def calcDegree(g): results = np.array(g.degree(mode=\"ALL\")) return results, np.average(results) def calcInDegree(g): if(not g.is_directed()): return",
"np.isfinite(numericValue) except ValueError: return False class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (np.int_,",
"g.is_directed()): return (None,None) results = np.array(g.indegree()) return results, np.average(results) def calcOutDegree(g): if(not g.is_directed()):",
"compressed=True) outputNetworks = [] for network in tqdm(networks): weighted = \"weight\" in network.edge_attributes()",
"as mpl mpl.use('Agg') import matplotlib.pyplot as plt def calcModularity(g): if(\"Community\" in g.vertex_attributes()): Ci",
"if(argCount > 1): configFilename = sys.argv[1] outputDirectory = \"output\" outputFile = PJ(outputDirectory,\"network.json.gz\") if(not",
"communityDegrees = {community:0 for community in nodeCommunities} for community,weight in cneighs[i]: communityDegrees[community]+=weight kappasi[i]",
"ret = obj.tolist() else: ret = json.JSONEncoder.default(self, obj) if isinstance(ret, (float)): if math.isnan(ret):",
"config): richClubPercentage = config[\"richClubPercentage\"]; networks = jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks = [] for network",
"for vertexID,weigth in neigh] for neigh in neighs] kappa = np.zeros(g.vcount()) kappaSi =",
"# \"retain-weights\":false, # \"threshold\": \"none\" richClubPercentage = 90 if(\"richClubPercentage\" in config): richClubPercentage =",
": calcParticipationCoeff, \"Modularity\" : calcModularity, } def isFloat(value): if(value is None): return False",
"if(not g.is_directed()): return (None,None) results = np.array(g.indegree()) return results, np.average(results) def calcOutDegree(g): if(not",
"return None,RC def calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g): if(\"weight\" in g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\")",
"None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False): d = {ni: indi for indi, ni",
"import join as PJ import re import json import numpy as np from",
"= np.std(kappaSi[ci]) zmodule = np.zeros(g.vcount()) for i in range(g.vcount()): ci = Ci[i] if(stdKappaSi[ci]>0):",
"[[(e.target,e[\"weight\"]) if e.target!=i else (e.source,e[\"weight\"]) for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())]",
"\"Degree\" : calcDegree, \"InDegree\" : calcInDegree, \"OutDegree\" : calcOutDegree, \"Strength\" : calcStrength, \"InStrength\"",
"calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) neighs = getNeighborhoods(g,mode=mode)",
"not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"IN\", weights = \"weight\")) return results, np.average(results)",
"{ \"Degree\" : calcDegree, \"InDegree\" : calcInDegree, \"OutDegree\" : calcOutDegree, \"Strength\" : calcStrength,",
"else: sys.exit() def exitAppWithError(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) exitApp()",
"= g.neighbors(node1) viz2 = g.neighbors(node2) sharedNei = set(viz1) & set(viz2) if ((degree[node1]+degree[node2]) >",
"vnum < 3: return None,0 denom = (vnum-1)*(vnum-2) temparr = [2*i/denom for i",
"sharedNei = set(viz1) & set(viz2) if ((degree[node1]+degree[node2]) > 2): matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2) else:",
"calcStrength, \"InStrength\" : calcInStrength, \"OutStrength\" : calcOutStrength, \"ClusteringCoefficient\" : calcClusteringCoefficient, \"Coreness\" : calcCoreness,",
"in enumerate(set(names))} numbers = [d[ni] for ni in names] if(returnDict): return numbers,d else:",
"(e.source,1) for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in",
"np.sum(np.power(list(communityDegrees.values()),2)) result = 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] = 0 return result,None measurements = { \"Degree\"",
"community in nodeCommunities} for community,weight in cneighs[i]: communityDegrees[community]+=weight kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2)) result =",
"enumerate(g.es): node1,node2 = e.tuple viz1 = g.neighbors(node1) viz2 = g.neighbors(node2) sharedNei = set(viz1)",
"# \"threshold\": \"none\" richClubPercentage = 90 if(\"richClubPercentage\" in config): richClubPercentage = config[\"richClubPercentage\"]; networks",
"vnum = G.vcount() if vnum < 3: return None,0 denom = (vnum-1)*(vnum-2) temparr",
"return None,sum(max_temparr-i for i in temparr)/(vnum-1) def calcRichClubCoefficient(g, highest=True, scores=None, indices_only=False): Trc =",
"return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False): d = {ni: indi for indi,",
"e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] else: return [[(e.target,1) if e.target!=i else",
"in g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False): d = {ni: indi",
"reindexList(g.vs[\"Community\"]) else: return (None,None) neighs = getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth in",
"for community,weight in cneighs[i] if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi = np.zeros(max(Ci)+1) stdKappaSi = np.zeros(max(Ci)+1)",
"[[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh in neighs] if(\"weight\" in g.edge_attributes()): degrees",
"isinstance(ret, (bytes, bytearray)): ret = ret.decode(\"utf-8\") return ret results = {\"errors\": [], \"warnings\":",
"calcMatchIndex(g): degree = np.array(g.degree()) matchIndex = np.zeros(g.ecount()) for id,e in enumerate(g.es): node1,node2 =",
": calcDegreeAssortativity, \"Diameter\" : calcDiameter, \"ModuleDegreeZScore\" : calcModuleDegreeZScore, \"ParticipationCoeff\" : calcParticipationCoeff, \"Modularity\" :",
"in temparr)/(vnum-1) def calcRichClubCoefficient(g, highest=True, scores=None, indices_only=False): Trc = richClubPercentage degree = np.array(g.degree())",
"if(stdKappaSi[ci]>0): zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci =",
"\"warnings\": [], \"brainlife\": [], \"datatype_tags\": [], \"tags\": []} def warning(msg): global results results['warnings'].append(msg)",
"weighted = \"weight\" in network.edge_attributes() hasCommunities = \"Community\" in network.vertex_attributes() for measurement,measurementFunction in",
"calcInStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"IN\",",
"if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with open(configFilename, \"r\") as fd: config = json.load(fd) # \"transform\":\"absolute\",",
"results, None def calcMatchIndex(g): degree = np.array(g.degree()) matchIndex = np.zeros(g.ecount()) for id,e in",
"[[(e.target,1) if e.target!=i else (e.source,1) for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())]",
"import os.path from os.path import join as PJ import re import json import",
"RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC = 0 return None,RC def calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed())",
"import numpy as np from tqdm import tqdm import igraph as ig import",
"calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g): if(\"weight\" in g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return None,g.diameter(directed=g.is_directed())",
"[]} def warning(msg): global results results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\", \"msg\": msg}) print(msg) def error(msg):",
"enumerate(set(names))} numbers = [d[ni] for ni in names] if(returnDict): return numbers,d else: return",
"numbers = [d[ni] for ni in names] if(returnDict): return numbers,d else: return numbers",
"\"ParticipationCoeff\" : calcParticipationCoeff, \"Modularity\" : calcModularity, } def isFloat(value): if(value is None): return",
"i in range(g.vcount()): ci = Ci[i] if(stdKappaSi[ci]>0): zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None def",
"def isFloat(value): if(value is None): return False try: numericValue = float(value) return np.isfinite(numericValue)",
"viz1 = g.neighbors(node1) viz2 = g.neighbors(node2) sharedNei = set(viz1) & set(viz2) if ((degree[node1]+degree[node2])",
"None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g): if(\"weight\" in g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False):",
"= getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh in neighs]",
"e.tuple viz1 = g.neighbors(node1) viz2 = g.neighbors(node2) sharedNei = set(viz1) & set(viz2) if",
"obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32,",
"\"weight\")) return results, np.average(results) def calcInStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()):",
"matchIndex = np.zeros(g.ecount()) for id,e in enumerate(g.es): node1,node2 = e.tuple viz1 = g.neighbors(node1)",
"zmodule = np.zeros(g.vcount()) for i in range(g.vcount()): ci = Ci[i] if(stdKappaSi[ci]>0): zmodule[i] =",
"len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id] = 0 meanMatchIndex = np.mean(matchIndex) return None, meanMatchIndex def calcBetweenessCentrality(g):",
"2): matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id] = 0 meanMatchIndex = np.mean(matchIndex) return None,",
"mpl mpl.use('Agg') import matplotlib.pyplot as plt def calcModularity(g): if(\"Community\" in g.vertex_attributes()): Ci =",
"if(\"weight\" in g.edge_attributes()): return [[(e.target,e[\"weight\"]) if e.target!=i else (e.source,e[\"weight\"]) for e in g.es[g.incident(i,mode=mode)]]",
"e.target!=i else (e.source,e[\"weight\"]) for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] else: return",
"in neighs] kappa = np.zeros(g.vcount()) kappaSi = [[] for _ in range(max(Ci)+1)] for",
"np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): ret = int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32,",
"= np.mean(matchIndex) return None, meanMatchIndex def calcBetweenessCentrality(g): result = np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result) def",
"results = {\"errors\": [], \"warnings\": [], \"brainlife\": [], \"datatype_tags\": [], \"tags\": []} def",
": calcStrength, \"InStrength\" : calcInStrength, \"OutStrength\" : calcOutStrength, \"ClusteringCoefficient\" : calcClusteringCoefficient, \"Coreness\" :",
"getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in g.edge_attributes()): return [[(e.target,e[\"weight\"]) if e.target!=i else (e.source,e[\"weight\"]) for e in",
"return np.nan_to_num(results,0), np.nanmean(results) def calcCoreness(g): results = np.array(g.coreness(mode=\"ALL\")) return results, None def calcMatchIndex(g):",
"\"OutStrength\" : calcOutStrength, \"ClusteringCoefficient\" : calcClusteringCoefficient, \"Coreness\" : calcCoreness, \"MatchIndex\" : calcMatchIndex, \"BetweenessCentrality\"",
"calcClusteringCoefficient, \"Coreness\" : calcCoreness, \"MatchIndex\" : calcMatchIndex, \"BetweenessCentrality\" : calcBetweenessCentrality, \"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted,",
"cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh in neighs] if(\"weight\" in",
"= int(np.percentile(degree,Trc)) indNodes = np.nonzero(degree>=dT)[0] indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1): RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1))",
"= 0 return result,None measurements = { \"Degree\" : calcDegree, \"InDegree\" : calcInDegree,",
"results results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\", \"msg\": msg}) print(msg) def error(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\":",
"for ni in names] if(returnDict): return numbers,d else: return numbers def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\"",
"return (None,None) if(\"weight\" in g.edge_attributes()): return None, g.modularity(Ci, weights=\"weight\"); else: return None, g.modularity(Ci,",
"zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) neighs",
"class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32,",
"in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] else: return [[(e.target,1) if e.target!=i else (e.source,1)",
"weights=\"weight\"); else: return None, g.modularity(Ci, weights=None); def calcDegree(g): results = np.array(g.degree(mode=\"ALL\")) return results,",
"# \"transform\":\"absolute\", //\"absolute\" or \"signed\" # \"retain-weights\":false, # \"threshold\": \"none\" richClubPercentage = 90",
"np.std(kappaSi[ci]) zmodule = np.zeros(g.vcount()) for i in range(g.vcount()): ci = Ci[i] if(stdKappaSi[ci]>0): zmodule[i]",
"neighs] if(\"weight\" in g.edge_attributes()): degrees = np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees = np.array(g.degree(mode=mode)) kappasi =",
"with open(configFilename, \"r\") as fd: config = json.load(fd) # \"transform\":\"absolute\", //\"absolute\" or \"signed\"",
"return None, g.modularity(Ci, weights=\"weight\"); else: return None, g.modularity(Ci, weights=None); def calcDegree(g): results =",
"else (e.source,e[\"weight\"]) for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] else: return [[(e.target,1)",
"outputFile = PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with open(configFilename, \"r\") as fd: config =",
"\"RichClubCoefficient\" : calcRichClubCoefficient, \"DegreeAssortativity\" : calcDegreeAssortativity, \"Diameter\" : calcDiameter, \"ModuleDegreeZScore\" : calcModuleDegreeZScore, \"ParticipationCoeff\"",
"np.average(results) def calcClusteringCoefficient(g): # if(\"weight\" in g.edge_attributes()): results = g.transitivity_local_undirected(weights=None) # else: #",
"ret = float(obj) elif isinstance(obj, (np.ndarray,)): ret = obj.tolist() else: ret = json.JSONEncoder.default(self,",
"results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) exitApp() configFilename = \"config.json\" argCount = len(sys.argv)",
"= float(value) return np.isfinite(numericValue) except ValueError: return False class NumpyEncoder(json.JSONEncoder): def default(self, obj):",
"if(\"weight\" not in g.edge_attributes()): return (None,None) results = np.array(g.strength(mode=\"ALL\", weights = \"weight\")) return",
"\"brainlife\": [], \"datatype_tags\": [], \"tags\": []} def warning(msg): global results results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\",",
"config[\"richClubPercentage\"]; networks = jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks = [] for network in tqdm(networks): weighted",
"len(sys.argv) if(argCount > 1): configFilename = sys.argv[1] outputDirectory = \"output\" outputFile = PJ(outputDirectory,\"network.json.gz\")",
"calcDegree, \"InDegree\" : calcInDegree, \"OutDegree\" : calcOutDegree, \"Strength\" : calcStrength, \"InStrength\" : calcInStrength,",
"cneighs[i] if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi = np.zeros(max(Ci)+1) stdKappaSi = np.zeros(max(Ci)+1) for ci in",
"results, np.average(results) def calcOutDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.outdegree()) return results,",
"for id,e in enumerate(g.es): node1,node2 = e.tuple viz1 = g.neighbors(node1) viz2 = g.neighbors(node2)",
"[d[ni] for ni in names] if(returnDict): return numbers,d else: return numbers def getNeighborhoods(g,mode=\"ALL\"):",
"avgKappaSi = np.zeros(max(Ci)+1) stdKappaSi = np.zeros(max(Ci)+1) for ci in range(len(kappaSi)): avgKappaSi[ci] = np.average(kappaSi[ci])",
"= np.array(g.degree(mode=mode)) kappasi = np.zeros(g.vcount()) for i in range(g.vcount()): nodeCommunities = set([community for",
"results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) def exitApp(): global results with open(\"product.json\", \"w\")",
"indi for indi, ni in enumerate(set(names))} numbers = [d[ni] for ni in names]",
"vertexID,weigth in neigh] for neigh in neighs] if(\"weight\" in g.edge_attributes()): degrees = np.array(g.strength(mode=mode,weights=\"weight\"))",
"if(nodePropData is not None): network.vs[measurement] = nodePropData if(networkPropData is not None): if(nodePropData is",
"g.edge_attributes() or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"IN\", weights = \"weight\")) return",
"int(np.percentile(degree,Trc)) indNodes = np.nonzero(degree>=dT)[0] indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1): RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else:",
"float(obj) elif isinstance(obj, (np.ndarray,)): ret = obj.tolist() else: ret = json.JSONEncoder.default(self, obj) if",
"stdKappaSi[ci] = np.std(kappaSi[ci]) zmodule = np.zeros(g.vcount()) for i in range(g.vcount()): ci = Ci[i]",
"if e.target!=i else (e.source,1) for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] def",
"# if(\"weight\" in g.edge_attributes()): results = g.transitivity_local_undirected(weights=None) # else: # results = g.transitivity_local_undirected(weights=\"weight\")",
"if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)):",
"not in g.edge_attributes() or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"OUT\", weights =",
"neighs = getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh in",
"degrees = np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees = np.array(g.degree(mode=mode)) kappasi = np.zeros(g.vcount()) for i in",
"return (None,None) results = np.array(g.indegree()) return results, np.average(results) def calcOutDegree(g): if(not g.is_directed()): return",
"result = np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result) def calcBetweenessCentralityWeighted(g): if(\"weight\" not in g.edge_attributes()): return (None,None)",
"network.vertex_attributes() for measurement,measurementFunction in measurements.items(): nodePropData,networkPropData = measurementFunction(network) if(nodePropData is not None): network.vs[measurement]",
"def exitAppWithError(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) exitApp() configFilename =",
"def calcCoreness(g): results = np.array(g.coreness(mode=\"ALL\")) return results, None def calcMatchIndex(g): degree = np.array(g.degree())",
"np.zeros(g.vcount()) for i in range(g.vcount()): nodeCommunities = set([community for community,weight in cneighs[i]]) communityDegrees",
"= np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees = np.array(g.degree(mode=mode)) kappasi = np.zeros(g.vcount()) for i in range(g.vcount()):",
"\"InDegree\" : calcInDegree, \"OutDegree\" : calcOutDegree, \"Strength\" : calcStrength, \"InStrength\" : calcInStrength, \"OutStrength\"",
"exitAppWithError(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) exitApp() configFilename = \"config.json\"",
"= json.load(fd) # \"transform\":\"absolute\", //\"absolute\" or \"signed\" # \"retain-weights\":false, # \"threshold\": \"none\" richClubPercentage",
"sys.exit() def exitAppWithError(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) exitApp() configFilename",
"meanMatchIndex = np.mean(matchIndex) return None, meanMatchIndex def calcBetweenessCentrality(g): result = np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result)",
"def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in g.edge_attributes()): return [[(e.target,e[\"weight\"]) if e.target!=i else (e.source,e[\"weight\"]) for e",
"\"MatchIndex\" : calcMatchIndex, \"BetweenessCentrality\" : calcBetweenessCentrality, \"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted, \"BetweennessCentralization\" : calcBetweennessCentralization, \"RichClubCoefficient\"",
"e.target!=i else (e.source,1) for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"):",
"= np.array(g.coreness(mode=\"ALL\")) return results, None def calcMatchIndex(g): degree = np.array(g.degree()) matchIndex = np.zeros(g.ecount())",
"scores=None, indices_only=False): Trc = richClubPercentage degree = np.array(g.degree()) edges = np.array(g.get_edgelist()) sourceDegree,targetDegree =",
"= len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id] = 0 meanMatchIndex = np.mean(matchIndex) return None, meanMatchIndex def",
"Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) if(\"weight\" in g.edge_attributes()): return None, g.modularity(Ci, weights=\"weight\");",
"return (None,None) neighs = getNeighborhoods(g,mode=mode) cneighs = [[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for",
"np.float32, np.float64)): ret = float(obj) elif isinstance(obj, (np.ndarray,)): ret = obj.tolist() else: ret",
"np from tqdm import tqdm import igraph as ig import jgf import matplotlib",
"None,sum(max_temparr-i for i in temparr)/(vnum-1) def calcRichClubCoefficient(g, highest=True, scores=None, indices_only=False): Trc = richClubPercentage",
"stdKappaSi = np.zeros(max(Ci)+1) for ci in range(len(kappaSi)): avgKappaSi[ci] = np.average(kappaSi[ci]) stdKappaSi[ci] = np.std(kappaSi[ci])",
"ret = None if isinstance(ret, (bytes, bytearray)): ret = ret.decode(\"utf-8\") return ret results",
"return None, g.modularity(Ci, weights=None); def calcDegree(g): results = np.array(g.degree(mode=\"ALL\")) return results, np.average(results) def",
"= np.zeros(max(Ci)+1) for ci in range(len(kappaSi)): avgKappaSi[ci] = np.average(kappaSi[ci]) stdKappaSi[ci] = np.std(kappaSi[ci]) zmodule",
"(None,None) results = np.array(g.strength(mode=\"OUT\", weights = \"weight\")) return results, np.average(results) def calcClusteringCoefficient(g): #",
"= max(temparr) return None,sum(max_temparr-i for i in temparr)/(vnum-1) def calcRichClubCoefficient(g, highest=True, scores=None, indices_only=False):",
"return result,np.average(result) def calcBetweenessCentralityWeighted(g): if(\"weight\" not in g.edge_attributes()): return (None,None) result = np.array(g.betweenness(weights=\"weight\"))",
"np.float64)): ret = float(obj) elif isinstance(obj, (np.ndarray,)): ret = obj.tolist() else: ret =",
"\"datatype_tags\": [], \"tags\": []} def warning(msg): global results results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\", \"msg\": msg})",
"Ci[i] if(stdKappaSi[ci]>0): zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci",
"result,np.average(result) def calcBetweenessCentralityWeighted(g): if(\"weight\" not in g.edge_attributes()): return (None,None) result = np.array(g.betweenness(weights=\"weight\")) return",
"return None, meanMatchIndex def calcBetweenessCentrality(g): result = np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result) def calcBetweenessCentralityWeighted(g): if(\"weight\"",
"results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\", \"msg\": msg}) print(msg) def error(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\",",
"fd: config = json.load(fd) # \"transform\":\"absolute\", //\"absolute\" or \"signed\" # \"retain-weights\":false, # \"threshold\":",
"if vnum < 3: return None,0 denom = (vnum-1)*(vnum-2) temparr = [2*i/denom for",
"nodePropData,networkPropData = measurementFunction(network) if(nodePropData is not None): network.vs[measurement] = nodePropData if(networkPropData is not",
"as fp: json.dump(results, fp, cls=NumpyEncoder) if len(results[\"errors\"]) > 0: sys.exit(1) else: sys.exit() def",
"{community:0 for community in nodeCommunities} for community,weight in cneighs[i]: communityDegrees[community]+=weight kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2))",
"range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) neighs",
"in measurements.items(): nodePropData,networkPropData = measurementFunction(network) if(nodePropData is not None): network.vs[measurement] = nodePropData if(networkPropData",
"np.nonzero(degree>=dT)[0] indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1): RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC = 0",
"np.zeros(max(Ci)+1) stdKappaSi = np.zeros(max(Ci)+1) for ci in range(len(kappaSi)): avgKappaSi[ci] = np.average(kappaSi[ci]) stdKappaSi[ci] =",
"if(\"weight\" in g.edge_attributes()): degrees = np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees = np.array(g.degree(mode=mode)) kappasi = np.zeros(g.vcount())",
"#!/usr/bin/env python import sys import os.path from os.path import join as PJ import",
"for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()):",
"if isinstance(ret, (bytes, bytearray)): ret = ret.decode(\"utf-8\") return ret results = {\"errors\": [],",
"(vnum-1)*(vnum-2) temparr = [2*i/denom for i in G.betweenness()] max_temparr = max(temparr) return None,sum(max_temparr-i",
"= json.JSONEncoder.default(self, obj) if isinstance(ret, (float)): if math.isnan(ret): ret = None if isinstance(ret,",
"= [] for network in tqdm(networks): weighted = \"weight\" in network.edge_attributes() hasCommunities =",
"max_temparr = max(temparr) return None,sum(max_temparr-i for i in temparr)/(vnum-1) def calcRichClubCoefficient(g, highest=True, scores=None,",
"np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): ret = int(obj) elif isinstance(obj,",
"np.average(results) def calcOutDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.outdegree()) return results, np.average(results)",
"= np.zeros(g.vcount()) for i in range(g.vcount()): ci = Ci[i] if(stdKappaSi[ci]>0): zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci]",
"i in range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return",
"def calcInStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return (None,None) results =",
"ret = json.JSONEncoder.default(self, obj) if isinstance(ret, (float)): if math.isnan(ret): ret = None if",
"= \"config.json\" argCount = len(sys.argv) if(argCount > 1): configFilename = sys.argv[1] outputDirectory =",
"g.is_directed()): return (None,None) results = np.array(g.outdegree()) return results, np.average(results) def calcStrength(g): if(\"weight\" not",
"join as PJ import re import json import numpy as np from tqdm",
"calcModularity, } def isFloat(value): if(value is None): return False try: numericValue = float(value)",
"(np.ndarray,)): ret = obj.tolist() else: ret = json.JSONEncoder.default(self, obj) if isinstance(ret, (float)): if",
"g.neighbors(node2) sharedNei = set(viz1) & set(viz2) if ((degree[node1]+degree[node2]) > 2): matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2)",
"None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False): d = {ni: indi for indi, ni in enumerate(set(names))} numbers",
"global results results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\", \"msg\": msg}) print(msg) def error(msg): global results results['errors'].append(msg)",
"\"weight\" in network.edge_attributes() hasCommunities = \"Community\" in network.vertex_attributes() for measurement,measurementFunction in measurements.items(): nodePropData,networkPropData",
"for e in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] else: return [[(e.target,1) if e.target!=i",
"(kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return",
"= [[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh in neighs] kappa = np.zeros(g.vcount())",
"ig import jgf import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt def",
"msg}) print(msg) def error(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) def",
"ci in range(len(kappaSi)): avgKappaSi[ci] = np.average(kappaSi[ci]) stdKappaSi[ci] = np.std(kappaSi[ci]) zmodule = np.zeros(g.vcount()) for",
"np.array(g.degree(mode=mode)) kappasi = np.zeros(g.vcount()) for i in range(g.vcount()): nodeCommunities = set([community for community,weight",
"= np.zeros(max(Ci)+1) stdKappaSi = np.zeros(max(Ci)+1) for ci in range(len(kappaSi)): avgKappaSi[ci] = np.average(kappaSi[ci]) stdKappaSi[ci]",
"denom = (vnum-1)*(vnum-2) temparr = [2*i/denom for i in G.betweenness()] max_temparr = max(temparr)",
"as ig import jgf import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt",
"= \"weight\" in network.edge_attributes() hasCommunities = \"Community\" in network.vertex_attributes() for measurement,measurementFunction in measurements.items():",
"kappasi = np.zeros(g.vcount()) for i in range(g.vcount()): nodeCommunities = set([community for community,weight in",
"for i in range(g.vcount()): nodeCommunities = set([community for community,weight in cneighs[i]]) communityDegrees =",
"in g.edge_attributes()): degrees = np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees = np.array(g.degree(mode=mode)) kappasi = np.zeros(g.vcount()) for",
"in network.vertex_attributes() for measurement,measurementFunction in measurements.items(): nodePropData,networkPropData = measurementFunction(network) if(nodePropData is not None):",
"g.modularity(Ci, weights=None); def calcDegree(g): results = np.array(g.degree(mode=\"ALL\")) return results, np.average(results) def calcInDegree(g): if(not",
"np.average(kappaSi[ci]) stdKappaSi[ci] = np.std(kappaSi[ci]) zmodule = np.zeros(g.vcount()) for i in range(g.vcount()): ci =",
"return [[(e.target,e[\"weight\"]) if e.target!=i else (e.source,e[\"weight\"]) for e in g.es[g.incident(i,mode=mode)]] for i in",
"[], \"tags\": []} def warning(msg): global results results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\", \"msg\": msg}) print(msg)",
"np.zeros(max(Ci)+1) for ci in range(len(kappaSi)): avgKappaSi[ci] = np.average(kappaSi[ci]) stdKappaSi[ci] = np.std(kappaSi[ci]) zmodule =",
"temparr = [2*i/denom for i in G.betweenness()] max_temparr = max(temparr) return None,sum(max_temparr-i for",
"neigh] for neigh in neighs] if(\"weight\" in g.edge_attributes()): degrees = np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees",
"in enumerate(g.es): node1,node2 = e.tuple viz1 = g.neighbors(node1) viz2 = g.neighbors(node2) sharedNei =",
"not None): #Average measurement network[\"Avg. \"+measurement] = networkPropData else: network[measurement] = networkPropData outputNetworks.append(network)",
"np.mean(matchIndex) return None, meanMatchIndex def calcBetweenessCentrality(g): result = np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result) def calcBetweenessCentralityWeighted(g):",
"except ValueError: return False class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (np.int_, np.intc,",
"weights = \"weight\")) return results, np.average(results) def calcOutStrength(g): if(\"weight\" not in g.edge_attributes() or",
"\"InStrength\" : calcInStrength, \"OutStrength\" : calcOutStrength, \"ClusteringCoefficient\" : calcClusteringCoefficient, \"Coreness\" : calcCoreness, \"MatchIndex\"",
"for community,weight in cneighs[i]: communityDegrees[community]+=weight kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2)) result = 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] =",
"= np.array(g.get_edgelist()) sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]] dT = int(np.percentile(degree,Trc)) indNodes = np.nonzero(degree>=dT)[0] indEdges =",
"(float)): if math.isnan(ret): ret = None if isinstance(ret, (bytes, bytearray)): ret = ret.decode(\"utf-8\")",
"fp: json.dump(results, fp, cls=NumpyEncoder) if len(results[\"errors\"]) > 0: sys.exit(1) else: sys.exit() def exitAppWithError(msg):",
"indi, ni in enumerate(set(names))} numbers = [d[ni] for ni in names] if(returnDict): return",
"np.array(g.degree()) edges = np.array(g.get_edgelist()) sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]] dT = int(np.percentile(degree,Trc)) indNodes = np.nonzero(degree>=dT)[0]",
"for i in range(g.vcount())] else: return [[(e.target,1) if e.target!=i else (e.source,1) for e",
"vertexID,weigth in neigh] for neigh in neighs] kappa = np.zeros(g.vcount()) kappaSi = [[]",
"configFilename = sys.argv[1] outputDirectory = \"output\" outputFile = PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with",
"= \"output\" outputFile = PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with open(configFilename, \"r\") as fd:",
"or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"IN\", weights = \"weight\")) return results,",
"calcCoreness(g): results = np.array(g.coreness(mode=\"ALL\")) return results, None def calcMatchIndex(g): degree = np.array(g.degree()) matchIndex",
"re import json import numpy as np from tqdm import tqdm import igraph",
"(bytes, bytearray)): ret = ret.decode(\"utf-8\") return ret results = {\"errors\": [], \"warnings\": [],",
"(None,None) results = np.array(g.outdegree()) return results, np.average(results) def calcStrength(g): if(\"weight\" not in g.edge_attributes()):",
"results, np.average(results) def calcStrength(g): if(\"weight\" not in g.edge_attributes()): return (None,None) results = np.array(g.strength(mode=\"ALL\",",
"False class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16,",
"None,RC def calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g): if(\"weight\" in g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else:",
"for _ in range(max(Ci)+1)] for i in range(g.vcount()): kappa[i] = np.sum([weight for community,weight",
"print(msg) exitApp() configFilename = \"config.json\" argCount = len(sys.argv) if(argCount > 1): configFilename =",
"in cneighs[i]]) communityDegrees = {community:0 for community in nodeCommunities} for community,weight in cneighs[i]:",
"else: degrees = np.array(g.degree(mode=mode)) kappasi = np.zeros(g.vcount()) for i in range(g.vcount()): nodeCommunities =",
"if(nodePropData is not None): #Average measurement network[\"Avg. \"+measurement] = networkPropData else: network[measurement] =",
"def calcModularity(g): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) if(\"weight\" in",
"& set(viz2) if ((degree[node1]+degree[node2]) > 2): matchIndex[id] = len(sharedNei)/float(degree[node1]+degree[node2]-2) else: matchIndex[id] = 0",
"degree = np.array(g.degree()) edges = np.array(g.get_edgelist()) sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]] dT = int(np.percentile(degree,Trc)) indNodes",
"return results, None def calcMatchIndex(g): degree = np.array(g.degree()) matchIndex = np.zeros(g.ecount()) for id,e",
"\"error\", \"msg\": msg}) print(msg) exitApp() configFilename = \"config.json\" argCount = len(sys.argv) if(argCount >",
"calcInDegree, \"OutDegree\" : calcOutDegree, \"Strength\" : calcStrength, \"InStrength\" : calcInStrength, \"OutStrength\" : calcOutStrength,",
"= { \"Degree\" : calcDegree, \"InDegree\" : calcInDegree, \"OutDegree\" : calcOutDegree, \"Strength\" :",
"for i in range(g.vcount()): ci = Ci[i] if(stdKappaSi[ci]>0): zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None",
"= (vnum-1)*(vnum-2) temparr = [2*i/denom for i in G.betweenness()] max_temparr = max(temparr) return",
"ni in enumerate(set(names))} numbers = [d[ni] for ni in names] if(returnDict): return numbers,d",
"0 return result,None measurements = { \"Degree\" : calcDegree, \"InDegree\" : calcInDegree, \"OutDegree\"",
"open(\"product.json\", \"w\") as fp: json.dump(results, fp, cls=NumpyEncoder) if len(results[\"errors\"]) > 0: sys.exit(1) else:",
"calcOutDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.outdegree()) return results, np.average(results) def calcStrength(g):",
"weights=None); def calcDegree(g): results = np.array(g.degree(mode=\"ALL\")) return results, np.average(results) def calcInDegree(g): if(not g.is_directed()):",
"g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0), np.nanmean(results) def calcCoreness(g): results = np.array(g.coreness(mode=\"ALL\")) return results, None def",
"measurement network[\"Avg. \"+measurement] = networkPropData else: network[measurement] = networkPropData outputNetworks.append(network) jgf.igraph.save(outputNetworks, outputFile, compressed=True)",
"ci = Ci[i] if(stdKappaSi[ci]>0): zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in",
"results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) def exitApp(): global results with open(\"product.json\",",
"float(value) return np.isfinite(numericValue) except ValueError: return False class NumpyEncoder(json.JSONEncoder): def default(self, obj): if",
"tqdm import igraph as ig import jgf import matplotlib as mpl mpl.use('Agg') import",
"return results, np.average(results) def calcOutStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return",
"= g.neighbors(node2) sharedNei = set(viz1) & set(viz2) if ((degree[node1]+degree[node2]) > 2): matchIndex[id] =",
"elif isinstance(obj, (np.ndarray,)): ret = obj.tolist() else: ret = json.JSONEncoder.default(self, obj) if isinstance(ret,",
"in neigh] for neigh in neighs] kappa = np.zeros(g.vcount()) kappaSi = [[] for",
"return [[(e.target,1) if e.target!=i else (e.source,1) for e in g.es[g.incident(i,mode=mode)]] for i in",
"community,weight in cneighs[i]]) communityDegrees = {community:0 for community in nodeCommunities} for community,weight in",
"i in range(g.vcount()): nodeCommunities = set([community for community,weight in cneighs[i]]) communityDegrees = {community:0",
"= {\"errors\": [], \"warnings\": [], \"brainlife\": [], \"datatype_tags\": [], \"tags\": []} def warning(msg):",
"import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt def calcModularity(g): if(\"Community\" in",
"in range(g.vcount()): kappa[i] = np.sum([weight for community,weight in cneighs[i] if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi",
"cls=NumpyEncoder) if len(results[\"errors\"]) > 0: sys.exit(1) else: sys.exit() def exitAppWithError(msg): global results results['errors'].append(msg)",
"range(max(Ci)+1)] for i in range(g.vcount()): kappa[i] = np.sum([weight for community,weight in cneighs[i] if",
"(None,None) result = np.array(g.betweenness(weights=\"weight\")) return result,np.average(result) def calcBetweennessCentralization(G): vnum = G.vcount() if vnum",
"calcClusteringCoefficient(g): # if(\"weight\" in g.edge_attributes()): results = g.transitivity_local_undirected(weights=None) # else: # results =",
"json.load(fd) # \"transform\":\"absolute\", //\"absolute\" or \"signed\" # \"retain-weights\":false, # \"threshold\": \"none\" richClubPercentage =",
"calcDiameter, \"ModuleDegreeZScore\" : calcModuleDegreeZScore, \"ParticipationCoeff\" : calcParticipationCoeff, \"Modularity\" : calcModularity, } def isFloat(value):",
"isinstance(ret, (float)): if math.isnan(ret): ret = None if isinstance(ret, (bytes, bytearray)): ret =",
"> 0: sys.exit(1) else: sys.exit() def exitAppWithError(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\":",
"error(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) def exitApp(): global results",
"= PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with open(configFilename, \"r\") as fd: config = json.load(fd)",
"= g.transitivity_local_undirected(weights=None) # else: # results = g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0), np.nanmean(results) def calcCoreness(g):",
"kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2)) result = 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] = 0 return result,None measurements =",
"calcMatchIndex, \"BetweenessCentrality\" : calcBetweenessCentrality, \"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted, \"BetweennessCentralization\" : calcBetweennessCentralization, \"RichClubCoefficient\" : calcRichClubCoefficient,",
"os.path from os.path import join as PJ import re import json import numpy",
"i in temparr)/(vnum-1) def calcRichClubCoefficient(g, highest=True, scores=None, indices_only=False): Trc = richClubPercentage degree =",
"neighs] kappa = np.zeros(g.vcount()) kappaSi = [[] for _ in range(max(Ci)+1)] for i",
"\"Coreness\" : calcCoreness, \"MatchIndex\" : calcMatchIndex, \"BetweenessCentrality\" : calcBetweenessCentrality, \"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted, \"BetweennessCentralization\"",
"if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi = np.zeros(max(Ci)+1) stdKappaSi = np.zeros(max(Ci)+1) for ci in range(len(kappaSi)):",
"= (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else:",
"if len(results[\"errors\"]) > 0: sys.exit(1) else: sys.exit() def exitAppWithError(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\":",
"for neigh in neighs] if(\"weight\" in g.edge_attributes()): degrees = np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees =",
"range(len(kappaSi)): avgKappaSi[ci] = np.average(kappaSi[ci]) stdKappaSi[ci] = np.std(kappaSi[ci]) zmodule = np.zeros(g.vcount()) for i in",
"community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi = np.zeros(max(Ci)+1) stdKappaSi = np.zeros(max(Ci)+1) for ci in range(len(kappaSi)): avgKappaSi[ci]",
"\"BetweenessCentrality\" : calcBetweenessCentrality, \"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted, \"BetweennessCentralization\" : calcBetweennessCentralization, \"RichClubCoefficient\" : calcRichClubCoefficient, \"DegreeAssortativity\"",
"ValueError: return False class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp,",
"return result,np.average(result) def calcBetweennessCentralization(G): vnum = G.vcount() if vnum < 3: return None,0",
"Trc = richClubPercentage degree = np.array(g.degree()) edges = np.array(g.get_edgelist()) sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]] dT",
"numpy as np from tqdm import tqdm import igraph as ig import jgf",
"def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) neighs =",
"import re import json import numpy as np from tqdm import tqdm import",
"print(msg) def exitApp(): global results with open(\"product.json\", \"w\") as fp: json.dump(results, fp, cls=NumpyEncoder)",
"\"weight\")) return results, np.average(results) def calcOutStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()):",
": calcDegree, \"InDegree\" : calcInDegree, \"OutDegree\" : calcOutDegree, \"Strength\" : calcStrength, \"InStrength\" :",
"temparr)/(vnum-1) def calcRichClubCoefficient(g, highest=True, scores=None, indices_only=False): Trc = richClubPercentage degree = np.array(g.degree()) edges",
"if(\"weight\" in g.edge_attributes()): results = g.transitivity_local_undirected(weights=None) # else: # results = g.transitivity_local_undirected(weights=\"weight\") return",
"np.zeros(g.vcount()) for i in range(g.vcount()): ci = Ci[i] if(stdKappaSi[ci]>0): zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return",
"calcModuleDegreeZScore, \"ParticipationCoeff\" : calcParticipationCoeff, \"Modularity\" : calcModularity, } def isFloat(value): if(value is None):",
"np.array(g.betweenness(weights=\"weight\")) return result,np.average(result) def calcBetweennessCentralization(G): vnum = G.vcount() if vnum < 3: return",
"config = json.load(fd) # \"transform\":\"absolute\", //\"absolute\" or \"signed\" # \"retain-weights\":false, # \"threshold\": \"none\"",
"= np.array(g.degree()) matchIndex = np.zeros(g.ecount()) for id,e in enumerate(g.es): node1,node2 = e.tuple viz1",
"0 meanMatchIndex = np.mean(matchIndex) return None, meanMatchIndex def calcBetweenessCentrality(g): result = np.array(g.betweenness(directed=g.is_directed())) return",
"for vertexID,weigth in neigh] for neigh in neighs] if(\"weight\" in g.edge_attributes()): degrees =",
"np.uint16, np.uint32, np.uint64)): ret = int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): ret",
"or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"OUT\", weights = \"weight\")) return results,",
"with open(\"product.json\", \"w\") as fp: json.dump(results, fp, cls=NumpyEncoder) if len(results[\"errors\"]) > 0: sys.exit(1)",
"{ni: indi for indi, ni in enumerate(set(names))} numbers = [d[ni] for ni in",
"in neighs] if(\"weight\" in g.edge_attributes()): degrees = np.array(g.strength(mode=mode,weights=\"weight\")) else: degrees = np.array(g.degree(mode=mode)) kappasi",
"nodeCommunities = set([community for community,weight in cneighs[i]]) communityDegrees = {community:0 for community in",
"calcRichClubCoefficient, \"DegreeAssortativity\" : calcDegreeAssortativity, \"Diameter\" : calcDiameter, \"ModuleDegreeZScore\" : calcModuleDegreeZScore, \"ParticipationCoeff\" : calcParticipationCoeff,",
"calcBetweenessCentrality(g): result = np.array(g.betweenness(directed=g.is_directed())) return result,np.average(result) def calcBetweenessCentralityWeighted(g): if(\"weight\" not in g.edge_attributes()): return",
"return np.isfinite(numericValue) except ValueError: return False class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj,",
"G.betweenness()] max_temparr = max(temparr) return None,sum(max_temparr-i for i in temparr)/(vnum-1) def calcRichClubCoefficient(g, highest=True,",
"results, np.average(results) def calcClusteringCoefficient(g): # if(\"weight\" in g.edge_attributes()): results = g.transitivity_local_undirected(weights=None) # else:",
"in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) neighs = getNeighborhoods(g,mode=mode) cneighs =",
"not None): network.vs[measurement] = nodePropData if(networkPropData is not None): if(nodePropData is not None):",
"math.isnan(ret): ret = None if isinstance(ret, (bytes, bytearray)): ret = ret.decode(\"utf-8\") return ret",
"calcBetweennessCentralization(G): vnum = G.vcount() if vnum < 3: return None,0 denom = (vnum-1)*(vnum-2)",
"else: RC = 0 return None,RC def calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g): if(\"weight\"",
"90 if(\"richClubPercentage\" in config): richClubPercentage = config[\"richClubPercentage\"]; networks = jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks =",
"for community in nodeCommunities} for community,weight in cneighs[i]: communityDegrees[community]+=weight kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2)) result",
"# results = g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0), np.nanmean(results) def calcCoreness(g): results = np.array(g.coreness(mode=\"ALL\")) return",
"def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) neighs =",
"(None,None) results = np.array(g.strength(mode=\"ALL\", weights = \"weight\")) return results, np.average(results) def calcInStrength(g): if(\"weight\"",
"kappaSi = [[] for _ in range(max(Ci)+1)] for i in range(g.vcount()): kappa[i] =",
"def error(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) def exitApp(): global",
"\"Community\" in network.vertex_attributes() for measurement,measurementFunction in measurements.items(): nodePropData,networkPropData = measurementFunction(network) if(nodePropData is not",
"else: ret = json.JSONEncoder.default(self, obj) if isinstance(ret, (float)): if math.isnan(ret): ret = None",
"if isinstance(ret, (float)): if math.isnan(ret): ret = None if isinstance(ret, (bytes, bytearray)): ret",
"None, g.modularity(Ci, weights=\"weight\"); else: return None, g.modularity(Ci, weights=None); def calcDegree(g): results = np.array(g.degree(mode=\"ALL\"))",
"= np.array(g.strength(mode=\"ALL\", weights = \"weight\")) return results, np.average(results) def calcInStrength(g): if(\"weight\" not in",
"isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): ret",
"i in range(g.vcount())] else: return [[(e.target,1) if e.target!=i else (e.source,1) for e in",
"nodeCommunities} for community,weight in cneighs[i]: communityDegrees[community]+=weight kappasi[i] = np.sum(np.power(list(communityDegrees.values()),2)) result = 1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0]",
"reindexList(g.vs[\"Community\"]) else: return (None,None) if(\"weight\" in g.edge_attributes()): return None, g.modularity(Ci, weights=\"weight\"); else: return",
"result,np.average(result) def calcBetweennessCentralization(G): vnum = G.vcount() if vnum < 3: return None,0 denom",
"in cneighs[i] if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi = np.zeros(max(Ci)+1) stdKappaSi = np.zeros(max(Ci)+1) for ci",
"1): configFilename = sys.argv[1] outputDirectory = \"output\" outputFile = PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory)",
"= \"weight\")) return results, np.average(results) def calcOutStrength(g): if(\"weight\" not in g.edge_attributes() or not",
"\"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted, \"BetweennessCentralization\" : calcBetweennessCentralization, \"RichClubCoefficient\" : calcRichClubCoefficient, \"DegreeAssortativity\" : calcDegreeAssortativity, \"Diameter\"",
"exitApp() configFilename = \"config.json\" argCount = len(sys.argv) if(argCount > 1): configFilename = sys.argv[1]",
"(np.float_, np.float16, np.float32, np.float64)): ret = float(obj) elif isinstance(obj, (np.ndarray,)): ret = obj.tolist()",
"not None): if(nodePropData is not None): #Average measurement network[\"Avg. \"+measurement] = networkPropData else:",
"json.dump(results, fp, cls=NumpyEncoder) if len(results[\"errors\"]) > 0: sys.exit(1) else: sys.exit() def exitAppWithError(msg): global",
"ni in names] if(returnDict): return numbers,d else: return numbers def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in",
"not in g.edge_attributes()): return (None,None) results = np.array(g.strength(mode=\"ALL\", weights = \"weight\")) return results,",
"= [[] for _ in range(max(Ci)+1)] for i in range(g.vcount()): kappa[i] = np.sum([weight",
": calcBetweenessCentralityWeighted, \"BetweennessCentralization\" : calcBetweennessCentralization, \"RichClubCoefficient\" : calcRichClubCoefficient, \"DegreeAssortativity\" : calcDegreeAssortativity, \"Diameter\" :",
": calcRichClubCoefficient, \"DegreeAssortativity\" : calcDegreeAssortativity, \"Diameter\" : calcDiameter, \"ModuleDegreeZScore\" : calcModuleDegreeZScore, \"ParticipationCoeff\" :",
"in names] if(returnDict): return numbers,d else: return numbers def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in g.edge_attributes()):",
"community,weight in cneighs[i] if community==Ci[i]]) kappaSi[Ci[i]].append(kappa[i]) avgKappaSi = np.zeros(max(Ci)+1) stdKappaSi = np.zeros(max(Ci)+1) for",
"if(\"weight\" in g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False): d = {ni:",
"calcCoreness, \"MatchIndex\" : calcMatchIndex, \"BetweenessCentrality\" : calcBetweenessCentrality, \"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted, \"BetweennessCentralization\" : calcBetweennessCentralization,",
"= nodePropData if(networkPropData is not None): if(nodePropData is not None): #Average measurement network[\"Avg.",
"if (indNodes.size>1): RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC = 0 return None,RC def calcDegreeAssortativity(g):",
"= [2*i/denom for i in G.betweenness()] max_temparr = max(temparr) return None,sum(max_temparr-i for i",
"results, np.average(results) def calcOutStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return (None,None)",
"//\"absolute\" or \"signed\" # \"retain-weights\":false, # \"threshold\": \"none\" richClubPercentage = 90 if(\"richClubPercentage\" in",
"return result,None measurements = { \"Degree\" : calcDegree, \"InDegree\" : calcInDegree, \"OutDegree\" :",
"def calcOutDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.outdegree()) return results, np.average(results) def",
"results = np.array(g.strength(mode=\"OUT\", weights = \"weight\")) return results, np.average(results) def calcClusteringCoefficient(g): # if(\"weight\"",
"= set([community for community,weight in cneighs[i]]) communityDegrees = {community:0 for community in nodeCommunities}",
"else: return (None,None) if(\"weight\" in g.edge_attributes()): return None, g.modularity(Ci, weights=\"weight\"); else: return None,",
"return results, np.average(results) def calcInDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.indegree()) return",
"calcOutStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"OUT\",",
"\"Strength\" : calcStrength, \"InStrength\" : calcInStrength, \"OutStrength\" : calcOutStrength, \"ClusteringCoefficient\" : calcClusteringCoefficient, \"Coreness\"",
"results = np.array(g.degree(mode=\"ALL\")) return results, np.average(results) def calcInDegree(g): if(not g.is_directed()): return (None,None) results",
"np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): ret = int(obj)",
"np.average(results) def calcInStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return (None,None) results",
"results = g.transitivity_local_undirected(weights=None) # else: # results = g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0), np.nanmean(results) def",
"weights = \"weight\")) return results, np.average(results) def calcClusteringCoefficient(g): # if(\"weight\" in g.edge_attributes()): results",
"result[degrees==0.0] = 0 return result,None measurements = { \"Degree\" : calcDegree, \"InDegree\" :",
"kappaSi[Ci[i]].append(kappa[i]) avgKappaSi = np.zeros(max(Ci)+1) stdKappaSi = np.zeros(max(Ci)+1) for ci in range(len(kappaSi)): avgKappaSi[ci] =",
"0: sys.exit(1) else: sys.exit() def exitAppWithError(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg})",
"network in tqdm(networks): weighted = \"weight\" in network.edge_attributes() hasCommunities = \"Community\" in network.vertex_attributes()",
"in g.edge_attributes()): results = g.transitivity_local_undirected(weights=None) # else: # results = g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0),",
": calcCoreness, \"MatchIndex\" : calcMatchIndex, \"BetweenessCentrality\" : calcBetweenessCentrality, \"BetweenessCentralityWeighted\" : calcBetweenessCentralityWeighted, \"BetweennessCentralization\" :",
"= Ci[i] if(stdKappaSi[ci]>0): zmodule[i] = (kappa[i]-avgKappaSi[ci])/stdKappaSi[ci] return zmodule,None def calcParticipationCoeff(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()):",
"degree[edges[:,0]],degree[edges[:,1]] dT = int(np.percentile(degree,Trc)) indNodes = np.nonzero(degree>=dT)[0] indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1): RC",
"\"warning\", \"msg\": msg}) print(msg) def error(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg})",
"in tqdm(networks): weighted = \"weight\" in network.edge_attributes() hasCommunities = \"Community\" in network.vertex_attributes() for",
"return results, np.average(results) def calcInStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return",
"results = np.array(g.outdegree()) return results, np.average(results) def calcStrength(g): if(\"weight\" not in g.edge_attributes()): return",
"\"msg\": msg}) print(msg) exitApp() configFilename = \"config.json\" argCount = len(sys.argv) if(argCount > 1):",
"def calcMatchIndex(g): degree = np.array(g.degree()) matchIndex = np.zeros(g.ecount()) for id,e in enumerate(g.es): node1,node2",
"[2*i/denom for i in G.betweenness()] max_temparr = max(temparr) return None,sum(max_temparr-i for i in",
"ret.decode(\"utf-8\") return ret results = {\"errors\": [], \"warnings\": [], \"brainlife\": [], \"datatype_tags\": [],",
"g.edge_attributes()): return None,g.diameter(directed=g.is_directed(),weights=\"weight\") else: return None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False): d = {ni: indi for",
"sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]] dT = int(np.percentile(degree,Trc)) indNodes = np.nonzero(degree>=dT)[0] indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if",
"= e.tuple viz1 = g.neighbors(node1) viz2 = g.neighbors(node2) sharedNei = set(viz1) & set(viz2)",
"return (None,None) results = np.array(g.outdegree()) return results, np.average(results) def calcStrength(g): if(\"weight\" not in",
"\"error\", \"msg\": msg}) print(msg) def exitApp(): global results with open(\"product.json\", \"w\") as fp:",
"open(configFilename, \"r\") as fd: config = json.load(fd) # \"transform\":\"absolute\", //\"absolute\" or \"signed\" #",
"= np.array(g.strength(mode=\"OUT\", weights = \"weight\")) return results, np.average(results) def calcClusteringCoefficient(g): # if(\"weight\" in",
"in g.edge_attributes() or not g.is_directed()): return (None,None) results = np.array(g.strength(mode=\"IN\", weights = \"weight\"))",
"results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) exitApp() configFilename = \"config.json\" argCount =",
"in g.es[g.incident(i,mode=mode)]] for i in range(g.vcount())] def calcModuleDegreeZScore(g,mode=\"ALL\"): if(\"Community\" in g.vertex_attributes()): Ci =",
"if(returnDict): return numbers,d else: return numbers def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in g.edge_attributes()): return [[(e.target,e[\"weight\"])",
"1.0-kappasi/np.power(degrees,2.0) result[degrees==0.0] = 0 return result,None measurements = { \"Degree\" : calcDegree, \"InDegree\"",
"networks = jgf.igraph.load(config[\"network\"], compressed=True) outputNetworks = [] for network in tqdm(networks): weighted =",
"print(msg) def error(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\", \"msg\": msg}) print(msg) def exitApp():",
"numbers def getNeighborhoods(g,mode=\"ALL\"): if(\"weight\" in g.edge_attributes()): return [[(e.target,e[\"weight\"]) if e.target!=i else (e.source,e[\"weight\"]) for",
"in range(len(kappaSi)): avgKappaSi[ci] = np.average(kappaSi[ci]) stdKappaSi[ci] = np.std(kappaSi[ci]) zmodule = np.zeros(g.vcount()) for i",
"bytearray)): ret = ret.decode(\"utf-8\") return ret results = {\"errors\": [], \"warnings\": [], \"brainlife\":",
"i in G.betweenness()] max_temparr = max(temparr) return None,sum(max_temparr-i for i in temparr)/(vnum-1) def",
"g.neighbors(node1) viz2 = g.neighbors(node2) sharedNei = set(viz1) & set(viz2) if ((degree[node1]+degree[node2]) > 2):",
"import matplotlib.pyplot as plt def calcModularity(g): if(\"Community\" in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else:",
"return None,g.diameter(directed=g.is_directed()) def reindexList(names,returnDict=False): d = {ni: indi for indi, ni in enumerate(set(names))}",
": calcInDegree, \"OutDegree\" : calcOutDegree, \"Strength\" : calcStrength, \"InStrength\" : calcInStrength, \"OutStrength\" :",
"results = np.array(g.strength(mode=\"ALL\", weights = \"weight\")) return results, np.average(results) def calcInStrength(g): if(\"weight\" not",
"else: # results = g.transitivity_local_undirected(weights=\"weight\") return np.nan_to_num(results,0), np.nanmean(results) def calcCoreness(g): results = np.array(g.coreness(mode=\"ALL\"))",
"g.edge_attributes()): return None, g.modularity(Ci, weights=\"weight\"); else: return None, g.modularity(Ci, weights=None); def calcDegree(g): results",
"\"w\") as fp: json.dump(results, fp, cls=NumpyEncoder) if len(results[\"errors\"]) > 0: sys.exit(1) else: sys.exit()",
"None): return False try: numericValue = float(value) return np.isfinite(numericValue) except ValueError: return False",
"\"config.json\" argCount = len(sys.argv) if(argCount > 1): configFilename = sys.argv[1] outputDirectory = \"output\"",
"= obj.tolist() else: ret = json.JSONEncoder.default(self, obj) if isinstance(ret, (float)): if math.isnan(ret): ret",
"in range(g.vcount())] else: return [[(e.target,1) if e.target!=i else (e.source,1) for e in g.es[g.incident(i,mode=mode)]]",
"return (None,None) results = np.array(g.strength(mode=\"IN\", weights = \"weight\")) return results, np.average(results) def calcOutStrength(g):",
"= richClubPercentage degree = np.array(g.degree()) edges = np.array(g.get_edgelist()) sourceDegree,targetDegree = degree[edges[:,0]],degree[edges[:,1]] dT =",
"= [[(Ci[vertexID],weigth) for vertexID,weigth in neigh] for neigh in neighs] if(\"weight\" in g.edge_attributes()):",
"len(results[\"errors\"]) > 0: sys.exit(1) else: sys.exit() def exitAppWithError(msg): global results results['errors'].append(msg) #results['brainlife'].append({\"type\": \"error\",",
"= sys.argv[1] outputDirectory = \"output\" outputFile = PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)): os.makedirs(outputDirectory) with open(configFilename,",
"calcInDegree(g): if(not g.is_directed()): return (None,None) results = np.array(g.indegree()) return results, np.average(results) def calcOutDegree(g):",
"= np.array(g.degree(mode=\"ALL\")) return results, np.average(results) def calcInDegree(g): if(not g.is_directed()): return (None,None) results =",
"= np.array(g.strength(mode=\"IN\", weights = \"weight\")) return results, np.average(results) def calcOutStrength(g): if(\"weight\" not in",
"return (None,None) result = np.array(g.betweenness(weights=\"weight\")) return result,np.average(result) def calcBetweennessCentralization(G): vnum = G.vcount() if",
"range(g.vcount()): nodeCommunities = set([community for community,weight in cneighs[i]]) communityDegrees = {community:0 for community",
"0 return None,RC def calcDegreeAssortativity(g): return None,g.assortativity_degree(directed=g.is_directed()) def calcDiameter(g): if(\"weight\" in g.edge_attributes()): return",
"> 1): configFilename = sys.argv[1] outputDirectory = \"output\" outputFile = PJ(outputDirectory,\"network.json.gz\") if(not os.path.exists(outputDirectory)):",
"warning(msg): global results results['warnings'].append(msg) #results['brainlife'].append({\"type\": \"warning\", \"msg\": msg}) print(msg) def error(msg): global results",
"\"none\" richClubPercentage = 90 if(\"richClubPercentage\" in config): richClubPercentage = config[\"richClubPercentage\"]; networks = jgf.igraph.load(config[\"network\"],",
"results, np.average(results) def calcInStrength(g): if(\"weight\" not in g.edge_attributes() or not g.is_directed()): return (None,None)",
"in g.vertex_attributes()): Ci = reindexList(g.vs[\"Community\"]) else: return (None,None) if(\"weight\" in g.edge_attributes()): return None,",
"indNodes = np.nonzero(degree>=dT)[0] indEdges = np.nonzero((sourceDegree>=dT)&(targetDegree>=dT))[0] if (indNodes.size>1): RC = 2.*indEdges.size/(indNodes.size*(indNodes.size-1)) else: RC",
"for i in temparr)/(vnum-1) def calcRichClubCoefficient(g, highest=True, scores=None, indices_only=False): Trc = richClubPercentage degree"
] |
[
"async def on_message(message): if message.author == client.user: return if not me in str(message.author):",
"requests from bs4 import BeautifulSoup from json_extract import json_extract HOST = json_extract(\"host\") PORT",
"if message.content.lower().startswith(\"!doathing\"): req = requests.get(URL + \"/testDevice/doAThing\") if req.status_code==200: await message.channel.send(content=\"Did nothing successfully!\")",
"nothing! Error code {}.\".format(req.status_code)) return if message.content.lower().startswith(\"!getathing\"): req = requests.post(URL + \"/testDevice/getAThing\") if",
"from json_extract import json_extract HOST = json_extract(\"host\") PORT = json_extract(\"port\") URL = \"http://{}:{}\".format(HOST,",
"server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"): req =",
"= \"Lamp turned on successfully!\" else: msg = \"Lamp turned off successfully!\" await",
"\"\" if \"on\" in message.content.lower(): msg = \"Lamp turned on successfully!\" else: msg",
"import requests from bs4 import BeautifulSoup from json_extract import json_extract HOST = json_extract(\"host\")",
"if message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"): req = requests.get(URL + \"/garageDoor/toggleGarage\") if req.status_code==200: msg =",
"await message.channel.send(content=msg) return if message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"): req = requests.get(URL + \"/chandlerLamp/lampSwitch\") if",
"msg = \"\" if \"open\" in message.content.lower(): msg = \"Garage Door opened successfully!\"",
"\"/testDevice/doAThing\") if req.status_code==200: await message.channel.send(content=\"Did nothing successfully!\") else: await message.channel.send(content=\"Failed to do nothing!",
"successfully!\") else: await message.channel.send(content=\"Failed to do nothing! Error code {}.\".format(req.status_code)) return if message.content.lower().startswith(\"!getathing\"):",
"await message.channel.send(content=\"Failed to do nothing! Error code {}.\".format(req.status_code)) return if message.content.lower().startswith(\"!getathing\"): req =",
"\"/garageDoor/toggleGarage\") if req.status_code==200: msg = \"\" if \"open\" in message.content.lower(): msg = \"Garage",
"return if message.content.lower().startswith(\"!getathing\"): req = requests.post(URL + \"/testDevice/getAThing\") if req.status_code==200: page = BeautifulSoup(req.content,",
"message.content.lower().startswith(\"!getathing\"): req = requests.post(URL + \"/testDevice/getAThing\") if req.status_code==200: page = BeautifulSoup(req.content, \"html.parser\") await",
"if \"open\" in message.content.lower(): msg = \"Garage Door opened successfully!\" else: msg =",
"return @client.event # the on_ready event async def on_ready(): print('Logged in as') print(client.user.name)",
"page = BeautifulSoup(req.content, \"html.parser\") msg = page.h1.text + \"\\n\" + page.p.text await message.channel.send(content=msg)",
"or message.content.lower().startswith(\"!turnofflamp\"): req = requests.get(URL + \"/chandlerLamp/lampSwitch\") if req.status_code==200: msg = \"\" if",
"Error code {}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"): req = requests.post(URL + \"/garageDoor/getGarage\") if req.status_code ==",
"was an error with your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return",
"<filename>discordBot/bot.py import discord import requests from bs4 import BeautifulSoup from json_extract import json_extract",
"to do nothing! Error code {}.\".format(req.status_code)) return if message.content.lower().startswith(\"!getathing\"): req = requests.post(URL +",
"returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return @client.event # the on_ready event async def",
"json_extract(\"host\") PORT = json_extract(\"port\") URL = \"http://{}:{}\".format(HOST, PORT) token = json_extract(\"token\") me =",
"req.status_code==200: page = BeautifulSoup(req.content, \"html.parser\") await message.channel.send(content=page.p.text) else: await message.channel.send(content=\"Failed to get nothing!",
"server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return @client.event # the on_ready event async",
"not me in str(message.author): print(message.author) return if message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"): req = requests.get(URL",
"= BeautifulSoup(req.content, \"html.parser\") msg = page.h1.text + \"\\n\" + page.p.text await message.channel.send(content=msg) return",
"= requests.get(URL + \"/garageDoor/toggleGarage\") if req.status_code==200: msg = \"\" if \"open\" in message.content.lower():",
"return else: msg = \"There was an error with your request: server returned",
"= \"http://{}:{}\".format(HOST, PORT) token = json_extract(\"token\") me = json_extract(\"admin\") client = discord.Client() @client.event",
"+ \"/chandlerLamp/lampSwitch\") if req.status_code==200: msg = \"\" if \"on\" in message.content.lower(): msg =",
"message.content.lower().startswith(\"!garagestatus\"): req = requests.post(URL + \"/garageDoor/getGarage\") if req.status_code == 200: page = BeautifulSoup(req.content,",
"to get nothing! Error code {}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"): req = requests.post(URL + \"/garageDoor/getGarage\")",
"requests.get(URL + \"/chandlerLamp/lampSwitch\") if req.status_code==200: msg = \"\" if \"on\" in message.content.lower(): msg",
"return if message.content.lower().startswith(\"!doathing\"): req = requests.get(URL + \"/testDevice/doAThing\") if req.status_code==200: await message.channel.send(content=\"Did nothing",
"in message.content.lower(): msg = \"Garage Door opened successfully!\" else: msg = \"Garage Door",
"msg = page.h1.text + \"\\n\" + page.p.text await message.channel.send(content=msg) return else: msg =",
"me = json_extract(\"admin\") client = discord.Client() @client.event async def on_message(message): if message.author ==",
"json_extract(\"admin\") client = discord.Client() @client.event async def on_message(message): if message.author == client.user: return",
"Door closed successfully!\" await message.channel.send(content=msg) return else: msg = \"There was an error",
"message.channel.send(content=msg) return else: msg = \"There was an error with your request: server",
"msg = \"There was an error with your request: server returned code {}.\".format(req.status_code)",
"successfully!\" else: msg = \"Lamp turned off successfully!\" await message.channel.send(content=msg) return else: msg",
"\"/garageDoor/getGarage\") if req.status_code == 200: page = BeautifulSoup(req.content, \"html.parser\") msg = page.h1.text +",
"\"/testDevice/getAThing\") if req.status_code==200: page = BeautifulSoup(req.content, \"html.parser\") await message.channel.send(content=page.p.text) else: await message.channel.send(content=\"Failed to",
"successfully!\" await message.channel.send(content=msg) return else: msg = \"There was an error with your",
"# the on_ready event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------')",
"on successfully!\" else: msg = \"Lamp turned off successfully!\" await message.channel.send(content=msg) return else:",
"if req.status_code==200: msg = \"\" if \"open\" in message.content.lower(): msg = \"Garage Door",
"= \"Garage Door opened successfully!\" else: msg = \"Garage Door closed successfully!\" await",
"message.content.lower(): msg = \"Lamp turned on successfully!\" else: msg = \"Lamp turned off",
"client.user: return if not me in str(message.author): print(message.author) return if message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"):",
"json_extract(\"port\") URL = \"http://{}:{}\".format(HOST, PORT) token = json_extract(\"token\") me = json_extract(\"admin\") client =",
"msg = \"\" if \"on\" in message.content.lower(): msg = \"Lamp turned on successfully!\"",
"discord.Client() @client.event async def on_message(message): if message.author == client.user: return if not me",
"code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"): req = requests.get(URL +",
"req.status_code==200: await message.channel.send(content=\"Did nothing successfully!\") else: await message.channel.send(content=\"Failed to do nothing! Error code",
"turned on successfully!\" else: msg = \"Lamp turned off successfully!\" await message.channel.send(content=msg) return",
"= BeautifulSoup(req.content, \"html.parser\") await message.channel.send(content=page.p.text) else: await message.channel.send(content=\"Failed to get nothing! Error code",
"Error code {}.\".format(req.status_code)) return if message.content.lower().startswith(\"!getathing\"): req = requests.post(URL + \"/testDevice/getAThing\") if req.status_code==200:",
"me in str(message.author): print(message.author) return if message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"): req = requests.get(URL +",
"return if message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"): req = requests.get(URL + \"/garageDoor/toggleGarage\") if req.status_code==200: msg",
"import BeautifulSoup from json_extract import json_extract HOST = json_extract(\"host\") PORT = json_extract(\"port\") URL",
"message.channel.send(content=msg) return if message.content.lower().startswith(\"!doathing\"): req = requests.get(URL + \"/testDevice/doAThing\") if req.status_code==200: await message.channel.send(content=\"Did",
"on_message(message): if message.author == client.user: return if not me in str(message.author): print(message.author) return",
"opened successfully!\" else: msg = \"Garage Door closed successfully!\" await message.channel.send(content=msg) return else:",
"req = requests.get(URL + \"/testDevice/doAThing\") if req.status_code==200: await message.channel.send(content=\"Did nothing successfully!\") else: await",
"message.channel.send(content=\"Failed to get nothing! Error code {}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"): req = requests.post(URL +",
"message.content.lower(): msg = \"Garage Door opened successfully!\" else: msg = \"Garage Door closed",
"json_extract import json_extract HOST = json_extract(\"host\") PORT = json_extract(\"port\") URL = \"http://{}:{}\".format(HOST, PORT)",
"returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"): req = requests.get(URL",
"return if not me in str(message.author): print(message.author) return if message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"): req",
"str(message.author): print(message.author) return if message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"): req = requests.get(URL + \"/garageDoor/toggleGarage\") if",
"request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"): req",
"== 200: page = BeautifulSoup(req.content, \"html.parser\") msg = page.h1.text + \"\\n\" + page.p.text",
"def on_message(message): if message.author == client.user: return if not me in str(message.author): print(message.author)",
"if req.status_code==200: await message.channel.send(content=\"Did nothing successfully!\") else: await message.channel.send(content=\"Failed to do nothing! Error",
"the on_ready event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') client.run(token)",
"msg = \"Garage Door opened successfully!\" else: msg = \"Garage Door closed successfully!\"",
"await message.channel.send(content=msg) return @client.event # the on_ready event async def on_ready(): print('Logged in",
"= \"\" if \"open\" in message.content.lower(): msg = \"Garage Door opened successfully!\" else:",
"@client.event async def on_message(message): if message.author == client.user: return if not me in",
"page.h1.text + \"\\n\" + page.p.text await message.channel.send(content=msg) return else: msg = \"There was",
"message.channel.send(content=msg) return if message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"): req = requests.get(URL + \"/chandlerLamp/lampSwitch\") if req.status_code==200:",
"= json_extract(\"host\") PORT = json_extract(\"port\") URL = \"http://{}:{}\".format(HOST, PORT) token = json_extract(\"token\") me",
"await message.channel.send(content=\"Failed to get nothing! Error code {}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"): req = requests.post(URL",
"import discord import requests from bs4 import BeautifulSoup from json_extract import json_extract HOST",
"else: msg = \"Garage Door closed successfully!\" await message.channel.send(content=msg) return else: msg =",
"closed successfully!\" await message.channel.send(content=msg) return else: msg = \"There was an error with",
"PORT = json_extract(\"port\") URL = \"http://{}:{}\".format(HOST, PORT) token = json_extract(\"token\") me = json_extract(\"admin\")",
"your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return @client.event # the on_ready",
"await message.channel.send(content=msg) return else: msg = \"There was an error with your request:",
"await message.channel.send(content=msg) return if message.content.lower().startswith(\"!doathing\"): req = requests.get(URL + \"/testDevice/doAThing\") if req.status_code==200: await",
"code {}.\".format(req.status_code) await message.channel.send(content=msg) return @client.event # the on_ready event async def on_ready():",
"your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"):",
"if req.status_code==200: page = BeautifulSoup(req.content, \"html.parser\") await message.channel.send(content=page.p.text) else: await message.channel.send(content=\"Failed to get",
"+ \"/garageDoor/getGarage\") if req.status_code == 200: page = BeautifulSoup(req.content, \"html.parser\") msg = page.h1.text",
"if req.status_code==200: msg = \"\" if \"on\" in message.content.lower(): msg = \"Lamp turned",
"req = requests.get(URL + \"/garageDoor/toggleGarage\") if req.status_code==200: msg = \"\" if \"open\" in",
"= page.h1.text + \"\\n\" + page.p.text await message.channel.send(content=msg) return else: msg = \"There",
"+ \"/garageDoor/toggleGarage\") if req.status_code==200: msg = \"\" if \"open\" in message.content.lower(): msg =",
"in str(message.author): print(message.author) return if message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"): req = requests.get(URL + \"/garageDoor/toggleGarage\")",
"msg = \"Lamp turned on successfully!\" else: msg = \"Lamp turned off successfully!\"",
"else: await message.channel.send(content=\"Failed to get nothing! Error code {}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"): req =",
"json_extract HOST = json_extract(\"host\") PORT = json_extract(\"port\") URL = \"http://{}:{}\".format(HOST, PORT) token =",
"else: msg = \"There was an error with your request: server returned code",
"message.content.lower().startswith(\"!doathing\"): req = requests.get(URL + \"/testDevice/doAThing\") if req.status_code==200: await message.channel.send(content=\"Did nothing successfully!\") else:",
"import json_extract HOST = json_extract(\"host\") PORT = json_extract(\"port\") URL = \"http://{}:{}\".format(HOST, PORT) token",
"+ \"\\n\" + page.p.text await message.channel.send(content=msg) return else: msg = \"There was an",
"print(message.author) return if message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"): req = requests.get(URL + \"/garageDoor/toggleGarage\") if req.status_code==200:",
"requests.get(URL + \"/garageDoor/toggleGarage\") if req.status_code==200: msg = \"\" if \"open\" in message.content.lower(): msg",
"error with your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!doathing\"):",
"PORT) token = json_extract(\"token\") me = json_extract(\"admin\") client = discord.Client() @client.event async def",
"= requests.post(URL + \"/testDevice/getAThing\") if req.status_code==200: page = BeautifulSoup(req.content, \"html.parser\") await message.channel.send(content=page.p.text) else:",
"= \"\" if \"on\" in message.content.lower(): msg = \"Lamp turned on successfully!\" else:",
"\"Lamp turned off successfully!\" await message.channel.send(content=msg) return else: msg = \"There was an",
"message.channel.send(content=\"Failed to do nothing! Error code {}.\".format(req.status_code)) return if message.content.lower().startswith(\"!getathing\"): req = requests.post(URL",
"requests.get(URL + \"/testDevice/doAThing\") if req.status_code==200: await message.channel.send(content=\"Did nothing successfully!\") else: await message.channel.send(content=\"Failed to",
"{}.\".format(req.status_code) await message.channel.send(content=msg) return @client.event # the on_ready event async def on_ready(): print('Logged",
"else: msg = \"Lamp turned off successfully!\" await message.channel.send(content=msg) return else: msg =",
"requests.post(URL + \"/testDevice/getAThing\") if req.status_code==200: page = BeautifulSoup(req.content, \"html.parser\") await message.channel.send(content=page.p.text) else: await",
"= requests.post(URL + \"/garageDoor/getGarage\") if req.status_code == 200: page = BeautifulSoup(req.content, \"html.parser\") msg",
"else: await message.channel.send(content=\"Failed to do nothing! Error code {}.\".format(req.status_code)) return if message.content.lower().startswith(\"!getathing\"): req",
"Door opened successfully!\" else: msg = \"Garage Door closed successfully!\" await message.channel.send(content=msg) return",
"= \"There was an error with your request: server returned code {}.\".format(req.status_code) await",
"await message.channel.send(content=\"Did nothing successfully!\") else: await message.channel.send(content=\"Failed to do nothing! Error code {}.\".format(req.status_code))",
"error with your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return @client.event #",
"req = requests.post(URL + \"/testDevice/getAThing\") if req.status_code==200: page = BeautifulSoup(req.content, \"html.parser\") await message.channel.send(content=page.p.text)",
"\"\" if \"open\" in message.content.lower(): msg = \"Garage Door opened successfully!\" else: msg",
"code {}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"): req = requests.post(URL + \"/garageDoor/getGarage\") if req.status_code == 200:",
"req = requests.post(URL + \"/garageDoor/getGarage\") if req.status_code == 200: page = BeautifulSoup(req.content, \"html.parser\")",
"request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return @client.event # the on_ready event",
"if message.content.lower().startswith(\"!getathing\"): req = requests.post(URL + \"/testDevice/getAThing\") if req.status_code==200: page = BeautifulSoup(req.content, \"html.parser\")",
"= \"Garage Door closed successfully!\" await message.channel.send(content=msg) return else: msg = \"There was",
"returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!doathing\"): req = requests.get(URL + \"/testDevice/doAThing\")",
"page.p.text await message.channel.send(content=msg) return else: msg = \"There was an error with your",
"msg = \"Garage Door closed successfully!\" await message.channel.send(content=msg) return else: msg = \"There",
"\"html.parser\") msg = page.h1.text + \"\\n\" + page.p.text await message.channel.send(content=msg) return else: msg",
"URL = \"http://{}:{}\".format(HOST, PORT) token = json_extract(\"token\") me = json_extract(\"admin\") client = discord.Client()",
"\"/chandlerLamp/lampSwitch\") if req.status_code==200: msg = \"\" if \"on\" in message.content.lower(): msg = \"Lamp",
"\"Lamp turned on successfully!\" else: msg = \"Lamp turned off successfully!\" await message.channel.send(content=msg)",
"\"on\" in message.content.lower(): msg = \"Lamp turned on successfully!\" else: msg = \"Lamp",
"page = BeautifulSoup(req.content, \"html.parser\") await message.channel.send(content=page.p.text) else: await message.channel.send(content=\"Failed to get nothing! Error",
"get nothing! Error code {}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"): req = requests.post(URL + \"/garageDoor/getGarage\") if",
"message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"): req = requests.get(URL + \"/chandlerLamp/lampSwitch\") if req.status_code==200: msg = \"\"",
"\"open\" in message.content.lower(): msg = \"Garage Door opened successfully!\" else: msg = \"Garage",
"if not me in str(message.author): print(message.author) return if message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"): req =",
"from bs4 import BeautifulSoup from json_extract import json_extract HOST = json_extract(\"host\") PORT =",
"+ page.p.text await message.channel.send(content=msg) return else: msg = \"There was an error with",
"if message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"): req = requests.get(URL + \"/chandlerLamp/lampSwitch\") if req.status_code==200: msg =",
"an error with your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if",
"if \"on\" in message.content.lower(): msg = \"Lamp turned on successfully!\" else: msg =",
"off successfully!\" await message.channel.send(content=msg) return else: msg = \"There was an error with",
"if req.status_code == 200: page = BeautifulSoup(req.content, \"html.parser\") msg = page.h1.text + \"\\n\"",
"= json_extract(\"token\") me = json_extract(\"admin\") client = discord.Client() @client.event async def on_message(message): if",
"request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!doathing\"): req = requests.get(URL",
"if message.content.lower().startswith(\"!garagestatus\"): req = requests.post(URL + \"/garageDoor/getGarage\") if req.status_code == 200: page =",
"= requests.get(URL + \"/chandlerLamp/lampSwitch\") if req.status_code==200: msg = \"\" if \"on\" in message.content.lower():",
"\"http://{}:{}\".format(HOST, PORT) token = json_extract(\"token\") me = json_extract(\"admin\") client = discord.Client() @client.event async",
"= json_extract(\"admin\") client = discord.Client() @client.event async def on_message(message): if message.author == client.user:",
"discord import requests from bs4 import BeautifulSoup from json_extract import json_extract HOST =",
"token = json_extract(\"token\") me = json_extract(\"admin\") client = discord.Client() @client.event async def on_message(message):",
"req = requests.get(URL + \"/chandlerLamp/lampSwitch\") if req.status_code==200: msg = \"\" if \"on\" in",
"BeautifulSoup(req.content, \"html.parser\") msg = page.h1.text + \"\\n\" + page.p.text await message.channel.send(content=msg) return else:",
"server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!doathing\"): req = requests.get(URL +",
"\"Garage Door opened successfully!\" else: msg = \"Garage Door closed successfully!\" await message.channel.send(content=msg)",
"\"There was an error with your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg)",
"or message.content.lower().startswith(\"!closegaragedoor\"): req = requests.get(URL + \"/garageDoor/toggleGarage\") if req.status_code==200: msg = \"\" if",
"{}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"): req = requests.get(URL + \"/chandlerLamp/lampSwitch\")",
"BeautifulSoup(req.content, \"html.parser\") await message.channel.send(content=page.p.text) else: await message.channel.send(content=\"Failed to get nothing! Error code {}.\".format(req.status_code))",
"== client.user: return if not me in str(message.author): print(message.author) return if message.content.lower().startswith(\"!opengaragedoor\") or",
"{}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"): req = requests.post(URL + \"/garageDoor/getGarage\") if req.status_code == 200: page",
"error with your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!turnonlamp\")",
"with your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!doathing\"): req",
"await message.channel.send(content=page.p.text) else: await message.channel.send(content=\"Failed to get nothing! Error code {}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"):",
"message.content.lower().startswith(\"!opengaragedoor\") or message.content.lower().startswith(\"!closegaragedoor\"): req = requests.get(URL + \"/garageDoor/toggleGarage\") if req.status_code==200: msg = \"\"",
"nothing successfully!\") else: await message.channel.send(content=\"Failed to do nothing! Error code {}.\".format(req.status_code)) return if",
"message.channel.send(content=msg) return @client.event # the on_ready event async def on_ready(): print('Logged in as')",
"nothing! Error code {}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"): req = requests.post(URL + \"/garageDoor/getGarage\") if req.status_code",
"BeautifulSoup from json_extract import json_extract HOST = json_extract(\"host\") PORT = json_extract(\"port\") URL =",
"= discord.Client() @client.event async def on_message(message): if message.author == client.user: return if not",
"code {}.\".format(req.status_code)) return if message.content.lower().startswith(\"!getathing\"): req = requests.post(URL + \"/testDevice/getAThing\") if req.status_code==200: page",
"\"\\n\" + page.p.text await message.channel.send(content=msg) return else: msg = \"There was an error",
"HOST = json_extract(\"host\") PORT = json_extract(\"port\") URL = \"http://{}:{}\".format(HOST, PORT) token = json_extract(\"token\")",
"message.channel.send(content=page.p.text) else: await message.channel.send(content=\"Failed to get nothing! Error code {}.\".format(req.status_code)) if message.content.lower().startswith(\"!garagestatus\"): req",
"req.status_code == 200: page = BeautifulSoup(req.content, \"html.parser\") msg = page.h1.text + \"\\n\" +",
"successfully!\" else: msg = \"Garage Door closed successfully!\" await message.channel.send(content=msg) return else: msg",
"= requests.get(URL + \"/testDevice/doAThing\") if req.status_code==200: await message.channel.send(content=\"Did nothing successfully!\") else: await message.channel.send(content=\"Failed",
"+ \"/testDevice/getAThing\") if req.status_code==200: page = BeautifulSoup(req.content, \"html.parser\") await message.channel.send(content=page.p.text) else: await message.channel.send(content=\"Failed",
"do nothing! Error code {}.\".format(req.status_code)) return if message.content.lower().startswith(\"!getathing\"): req = requests.post(URL + \"/testDevice/getAThing\")",
"message.content.lower().startswith(\"!closegaragedoor\"): req = requests.get(URL + \"/garageDoor/toggleGarage\") if req.status_code==200: msg = \"\" if \"open\"",
"message.channel.send(content=\"Did nothing successfully!\") else: await message.channel.send(content=\"Failed to do nothing! Error code {}.\".format(req.status_code)) return",
"json_extract(\"token\") me = json_extract(\"admin\") client = discord.Client() @client.event async def on_message(message): if message.author",
"= \"Lamp turned off successfully!\" await message.channel.send(content=msg) return else: msg = \"There was",
"message.content.lower().startswith(\"!turnofflamp\"): req = requests.get(URL + \"/chandlerLamp/lampSwitch\") if req.status_code==200: msg = \"\" if \"on\"",
"with your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return @client.event # the",
"with your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!turnonlamp\") or",
"return if message.content.lower().startswith(\"!turnonlamp\") or message.content.lower().startswith(\"!turnofflamp\"): req = requests.get(URL + \"/chandlerLamp/lampSwitch\") if req.status_code==200: msg",
"msg = \"Lamp turned off successfully!\" await message.channel.send(content=msg) return else: msg = \"There",
"if message.author == client.user: return if not me in str(message.author): print(message.author) return if",
"req.status_code==200: msg = \"\" if \"open\" in message.content.lower(): msg = \"Garage Door opened",
"your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!doathing\"): req =",
"requests.post(URL + \"/garageDoor/getGarage\") if req.status_code == 200: page = BeautifulSoup(req.content, \"html.parser\") msg =",
"client = discord.Client() @client.event async def on_message(message): if message.author == client.user: return if",
"bs4 import BeautifulSoup from json_extract import json_extract HOST = json_extract(\"host\") PORT = json_extract(\"port\")",
"turned off successfully!\" await message.channel.send(content=msg) return else: msg = \"There was an error",
"+ \"/testDevice/doAThing\") if req.status_code==200: await message.channel.send(content=\"Did nothing successfully!\") else: await message.channel.send(content=\"Failed to do",
"in message.content.lower(): msg = \"Lamp turned on successfully!\" else: msg = \"Lamp turned",
"{}.\".format(req.status_code)) return if message.content.lower().startswith(\"!getathing\"): req = requests.post(URL + \"/testDevice/getAThing\") if req.status_code==200: page =",
"200: page = BeautifulSoup(req.content, \"html.parser\") msg = page.h1.text + \"\\n\" + page.p.text await",
"@client.event # the on_ready event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id)",
"an error with your request: server returned code {}.\".format(req.status_code) await message.channel.send(content=msg) return @client.event",
"req.status_code==200: msg = \"\" if \"on\" in message.content.lower(): msg = \"Lamp turned on",
"message.author == client.user: return if not me in str(message.author): print(message.author) return if message.content.lower().startswith(\"!opengaragedoor\")",
"\"html.parser\") await message.channel.send(content=page.p.text) else: await message.channel.send(content=\"Failed to get nothing! Error code {}.\".format(req.status_code)) if",
"code {}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!doathing\"): req = requests.get(URL + \"/testDevice/doAThing\") if",
"= json_extract(\"port\") URL = \"http://{}:{}\".format(HOST, PORT) token = json_extract(\"token\") me = json_extract(\"admin\") client",
"{}.\".format(req.status_code) await message.channel.send(content=msg) return if message.content.lower().startswith(\"!doathing\"): req = requests.get(URL + \"/testDevice/doAThing\") if req.status_code==200:",
"\"Garage Door closed successfully!\" await message.channel.send(content=msg) return else: msg = \"There was an"
] |
[
"Object class Address(Object): \"\"\" Describes an address Attributes: ID (:obj:`str`): ``Address`` Args: country_code",
"read(q: dict, *args) -> \"Address\": country_code = q.get('country_code') state = q.get('state') city =",
"street_line1 (:obj:`str`): First line of the address street_line2 (:obj:`str`): Second line of the",
"ID = \"address\" def __init__(self, country_code, state, city, street_line1, street_line2, postal_code, **kwargs): self.country_code",
"def __init__(self, country_code, state, city, street_line1, street_line2, postal_code, **kwargs): self.country_code = country_code #",
"line of the address street_line2 (:obj:`str`): Second line of the address postal_code (:obj:`str`):",
"q.get('city') street_line1 = q.get('street_line1') street_line2 = q.get('street_line2') postal_code = q.get('postal_code') return Address(country_code, state,",
"<reponame>iTeam-co/pytglib from ..utils import Object class Address(Object): \"\"\" Describes an address Attributes: ID",
"-> \"Address\": country_code = q.get('country_code') state = q.get('state') city = q.get('city') street_line1 =",
"Args: country_code (:obj:`str`): A two-letter ISO 3166-1 alpha-2 country code state (:obj:`str`): State,",
"\"Address\": country_code = q.get('country_code') state = q.get('state') city = q.get('city') street_line1 = q.get('street_line1')",
"postal code Returns: Address Raises: :class:`telegram.Error` \"\"\" ID = \"address\" def __init__(self, country_code,",
"str self.street_line2 = street_line2 # str self.postal_code = postal_code # str @staticmethod def",
"dict, *args) -> \"Address\": country_code = q.get('country_code') state = q.get('state') city = q.get('city')",
"ISO 3166-1 alpha-2 country code state (:obj:`str`): State, if applicable city (:obj:`str`): City",
":class:`telegram.Error` \"\"\" ID = \"address\" def __init__(self, country_code, state, city, street_line1, street_line2, postal_code,",
"street_line1, street_line2, postal_code, **kwargs): self.country_code = country_code # str self.state = state #",
"= country_code # str self.state = state # str self.city = city #",
"address street_line2 (:obj:`str`): Second line of the address postal_code (:obj:`str`): Address postal code",
"postal_code # str @staticmethod def read(q: dict, *args) -> \"Address\": country_code = q.get('country_code')",
"street_line1 # str self.street_line2 = street_line2 # str self.postal_code = postal_code # str",
"str @staticmethod def read(q: dict, *args) -> \"Address\": country_code = q.get('country_code') state =",
"# str self.street_line1 = street_line1 # str self.street_line2 = street_line2 # str self.postal_code",
"alpha-2 country code state (:obj:`str`): State, if applicable city (:obj:`str`): City street_line1 (:obj:`str`):",
"\"\"\" Describes an address Attributes: ID (:obj:`str`): ``Address`` Args: country_code (:obj:`str`): A two-letter",
"state = q.get('state') city = q.get('city') street_line1 = q.get('street_line1') street_line2 = q.get('street_line2') postal_code",
"country_code (:obj:`str`): A two-letter ISO 3166-1 alpha-2 country code state (:obj:`str`): State, if",
"State, if applicable city (:obj:`str`): City street_line1 (:obj:`str`): First line of the address",
"self.state = state # str self.city = city # str self.street_line1 = street_line1",
"= q.get('state') city = q.get('city') street_line1 = q.get('street_line1') street_line2 = q.get('street_line2') postal_code =",
"self.street_line2 = street_line2 # str self.postal_code = postal_code # str @staticmethod def read(q:",
"# str self.postal_code = postal_code # str @staticmethod def read(q: dict, *args) ->",
"address Attributes: ID (:obj:`str`): ``Address`` Args: country_code (:obj:`str`): A two-letter ISO 3166-1 alpha-2",
"__init__(self, country_code, state, city, street_line1, street_line2, postal_code, **kwargs): self.country_code = country_code # str",
"self.postal_code = postal_code # str @staticmethod def read(q: dict, *args) -> \"Address\": country_code",
"= state # str self.city = city # str self.street_line1 = street_line1 #",
"Address postal code Returns: Address Raises: :class:`telegram.Error` \"\"\" ID = \"address\" def __init__(self,",
"= q.get('city') street_line1 = q.get('street_line1') street_line2 = q.get('street_line2') postal_code = q.get('postal_code') return Address(country_code,",
"line of the address postal_code (:obj:`str`): Address postal code Returns: Address Raises: :class:`telegram.Error`",
"from ..utils import Object class Address(Object): \"\"\" Describes an address Attributes: ID (:obj:`str`):",
"postal_code (:obj:`str`): Address postal code Returns: Address Raises: :class:`telegram.Error` \"\"\" ID = \"address\"",
"(:obj:`str`): Address postal code Returns: Address Raises: :class:`telegram.Error` \"\"\" ID = \"address\" def",
"street_line2, postal_code, **kwargs): self.country_code = country_code # str self.state = state # str",
"str self.postal_code = postal_code # str @staticmethod def read(q: dict, *args) -> \"Address\":",
"A two-letter ISO 3166-1 alpha-2 country code state (:obj:`str`): State, if applicable city",
"str self.state = state # str self.city = city # str self.street_line1 =",
"= postal_code # str @staticmethod def read(q: dict, *args) -> \"Address\": country_code =",
"self.street_line1 = street_line1 # str self.street_line2 = street_line2 # str self.postal_code = postal_code",
"address postal_code (:obj:`str`): Address postal code Returns: Address Raises: :class:`telegram.Error` \"\"\" ID =",
"country_code, state, city, street_line1, street_line2, postal_code, **kwargs): self.country_code = country_code # str self.state",
"(:obj:`str`): ``Address`` Args: country_code (:obj:`str`): A two-letter ISO 3166-1 alpha-2 country code state",
"country code state (:obj:`str`): State, if applicable city (:obj:`str`): City street_line1 (:obj:`str`): First",
"state # str self.city = city # str self.street_line1 = street_line1 # str",
"= street_line2 # str self.postal_code = postal_code # str @staticmethod def read(q: dict,",
"postal_code, **kwargs): self.country_code = country_code # str self.state = state # str self.city",
"state, city, street_line1, street_line2, postal_code, **kwargs): self.country_code = country_code # str self.state =",
"street_line1 = q.get('street_line1') street_line2 = q.get('street_line2') postal_code = q.get('postal_code') return Address(country_code, state, city,",
"= \"address\" def __init__(self, country_code, state, city, street_line1, street_line2, postal_code, **kwargs): self.country_code =",
"import Object class Address(Object): \"\"\" Describes an address Attributes: ID (:obj:`str`): ``Address`` Args:",
"Address(Object): \"\"\" Describes an address Attributes: ID (:obj:`str`): ``Address`` Args: country_code (:obj:`str`): A",
"self.city = city # str self.street_line1 = street_line1 # str self.street_line2 = street_line2",
"street_line2 (:obj:`str`): Second line of the address postal_code (:obj:`str`): Address postal code Returns:",
"Describes an address Attributes: ID (:obj:`str`): ``Address`` Args: country_code (:obj:`str`): A two-letter ISO",
"def read(q: dict, *args) -> \"Address\": country_code = q.get('country_code') state = q.get('state') city",
"str self.street_line1 = street_line1 # str self.street_line2 = street_line2 # str self.postal_code =",
"(:obj:`str`): City street_line1 (:obj:`str`): First line of the address street_line2 (:obj:`str`): Second line",
"Address Raises: :class:`telegram.Error` \"\"\" ID = \"address\" def __init__(self, country_code, state, city, street_line1,",
"# str self.city = city # str self.street_line1 = street_line1 # str self.street_line2",
"street_line2 = q.get('street_line2') postal_code = q.get('postal_code') return Address(country_code, state, city, street_line1, street_line2, postal_code)",
"q.get('state') city = q.get('city') street_line1 = q.get('street_line1') street_line2 = q.get('street_line2') postal_code = q.get('postal_code')",
"an address Attributes: ID (:obj:`str`): ``Address`` Args: country_code (:obj:`str`): A two-letter ISO 3166-1",
"the address street_line2 (:obj:`str`): Second line of the address postal_code (:obj:`str`): Address postal",
"City street_line1 (:obj:`str`): First line of the address street_line2 (:obj:`str`): Second line of",
"city # str self.street_line1 = street_line1 # str self.street_line2 = street_line2 # str",
"of the address postal_code (:obj:`str`): Address postal code Returns: Address Raises: :class:`telegram.Error` \"\"\"",
"city, street_line1, street_line2, postal_code, **kwargs): self.country_code = country_code # str self.state = state",
"of the address street_line2 (:obj:`str`): Second line of the address postal_code (:obj:`str`): Address",
"applicable city (:obj:`str`): City street_line1 (:obj:`str`): First line of the address street_line2 (:obj:`str`):",
"if applicable city (:obj:`str`): City street_line1 (:obj:`str`): First line of the address street_line2",
"= city # str self.street_line1 = street_line1 # str self.street_line2 = street_line2 #",
"``Address`` Args: country_code (:obj:`str`): A two-letter ISO 3166-1 alpha-2 country code state (:obj:`str`):",
"two-letter ISO 3166-1 alpha-2 country code state (:obj:`str`): State, if applicable city (:obj:`str`):",
"**kwargs): self.country_code = country_code # str self.state = state # str self.city =",
"(:obj:`str`): Second line of the address postal_code (:obj:`str`): Address postal code Returns: Address",
"# str self.state = state # str self.city = city # str self.street_line1",
"Attributes: ID (:obj:`str`): ``Address`` Args: country_code (:obj:`str`): A two-letter ISO 3166-1 alpha-2 country",
"(:obj:`str`): First line of the address street_line2 (:obj:`str`): Second line of the address",
"code state (:obj:`str`): State, if applicable city (:obj:`str`): City street_line1 (:obj:`str`): First line",
"(:obj:`str`): A two-letter ISO 3166-1 alpha-2 country code state (:obj:`str`): State, if applicable",
"str self.city = city # str self.street_line1 = street_line1 # str self.street_line2 =",
"city (:obj:`str`): City street_line1 (:obj:`str`): First line of the address street_line2 (:obj:`str`): Second",
"Returns: Address Raises: :class:`telegram.Error` \"\"\" ID = \"address\" def __init__(self, country_code, state, city,",
"city = q.get('city') street_line1 = q.get('street_line1') street_line2 = q.get('street_line2') postal_code = q.get('postal_code') return",
"ID (:obj:`str`): ``Address`` Args: country_code (:obj:`str`): A two-letter ISO 3166-1 alpha-2 country code",
"= q.get('country_code') state = q.get('state') city = q.get('city') street_line1 = q.get('street_line1') street_line2 =",
"Second line of the address postal_code (:obj:`str`): Address postal code Returns: Address Raises:",
"3166-1 alpha-2 country code state (:obj:`str`): State, if applicable city (:obj:`str`): City street_line1",
"the address postal_code (:obj:`str`): Address postal code Returns: Address Raises: :class:`telegram.Error` \"\"\" ID",
"Raises: :class:`telegram.Error` \"\"\" ID = \"address\" def __init__(self, country_code, state, city, street_line1, street_line2,",
"country_code = q.get('country_code') state = q.get('state') city = q.get('city') street_line1 = q.get('street_line1') street_line2",
"\"address\" def __init__(self, country_code, state, city, street_line1, street_line2, postal_code, **kwargs): self.country_code = country_code",
"country_code # str self.state = state # str self.city = city # str",
"\"\"\" ID = \"address\" def __init__(self, country_code, state, city, street_line1, street_line2, postal_code, **kwargs):",
"= q.get('street_line1') street_line2 = q.get('street_line2') postal_code = q.get('postal_code') return Address(country_code, state, city, street_line1,",
"class Address(Object): \"\"\" Describes an address Attributes: ID (:obj:`str`): ``Address`` Args: country_code (:obj:`str`):",
"(:obj:`str`): State, if applicable city (:obj:`str`): City street_line1 (:obj:`str`): First line of the",
"self.country_code = country_code # str self.state = state # str self.city = city",
"..utils import Object class Address(Object): \"\"\" Describes an address Attributes: ID (:obj:`str`): ``Address``",
"@staticmethod def read(q: dict, *args) -> \"Address\": country_code = q.get('country_code') state = q.get('state')",
"= street_line1 # str self.street_line2 = street_line2 # str self.postal_code = postal_code #",
"code Returns: Address Raises: :class:`telegram.Error` \"\"\" ID = \"address\" def __init__(self, country_code, state,",
"q.get('street_line1') street_line2 = q.get('street_line2') postal_code = q.get('postal_code') return Address(country_code, state, city, street_line1, street_line2,",
"street_line2 # str self.postal_code = postal_code # str @staticmethod def read(q: dict, *args)",
"*args) -> \"Address\": country_code = q.get('country_code') state = q.get('state') city = q.get('city') street_line1",
"First line of the address street_line2 (:obj:`str`): Second line of the address postal_code",
"# str self.street_line2 = street_line2 # str self.postal_code = postal_code # str @staticmethod",
"q.get('country_code') state = q.get('state') city = q.get('city') street_line1 = q.get('street_line1') street_line2 = q.get('street_line2')",
"state (:obj:`str`): State, if applicable city (:obj:`str`): City street_line1 (:obj:`str`): First line of",
"# str @staticmethod def read(q: dict, *args) -> \"Address\": country_code = q.get('country_code') state"
] |
[
"range(n): s = input().strip() letters = set() cost = 0 for ch in",
"set() cost = 0 for ch in s: if not ch in letters:",
"0 for ch in s: if not ch in letters: letters.add(ch) cost +=",
"s = input().strip() letters = set() cost = 0 for ch in s:",
"for a0 in range(n): s = input().strip() letters = set() cost = 0",
"= input().strip() letters = set() cost = 0 for ch in s: if",
"in range(n): s = input().strip() letters = set() cost = 0 for ch",
"ch in s: if not ch in letters: letters.add(ch) cost += 1 print(cost)",
"letters = set() cost = 0 for ch in s: if not ch",
"cost = 0 for ch in s: if not ch in letters: letters.add(ch)",
"import sys n = int(input().strip()) for a0 in range(n): s = input().strip() letters",
"for ch in s: if not ch in letters: letters.add(ch) cost += 1",
"n = int(input().strip()) for a0 in range(n): s = input().strip() letters = set()",
"sys n = int(input().strip()) for a0 in range(n): s = input().strip() letters =",
"= set() cost = 0 for ch in s: if not ch in",
"a0 in range(n): s = input().strip() letters = set() cost = 0 for",
"int(input().strip()) for a0 in range(n): s = input().strip() letters = set() cost =",
"input().strip() letters = set() cost = 0 for ch in s: if not",
"= 0 for ch in s: if not ch in letters: letters.add(ch) cost",
"= int(input().strip()) for a0 in range(n): s = input().strip() letters = set() cost",
"#!/bin/python3 import sys n = int(input().strip()) for a0 in range(n): s = input().strip()"
] |
[
"coding:utf-8 -*- # @author xupingmao # @since 2022/01/26 16:35:51 # @modified 2022/01/26 16:36:46",
"xupingmao # @since 2022/01/26 16:35:51 # @modified 2022/01/26 16:36:46 # @filename pyx_fib2.py import",
"# -*- coding:utf-8 -*- # @author xupingmao # @since 2022/01/26 16:35:51 # @modified",
"-*- # @author xupingmao # @since 2022/01/26 16:35:51 # @modified 2022/01/26 16:36:46 #",
"2022/01/26 16:35:51 # @modified 2022/01/26 16:36:46 # @filename pyx_fib2.py import pyximport pyximport.install() import",
"-*- coding:utf-8 -*- # @author xupingmao # @since 2022/01/26 16:35:51 # @modified 2022/01/26",
"@author xupingmao # @since 2022/01/26 16:35:51 # @modified 2022/01/26 16:36:46 # @filename pyx_fib2.py",
"@since 2022/01/26 16:35:51 # @modified 2022/01/26 16:36:46 # @filename pyx_fib2.py import pyximport pyximport.install()",
"16:35:51 # @modified 2022/01/26 16:36:46 # @filename pyx_fib2.py import pyximport pyximport.install() import fib2",
"# @since 2022/01/26 16:35:51 # @modified 2022/01/26 16:36:46 # @filename pyx_fib2.py import pyximport",
"<filename>src/010_fib/pyx_fib2.py # -*- coding:utf-8 -*- # @author xupingmao # @since 2022/01/26 16:35:51 #",
"# @modified 2022/01/26 16:36:46 # @filename pyx_fib2.py import pyximport pyximport.install() import fib2 fib2.run()",
"# @author xupingmao # @since 2022/01/26 16:35:51 # @modified 2022/01/26 16:36:46 # @filename"
] |
[
"None else sys.stdout query_term = args.query logging.info(\"INPUT DIR: %r\" % i_dir) logging.info(\"OUT FILE:",
"USC Information Sciences Institute # Author: <NAME> <<EMAIL>> # URL: <http://nlg.isi.edu/> # For",
"= pickle.dumps str_to_obj = pickle.loads index = SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str, str_to_obj) index.load_all() results",
"parser.add_argument(\"-i\", \"--index\", default=\"lfindex\", help=\"LF sentences index directory\", type=str) parser.add_argument(\"-o\", \"--output\", default=None, type=str) parser.add_argument(\"-q\",",
"\"--output\", default=None, type=str) parser.add_argument(\"-q\", \"--query\", default=None, type=str) args = parser.parse_args() i_dir = args.inputdir",
"\"w\") if args.output is not None else sys.stdout query_term = args.query logging.info(\"INPUT DIR:",
"query_term) obj_to_terms = sent_to_terms obj_to_str = pickle.dumps str_to_obj = pickle.loads index = SimpleObjectIndex(i_dir,",
"pickle.loads index = SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str, str_to_obj) index.load_all() results = index.find(query_terms=(query_term,)) o_file.write(\"FOUND (%d):\\n\"",
"import sent_to_terms if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\", default=\"lfindex\",",
"is not None else sys.stdout query_term = args.query logging.info(\"INPUT DIR: %r\" % i_dir)",
"coding: utf-8 # Copyright (C) USC Information Sciences Institute # Author: <NAME> <<EMAIL>>",
"%r\" % o_file) logging.info(\"QUERY: %s\" % query_term) obj_to_terms = sent_to_terms obj_to_str = pickle.dumps",
"# URL: <http://nlg.isi.edu/> # For more information, see README.md # For license information,",
"str_to_obj = pickle.loads index = SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str, str_to_obj) index.load_all() results = index.find(query_terms=(query_term,))",
"= args.inputdir o_file = open(args.output, \"w\") if args.output is not None else sys.stdout",
"parser = argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\", default=\"lfindex\", help=\"LF sentences index directory\", type=str) parser.add_argument(\"-o\", \"--output\",",
"% query_term) obj_to_terms = sent_to_terms obj_to_str = pickle.dumps str_to_obj = pickle.loads index =",
"more information, see README.md # For license information, see LICENSE import sys import",
"utf-8 # Copyright (C) USC Information Sciences Institute # Author: <NAME> <<EMAIL>> #",
"import cPickle as pickle from mokujin.index import SimpleObjectIndex from createlfindex import sent_to_terms if",
"obj_to_terms = sent_to_terms obj_to_str = pickle.dumps str_to_obj = pickle.loads index = SimpleObjectIndex(i_dir, obj_to_terms,",
"README.md # For license information, see LICENSE import sys import logging import argparse",
"sent_to_terms if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\", default=\"lfindex\", help=\"LF",
"# For more information, see README.md # For license information, see LICENSE import",
"#!/usr/bin/env python # coding: utf-8 # Copyright (C) USC Information Sciences Institute #",
"default=None, type=str) args = parser.parse_args() i_dir = args.inputdir o_file = open(args.output, \"w\") if",
"Author: <NAME> <<EMAIL>> # URL: <http://nlg.isi.edu/> # For more information, see README.md #",
"import SimpleObjectIndex from createlfindex import sent_to_terms if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) parser =",
"__name__ == \"__main__\": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\", default=\"lfindex\", help=\"LF sentences index",
"results = index.find(query_terms=(query_term,)) o_file.write(\"FOUND (%d):\\n\" % len(results)) for sent in results: o_file.write(sent.raw_text.encode(\"utf-8\")) o_file.write(\"\\n\")",
"<NAME> <<EMAIL>> # URL: <http://nlg.isi.edu/> # For more information, see README.md # For",
"\"--query\", default=None, type=str) args = parser.parse_args() i_dir = args.inputdir o_file = open(args.output, \"w\")",
"help=\"LF sentences index directory\", type=str) parser.add_argument(\"-o\", \"--output\", default=None, type=str) parser.add_argument(\"-q\", \"--query\", default=None, type=str)",
"SimpleObjectIndex from createlfindex import sent_to_terms if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser()",
"parser.add_argument(\"-q\", \"--query\", default=None, type=str) args = parser.parse_args() i_dir = args.inputdir o_file = open(args.output,",
"Sciences Institute # Author: <NAME> <<EMAIL>> # URL: <http://nlg.isi.edu/> # For more information,",
"= sent_to_terms obj_to_str = pickle.dumps str_to_obj = pickle.loads index = SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str,",
"% o_file) logging.info(\"QUERY: %s\" % query_term) obj_to_terms = sent_to_terms obj_to_str = pickle.dumps str_to_obj",
"not None else sys.stdout query_term = args.query logging.info(\"INPUT DIR: %r\" % i_dir) logging.info(\"OUT",
"index = SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str, str_to_obj) index.load_all() results = index.find(query_terms=(query_term,)) o_file.write(\"FOUND (%d):\\n\" %",
"obj_to_str = pickle.dumps str_to_obj = pickle.loads index = SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str, str_to_obj) index.load_all()",
"URL: <http://nlg.isi.edu/> # For more information, see README.md # For license information, see",
"import sys import logging import argparse import cPickle as pickle from mokujin.index import",
"== \"__main__\": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\", default=\"lfindex\", help=\"LF sentences index directory\",",
"logging.info(\"INPUT DIR: %r\" % i_dir) logging.info(\"OUT FILE: %r\" % o_file) logging.info(\"QUERY: %s\" %",
"index.load_all() results = index.find(query_terms=(query_term,)) o_file.write(\"FOUND (%d):\\n\" % len(results)) for sent in results: o_file.write(sent.raw_text.encode(\"utf-8\"))",
"<http://nlg.isi.edu/> # For more information, see README.md # For license information, see LICENSE",
"mokujin.index import SimpleObjectIndex from createlfindex import sent_to_terms if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) parser",
"args.inputdir o_file = open(args.output, \"w\") if args.output is not None else sys.stdout query_term",
"sys import logging import argparse import cPickle as pickle from mokujin.index import SimpleObjectIndex",
"from createlfindex import sent_to_terms if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument(\"-i\",",
"i_dir) logging.info(\"OUT FILE: %r\" % o_file) logging.info(\"QUERY: %s\" % query_term) obj_to_terms = sent_to_terms",
"<<EMAIL>> # URL: <http://nlg.isi.edu/> # For more information, see README.md # For license",
"logging.info(\"QUERY: %s\" % query_term) obj_to_terms = sent_to_terms obj_to_str = pickle.dumps str_to_obj = pickle.loads",
"if args.output is not None else sys.stdout query_term = args.query logging.info(\"INPUT DIR: %r\"",
"str_to_obj) index.load_all() results = index.find(query_terms=(query_term,)) o_file.write(\"FOUND (%d):\\n\" % len(results)) for sent in results:",
"# Author: <NAME> <<EMAIL>> # URL: <http://nlg.isi.edu/> # For more information, see README.md",
"directory\", type=str) parser.add_argument(\"-o\", \"--output\", default=None, type=str) parser.add_argument(\"-q\", \"--query\", default=None, type=str) args = parser.parse_args()",
"type=str) parser.add_argument(\"-q\", \"--query\", default=None, type=str) args = parser.parse_args() i_dir = args.inputdir o_file =",
"# For license information, see LICENSE import sys import logging import argparse import",
"Copyright (C) USC Information Sciences Institute # Author: <NAME> <<EMAIL>> # URL: <http://nlg.isi.edu/>",
"logging import argparse import cPickle as pickle from mokujin.index import SimpleObjectIndex from createlfindex",
"= argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\", default=\"lfindex\", help=\"LF sentences index directory\", type=str) parser.add_argument(\"-o\", \"--output\", default=None,",
"<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # Copyright (C) USC Information Sciences Institute",
"logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\", default=\"lfindex\", help=\"LF sentences index directory\", type=str) parser.add_argument(\"-o\",",
"args.query logging.info(\"INPUT DIR: %r\" % i_dir) logging.info(\"OUT FILE: %r\" % o_file) logging.info(\"QUERY: %s\"",
"= SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str, str_to_obj) index.load_all() results = index.find(query_terms=(query_term,)) o_file.write(\"FOUND (%d):\\n\" % len(results))",
"argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\", default=\"lfindex\", help=\"LF sentences index directory\", type=str) parser.add_argument(\"-o\", \"--output\", default=None, type=str)",
"i_dir = args.inputdir o_file = open(args.output, \"w\") if args.output is not None else",
"args = parser.parse_args() i_dir = args.inputdir o_file = open(args.output, \"w\") if args.output is",
"o_file) logging.info(\"QUERY: %s\" % query_term) obj_to_terms = sent_to_terms obj_to_str = pickle.dumps str_to_obj =",
"if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\", default=\"lfindex\", help=\"LF sentences",
"\"__main__\": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\", default=\"lfindex\", help=\"LF sentences index directory\", type=str)",
"Information Sciences Institute # Author: <NAME> <<EMAIL>> # URL: <http://nlg.isi.edu/> # For more",
"= pickle.loads index = SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str, str_to_obj) index.load_all() results = index.find(query_terms=(query_term,)) o_file.write(\"FOUND",
"LICENSE import sys import logging import argparse import cPickle as pickle from mokujin.index",
"DIR: %r\" % i_dir) logging.info(\"OUT FILE: %r\" % o_file) logging.info(\"QUERY: %s\" % query_term)",
"license information, see LICENSE import sys import logging import argparse import cPickle as",
"(C) USC Information Sciences Institute # Author: <NAME> <<EMAIL>> # URL: <http://nlg.isi.edu/> #",
"Institute # Author: <NAME> <<EMAIL>> # URL: <http://nlg.isi.edu/> # For more information, see",
"information, see README.md # For license information, see LICENSE import sys import logging",
"default=\"lfindex\", help=\"LF sentences index directory\", type=str) parser.add_argument(\"-o\", \"--output\", default=None, type=str) parser.add_argument(\"-q\", \"--query\", default=None,",
"from mokujin.index import SimpleObjectIndex from createlfindex import sent_to_terms if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO)",
"index directory\", type=str) parser.add_argument(\"-o\", \"--output\", default=None, type=str) parser.add_argument(\"-q\", \"--query\", default=None, type=str) args =",
"query_term = args.query logging.info(\"INPUT DIR: %r\" % i_dir) logging.info(\"OUT FILE: %r\" % o_file)",
"obj_to_str, str_to_obj) index.load_all() results = index.find(query_terms=(query_term,)) o_file.write(\"FOUND (%d):\\n\" % len(results)) for sent in",
"import logging import argparse import cPickle as pickle from mokujin.index import SimpleObjectIndex from",
"import argparse import cPickle as pickle from mokujin.index import SimpleObjectIndex from createlfindex import",
"open(args.output, \"w\") if args.output is not None else sys.stdout query_term = args.query logging.info(\"INPUT",
"default=None, type=str) parser.add_argument(\"-q\", \"--query\", default=None, type=str) args = parser.parse_args() i_dir = args.inputdir o_file",
"args.output is not None else sys.stdout query_term = args.query logging.info(\"INPUT DIR: %r\" %",
"as pickle from mokujin.index import SimpleObjectIndex from createlfindex import sent_to_terms if __name__ ==",
"parser.add_argument(\"-o\", \"--output\", default=None, type=str) parser.add_argument(\"-q\", \"--query\", default=None, type=str) args = parser.parse_args() i_dir =",
"For license information, see LICENSE import sys import logging import argparse import cPickle",
"type=str) args = parser.parse_args() i_dir = args.inputdir o_file = open(args.output, \"w\") if args.output",
"argparse import cPickle as pickle from mokujin.index import SimpleObjectIndex from createlfindex import sent_to_terms",
"else sys.stdout query_term = args.query logging.info(\"INPUT DIR: %r\" % i_dir) logging.info(\"OUT FILE: %r\"",
"sentences index directory\", type=str) parser.add_argument(\"-o\", \"--output\", default=None, type=str) parser.add_argument(\"-q\", \"--query\", default=None, type=str) args",
"# Copyright (C) USC Information Sciences Institute # Author: <NAME> <<EMAIL>> # URL:",
"= open(args.output, \"w\") if args.output is not None else sys.stdout query_term = args.query",
"python # coding: utf-8 # Copyright (C) USC Information Sciences Institute # Author:",
"pickle.dumps str_to_obj = pickle.loads index = SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str, str_to_obj) index.load_all() results =",
"% i_dir) logging.info(\"OUT FILE: %r\" % o_file) logging.info(\"QUERY: %s\" % query_term) obj_to_terms =",
"# coding: utf-8 # Copyright (C) USC Information Sciences Institute # Author: <NAME>",
"obj_to_terms, obj_to_str, str_to_obj) index.load_all() results = index.find(query_terms=(query_term,)) o_file.write(\"FOUND (%d):\\n\" % len(results)) for sent",
"cPickle as pickle from mokujin.index import SimpleObjectIndex from createlfindex import sent_to_terms if __name__",
"For more information, see README.md # For license information, see LICENSE import sys",
"pickle from mokujin.index import SimpleObjectIndex from createlfindex import sent_to_terms if __name__ == \"__main__\":",
"o_file = open(args.output, \"w\") if args.output is not None else sys.stdout query_term =",
"%s\" % query_term) obj_to_terms = sent_to_terms obj_to_str = pickle.dumps str_to_obj = pickle.loads index",
"= parser.parse_args() i_dir = args.inputdir o_file = open(args.output, \"w\") if args.output is not",
"logging.info(\"OUT FILE: %r\" % o_file) logging.info(\"QUERY: %s\" % query_term) obj_to_terms = sent_to_terms obj_to_str",
"information, see LICENSE import sys import logging import argparse import cPickle as pickle",
"= args.query logging.info(\"INPUT DIR: %r\" % i_dir) logging.info(\"OUT FILE: %r\" % o_file) logging.info(\"QUERY:",
"\"--index\", default=\"lfindex\", help=\"LF sentences index directory\", type=str) parser.add_argument(\"-o\", \"--output\", default=None, type=str) parser.add_argument(\"-q\", \"--query\",",
"createlfindex import sent_to_terms if __name__ == \"__main__\": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument(\"-i\", \"--index\",",
"see README.md # For license information, see LICENSE import sys import logging import",
"SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str, str_to_obj) index.load_all() results = index.find(query_terms=(query_term,)) o_file.write(\"FOUND (%d):\\n\" % len(results)) for",
"see LICENSE import sys import logging import argparse import cPickle as pickle from",
"%r\" % i_dir) logging.info(\"OUT FILE: %r\" % o_file) logging.info(\"QUERY: %s\" % query_term) obj_to_terms",
"sent_to_terms obj_to_str = pickle.dumps str_to_obj = pickle.loads index = SimpleObjectIndex(i_dir, obj_to_terms, obj_to_str, str_to_obj)",
"FILE: %r\" % o_file) logging.info(\"QUERY: %s\" % query_term) obj_to_terms = sent_to_terms obj_to_str =",
"parser.parse_args() i_dir = args.inputdir o_file = open(args.output, \"w\") if args.output is not None",
"sys.stdout query_term = args.query logging.info(\"INPUT DIR: %r\" % i_dir) logging.info(\"OUT FILE: %r\" %",
"type=str) parser.add_argument(\"-o\", \"--output\", default=None, type=str) parser.add_argument(\"-q\", \"--query\", default=None, type=str) args = parser.parse_args() i_dir"
] |
[
"success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView): model = InovacaoAberta success_url = reverse_lazy('desafioInovacao') # Ação",
"class InovacaoAbertaCreate(CreateView): model = InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView):",
"InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView): model = InovacaoAberta fields",
"from .models import InovacaoAberta # Desafios de Inovação class DesafioInovacao(generic.ListView): model = DesafioInovacao",
"InovacaoAberta context_object_name = 'inovacaoAberta_list' template_name = 'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView): model = InovacaoAberta class",
"InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaDelete(DeleteView): model = InovacaoAberta success_url",
"= '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView): model = DesafioInovacao fields = '__all__'",
"= '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView): model = InovacaoAberta success_url = reverse_lazy('desafioInovacao')",
"fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView): model = DesafioInovacao fields =",
"= reverse_lazy('desafioInovacao') # Ação de Inovação Aberta class InovacaoAberta(generic.ListView): model = InovacaoAberta context_object_name",
"= reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView): model = InovacaoAberta success_url = reverse_lazy('desafioInovacao') # Ação de",
"= 'inovacaoAberta_list' template_name = 'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView): model = InovacaoAberta class InovacaoAbertaCreate(CreateView): model",
"InovacaoAbertaUpdate(UpdateView): model = InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaDelete(DeleteView): model",
"CreateView, UpdateView, DeleteView from .models import DesafioInovacao from .models import InovacaoAberta # Desafios",
"model = DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView): model =",
"generic from django.urls import reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models",
"import InovacaoAberta # Desafios de Inovação class DesafioInovacao(generic.ListView): model = DesafioInovacao context_object_name =",
"model = InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView): model =",
"model = DesafioInovacao context_object_name = 'desafioInovacao_list' template_name = 'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView): model =",
"DesafioInovacao context_object_name = 'desafioInovacao_list' template_name = 'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView): model = DesafioInovacao class",
"import DesafioInovacao from .models import InovacaoAberta # Desafios de Inovação class DesafioInovacao(generic.ListView): model",
"class DesafioInovacaoDetailView(generic.DetailView): model = DesafioInovacao class DesafioInovacaoCreate(CreateView): model = DesafioInovacao fields = '__all__'",
"DesafioInovacaoDetailView(generic.DetailView): model = DesafioInovacao class DesafioInovacaoCreate(CreateView): model = DesafioInovacao fields = '__all__' success_url",
"# Ação de Inovação Aberta class InovacaoAberta(generic.ListView): model = InovacaoAberta context_object_name = 'inovacaoAberta_list'",
"success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView): model = DesafioInovacao fields = '__all__' success_url =",
"DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView): model = DesafioInovacao fields",
"'__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView): model = InovacaoAberta fields = '__all__' success_url",
"= reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView): model = InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta')",
"DeleteView from .models import DesafioInovacao from .models import InovacaoAberta # Desafios de Inovação",
"'inovacaoAberta_list' template_name = 'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView): model = InovacaoAberta class InovacaoAbertaCreate(CreateView): model =",
"context_object_name = 'desafioInovacao_list' template_name = 'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView): model = DesafioInovacao class DesafioInovacaoCreate(CreateView):",
"DesafioInovacao(generic.ListView): model = DesafioInovacao context_object_name = 'desafioInovacao_list' template_name = 'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView): model",
"reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView): model = InovacaoAberta success_url = reverse_lazy('desafioInovacao') # Ação de Inovação",
"= 'desafioInovacao_list' template_name = 'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView): model = DesafioInovacao class DesafioInovacaoCreate(CreateView): model",
"success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView): model = InovacaoAberta fields = '__all__' success_url =",
"template_name = 'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView): model = InovacaoAberta class InovacaoAbertaCreate(CreateView): model = InovacaoAberta",
"de Inovação Aberta class InovacaoAberta(generic.ListView): model = InovacaoAberta context_object_name = 'inovacaoAberta_list' template_name =",
"DesafioInovacaoUpdate(UpdateView): model = DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView): model",
"model = InovacaoAberta success_url = reverse_lazy('desafioInovacao') # Ação de Inovação Aberta class InovacaoAberta(generic.ListView):",
"class InovacaoAberta(generic.ListView): model = InovacaoAberta context_object_name = 'inovacaoAberta_list' template_name = 'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView):",
"InovacaoAbertaCreate(CreateView): model = InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView): model",
"= DesafioInovacao class DesafioInovacaoCreate(CreateView): model = DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao')",
"template_name = 'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView): model = DesafioInovacao class DesafioInovacaoCreate(CreateView): model = DesafioInovacao",
".models import InovacaoAberta # Desafios de Inovação class DesafioInovacao(generic.ListView): model = DesafioInovacao context_object_name",
"InovacaoAbertaDetailView(generic.DetailView): model = InovacaoAberta class InovacaoAbertaCreate(CreateView): model = InovacaoAberta fields = '__all__' success_url",
"DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView): model = InovacaoAberta success_url",
"model = InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaDelete(DeleteView): model =",
"= DesafioInovacao context_object_name = 'desafioInovacao_list' template_name = 'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView): model = DesafioInovacao",
"fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaDelete(DeleteView): model = InovacaoAberta success_url =",
"'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView): model = DesafioInovacao class DesafioInovacaoCreate(CreateView): model = DesafioInovacao fields =",
"= InovacaoAberta class InovacaoAbertaCreate(CreateView): model = InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta')",
"fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView): model = InovacaoAberta success_url =",
"DesafioInovacao from .models import InovacaoAberta # Desafios de Inovação class DesafioInovacao(generic.ListView): model =",
"'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView): model = InovacaoAberta class InovacaoAbertaCreate(CreateView): model = InovacaoAberta fields =",
".models import DesafioInovacao from .models import InovacaoAberta # Desafios de Inovação class DesafioInovacao(generic.ListView):",
"'__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView): model = DesafioInovacao fields = '__all__' success_url",
"UpdateView, DeleteView from .models import DesafioInovacao from .models import InovacaoAberta # Desafios de",
"reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView): model = DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class",
"InovacaoAberta(generic.ListView): model = InovacaoAberta context_object_name = 'inovacaoAberta_list' template_name = 'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView): model",
"Ação de Inovação Aberta class InovacaoAberta(generic.ListView): model = InovacaoAberta context_object_name = 'inovacaoAberta_list' template_name",
"= InovacaoAberta success_url = reverse_lazy('desafioInovacao') # Ação de Inovação Aberta class InovacaoAberta(generic.ListView): model",
"class DesafioInovacaoCreate(CreateView): model = DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView):",
"import reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import DesafioInovacao from",
"= 'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView): model = InovacaoAberta class InovacaoAbertaCreate(CreateView): model = InovacaoAberta fields",
"import render from django.views import generic from django.urls import reverse_lazy from django.views.generic.edit import",
"success_url = reverse_lazy('desafioInovacao') # Ação de Inovação Aberta class InovacaoAberta(generic.ListView): model = InovacaoAberta",
"class InovacaoAbertaUpdate(UpdateView): model = InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaDelete(DeleteView):",
"from django.urls import reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import",
"InovacaoAberta class InovacaoAbertaCreate(CreateView): model = InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class",
"DesafioInovacaoDelete(DeleteView): model = InovacaoAberta success_url = reverse_lazy('desafioInovacao') # Ação de Inovação Aberta class",
"= InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView): model = InovacaoAberta",
"= reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView): model = DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao')",
"'__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView): model = InovacaoAberta success_url = reverse_lazy('desafioInovacao') #",
"django.views import generic from django.urls import reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView",
"= InovacaoAberta context_object_name = 'inovacaoAberta_list' template_name = 'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView): model = InovacaoAberta",
"= DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView): model = DesafioInovacao",
"django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import DesafioInovacao from .models import InovacaoAberta",
"reverse_lazy('desafioInovacao') # Ação de Inovação Aberta class InovacaoAberta(generic.ListView): model = InovacaoAberta context_object_name =",
"class DesafioInovacaoUpdate(UpdateView): model = DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView):",
"Inovação Aberta class InovacaoAberta(generic.ListView): model = InovacaoAberta context_object_name = 'inovacaoAberta_list' template_name = 'prospeccao/inovacaoAberta_list.html'",
"model = DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView): model =",
"model = InovacaoAberta context_object_name = 'inovacaoAberta_list' template_name = 'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView): model =",
"render from django.views import generic from django.urls import reverse_lazy from django.views.generic.edit import CreateView,",
"django.urls import reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import DesafioInovacao",
"model = InovacaoAberta class InovacaoAbertaCreate(CreateView): model = InovacaoAberta fields = '__all__' success_url =",
"from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import DesafioInovacao from .models import",
"import generic from django.urls import reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView from",
"= InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaDelete(DeleteView): model = InovacaoAberta",
"= '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView): model = InovacaoAberta fields = '__all__'",
"from django.views import generic from django.urls import reverse_lazy from django.views.generic.edit import CreateView, UpdateView,",
"reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import DesafioInovacao from .models",
"Desafios de Inovação class DesafioInovacao(generic.ListView): model = DesafioInovacao context_object_name = 'desafioInovacao_list' template_name =",
"de Inovação class DesafioInovacao(generic.ListView): model = DesafioInovacao context_object_name = 'desafioInovacao_list' template_name = 'prospeccao/desafioInovacao_list.html'",
"# Desafios de Inovação class DesafioInovacao(generic.ListView): model = DesafioInovacao context_object_name = 'desafioInovacao_list' template_name",
"from .models import DesafioInovacao from .models import InovacaoAberta # Desafios de Inovação class",
"reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView): model = InovacaoAberta fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class",
"= DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoDelete(DeleteView): model = InovacaoAberta",
"= 'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView): model = DesafioInovacao class DesafioInovacaoCreate(CreateView): model = DesafioInovacao fields",
"model = DesafioInovacao class DesafioInovacaoCreate(CreateView): model = DesafioInovacao fields = '__all__' success_url =",
"class DesafioInovacaoDelete(DeleteView): model = InovacaoAberta success_url = reverse_lazy('desafioInovacao') # Ação de Inovação Aberta",
"class InovacaoAbertaDetailView(generic.DetailView): model = InovacaoAberta class InovacaoAbertaCreate(CreateView): model = InovacaoAberta fields = '__all__'",
"fields = '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaUpdate(UpdateView): model = InovacaoAberta fields =",
"Inovação class DesafioInovacao(generic.ListView): model = DesafioInovacao context_object_name = 'desafioInovacao_list' template_name = 'prospeccao/desafioInovacao_list.html' class",
"from django.shortcuts import render from django.views import generic from django.urls import reverse_lazy from",
"context_object_name = 'inovacaoAberta_list' template_name = 'prospeccao/inovacaoAberta_list.html' class InovacaoAbertaDetailView(generic.DetailView): model = InovacaoAberta class InovacaoAbertaCreate(CreateView):",
"DesafioInovacao class DesafioInovacaoCreate(CreateView): model = DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class",
"= '__all__' success_url = reverse_lazy('inovacaoAberta') class InovacaoAbertaDelete(DeleteView): model = InovacaoAberta success_url = reverse_lazy('inovacaoAberta')",
"django.shortcuts import render from django.views import generic from django.urls import reverse_lazy from django.views.generic.edit",
"import CreateView, UpdateView, DeleteView from .models import DesafioInovacao from .models import InovacaoAberta #",
"'desafioInovacao_list' template_name = 'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView): model = DesafioInovacao class DesafioInovacaoCreate(CreateView): model =",
"DesafioInovacaoCreate(CreateView): model = DesafioInovacao fields = '__all__' success_url = reverse_lazy('desafioInovacao') class DesafioInovacaoUpdate(UpdateView): model",
"class DesafioInovacao(generic.ListView): model = DesafioInovacao context_object_name = 'desafioInovacao_list' template_name = 'prospeccao/desafioInovacao_list.html' class DesafioInovacaoDetailView(generic.DetailView):",
"Aberta class InovacaoAberta(generic.ListView): model = InovacaoAberta context_object_name = 'inovacaoAberta_list' template_name = 'prospeccao/inovacaoAberta_list.html' class",
"InovacaoAberta # Desafios de Inovação class DesafioInovacao(generic.ListView): model = DesafioInovacao context_object_name = 'desafioInovacao_list'",
"InovacaoAberta success_url = reverse_lazy('desafioInovacao') # Ação de Inovação Aberta class InovacaoAberta(generic.ListView): model ="
] |
[
"[0, 0, 0, 1, 0], [1, 0, 1, 0, 1]] Output: 1 Explanation:",
"= [[1, 1, 1], [1, 1, 1], [1, 1, 1]] Output: 9 Explanation:",
"grid = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] Output: 9",
"0 or 1, find the number of corner rectangles. A corner rectangle is",
"are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.",
"number of rows and columns of grid will each be in the range",
"0], [1, 0, 1, 0, 1]] Output: 1 Explanation: There is only one",
"the value 1. Also, all four 1s used must be distinct. Example 1:",
"Example 2: Input: grid = [[1, 1, 1], [1, 1, 1], [1, 1,",
"grid or not grid[0]: return 0 dp_set = [] res = 0 for",
"Note that only the corners need to have the value 1. Also, all",
"grid: List[List[int]]) -> int: if not grid or not grid[0]: return 0 dp_set",
"= 0 for c in range(w): if grid[i][c] and grid[j][c]: res += count",
"to have the value 1. Also, all four 1s used must be distinct.",
"grid[0]: return 0 dp_set = [] res = 0 for y in range(len(grid)):",
"in range(h -1): for j in range(i+1, h): count = 0 for c",
"Medium Given a grid where each entry is only 0 or 1, find",
"will each be in the range [1, 200]. Each grid[i][j] will be either",
"each be in the range [1, 200]. Each grid[i][j] will be either 0",
"range [1, 200]. Each grid[i][j] will be either 0 or 1. The number",
"distinct. Example 1: Input: grid = [[1, 0, 0, 1, 0], [0, 0,",
"0 h, w = len(grid), len(grid[0]) res = 0 for i in range(h",
"only 0 or 1, find the number of corner rectangles. A corner rectangle",
"-1): for j in range(i+1, h): count = 0 for c in range(w):",
"and one 3x3 rectangle. Example 3: Input: grid = [[1, 1, 1, 1]]",
"range(w): if grid[i][c] and grid[j][c]: res += count count += 1 return res",
"dp_set = [] res = 0 for y in range(len(grid)): dp_set.append(set(idx for idx,val",
"value 1. Also, all four 1s used must be distinct. Example 1: Input:",
"1, 1, 1]] Output: 0 Explanation: Rectangles must have four distinct corners. Note:",
"Rectangles Medium Given a grid where each entry is only 0 or 1,",
"grid where each entry is only 0 or 1, find the number of",
"of corner rectangles. A corner rectangle is 4 distinct 1s on the grid",
"[1, 1, 1], [1, 1, 1]] Output: 9 Explanation: There are four 2x2",
"be at most 6000. \"\"\" class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int:",
"or not grid[0]: return 0 h, w = len(grid), len(grid[0]) res = 0",
"return res class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: if not grid",
"Of Corner Rectangles Medium Given a grid where each entry is only 0",
"or 1. The number of 1s in the grid will be at most",
"that only the corners need to have the value 1. Also, all four",
"rectangle. Note that only the corners need to have the value 1. Also,",
"0 for c in range(w): if grid[i][c] and grid[j][c]: res += count count",
"number of corner rectangles. A corner rectangle is 4 distinct 1s on the",
"the grid that form an axis-aligned rectangle. Note that only the corners need",
"A corner rectangle is 4 distinct 1s on the grid that form an",
"matches >= 2: res += matches * (matches-1) // 2 return res class",
"grid = [[1, 1, 1, 1]] Output: 0 Explanation: Rectangles must have four",
"Note: The number of rows and columns of grid will each be in",
"in range(w): if grid[i][c] and grid[j][c]: res += count count += 1 return",
"0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [1, 0,",
"an axis-aligned rectangle. Note that only the corners need to have the value",
"0 Explanation: Rectangles must have four distinct corners. Note: The number of rows",
"rectangle. Example 3: Input: grid = [[1, 1, 1, 1]] Output: 0 Explanation:",
"Example 1: Input: grid = [[1, 0, 0, 1, 0], [0, 0, 1,",
"& dp_set[prev]) if matches >= 2: res += matches * (matches-1) // 2",
"for i in range(h -1): for j in range(i+1, h): count = 0",
"* (matches-1) // 2 return res class Solution: def countCornerRectangles(self, grid: List[List[int]]) ->",
"0, 1], [0, 0, 0, 1, 0], [1, 0, 1, 0, 1]] Output:",
"in the grid will be at most 6000. \"\"\" class Solution: def countCornerRectangles(self,",
"countCornerRectangles(self, grid: List[List[int]]) -> int: if not grid or not grid[0]: return 0",
"corners. Note: The number of rows and columns of grid will each be",
"columns of grid will each be in the range [1, 200]. Each grid[i][j]",
"enumerate(grid[y]) if val)) for prev in range(y): matches = len(dp_set[y] & dp_set[prev]) if",
"the corners need to have the value 1. Also, all four 1s used",
"res = 0 for y in range(len(grid)): dp_set.append(set(idx for idx,val in enumerate(grid[y]) if",
"Corner Rectangles Medium Given a grid where each entry is only 0 or",
"There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3",
"return 0 h, w = len(grid), len(grid[0]) res = 0 for i in",
"1, find the number of corner rectangles. A corner rectangle is 4 distinct",
"have four distinct corners. Note: The number of rows and columns of grid",
"0 for y in range(len(grid)): dp_set.append(set(idx for idx,val in enumerate(grid[y]) if val)) for",
"in range(len(grid)): dp_set.append(set(idx for idx,val in enumerate(grid[y]) if val)) for prev in range(y):",
"need to have the value 1. Also, all four 1s used must be",
"Also, all four 1s used must be distinct. Example 1: Input: grid =",
"1s on the grid that form an axis-aligned rectangle. Note that only the",
"3x2 rectangles, and one 3x3 rectangle. Example 3: Input: grid = [[1, 1,",
"be distinct. Example 1: Input: grid = [[1, 0, 0, 1, 0], [0,",
"range(len(grid)): dp_set.append(set(idx for idx,val in enumerate(grid[y]) if val)) for prev in range(y): matches",
"res = 0 for i in range(h -1): for j in range(i+1, h):",
"count = 0 for c in range(w): if grid[i][c] and grid[j][c]: res +=",
"either 0 or 1. The number of 1s in the grid will be",
"j in range(i+1, h): count = 0 for c in range(w): if grid[i][c]",
"grid or not grid[0]: return 0 h, w = len(grid), len(grid[0]) res =",
"There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example",
"corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example 2: Input: grid = [[1, 1, 1],",
"Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].",
"List[List[int]]) -> int: if not grid or not grid[0]: return 0 dp_set =",
"grid = [[1, 0, 0, 1, 0], [0, 0, 1, 0, 1], [0,",
"1, 1]] Output: 9 Explanation: There are four 2x2 rectangles, four 2x3 and",
"2 return res class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: if not",
"for j in range(i+1, h): count = 0 for c in range(w): if",
"len(dp_set[y] & dp_set[prev]) if matches >= 2: res += matches * (matches-1) //",
"// 2 return res class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: if",
"Number Of Corner Rectangles Medium Given a grid where each entry is only",
"res += matches * (matches-1) // 2 return res class Solution: def countCornerRectangles(self,",
"0 or 1. The number of 1s in the grid will be at",
"is 4 distinct 1s on the grid that form an axis-aligned rectangle. Note",
"Input: grid = [[1, 0, 0, 1, 0], [0, 0, 1, 0, 1],",
"rectangles, and one 3x3 rectangle. Example 3: Input: grid = [[1, 1, 1,",
"find the number of corner rectangles. A corner rectangle is 4 distinct 1s",
"1. The number of 1s in the grid will be at most 6000.",
"1, 0, 1], [0, 0, 0, 1, 0], [1, 0, 1, 0, 1]]",
"corners need to have the value 1. Also, all four 1s used must",
"and 3x2 rectangles, and one 3x3 rectangle. Example 3: Input: grid = [[1,",
"0, 1, 0], [1, 0, 1, 0, 1]] Output: 1 Explanation: There is",
"[0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [1, 0, 1,",
"0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 0],",
"form an axis-aligned rectangle. Note that only the corners need to have the",
"or not grid[0]: return 0 dp_set = [] res = 0 for y",
"(matches-1) // 2 return res class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int:",
"int: if not grid or not grid[0]: return 0 dp_set = [] res",
"must be distinct. Example 1: Input: grid = [[1, 0, 0, 1, 0],",
"1, 1], [1, 1, 1]] Output: 9 Explanation: There are four 2x2 rectangles,",
"and columns of grid will each be in the range [1, 200]. Each",
"[[1, 1, 1], [1, 1, 1], [1, 1, 1]] Output: 9 Explanation: There",
"1]] Output: 1 Explanation: There is only one corner rectangle, with corners grid[1][2],",
"most 6000. \"\"\" class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: if not",
"y in range(len(grid)): dp_set.append(set(idx for idx,val in enumerate(grid[y]) if val)) for prev in",
"int: if not grid or not grid[0]: return 0 h, w = len(grid),",
"val)) for prev in range(y): matches = len(dp_set[y] & dp_set[prev]) if matches >=",
"= [[1, 0, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0,",
"of grid will each be in the range [1, 200]. Each grid[i][j] will",
"0 dp_set = [] res = 0 for y in range(len(grid)): dp_set.append(set(idx for",
"= len(grid), len(grid[0]) res = 0 for i in range(h -1): for j",
"have the value 1. Also, all four 1s used must be distinct. Example",
"Input: grid = [[1, 1, 1, 1]] Output: 0 Explanation: Rectangles must have",
"is only 0 or 1, find the number of corner rectangles. A corner",
"grid[i][j] will be either 0 or 1. The number of 1s in the",
"range(i+1, h): count = 0 for c in range(w): if grid[i][c] and grid[j][c]:",
"if not grid or not grid[0]: return 0 h, w = len(grid), len(grid[0])",
"Output: 1 Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4],",
"1 Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2],",
"rectangles. A corner rectangle is 4 distinct 1s on the grid that form",
"\"\"\" 0750. Number Of Corner Rectangles Medium Given a grid where each entry",
"Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one",
"3x3 rectangle. Example 3: Input: grid = [[1, 1, 1, 1]] Output: 0",
"in the range [1, 200]. Each grid[i][j] will be either 0 or 1.",
"h, w = len(grid), len(grid[0]) res = 0 for i in range(h -1):",
"corner rectangles. A corner rectangle is 4 distinct 1s on the grid that",
"2: Input: grid = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]",
"[1, 1, 1]] Output: 9 Explanation: There are four 2x2 rectangles, four 2x3",
"four distinct corners. Note: The number of rows and columns of grid will",
"+= matches * (matches-1) // 2 return res class Solution: def countCornerRectangles(self, grid:",
"The number of rows and columns of grid will each be in the",
"is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example 2:",
"will be at most 6000. \"\"\" class Solution: def countCornerRectangles(self, grid: List[List[int]]) ->",
"only the corners need to have the value 1. Also, all four 1s",
"6000. \"\"\" class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: if not grid",
"i in range(h -1): for j in range(i+1, h): count = 0 for",
"each entry is only 0 or 1, find the number of corner rectangles.",
"four 2x3 and 3x2 rectangles, and one 3x3 rectangle. Example 3: Input: grid",
"200]. Each grid[i][j] will be either 0 or 1. The number of 1s",
"that form an axis-aligned rectangle. Note that only the corners need to have",
"1, 0], [1, 0, 1, 0, 1]] Output: 1 Explanation: There is only",
"must have four distinct corners. Note: The number of rows and columns of",
"of 1s in the grid will be at most 6000. \"\"\" class Solution:",
"range(y): matches = len(dp_set[y] & dp_set[prev]) if matches >= 2: res += matches",
"grid[1][4], grid[3][2], grid[3][4]. Example 2: Input: grid = [[1, 1, 1], [1, 1,",
"of rows and columns of grid will each be in the range [1,",
"w = len(grid), len(grid[0]) res = 0 for i in range(h -1): for",
"not grid or not grid[0]: return 0 dp_set = [] res = 0",
"the number of corner rectangles. A corner rectangle is 4 distinct 1s on",
"1. Also, all four 1s used must be distinct. Example 1: Input: grid",
"only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example 2: Input:",
"in range(i+1, h): count = 0 for c in range(w): if grid[i][c] and",
"2x3 and 3x2 rectangles, and one 3x3 rectangle. Example 3: Input: grid =",
"prev in range(y): matches = len(dp_set[y] & dp_set[prev]) if matches >= 2: res",
"Output: 9 Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles,",
"be in the range [1, 200]. Each grid[i][j] will be either 0 or",
"for prev in range(y): matches = len(dp_set[y] & dp_set[prev]) if matches >= 2:",
"Rectangles must have four distinct corners. Note: The number of rows and columns",
"[1, 200]. Each grid[i][j] will be either 0 or 1. The number of",
"class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: if not grid or not",
"not grid or not grid[0]: return 0 h, w = len(grid), len(grid[0]) res",
"\"\"\" class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: if not grid or",
"grid[0]: return 0 h, w = len(grid), len(grid[0]) res = 0 for i",
"0750. Number Of Corner Rectangles Medium Given a grid where each entry is",
"for c in range(w): if grid[i][c] and grid[j][c]: res += count count +=",
"The number of 1s in the grid will be at most 6000. \"\"\"",
"len(grid[0]) res = 0 for i in range(h -1): for j in range(i+1,",
"= [[1, 1, 1, 1]] Output: 0 Explanation: Rectangles must have four distinct",
"in range(y): matches = len(dp_set[y] & dp_set[prev]) if matches >= 2: res +=",
"-> int: if not grid or not grid[0]: return 0 dp_set = []",
">= 2: res += matches * (matches-1) // 2 return res class Solution:",
"res class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: if not grid or",
"0, 1, 0, 1], [0, 0, 0, 1, 0], [1, 0, 1, 0,",
"1], [1, 1, 1], [1, 1, 1]] Output: 9 Explanation: There are four",
"matches * (matches-1) // 2 return res class Solution: def countCornerRectangles(self, grid: List[List[int]])",
"1, 0, 1]] Output: 1 Explanation: There is only one corner rectangle, with",
"dp_set[prev]) if matches >= 2: res += matches * (matches-1) // 2 return",
"or 1, find the number of corner rectangles. A corner rectangle is 4",
"be either 0 or 1. The number of 1s in the grid will",
"Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: if not grid or not grid[0]:",
"idx,val in enumerate(grid[y]) if val)) for prev in range(y): matches = len(dp_set[y] &",
"0, 0, 1, 0], [1, 0, 1, 0, 1]] Output: 1 Explanation: There",
"Given a grid where each entry is only 0 or 1, find the",
"grid that form an axis-aligned rectangle. Note that only the corners need to",
"1s used must be distinct. Example 1: Input: grid = [[1, 0, 0,",
"1: Input: grid = [[1, 0, 0, 1, 0], [0, 0, 1, 0,",
"= 0 for y in range(len(grid)): dp_set.append(set(idx for idx,val in enumerate(grid[y]) if val))",
"for y in range(len(grid)): dp_set.append(set(idx for idx,val in enumerate(grid[y]) if val)) for prev",
"4 distinct 1s on the grid that form an axis-aligned rectangle. Note that",
"1s in the grid will be at most 6000. \"\"\" class Solution: def",
"0 for i in range(h -1): for j in range(i+1, h): count =",
"[[1, 0, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0,",
"distinct 1s on the grid that form an axis-aligned rectangle. Note that only",
"= len(dp_set[y] & dp_set[prev]) if matches >= 2: res += matches * (matches-1)",
"1], [0, 0, 0, 1, 0], [1, 0, 1, 0, 1]] Output: 1",
"2: res += matches * (matches-1) // 2 return res class Solution: def",
"Output: 0 Explanation: Rectangles must have four distinct corners. Note: The number of",
"where each entry is only 0 or 1, find the number of corner",
"[[1, 1, 1, 1]] Output: 0 Explanation: Rectangles must have four distinct corners.",
"not grid[0]: return 0 dp_set = [] res = 0 for y in",
"[] res = 0 for y in range(len(grid)): dp_set.append(set(idx for idx,val in enumerate(grid[y])",
"List[List[int]]) -> int: if not grid or not grid[0]: return 0 h, w",
"3: Input: grid = [[1, 1, 1, 1]] Output: 0 Explanation: Rectangles must",
"all four 1s used must be distinct. Example 1: Input: grid = [[1,",
"0, 1, 0, 1]] Output: 1 Explanation: There is only one corner rectangle,",
"not grid[0]: return 0 h, w = len(grid), len(grid[0]) res = 0 for",
"grid will each be in the range [1, 200]. Each grid[i][j] will be",
"0, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1,",
"[1, 0, 1, 0, 1]] Output: 1 Explanation: There is only one corner",
"for idx,val in enumerate(grid[y]) if val)) for prev in range(y): matches = len(dp_set[y]",
"one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example 2: Input: grid",
"axis-aligned rectangle. Note that only the corners need to have the value 1.",
"four 1s used must be distinct. Example 1: Input: grid = [[1, 0,",
"corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example 2: Input: grid =",
"corner rectangle is 4 distinct 1s on the grid that form an axis-aligned",
"1, 1]] Output: 0 Explanation: Rectangles must have four distinct corners. Note: The",
"distinct corners. Note: The number of rows and columns of grid will each",
"rows and columns of grid will each be in the range [1, 200].",
"-> int: if not grid or not grid[0]: return 0 h, w =",
"at most 6000. \"\"\" class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: if",
"= [] res = 0 for y in range(len(grid)): dp_set.append(set(idx for idx,val in",
"range(h -1): for j in range(i+1, h): count = 0 for c in",
"h): count = 0 for c in range(w): if grid[i][c] and grid[j][c]: res",
"the grid will be at most 6000. \"\"\" class Solution: def countCornerRectangles(self, grid:",
"Each grid[i][j] will be either 0 or 1. The number of 1s in",
"if val)) for prev in range(y): matches = len(dp_set[y] & dp_set[prev]) if matches",
"9 Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and",
"entry is only 0 or 1, find the number of corner rectangles. A",
"grid[3][2], grid[3][4]. Example 2: Input: grid = [[1, 1, 1], [1, 1, 1],",
"in enumerate(grid[y]) if val)) for prev in range(y): matches = len(dp_set[y] & dp_set[prev])",
"rectangle is 4 distinct 1s on the grid that form an axis-aligned rectangle.",
"1], [1, 1, 1]] Output: 9 Explanation: There are four 2x2 rectangles, four",
"grid: List[List[int]]) -> int: if not grid or not grid[0]: return 0 h,",
"the range [1, 200]. Each grid[i][j] will be either 0 or 1. The",
"2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle. Example 3:",
"will be either 0 or 1. The number of 1s in the grid",
"rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example 2: Input: grid = [[1,",
"number of 1s in the grid will be at most 6000. \"\"\" class",
"Input: grid = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] Output:",
"four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle. Example",
"1]] Output: 0 Explanation: Rectangles must have four distinct corners. Note: The number",
"Example 3: Input: grid = [[1, 1, 1, 1]] Output: 0 Explanation: Rectangles",
"on the grid that form an axis-aligned rectangle. Note that only the corners",
"c in range(w): if grid[i][c] and grid[j][c]: res += count count += 1",
"rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle. Example 3: Input:",
"Explanation: Rectangles must have four distinct corners. Note: The number of rows and",
"1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [1,",
"a grid where each entry is only 0 or 1, find the number",
"if matches >= 2: res += matches * (matches-1) // 2 return res",
"grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example 2: Input: grid = [[1, 1, 1], [1,",
"return 0 dp_set = [] res = 0 for y in range(len(grid)): dp_set.append(set(idx",
"= 0 for i in range(h -1): for j in range(i+1, h): count",
"def countCornerRectangles(self, grid: List[List[int]]) -> int: if not grid or not grid[0]: return",
"0, 1]] Output: 1 Explanation: There is only one corner rectangle, with corners",
"if not grid or not grid[0]: return 0 dp_set = [] res =",
"dp_set.append(set(idx for idx,val in enumerate(grid[y]) if val)) for prev in range(y): matches =",
"matches = len(dp_set[y] & dp_set[prev]) if matches >= 2: res += matches *",
"len(grid), len(grid[0]) res = 0 for i in range(h -1): for j in",
"1, 1], [1, 1, 1], [1, 1, 1]] Output: 9 Explanation: There are",
"1]] Output: 9 Explanation: There are four 2x2 rectangles, four 2x3 and 3x2",
"with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. Example 2: Input: grid = [[1, 1,",
"grid[3][4]. Example 2: Input: grid = [[1, 1, 1], [1, 1, 1], [1,",
"used must be distinct. Example 1: Input: grid = [[1, 0, 0, 1,",
"grid will be at most 6000. \"\"\" class Solution: def countCornerRectangles(self, grid: List[List[int]])",
"one 3x3 rectangle. Example 3: Input: grid = [[1, 1, 1, 1]] Output:"
] |
[
"= [ (\"\", timedelta(seconds=0)), (\" \", timedelta(seconds=0)), (\"0\", timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)), (\"0 s\",",
"(\"5m 100s\", timedelta(minutes=5, seconds=100)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h3m4s\", timedelta(hours=2, minutes=3,",
"(\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h3m4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h 3m 4s\",",
"(\"0s\", timedelta(seconds=0)), (\"0 s\", timedelta(seconds=0)), (\"10\", timedelta(seconds=10)), (\"100\", timedelta(seconds=100)), (\"5m 10s\", timedelta(minutes=5, seconds=10)),",
"timedelta(hours=10)), (\"1d 2h 3m 4s\", timedelta(days=1, hours=2, minutes=3, seconds=4)), (\"4w\", timedelta(days=28)), (\"4w 1d\",",
"(\"1d 2h 3m 4s\", timedelta(days=1, hours=2, minutes=3, seconds=4)), (\"4w\", timedelta(days=28)), (\"4w 1d\", timedelta(days=29)),",
"3m 4s\", timedelta(days=1, hours=2, minutes=3, seconds=4)), (\"4w\", timedelta(days=28)), (\"4w 1d\", timedelta(days=29)), ] @pytest.mark.parametrize(\"s,",
"timedelta(seconds=0)), (\" \", timedelta(seconds=0)), (\"0\", timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)), (\"0 s\", timedelta(seconds=0)), (\"10\", timedelta(seconds=10)),",
"minutes=3, seconds=4)), (\"2h3m4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"10h\",",
"timer_cli.main import _parse_timedelta timedelta_test_cases = [ (\"\", timedelta(seconds=0)), (\" \", timedelta(seconds=0)), (\"0\", timedelta(seconds=0)),",
"timedelta(hours=2, minutes=3, seconds=4)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"10h\", timedelta(hours=10)), (\"1d 2h",
"import _parse_timedelta timedelta_test_cases = [ (\"\", timedelta(seconds=0)), (\" \", timedelta(seconds=0)), (\"0\", timedelta(seconds=0)), (\"0s\",",
"3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h3m4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h 3m 4s\", timedelta(hours=2,",
"[ (\"\", timedelta(seconds=0)), (\" \", timedelta(seconds=0)), (\"0\", timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)), (\"0 s\", timedelta(seconds=0)),",
"(\"4w\", timedelta(days=28)), (\"4w 1d\", timedelta(days=29)), ] @pytest.mark.parametrize(\"s, d\", timedelta_test_cases) def test_parse_timedelta(s, d): assert",
"seconds=4)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"10h\", timedelta(hours=10)), (\"1d 2h 3m 4s\",",
"seconds=4)), (\"10h\", timedelta(hours=10)), (\"1d 2h 3m 4s\", timedelta(days=1, hours=2, minutes=3, seconds=4)), (\"4w\", timedelta(days=28)),",
"(\"10h\", timedelta(hours=10)), (\"1d 2h 3m 4s\", timedelta(days=1, hours=2, minutes=3, seconds=4)), (\"4w\", timedelta(days=28)), (\"4w",
"(\"10\", timedelta(seconds=10)), (\"100\", timedelta(seconds=100)), (\"5m 10s\", timedelta(minutes=5, seconds=10)), (\"5m 100s\", timedelta(minutes=5, seconds=100)), (\"2h",
"import pytest from timer_cli.main import _parse_timedelta timedelta_test_cases = [ (\"\", timedelta(seconds=0)), (\" \",",
"seconds=100)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h3m4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h 3m",
"seconds=4)), (\"2h3m4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"10h\", timedelta(hours=10)),",
"datetime import timedelta import pytest from timer_cli.main import _parse_timedelta timedelta_test_cases = [ (\"\",",
"timedelta(seconds=0)), (\"0 s\", timedelta(seconds=0)), (\"10\", timedelta(seconds=10)), (\"100\", timedelta(seconds=100)), (\"5m 10s\", timedelta(minutes=5, seconds=10)), (\"5m",
"s\", timedelta(seconds=0)), (\"10\", timedelta(seconds=10)), (\"100\", timedelta(seconds=100)), (\"5m 10s\", timedelta(minutes=5, seconds=10)), (\"5m 100s\", timedelta(minutes=5,",
"(\"5m 10s\", timedelta(minutes=5, seconds=10)), (\"5m 100s\", timedelta(minutes=5, seconds=100)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3,",
"2h 3m 4s\", timedelta(days=1, hours=2, minutes=3, seconds=4)), (\"4w\", timedelta(days=28)), (\"4w 1d\", timedelta(days=29)), ]",
"(\"4w 1d\", timedelta(days=29)), ] @pytest.mark.parametrize(\"s, d\", timedelta_test_cases) def test_parse_timedelta(s, d): assert _parse_timedelta(s) ==",
"_parse_timedelta timedelta_test_cases = [ (\"\", timedelta(seconds=0)), (\" \", timedelta(seconds=0)), (\"0\", timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)),",
"timedelta(days=1, hours=2, minutes=3, seconds=4)), (\"4w\", timedelta(days=28)), (\"4w 1d\", timedelta(days=29)), ] @pytest.mark.parametrize(\"s, d\", timedelta_test_cases)",
"(\" \", timedelta(seconds=0)), (\"0\", timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)), (\"0 s\", timedelta(seconds=0)), (\"10\", timedelta(seconds=10)), (\"100\",",
"(\"100\", timedelta(seconds=100)), (\"5m 10s\", timedelta(minutes=5, seconds=10)), (\"5m 100s\", timedelta(minutes=5, seconds=100)), (\"2h 3m 4s\",",
"timedelta(seconds=0)), (\"0\", timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)), (\"0 s\", timedelta(seconds=0)), (\"10\", timedelta(seconds=10)), (\"100\", timedelta(seconds=100)), (\"5m",
"timedelta(days=28)), (\"4w 1d\", timedelta(days=29)), ] @pytest.mark.parametrize(\"s, d\", timedelta_test_cases) def test_parse_timedelta(s, d): assert _parse_timedelta(s)",
"(\"\", timedelta(seconds=0)), (\" \", timedelta(seconds=0)), (\"0\", timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)), (\"0 s\", timedelta(seconds=0)), (\"10\",",
"import timedelta import pytest from timer_cli.main import _parse_timedelta timedelta_test_cases = [ (\"\", timedelta(seconds=0)),",
"3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"10h\", timedelta(hours=10)), (\"1d 2h 3m 4s\", timedelta(days=1, hours=2,",
"1d\", timedelta(days=29)), ] @pytest.mark.parametrize(\"s, d\", timedelta_test_cases) def test_parse_timedelta(s, d): assert _parse_timedelta(s) == d",
"timedelta(minutes=5, seconds=100)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h3m4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h",
"timedelta(seconds=0)), (\"10\", timedelta(seconds=10)), (\"100\", timedelta(seconds=100)), (\"5m 10s\", timedelta(minutes=5, seconds=10)), (\"5m 100s\", timedelta(minutes=5, seconds=100)),",
"timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)), (\"0 s\", timedelta(seconds=0)), (\"10\", timedelta(seconds=10)), (\"100\", timedelta(seconds=100)), (\"5m 10s\", timedelta(minutes=5,",
"timedelta(hours=2, minutes=3, seconds=4)), (\"2h3m4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)),",
"seconds=10)), (\"5m 100s\", timedelta(minutes=5, seconds=100)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h3m4s\", timedelta(hours=2,",
"pytest from timer_cli.main import _parse_timedelta timedelta_test_cases = [ (\"\", timedelta(seconds=0)), (\" \", timedelta(seconds=0)),",
"4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"10h\", timedelta(hours=10)), (\"1d 2h 3m 4s\", timedelta(days=1, hours=2, minutes=3,",
"(\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"10h\", timedelta(hours=10)), (\"1d 2h 3m 4s\", timedelta(days=1,",
"seconds=4)), (\"4w\", timedelta(days=28)), (\"4w 1d\", timedelta(days=29)), ] @pytest.mark.parametrize(\"s, d\", timedelta_test_cases) def test_parse_timedelta(s, d):",
"4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h3m4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3,",
"minutes=3, seconds=4)), (\"10h\", timedelta(hours=10)), (\"1d 2h 3m 4s\", timedelta(days=1, hours=2, minutes=3, seconds=4)), (\"4w\",",
"from timer_cli.main import _parse_timedelta timedelta_test_cases = [ (\"\", timedelta(seconds=0)), (\" \", timedelta(seconds=0)), (\"0\",",
"10s\", timedelta(minutes=5, seconds=10)), (\"5m 100s\", timedelta(minutes=5, seconds=100)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)),",
"hours=2, minutes=3, seconds=4)), (\"4w\", timedelta(days=28)), (\"4w 1d\", timedelta(days=29)), ] @pytest.mark.parametrize(\"s, d\", timedelta_test_cases) def",
"100s\", timedelta(minutes=5, seconds=100)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h3m4s\", timedelta(hours=2, minutes=3, seconds=4)),",
"(\"2h3m4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"10h\", timedelta(hours=10)), (\"1d",
"(\"0\", timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)), (\"0 s\", timedelta(seconds=0)), (\"10\", timedelta(seconds=10)), (\"100\", timedelta(seconds=100)), (\"5m 10s\",",
"timedelta(minutes=5, seconds=10)), (\"5m 100s\", timedelta(minutes=5, seconds=100)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"2h3m4s\",",
"timedelta(seconds=100)), (\"5m 10s\", timedelta(minutes=5, seconds=10)), (\"5m 100s\", timedelta(minutes=5, seconds=100)), (\"2h 3m 4s\", timedelta(hours=2,",
"minutes=3, seconds=4)), (\"2h 3m 4s\", timedelta(hours=2, minutes=3, seconds=4)), (\"10h\", timedelta(hours=10)), (\"1d 2h 3m",
"4s\", timedelta(days=1, hours=2, minutes=3, seconds=4)), (\"4w\", timedelta(days=28)), (\"4w 1d\", timedelta(days=29)), ] @pytest.mark.parametrize(\"s, d\",",
"timedelta_test_cases = [ (\"\", timedelta(seconds=0)), (\" \", timedelta(seconds=0)), (\"0\", timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)), (\"0",
"minutes=3, seconds=4)), (\"4w\", timedelta(days=28)), (\"4w 1d\", timedelta(days=29)), ] @pytest.mark.parametrize(\"s, d\", timedelta_test_cases) def test_parse_timedelta(s,",
"(\"0 s\", timedelta(seconds=0)), (\"10\", timedelta(seconds=10)), (\"100\", timedelta(seconds=100)), (\"5m 10s\", timedelta(minutes=5, seconds=10)), (\"5m 100s\",",
"timedelta(seconds=10)), (\"100\", timedelta(seconds=100)), (\"5m 10s\", timedelta(minutes=5, seconds=10)), (\"5m 100s\", timedelta(minutes=5, seconds=100)), (\"2h 3m",
"\", timedelta(seconds=0)), (\"0\", timedelta(seconds=0)), (\"0s\", timedelta(seconds=0)), (\"0 s\", timedelta(seconds=0)), (\"10\", timedelta(seconds=10)), (\"100\", timedelta(seconds=100)),",
"timedelta(hours=2, minutes=3, seconds=4)), (\"10h\", timedelta(hours=10)), (\"1d 2h 3m 4s\", timedelta(days=1, hours=2, minutes=3, seconds=4)),",
"timedelta import pytest from timer_cli.main import _parse_timedelta timedelta_test_cases = [ (\"\", timedelta(seconds=0)), (\"",
"from datetime import timedelta import pytest from timer_cli.main import _parse_timedelta timedelta_test_cases = ["
] |
[
"file = [x.strip() for x in file] file = [x.split(\" \") for x",
"minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int: a;\\n\\n\" minizinc=minizinc+\"\\n constraint x0=0;\\n\" for x in file: minizinc=minizinc+\"constraint (\"",
"in x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\") mod 2=0 ;\\n\" minizinc2=\"a = \" for i",
"[x.strip() for x in file] file = [x.split(\" \") for x in file]",
"mod 2=0 ;\\n\" minizinc2=\"a = \" for i in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\"",
"Solver.lookup(\"gecode\") max=0 trivial = Model() FileName=\"small\" with open(FileName+\".txt\") as f: file=f.readlines() f.close() minizinc=\"\"",
"if int(y)>max: max=int(y) for y in range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int: a;\\n\\n\"",
"solutions result = instance.solve(intermediate_solutions=True) f = open(FileName+\"_solution.txt\", \"w\") for j in range(1,max+1): #print(\"x\"+str(j)+\"",
"in file: minizinc=minizinc+\"constraint (\" for y in x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\") mod 2=0",
"y in x: if int(y)>max: max=int(y) for y in range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\"",
";\\n\" minizinc+=\"\\nsolve minimize a;\\n\" print(max) print(minizinc) sum=0; trivial.add_string(minizinc) instance = Instance(gecode, trivial) #",
"x in file] print(file) for x in file: for y in x: if",
"in file] #file = [x.split(\"\\t\") for x in file] print(file) for x in",
"file] file = [x.split(\" \") for x in file] #file = [x.split(\"\\t\") for",
"a;\\n\\n\" minizinc=minizinc+\"\\n constraint x0=0;\\n\" for x in file: minizinc=minizinc+\"constraint (\" for y in",
"minizinc+=\"\\nsolve minimize a;\\n\" print(max) print(minizinc) sum=0; trivial.add_string(minizinc) instance = Instance(gecode, trivial) # Find",
"instance.solve(intermediate_solutions=True) f = open(FileName+\"_solution.txt\", \"w\") for j in range(1,max+1): #print(\"x\"+str(j)+\" = \") print(result[len(result)-1,",
"all intermediate solutions result = instance.solve(intermediate_solutions=True) f = open(FileName+\"_solution.txt\", \"w\") for j in",
"trivial.add_string(minizinc) instance = Instance(gecode, trivial) # Find and print all intermediate solutions result",
"= \") print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\") f.write(str(result[len(result)-1, \"x\"+str(j)] )+\"\\n\") sum+=result[len(result)-1, \"x\"+str(j)] f.write(\"\\nnumber = \"+str(sum))",
"FileName=\"small\" with open(FileName+\".txt\") as f: file=f.readlines() f.close() minizinc=\"\" file = [x.strip() for x",
"open(FileName+\"_solution.txt\", \"w\") for j in range(1,max+1): #print(\"x\"+str(j)+\" = \") print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\") f.write(str(result[len(result)-1,",
"Instance, Model, Solver gecode = Solver.lookup(\"gecode\") max=0 trivial = Model() FileName=\"small\" with open(FileName+\".txt\")",
"= Instance(gecode, trivial) # Find and print all intermediate solutions result = instance.solve(intermediate_solutions=True)",
"int: a;\\n\\n\" minizinc=minizinc+\"\\n constraint x0=0;\\n\" for x in file: minizinc=minizinc+\"constraint (\" for y",
"\" for i in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0 ;\\n\" minizinc+=\"\\nsolve minimize",
"[x.split(\" \") for x in file] #file = [x.split(\"\\t\") for x in file]",
"minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0 ;\\n\" minizinc+=\"\\nsolve minimize a;\\n\" print(max) print(minizinc) sum=0; trivial.add_string(minizinc) instance =",
";\\n\" minizinc2=\"a = \" for i in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0",
"x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\") mod 2=0 ;\\n\" minizinc2=\"a = \" for i in",
"for x in file: minizinc=minizinc+\"constraint (\" for y in x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\")",
"x: if int(y)>max: max=int(y) for y in range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int:",
"f = open(FileName+\"_solution.txt\", \"w\") for j in range(1,max+1): #print(\"x\"+str(j)+\" = \") print(result[len(result)-1, \"x\"+str(j)])",
"\"w\") for j in range(1,max+1): #print(\"x\"+str(j)+\" = \") print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\") f.write(str(result[len(result)-1, \"x\"+str(j)]",
"trivial = Model() FileName=\"small\" with open(FileName+\".txt\") as f: file=f.readlines() f.close() minizinc=\"\" file =",
"Model, Solver gecode = Solver.lookup(\"gecode\") max=0 trivial = Model() FileName=\"small\" with open(FileName+\".txt\") as",
"Find and print all intermediate solutions result = instance.solve(intermediate_solutions=True) f = open(FileName+\"_solution.txt\", \"w\")",
"y in range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int: a;\\n\\n\" minizinc=minizinc+\"\\n constraint x0=0;\\n\" for",
"file: minizinc=minizinc+\"constraint (\" for y in x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\") mod 2=0 ;\\n\"",
"for y in x: if int(y)>max: max=int(y) for y in range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\"",
"from minizinc import Instance, Model, Solver gecode = Solver.lookup(\"gecode\") max=0 trivial = Model()",
"in x: if int(y)>max: max=int(y) for y in range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var",
"minizinc=minizinc+\") mod 2=0 ;\\n\" minizinc2=\"a = \" for i in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1]",
"range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0 ;\\n\" minizinc+=\"\\nsolve minimize a;\\n\" print(max) print(minizinc) sum=0;",
"\") for x in file] #file = [x.split(\"\\t\") for x in file] print(file)",
"= Solver.lookup(\"gecode\") max=0 trivial = Model() FileName=\"small\" with open(FileName+\".txt\") as f: file=f.readlines() f.close()",
"minizinc=minizinc+\"\\n constraint x0=0;\\n\" for x in file: minizinc=minizinc+\"constraint (\" for y in x:",
"max=0 trivial = Model() FileName=\"small\" with open(FileName+\".txt\") as f: file=f.readlines() f.close() minizinc=\"\" file",
"for x in file: for y in x: if int(y)>max: max=int(y) for y",
"for i in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0 ;\\n\" minizinc+=\"\\nsolve minimize a;\\n\"",
"a;\\n\" print(max) print(minizinc) sum=0; trivial.add_string(minizinc) instance = Instance(gecode, trivial) # Find and print",
"= [x.split(\" \") for x in file] #file = [x.split(\"\\t\") for x in",
"for x in file] print(file) for x in file: for y in x:",
"with open(FileName+\".txt\") as f: file=f.readlines() f.close() minizinc=\"\" file = [x.strip() for x in",
"as f: file=f.readlines() f.close() minizinc=\"\" file = [x.strip() for x in file] file",
"in range(1,max+1): #print(\"x\"+str(j)+\" = \") print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\") f.write(str(result[len(result)-1, \"x\"+str(j)] )+\"\\n\") sum+=result[len(result)-1, \"x\"+str(j)]",
"in file] file = [x.split(\" \") for x in file] #file = [x.split(\"\\t\")",
"0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int: a;\\n\\n\" minizinc=minizinc+\"\\n constraint x0=0;\\n\" for x in file: minizinc=minizinc+\"constraint",
"minizinc import Instance, Model, Solver gecode = Solver.lookup(\"gecode\") max=0 trivial = Model() FileName=\"small\"",
"minizinc2=\"a = \" for i in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0 ;\\n\"",
"for x in file] file = [x.split(\" \") for x in file] #file",
"in file: for y in x: if int(y)>max: max=int(y) for y in range(0,max+1):",
"print(file) for x in file: for y in x: if int(y)>max: max=int(y) for",
"result = instance.solve(intermediate_solutions=True) f = open(FileName+\"_solution.txt\", \"w\") for j in range(1,max+1): #print(\"x\"+str(j)+\" =",
"x in file: minizinc=minizinc+\"constraint (\" for y in x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\") mod",
"file] #file = [x.split(\"\\t\") for x in file] print(file) for x in file:",
"\") print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\") f.write(str(result[len(result)-1, \"x\"+str(j)] )+\"\\n\") sum+=result[len(result)-1, \"x\"+str(j)] f.write(\"\\nnumber = \"+str(sum)) print(sum)",
"Model() FileName=\"small\" with open(FileName+\".txt\") as f: file=f.readlines() f.close() minizinc=\"\" file = [x.strip() for",
"y in x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\") mod 2=0 ;\\n\" minizinc2=\"a = \" for",
"instance = Instance(gecode, trivial) # Find and print all intermediate solutions result =",
"i in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0 ;\\n\" minizinc+=\"\\nsolve minimize a;\\n\" print(max)",
"open(FileName+\".txt\") as f: file=f.readlines() f.close() minizinc=\"\" file = [x.strip() for x in file]",
"# Find and print all intermediate solutions result = instance.solve(intermediate_solutions=True) f = open(FileName+\"_solution.txt\",",
"minimize a;\\n\" print(max) print(minizinc) sum=0; trivial.add_string(minizinc) instance = Instance(gecode, trivial) # Find and",
"minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\") mod 2=0 ;\\n\" minizinc2=\"a = \" for i in range(1,max+1):",
"= Model() FileName=\"small\" with open(FileName+\".txt\") as f: file=f.readlines() f.close() minizinc=\"\" file = [x.strip()",
"(\" for y in x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\") mod 2=0 ;\\n\" minizinc2=\"a =",
"2=0 ;\\n\" minizinc2=\"a = \" for i in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint",
"file] print(file) for x in file: for y in x: if int(y)>max: max=int(y)",
"print(max) print(minizinc) sum=0; trivial.add_string(minizinc) instance = Instance(gecode, trivial) # Find and print all",
"constraint x0=0;\\n\" for x in file: minizinc=minizinc+\"constraint (\" for y in x: minizinc=minizinc+\"x\"+y+\"+\"",
"in file] print(file) for x in file: for y in x: if int(y)>max:",
"trivial) # Find and print all intermediate solutions result = instance.solve(intermediate_solutions=True) f =",
"[x.split(\"\\t\") for x in file] print(file) for x in file: for y in",
"minizinc=minizinc+\"var int: a;\\n\\n\" minizinc=minizinc+\"\\n constraint x0=0;\\n\" for x in file: minizinc=minizinc+\"constraint (\" for",
"print(minizinc) sum=0; trivial.add_string(minizinc) instance = Instance(gecode, trivial) # Find and print all intermediate",
"= [x.strip() for x in file] file = [x.split(\" \") for x in",
"a!=0 ;\\n\" minizinc+=\"\\nsolve minimize a;\\n\" print(max) print(minizinc) sum=0; trivial.add_string(minizinc) instance = Instance(gecode, trivial)",
"#print(\"x\"+str(j)+\" = \") print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\") f.write(str(result[len(result)-1, \"x\"+str(j)] )+\"\\n\") sum+=result[len(result)-1, \"x\"+str(j)] f.write(\"\\nnumber =",
"range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int: a;\\n\\n\" minizinc=minizinc+\"\\n constraint x0=0;\\n\" for x in",
"Solver gecode = Solver.lookup(\"gecode\") max=0 trivial = Model() FileName=\"small\" with open(FileName+\".txt\") as f:",
"minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0 ;\\n\" minizinc+=\"\\nsolve minimize a;\\n\" print(max) print(minizinc) sum=0; trivial.add_string(minizinc)",
"x in file] file = [x.split(\" \") for x in file] #file =",
"file: for y in x: if int(y)>max: max=int(y) for y in range(0,max+1): minizinc=minizinc+\"var",
"file = [x.split(\" \") for x in file] #file = [x.split(\"\\t\") for x",
"f: file=f.readlines() f.close() minizinc=\"\" file = [x.strip() for x in file] file =",
"minizinc=minizinc[:-1] minizinc=minizinc+\") mod 2=0 ;\\n\" minizinc2=\"a = \" for i in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\"",
"int(y)>max: max=int(y) for y in range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int: a;\\n\\n\" minizinc=minizinc+\"\\n",
"= open(FileName+\"_solution.txt\", \"w\") for j in range(1,max+1): #print(\"x\"+str(j)+\" = \") print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\")",
"import Instance, Model, Solver gecode = Solver.lookup(\"gecode\") max=0 trivial = Model() FileName=\"small\" with",
"= [x.split(\"\\t\") for x in file] print(file) for x in file: for y",
"print all intermediate solutions result = instance.solve(intermediate_solutions=True) f = open(FileName+\"_solution.txt\", \"w\") for j",
"intermediate solutions result = instance.solve(intermediate_solutions=True) f = open(FileName+\"_solution.txt\", \"w\") for j in range(1,max+1):",
"minizinc=\"\" file = [x.strip() for x in file] file = [x.split(\" \") for",
"for j in range(1,max+1): #print(\"x\"+str(j)+\" = \") print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\") f.write(str(result[len(result)-1, \"x\"+str(j)] )+\"\\n\")",
"for x in file] #file = [x.split(\"\\t\") for x in file] print(file) for",
"x0=0;\\n\" for x in file: minizinc=minizinc+\"constraint (\" for y in x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1]",
"sum=0; trivial.add_string(minizinc) instance = Instance(gecode, trivial) # Find and print all intermediate solutions",
"minizinc+=\"\\nconstraint a!=0 ;\\n\" minizinc+=\"\\nsolve minimize a;\\n\" print(max) print(minizinc) sum=0; trivial.add_string(minizinc) instance = Instance(gecode,",
"= \" for i in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0 ;\\n\" minizinc+=\"\\nsolve",
"x in file] #file = [x.split(\"\\t\") for x in file] print(file) for x",
"file=f.readlines() f.close() minizinc=\"\" file = [x.strip() for x in file] file = [x.split(\"",
"minizinc=minizinc+\"constraint (\" for y in x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\") mod 2=0 ;\\n\" minizinc2=\"a",
"Instance(gecode, trivial) # Find and print all intermediate solutions result = instance.solve(intermediate_solutions=True) f",
"and print all intermediate solutions result = instance.solve(intermediate_solutions=True) f = open(FileName+\"_solution.txt\", \"w\") for",
"in range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int: a;\\n\\n\" minizinc=minizinc+\"\\n constraint x0=0;\\n\" for x",
"minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int: a;\\n\\n\" minizinc=minizinc+\"\\n constraint x0=0;\\n\" for x in file:",
"print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\") f.write(str(result[len(result)-1, \"x\"+str(j)] )+\"\\n\") sum+=result[len(result)-1, \"x\"+str(j)] f.write(\"\\nnumber = \"+str(sum)) print(sum) f.close()",
"range(1,max+1): #print(\"x\"+str(j)+\" = \") print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\") f.write(str(result[len(result)-1, \"x\"+str(j)] )+\"\\n\") sum+=result[len(result)-1, \"x\"+str(j)] f.write(\"\\nnumber",
"#file = [x.split(\"\\t\") for x in file] print(file) for x in file: for",
"in range(1,max+1): minizinc2=minizinc2+\"x\"+str(i)+\"+\" minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0 ;\\n\" minizinc+=\"\\nsolve minimize a;\\n\" print(max) print(minizinc)",
"for y in x: minizinc=minizinc+\"x\"+y+\"+\" minizinc=minizinc[:-1] minizinc=minizinc+\") mod 2=0 ;\\n\" minizinc2=\"a = \"",
"= instance.solve(intermediate_solutions=True) f = open(FileName+\"_solution.txt\", \"w\") for j in range(1,max+1): #print(\"x\"+str(j)+\" = \")",
"max=int(y) for y in range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int: a;\\n\\n\" minizinc=minizinc+\"\\n constraint",
"j in range(1,max+1): #print(\"x\"+str(j)+\" = \") print(result[len(result)-1, \"x\"+str(j)]) f.write(\"x\"+str(j)+\"=\") f.write(str(result[len(result)-1, \"x\"+str(j)] )+\"\\n\") sum+=result[len(result)-1,",
"x in file: for y in x: if int(y)>max: max=int(y) for y in",
"f.close() minizinc=\"\" file = [x.strip() for x in file] file = [x.split(\" \")",
"for y in range(0,max+1): minizinc=minizinc+\"var 0..1:x\"+str(y)+\";\\n\" minizinc=minizinc+\"\\n\" minizinc=minizinc+\"var int: a;\\n\\n\" minizinc=minizinc+\"\\n constraint x0=0;\\n\"",
"minizinc2=minizinc2[:-1] minizinc+=\"\\n\"+minizinc2+\";\\n\\n\" minizinc+=\"\\nconstraint a!=0 ;\\n\" minizinc+=\"\\nsolve minimize a;\\n\" print(max) print(minizinc) sum=0; trivial.add_string(minizinc) instance",
"gecode = Solver.lookup(\"gecode\") max=0 trivial = Model() FileName=\"small\" with open(FileName+\".txt\") as f: file=f.readlines()"
] |
[
"their assessment status :param application_id: :return: \"\"\" application = get_application_status(application_id=application_id) if not application:",
"in request.args.items(): if key in search_params: search_params.update({key: value}) applications = get_applications(params=search_params) todo_summary =",
"available applications from a given fund_id and round_id from the application store :param",
"Page showing available applications from a given fund_id and round_id from the application",
"fund rounds and are not shown in the assessor views \"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"])",
"value}) applications = get_applications(params=search_params) todo_summary = get_todo_summary() return render_template( \"landing.html\", applications=applications, search_params=search_params, todo_summary=todo_summary,",
"abort(404) return render_template( \"application.html\", application=application, fund=fund ) \"\"\" Legacy The following routes serve",
"str, round_id: str): \"\"\" Page showing available applications from a given fund_id and",
"request assess_bp = Blueprint( \"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", ) @assess_bp.route(\"/\", methods=[\"GET\"]) def funds():",
"@assess_bp.route(\"/landing/\", methods=[\"GET\"]) def landing(): \"\"\" Landing page for assessors Provides a summary of",
"fund = get_fund(application.fund_id) if not fund: abort(404) return render_template( \"application.html\", application=application, fund=fund )",
"rounds = get_rounds(fund_id) return render_template(\"fund.html\", fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def fund_round(fund_id: str, round_id:",
"a summary of available applications with a keyword searchable and filterable list of",
"import ASSESSMENT_HUB_ROUTE from flask import abort from flask import Blueprint from flask import",
"applications = get_applications(params=search_params) todo_summary = get_todo_summary() return render_template( \"landing.html\", applications=applications, search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join(",
"not fund: abort(404) rounds = get_rounds(fund_id) return render_template(\"fund.html\", fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def",
"Add request arg search params to dict for key, value in request.args.items(): if",
"str): \"\"\" Page showing available applications from a given fund_id and round_id from",
"Provides a summary of available applications with a keyword searchable and filterable list",
"= get_rounds(fund_id) return render_template(\"fund.html\", fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def fund_round(fund_id: str, round_id: str):",
"Page showing available funds from fund store :return: \"\"\" funds = get_funds() return",
"round_id from the application store :param fund_id: :param round_id: :return: \"\"\" fund =",
"\"order_rev\": \"\", \"status_only\": \"\", } # Add request arg search params to dict",
"= { \"id_contains\": \"\", \"order_by\": \"\", \"order_rev\": \"\", \"status_only\": \"\", } # Add",
"\"\", \"status_only\": \"\", } # Add request arg search params to dict for",
"APPLICATION_STORE_API_HOST_PUBLIC from app.config import ASSESSMENT_HUB_ROUTE from flask import abort from flask import Blueprint",
"if key in search_params: search_params.update({key: value}) applications = get_applications(params=search_params) todo_summary = get_todo_summary() return",
"the fund, application ID and all the application questions and their assessment status",
"the application questions and their assessment status :param application_id: :return: \"\"\" application =",
"applications=applications, search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ] ), ) @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"])",
"shown in the assessor views \"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def fund(fund_id: str): \"\"\" Page",
"methods=[\"GET\"]) def fund(fund_id: str): \"\"\" Page showing available rounds for a given fund",
"APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ] ), ) @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def application(application_id): \"\"\" Application summary",
"all the application questions and their assessment status :param application_id: :return: \"\"\" application",
":param application_id: :return: \"\"\" application = get_application_status(application_id=application_id) if not application: abort(404) fund =",
"the assessor views \"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def fund(fund_id: str): \"\"\" Page showing available",
"from app.config import ASSESSMENT_HUB_ROUTE from flask import abort from flask import Blueprint from",
"\"\"\" Page showing available rounds for a given fund from round store :param",
"not application: abort(404) fund = get_fund(application.fund_id) if not fund: abort(404) return render_template( \"application.html\",",
"available rounds for a given fund from round store :param fund_id: :return: \"\"\"",
"methods=[\"GET\"]) def fund_round(fund_id: str, round_id: str): \"\"\" Page showing available applications from a",
"\"\"\" Page showing available applications from a given fund_id and round_id from the",
"fund=fund ) \"\"\" Legacy The following routes serve information relating to individual funds",
"from fund store :return: \"\"\" funds = get_funds() return render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"])",
"abort(404) rounds = get_rounds(fund_id) return render_template(\"fund.html\", fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def fund_round(fund_id: str,",
"params search_params = { \"id_contains\": \"\", \"order_by\": \"\", \"order_rev\": \"\", \"status_only\": \"\", }",
"\"landing.html\", applications=applications, search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ] ), ) @assess_bp.route(\"/application/<application_id>\",",
"a keyword searchable and filterable list of applications and their statuses \"\"\" #",
"= get_todo_summary() return render_template( \"landing.html\", applications=applications, search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"),",
"@assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def fund(fund_id: str): \"\"\" Page showing available rounds for a given",
"\"\", \"order_by\": \"\", \"order_rev\": \"\", \"status_only\": \"\", } # Add request arg search",
"todo_summary=todo_summary, applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ] ), ) @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def application(application_id):",
"and all the application questions and their assessment status :param application_id: :return: \"\"\"",
"assess_bp = Blueprint( \"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", ) @assess_bp.route(\"/\", methods=[\"GET\"]) def funds(): \"\"\"",
"APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ] ), ) @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def application(application_id): \"\"\" Application summary page",
"\"\"\" Application summary page Shows information about the fund, application ID and all",
"Legacy The following routes serve information relating to individual funds and fund rounds",
"search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ] ), ) @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def",
"get_fund(application.fund_id) if not fund: abort(404) return render_template( \"application.html\", application=application, fund=fund ) \"\"\" Legacy",
"of applications and their statuses \"\"\" # Initialise empty search params search_params =",
"fund_round(fund_id: str, round_id: str): \"\"\" Page showing available applications from a given fund_id",
"if not fund: abort(404) return render_template( \"application.html\", application=application, fund=fund ) \"\"\" Legacy The",
"import request assess_bp = Blueprint( \"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", ) @assess_bp.route(\"/\", methods=[\"GET\"]) def",
"from app.config import APPLICATION_STORE_API_HOST_PUBLIC from app.config import ASSESSMENT_HUB_ROUTE from flask import abort from",
"the application store :param fund_id: :param round_id: :return: \"\"\" fund = get_fund(fund_id) if",
"search params search_params = { \"id_contains\": \"\", \"order_by\": \"\", \"order_rev\": \"\", \"status_only\": \"\",",
"application_id: :return: \"\"\" application = get_application_status(application_id=application_id) if not application: abort(404) fund = get_fund(application.fund_id)",
"\"\"), ] ), ) @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def application(application_id): \"\"\" Application summary page Shows",
"return render_template(\"fund.html\", fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def fund_round(fund_id: str, round_id: str): \"\"\" Page",
"# Initialise empty search params search_params = { \"id_contains\": \"\", \"order_by\": \"\", \"order_rev\":",
"\"\"\" fund = get_fund(fund_id) if not fund: abort(404) rounds = get_rounds(fund_id) return render_template(\"fund.html\",",
"request arg search params to dict for key, value in request.args.items(): if key",
"= get_funds() return render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"]) def landing(): \"\"\" Landing page for",
"information about the fund, application ID and all the application questions and their",
"from flask import render_template from flask import request assess_bp = Blueprint( \"assess_bp\", __name__,",
"fund: abort(404) rounds = get_rounds(fund_id) return render_template(\"fund.html\", fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def fund_round(fund_id:",
"\"application.html\", application=application, fund=fund ) \"\"\" Legacy The following routes serve information relating to",
"\"\"\" Legacy The following routes serve information relating to individual funds and fund",
"individual funds and fund rounds and are not shown in the assessor views",
"and their statuses \"\"\" # Initialise empty search params search_params = { \"id_contains\":",
") @assess_bp.route(\"/\", methods=[\"GET\"]) def funds(): \"\"\" Page showing available funds from fund store",
"abort(404) fund_round = get_round_with_applications( fund_id=fund_id, round_id=round_id ) if not fund_round: abort(404) return render_template(\"round.html\",",
"filterable list of applications and their statuses \"\"\" # Initialise empty search params",
"fund from round store :param fund_id: :return: \"\"\" fund = get_fund(fund_id) if not",
"= Blueprint( \"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", ) @assess_bp.route(\"/\", methods=[\"GET\"]) def funds(): \"\"\" Page",
"app.config import ASSESSMENT_HUB_ROUTE from flask import abort from flask import Blueprint from flask",
"not fund: abort(404) return render_template( \"application.html\", application=application, fund=fund ) \"\"\" Legacy The following",
"routes serve information relating to individual funds and fund rounds and are not",
":param fund_id: :param round_id: :return: \"\"\" fund = get_fund(fund_id) if not fund: abort(404)",
"\"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def fund(fund_id: str): \"\"\" Page showing available rounds for a",
"their statuses \"\"\" # Initialise empty search params search_params = { \"id_contains\": \"\",",
"get_application_status(application_id=application_id) if not application: abort(404) fund = get_fund(application.fund_id) if not fund: abort(404) return",
"def fund(fund_id: str): \"\"\" Page showing available rounds for a given fund from",
"given fund from round store :param fund_id: :return: \"\"\" fund = get_fund(fund_id) if",
":return: \"\"\" funds = get_funds() return render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"]) def landing(): \"\"\"",
"ASSESSMENT_HUB_ROUTE from flask import abort from flask import Blueprint from flask import render_template",
"Landing page for assessors Provides a summary of available applications with a keyword",
"import Blueprint from flask import render_template from flask import request assess_bp = Blueprint(",
"fund_id and round_id from the application store :param fund_id: :param round_id: :return: \"\"\"",
"template_folder=\"templates\", ) @assess_bp.route(\"/\", methods=[\"GET\"]) def funds(): \"\"\" Page showing available funds from fund",
"and are not shown in the assessor views \"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def fund(fund_id:",
"import APPLICATION_STORE_API_HOST_PUBLIC from app.config import ASSESSMENT_HUB_ROUTE from flask import abort from flask import",
"application=application, fund=fund ) \"\"\" Legacy The following routes serve information relating to individual",
"Blueprint( \"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", ) @assess_bp.route(\"/\", methods=[\"GET\"]) def funds(): \"\"\" Page showing",
"assessor views \"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def fund(fund_id: str): \"\"\" Page showing available rounds",
"fund_id: :param round_id: :return: \"\"\" fund = get_fund(fund_id) if not fund: abort(404) fund_round",
"summary page Shows information about the fund, application ID and all the application",
"round store :param fund_id: :return: \"\"\" fund = get_fund(fund_id) if not fund: abort(404)",
"available funds from fund store :return: \"\"\" funds = get_funds() return render_template(\"funds.html\", funds=funds)",
"if not fund: abort(404) fund_round = get_round_with_applications( fund_id=fund_id, round_id=round_id ) if not fund_round:",
"following routes serve information relating to individual funds and fund rounds and are",
"\"\"\" funds = get_funds() return render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"]) def landing(): \"\"\" Landing",
"value in request.args.items(): if key in search_params: search_params.update({key: value}) applications = get_applications(params=search_params) todo_summary",
":return: \"\"\" fund = get_fund(fund_id) if not fund: abort(404) fund_round = get_round_with_applications( fund_id=fund_id,",
"key, value in request.args.items(): if key in search_params: search_params.update({key: value}) applications = get_applications(params=search_params)",
"showing available funds from fund store :return: \"\"\" funds = get_funds() return render_template(\"funds.html\",",
"with a keyword searchable and filterable list of applications and their statuses \"\"\"",
"search params to dict for key, value in request.args.items(): if key in search_params:",
"render_template( \"landing.html\", applications=applications, search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ] ), )",
"todo_summary = get_todo_summary() return render_template( \"landing.html\", applications=applications, search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\",",
"), ) @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def application(application_id): \"\"\" Application summary page Shows information about",
"application store :param fund_id: :param round_id: :return: \"\"\" fund = get_fund(fund_id) if not",
"= get_application_status(application_id=application_id) if not application: abort(404) fund = get_fund(application.fund_id) if not fund: abort(404)",
"if not application: abort(404) fund = get_fund(application.fund_id) if not fund: abort(404) return render_template(",
"\"order_by\": \"\", \"order_rev\": \"\", \"status_only\": \"\", } # Add request arg search params",
"summary of available applications with a keyword searchable and filterable list of applications",
"from flask import Blueprint from flask import render_template from flask import request assess_bp",
"funds from fund store :return: \"\"\" funds = get_funds() return render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\",",
"applications from a given fund_id and round_id from the application store :param fund_id:",
"fund, application ID and all the application questions and their assessment status :param",
"store :param fund_id: :return: \"\"\" fund = get_fund(fund_id) if not fund: abort(404) rounds",
"app.assess.data import * from app.config import APPLICATION_STORE_API_HOST_PUBLIC from app.config import ASSESSMENT_HUB_ROUTE from flask",
"dict for key, value in request.args.items(): if key in search_params: search_params.update({key: value}) applications",
"get_fund(fund_id) if not fund: abort(404) fund_round = get_round_with_applications( fund_id=fund_id, round_id=round_id ) if not",
":return: \"\"\" fund = get_fund(fund_id) if not fund: abort(404) rounds = get_rounds(fund_id) return",
"serve information relating to individual funds and fund rounds and are not shown",
"import abort from flask import Blueprint from flask import render_template from flask import",
"from round store :param fund_id: :return: \"\"\" fund = get_fund(fund_id) if not fund:",
"applications with a keyword searchable and filterable list of applications and their statuses",
"request.args.items(): if key in search_params: search_params.update({key: value}) applications = get_applications(params=search_params) todo_summary = get_todo_summary()",
"assessment status :param application_id: :return: \"\"\" application = get_application_status(application_id=application_id) if not application: abort(404)",
"The following routes serve information relating to individual funds and fund rounds and",
"given fund_id and round_id from the application store :param fund_id: :param round_id: :return:",
"flask import request assess_bp = Blueprint( \"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", ) @assess_bp.route(\"/\", methods=[\"GET\"])",
"[ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ] ), ) @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def application(application_id): \"\"\" Application",
"views \"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def fund(fund_id: str): \"\"\" Page showing available rounds for",
"to individual funds and fund rounds and are not shown in the assessor",
"funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"]) def landing(): \"\"\" Landing page for assessors Provides a summary",
"abort(404) fund = get_fund(application.fund_id) if not fund: abort(404) return render_template( \"application.html\", application=application, fund=fund",
"in the assessor views \"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def fund(fund_id: str): \"\"\" Page showing",
"= get_fund(fund_id) if not fund: abort(404) fund_round = get_round_with_applications( fund_id=fund_id, round_id=round_id ) if",
"from a given fund_id and round_id from the application store :param fund_id: :param",
"and their assessment status :param application_id: :return: \"\"\" application = get_application_status(application_id=application_id) if not",
"search_params.update({key: value}) applications = get_applications(params=search_params) todo_summary = get_todo_summary() return render_template( \"landing.html\", applications=applications, search_params=search_params,",
"rounds for a given fund from round store :param fund_id: :return: \"\"\" fund",
"from the application store :param fund_id: :param round_id: :return: \"\"\" fund = get_fund(fund_id)",
"return render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"]) def landing(): \"\"\" Landing page for assessors Provides",
"fund = get_fund(fund_id) if not fund: abort(404) rounds = get_rounds(fund_id) return render_template(\"fund.html\", fund=fund,",
"funds(): \"\"\" Page showing available funds from fund store :return: \"\"\" funds =",
"import * from app.config import APPLICATION_STORE_API_HOST_PUBLIC from app.config import ASSESSMENT_HUB_ROUTE from flask import",
"round_id: :return: \"\"\" fund = get_fund(fund_id) if not fund: abort(404) fund_round = get_round_with_applications(",
"Initialise empty search params search_params = { \"id_contains\": \"\", \"order_by\": \"\", \"order_rev\": \"\",",
"render_template from flask import request assess_bp = Blueprint( \"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", )",
"search_params: search_params.update({key: value}) applications = get_applications(params=search_params) todo_summary = get_todo_summary() return render_template( \"landing.html\", applications=applications,",
"fund = get_fund(fund_id) if not fund: abort(404) fund_round = get_round_with_applications( fund_id=fund_id, round_id=round_id )",
") @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def application(application_id): \"\"\" Application summary page Shows information about the",
"to dict for key, value in request.args.items(): if key in search_params: search_params.update({key: value})",
"fund store :return: \"\"\" funds = get_funds() return render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"]) def",
"\"\", } # Add request arg search params to dict for key, value",
"flask import Blueprint from flask import render_template from flask import request assess_bp =",
"import render_template from flask import request assess_bp = Blueprint( \"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\",",
"fund: abort(404) return render_template( \"application.html\", application=application, fund=fund ) \"\"\" Legacy The following routes",
"application(application_id): \"\"\" Application summary page Shows information about the fund, application ID and",
"application: abort(404) fund = get_fund(application.fund_id) if not fund: abort(404) return render_template( \"application.html\", application=application,",
"return render_template( \"application.html\", application=application, fund=fund ) \"\"\" Legacy The following routes serve information",
"render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"]) def landing(): \"\"\" Landing page for assessors Provides a",
"methods=[\"GET\"]) def application(application_id): \"\"\" Application summary page Shows information about the fund, application",
"* from app.config import APPLICATION_STORE_API_HOST_PUBLIC from app.config import ASSESSMENT_HUB_ROUTE from flask import abort",
"= get_fund(fund_id) if not fund: abort(404) rounds = get_rounds(fund_id) return render_template(\"fund.html\", fund=fund, rounds=rounds)",
"a given fund_id and round_id from the application store :param fund_id: :param round_id:",
"# Add request arg search params to dict for key, value in request.args.items():",
"applications and their statuses \"\"\" # Initialise empty search params search_params = {",
"store :param fund_id: :param round_id: :return: \"\"\" fund = get_fund(fund_id) if not fund:",
"statuses \"\"\" # Initialise empty search params search_params = { \"id_contains\": \"\", \"order_by\":",
"applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ] ), ) @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def application(application_id): \"\"\"",
"store :return: \"\"\" funds = get_funds() return render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"]) def landing():",
"for key, value in request.args.items(): if key in search_params: search_params.update({key: value}) applications =",
"and filterable list of applications and their statuses \"\"\" # Initialise empty search",
"def fund_round(fund_id: str, round_id: str): \"\"\" Page showing available applications from a given",
"def application(application_id): \"\"\" Application summary page Shows information about the fund, application ID",
"url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", ) @assess_bp.route(\"/\", methods=[\"GET\"]) def funds(): \"\"\" Page showing available funds from",
"render_template( \"application.html\", application=application, fund=fund ) \"\"\" Legacy The following routes serve information relating",
"list of applications and their statuses \"\"\" # Initialise empty search params search_params",
"if not fund: abort(404) rounds = get_rounds(fund_id) return render_template(\"fund.html\", fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"])",
"for a given fund from round store :param fund_id: :return: \"\"\" fund =",
"empty search params search_params = { \"id_contains\": \"\", \"order_by\": \"\", \"order_rev\": \"\", \"status_only\":",
"from flask import abort from flask import Blueprint from flask import render_template from",
"methods=[\"GET\"]) def funds(): \"\"\" Page showing available funds from fund store :return: \"\"\"",
"flask import render_template from flask import request assess_bp = Blueprint( \"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE,",
"params to dict for key, value in request.args.items(): if key in search_params: search_params.update({key:",
"page Shows information about the fund, application ID and all the application questions",
"Page showing available rounds for a given fund from round store :param fund_id:",
"\"id_contains\": \"\", \"order_by\": \"\", \"order_rev\": \"\", \"status_only\": \"\", } # Add request arg",
"ID and all the application questions and their assessment status :param application_id: :return:",
"} # Add request arg search params to dict for key, value in",
"\"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", ) @assess_bp.route(\"/\", methods=[\"GET\"]) def funds(): \"\"\" Page showing available",
") \"\"\" Legacy The following routes serve information relating to individual funds and",
"Blueprint from flask import render_template from flask import request assess_bp = Blueprint( \"assess_bp\",",
"showing available rounds for a given fund from round store :param fund_id: :return:",
"Shows information about the fund, application ID and all the application questions and",
"a given fund from round store :param fund_id: :return: \"\"\" fund = get_fund(fund_id)",
"search_params = { \"id_contains\": \"\", \"order_by\": \"\", \"order_rev\": \"\", \"status_only\": \"\", } #",
"@assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def application(application_id): \"\"\" Application summary page Shows information about the fund,",
"fund_id: :return: \"\"\" fund = get_fund(fund_id) if not fund: abort(404) rounds = get_rounds(fund_id)",
"render_template(\"fund.html\", fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def fund_round(fund_id: str, round_id: str): \"\"\" Page showing",
"Application summary page Shows information about the fund, application ID and all the",
"fund_round = get_round_with_applications( fund_id=fund_id, round_id=round_id ) if not fund_round: abort(404) return render_template(\"round.html\", fund=fund,",
"application = get_application_status(application_id=application_id) if not application: abort(404) fund = get_fund(application.fund_id) if not fund:",
":param round_id: :return: \"\"\" fund = get_fund(fund_id) if not fund: abort(404) fund_round =",
"methods=[\"GET\"]) def landing(): \"\"\" Landing page for assessors Provides a summary of available",
"get_funds() return render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"]) def landing(): \"\"\" Landing page for assessors",
"= get_applications(params=search_params) todo_summary = get_todo_summary() return render_template( \"landing.html\", applications=applications, search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join( [",
"app.config import APPLICATION_STORE_API_HOST_PUBLIC from app.config import ASSESSMENT_HUB_ROUTE from flask import abort from flask",
"application ID and all the application questions and their assessment status :param application_id:",
"relating to individual funds and fund rounds and are not shown in the",
":param fund_id: :return: \"\"\" fund = get_fund(fund_id) if not fund: abort(404) rounds =",
"flask import abort from flask import Blueprint from flask import render_template from flask",
"\"\", \"order_rev\": \"\", \"status_only\": \"\", } # Add request arg search params to",
"get_rounds(fund_id) return render_template(\"fund.html\", fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def fund_round(fund_id: str, round_id: str): \"\"\"",
"fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def fund_round(fund_id: str, round_id: str): \"\"\" Page showing available",
"status :param application_id: :return: \"\"\" application = get_application_status(application_id=application_id) if not application: abort(404) fund",
"arg search params to dict for key, value in request.args.items(): if key in",
"def landing(): \"\"\" Landing page for assessors Provides a summary of available applications",
"\"\"\" application = get_application_status(application_id=application_id) if not application: abort(404) fund = get_fund(application.fund_id) if not",
"not fund: abort(404) fund_round = get_round_with_applications( fund_id=fund_id, round_id=round_id ) if not fund_round: abort(404)",
"questions and their assessment status :param application_id: :return: \"\"\" application = get_application_status(application_id=application_id) if",
"searchable and filterable list of applications and their statuses \"\"\" # Initialise empty",
"{ \"id_contains\": \"\", \"order_by\": \"\", \"order_rev\": \"\", \"status_only\": \"\", } # Add request",
"keyword searchable and filterable list of applications and their statuses \"\"\" # Initialise",
"get_applications(params=search_params) todo_summary = get_todo_summary() return render_template( \"landing.html\", applications=applications, search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC,",
"from app.assess.data import * from app.config import APPLICATION_STORE_API_HOST_PUBLIC from app.config import ASSESSMENT_HUB_ROUTE from",
"and fund rounds and are not shown in the assessor views \"\"\" @assess_bp.route(\"/<fund_id>/\",",
"\"\"\" Landing page for assessors Provides a summary of available applications with a",
"str): \"\"\" Page showing available rounds for a given fund from round store",
"rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def fund_round(fund_id: str, round_id: str): \"\"\" Page showing available applications",
"rounds and are not shown in the assessor views \"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def",
"__name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", ) @assess_bp.route(\"/\", methods=[\"GET\"]) def funds(): \"\"\" Page showing available funds",
"landing(): \"\"\" Landing page for assessors Provides a summary of available applications with",
"and round_id from the application store :param fund_id: :param round_id: :return: \"\"\" fund",
"of available applications with a keyword searchable and filterable list of applications and",
"def funds(): \"\"\" Page showing available funds from fund store :return: \"\"\" funds",
"page for assessors Provides a summary of available applications with a keyword searchable",
"return render_template( \"landing.html\", applications=applications, search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ] ),",
"\"status_only\": \"\", } # Add request arg search params to dict for key,",
"key in search_params: search_params.update({key: value}) applications = get_applications(params=search_params) todo_summary = get_todo_summary() return render_template(",
"in search_params: search_params.update({key: value}) applications = get_applications(params=search_params) todo_summary = get_todo_summary() return render_template( \"landing.html\",",
"] ), ) @assess_bp.route(\"/application/<application_id>\", methods=[\"GET\"]) def application(application_id): \"\"\" Application summary page Shows information",
"= get_round_with_applications( fund_id=fund_id, round_id=round_id ) if not fund_round: abort(404) return render_template(\"round.html\", fund=fund, round=fund_round)",
"are not shown in the assessor views \"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def fund(fund_id: str):",
"not shown in the assessor views \"\"\" @assess_bp.route(\"/<fund_id>/\", methods=[\"GET\"]) def fund(fund_id: str): \"\"\"",
"fund: abort(404) fund_round = get_round_with_applications( fund_id=fund_id, round_id=round_id ) if not fund_round: abort(404) return",
"from flask import request assess_bp = Blueprint( \"assess_bp\", __name__, url_prefix=ASSESSMENT_HUB_ROUTE, template_folder=\"templates\", ) @assess_bp.route(\"/\",",
"application questions and their assessment status :param application_id: :return: \"\"\" application = get_application_status(application_id=application_id)",
"\"\"\" Page showing available funds from fund store :return: \"\"\" funds = get_funds()",
"\"\"\" # Initialise empty search params search_params = { \"id_contains\": \"\", \"order_by\": \"\",",
"for assessors Provides a summary of available applications with a keyword searchable and",
"get_fund(fund_id) if not fund: abort(404) rounds = get_rounds(fund_id) return render_template(\"fund.html\", fund=fund, rounds=rounds) @assess_bp.route(\"/<fund_id>/<round_id>/\",",
"funds = get_funds() return render_template(\"funds.html\", funds=funds) @assess_bp.route(\"/landing/\", methods=[\"GET\"]) def landing(): \"\"\" Landing page",
"\"\"\" fund = get_fund(fund_id) if not fund: abort(404) fund_round = get_round_with_applications( fund_id=fund_id, round_id=round_id",
"@assess_bp.route(\"/\", methods=[\"GET\"]) def funds(): \"\"\" Page showing available funds from fund store :return:",
"information relating to individual funds and fund rounds and are not shown in",
"about the fund, application ID and all the application questions and their assessment",
":return: \"\"\" application = get_application_status(application_id=application_id) if not application: abort(404) fund = get_fund(application.fund_id) if",
"abort from flask import Blueprint from flask import render_template from flask import request",
"assessors Provides a summary of available applications with a keyword searchable and filterable",
"available applications with a keyword searchable and filterable list of applications and their",
"= get_fund(application.fund_id) if not fund: abort(404) return render_template( \"application.html\", application=application, fund=fund ) \"\"\"",
"funds and fund rounds and are not shown in the assessor views \"\"\"",
"fund(fund_id: str): \"\"\" Page showing available rounds for a given fund from round",
"@assess_bp.route(\"/<fund_id>/<round_id>/\", methods=[\"GET\"]) def fund_round(fund_id: str, round_id: str): \"\"\" Page showing available applications from",
"round_id: str): \"\"\" Page showing available applications from a given fund_id and round_id",
"showing available applications from a given fund_id and round_id from the application store",
"get_todo_summary() return render_template( \"landing.html\", applications=applications, search_params=search_params, todo_summary=todo_summary, applications_endpoint=\"\".join( [ APPLICATION_STORE_API_HOST_PUBLIC, APPLICATION_SEARCH_ENDPOINT.replace(\"{params}\", \"\"), ]"
] |
[
"in u.like: t = l.rstrip('/') try: t = isbn.index(t) except: continue t_list.append(t) like.append(t_list)",
"수정 books_file_name = 'API_test_books.csv' # 환경에 맞게 수정 df_books = pd.read_csv(file_path + books_file_name)",
"numpy as np def update(): ''' books = database.Book.objects() isbn = [] for",
"name = [] email = [] password = [] user_id = [] like",
"= database.User.objects() name = [] email = [] password = [] user_id =",
"[] for u in users: t_list = [] for l in u.like: t",
"[] for l in u.like: t = l.rstrip('/') try: t = isbn.index(t) except:",
"in books: isbn.append(b.isbn) ''' file_path = '/var/www/python_flask/main/recommendation/' # 환경에 맞게 수정 books_file_name =",
"'dummy_users.csv' # 환경에 맞게 수정 df_dummy_user = pd.read_csv(file_path + dummy_file_name) users = database.User.objects()",
"books = database.Book.objects() isbn = [] for b in books: isbn.append(b.isbn) ''' file_path",
"df_books = pd.read_csv(file_path + books_file_name) isbn = list(np.array(df_books['isbn']).tolist()) dummy_file_name = 'dummy_users.csv' # 환경에",
"try: t = isbn.index(t) except: continue t_list.append(t) like.append(t_list) name.append(u.name) email.append(u.email) password.append(<PASSWORD>) user_id.append(u.user_id) rank.append(u.rank)",
"as pd import numpy as np def update(): ''' books = database.Book.objects() isbn",
"''' books = database.Book.objects() isbn = [] for b in books: isbn.append(b.isbn) '''",
"l in u.like: t = l.rstrip('/') try: t = isbn.index(t) except: continue t_list.append(t)",
"pandas as pd import numpy as np def update(): ''' books = database.Book.objects()",
"''' file_path = '/var/www/python_flask/main/recommendation/' # 환경에 맞게 수정 books_file_name = 'API_test_books.csv' # 환경에",
"= pd.read_csv(file_path + books_file_name) isbn = list(np.array(df_books['isbn']).tolist()) dummy_file_name = 'dummy_users.csv' # 환경에 맞게",
"database import pandas as pd import numpy as np def update(): ''' books",
"sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))) from main.models import database import pandas as pd import numpy as np",
"= [] rank = [] unit = [] for u in users: t_list",
"import pandas as pd import numpy as np def update(): ''' books =",
"file_path = '/var/www/python_flask/main/recommendation/' # 환경에 맞게 수정 books_file_name = 'API_test_books.csv' # 환경에 맞게",
"password = [] user_id = [] like = [] rank = [] unit",
"os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))) from main.models import database import pandas as pd",
"import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))) from main.models import database import pandas as pd import",
"[] email = [] password = [] user_id = [] like = []",
"l.rstrip('/') try: t = isbn.index(t) except: continue t_list.append(t) like.append(t_list) name.append(u.name) email.append(u.email) password.append(<PASSWORD>) user_id.append(u.user_id)",
"as np def update(): ''' books = database.Book.objects() isbn = [] for b",
"sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))) from main.models import database import pandas as pd import numpy",
"pd.read_csv(file_path + books_file_name) isbn = list(np.array(df_books['isbn']).tolist()) dummy_file_name = 'dummy_users.csv' # 환경에 맞게 수정",
"+ dummy_file_name) users = database.User.objects() name = [] email = [] password =",
"[] user_id = [] like = [] rank = [] unit = []",
"users: t_list = [] for l in u.like: t = l.rstrip('/') try: t",
"= l.rstrip('/') try: t = isbn.index(t) except: continue t_list.append(t) like.append(t_list) name.append(u.name) email.append(u.email) password.append(<PASSWORD>)",
"list(np.array(df_books['isbn']).tolist()) dummy_file_name = 'dummy_users.csv' # 환경에 맞게 수정 df_dummy_user = pd.read_csv(file_path + dummy_file_name)",
"'/var/www/python_flask/main/recommendation/' # 환경에 맞게 수정 books_file_name = 'API_test_books.csv' # 환경에 맞게 수정 df_books",
"= list(np.array(df_books['isbn']).tolist()) dummy_file_name = 'dummy_users.csv' # 환경에 맞게 수정 df_dummy_user = pd.read_csv(file_path +",
"user_id = [] like = [] rank = [] unit = [] for",
"# 환경에 맞게 수정 books_file_name = 'API_test_books.csv' # 환경에 맞게 수정 df_books =",
"맞게 수정 df_books = pd.read_csv(file_path + books_file_name) isbn = list(np.array(df_books['isbn']).tolist()) dummy_file_name = 'dummy_users.csv'",
"def update(): ''' books = database.Book.objects() isbn = [] for b in books:",
"수정 df_books = pd.read_csv(file_path + books_file_name) isbn = list(np.array(df_books['isbn']).tolist()) dummy_file_name = 'dummy_users.csv' #",
"[] rank = [] unit = [] for u in users: t_list =",
"dummy_file_name) users = database.User.objects() name = [] email = [] password = []",
"database.User.objects() name = [] email = [] password = [] user_id = []",
"환경에 맞게 수정 df_dummy_user = pd.read_csv(file_path + dummy_file_name) users = database.User.objects() name =",
"[] password = [] user_id = [] like = [] rank = []",
"rank = [] unit = [] for u in users: t_list = []",
"database.Book.objects() isbn = [] for b in books: isbn.append(b.isbn) ''' file_path = '/var/www/python_flask/main/recommendation/'",
"users = database.User.objects() name = [] email = [] password = [] user_id",
"in users: t_list = [] for l in u.like: t = l.rstrip('/') try:",
"dummy_file_name = 'dummy_users.csv' # 환경에 맞게 수정 df_dummy_user = pd.read_csv(file_path + dummy_file_name) users",
"수정 df_dummy_user = pd.read_csv(file_path + dummy_file_name) users = database.User.objects() name = [] email",
"= [] like = [] rank = [] unit = [] for u",
"books: isbn.append(b.isbn) ''' file_path = '/var/www/python_flask/main/recommendation/' # 환경에 맞게 수정 books_file_name = 'API_test_books.csv'",
"u.like: t = l.rstrip('/') try: t = isbn.index(t) except: continue t_list.append(t) like.append(t_list) name.append(u.name)",
"= pd.read_csv(file_path + dummy_file_name) users = database.User.objects() name = [] email = []",
"like = [] rank = [] unit = [] for u in users:",
"'API_test_books.csv' # 환경에 맞게 수정 df_books = pd.read_csv(file_path + books_file_name) isbn = list(np.array(df_books['isbn']).tolist())",
"= [] unit = [] for u in users: t_list = [] for",
"= [] password = [] user_id = [] like = [] rank =",
"[] unit = [] for u in users: t_list = [] for l",
"for u in users: t_list = [] for l in u.like: t =",
"email = [] password = [] user_id = [] like = [] rank",
"= [] for u in users: t_list = [] for l in u.like:",
"update(): ''' books = database.Book.objects() isbn = [] for b in books: isbn.append(b.isbn)",
"import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))) from main.models import database import pandas as",
"<reponame>osamhack2021/AI_APP_handylib_devlib<filename>AI/recommendation/data_update.py<gh_stars>1-10 import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))) from main.models import database import pandas",
"books_file_name = 'API_test_books.csv' # 환경에 맞게 수정 df_books = pd.read_csv(file_path + books_file_name) isbn",
"np def update(): ''' books = database.Book.objects() isbn = [] for b in",
"환경에 맞게 수정 books_file_name = 'API_test_books.csv' # 환경에 맞게 수정 df_books = pd.read_csv(file_path",
"unit = [] for u in users: t_list = [] for l in",
"df_dummy_user = pd.read_csv(file_path + dummy_file_name) users = database.User.objects() name = [] email =",
"import numpy as np def update(): ''' books = database.Book.objects() isbn = []",
"isbn = [] for b in books: isbn.append(b.isbn) ''' file_path = '/var/www/python_flask/main/recommendation/' #",
"sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))) from main.models import database import pandas as pd import numpy as",
"for l in u.like: t = l.rstrip('/') try: t = isbn.index(t) except: continue",
"[] for b in books: isbn.append(b.isbn) ''' file_path = '/var/www/python_flask/main/recommendation/' # 환경에 맞게",
"# 환경에 맞게 수정 df_books = pd.read_csv(file_path + books_file_name) isbn = list(np.array(df_books['isbn']).tolist()) dummy_file_name",
"+ books_file_name) isbn = list(np.array(df_books['isbn']).tolist()) dummy_file_name = 'dummy_users.csv' # 환경에 맞게 수정 df_dummy_user",
"main.models import database import pandas as pd import numpy as np def update():",
"# 환경에 맞게 수정 df_dummy_user = pd.read_csv(file_path + dummy_file_name) users = database.User.objects() name",
"from main.models import database import pandas as pd import numpy as np def",
"= [] user_id = [] like = [] rank = [] unit =",
"pd.read_csv(file_path + dummy_file_name) users = database.User.objects() name = [] email = [] password",
"환경에 맞게 수정 df_books = pd.read_csv(file_path + books_file_name) isbn = list(np.array(df_books['isbn']).tolist()) dummy_file_name =",
"맞게 수정 df_dummy_user = pd.read_csv(file_path + dummy_file_name) users = database.User.objects() name = []",
"= [] for l in u.like: t = l.rstrip('/') try: t = isbn.index(t)",
"[] like = [] rank = [] unit = [] for u in",
"= 'dummy_users.csv' # 환경에 맞게 수정 df_dummy_user = pd.read_csv(file_path + dummy_file_name) users =",
"pd import numpy as np def update(): ''' books = database.Book.objects() isbn =",
"맞게 수정 books_file_name = 'API_test_books.csv' # 환경에 맞게 수정 df_books = pd.read_csv(file_path +",
"t_list = [] for l in u.like: t = l.rstrip('/') try: t =",
"= database.Book.objects() isbn = [] for b in books: isbn.append(b.isbn) ''' file_path =",
"isbn = list(np.array(df_books['isbn']).tolist()) dummy_file_name = 'dummy_users.csv' # 환경에 맞게 수정 df_dummy_user = pd.read_csv(file_path",
"books_file_name) isbn = list(np.array(df_books['isbn']).tolist()) dummy_file_name = 'dummy_users.csv' # 환경에 맞게 수정 df_dummy_user =",
"= '/var/www/python_flask/main/recommendation/' # 환경에 맞게 수정 books_file_name = 'API_test_books.csv' # 환경에 맞게 수정",
"isbn.append(b.isbn) ''' file_path = '/var/www/python_flask/main/recommendation/' # 환경에 맞게 수정 books_file_name = 'API_test_books.csv' #",
"= [] for b in books: isbn.append(b.isbn) ''' file_path = '/var/www/python_flask/main/recommendation/' # 환경에",
"for b in books: isbn.append(b.isbn) ''' file_path = '/var/www/python_flask/main/recommendation/' # 환경에 맞게 수정",
"b in books: isbn.append(b.isbn) ''' file_path = '/var/www/python_flask/main/recommendation/' # 환경에 맞게 수정 books_file_name",
"= 'API_test_books.csv' # 환경에 맞게 수정 df_books = pd.read_csv(file_path + books_file_name) isbn =",
"t = l.rstrip('/') try: t = isbn.index(t) except: continue t_list.append(t) like.append(t_list) name.append(u.name) email.append(u.email)",
"import database import pandas as pd import numpy as np def update(): '''",
"= [] email = [] password = [] user_id = [] like =",
"t = isbn.index(t) except: continue t_list.append(t) like.append(t_list) name.append(u.name) email.append(u.email) password.append(<PASSWORD>) user_id.append(u.user_id) rank.append(u.rank) unit.append(u.unit)",
"u in users: t_list = [] for l in u.like: t = l.rstrip('/')"
] |
[] |
[
"I*1./Gsmall.order(), ':', color = color) t, S, I, R = EoN.fast_SIR(Gbig, tau, gamma,",
"(1-rho)*Psi(x), lambda x: (1-rho)*DPsi(x), tau, gamma, 1-rho) I = EoN.subsample(report_times, t, I) plt.plot(report_times,",
"return (x**8 +x**2)/2. def DPsiBimodal(x): return(8*x**7 + 2*x)/2. def homogeneous(): return 5 def",
"# return k def PsiPowLaw(x): #print PlPk rval = 0 for k in",
"+= k*PlPk[k]*x**(k-1) return rval def get_G(N, Pk): while True: ks = [] for",
"= scipy.linspace(0,20,41) def process_degree_distribution(Gbig, Gsmall, color, Psi, DPsi, symbol): t, S, I, R",
"markeredgecolor='k') #<NAME> Gsmall = nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig = nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall, colors[0],",
"Nsmall = 5000 tau =0.4 gamma = 1. def poisson(): return scipy.random.poisson(5) def",
"gamma, rho=rho) plt.plot(t, I*1./Gbig.order(), color = color) N= Gbig.order()#N is arbitrary, but included",
"= get_G(Nsmall, {5:1.}) Gbig = get_G(Nbig, {5:1.}) process_degree_distribution(Gbig, Gsmall, colors[2], PsiHomogeneous, DPsiHomogeneous, 's')",
"Pk: if r<Pk[k]: break else: r-= Pk[k] ks.append(k) if sum(ks)%2==0: break G =",
"break G = nx.configuration_model(ks) return G report_times = scipy.linspace(0,20,41) def process_degree_distribution(Gbig, Gsmall, color,",
"N= Gbig.order()#N is arbitrary, but included because our implementation of EBCM assumes N",
"nx.configuration_model(ks) return G report_times = scipy.linspace(0,20,41) def process_degree_distribution(Gbig, Gsmall, color, Psi, DPsi, symbol):",
"rval def DPsiPowLaw(x): rval = 0 for k in PlPk: rval += k*PlPk[k]*x**(k-1)",
"k in PlPk: # r -= PlPk[k] # if r<0: # return k",
"def PsiHomogeneous(x): return x**5 def DPsiHomogeneous(x): return 5*x**4 PlPk = {} exponent =",
"PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave += k*PlPk[k] normfact= sum(PlPk.values()) for k in PlPk: PlPk[k] /= normfact",
"= 1. def poisson(): return scipy.random.poisson(5) def PsiPoisson(x): return scipy.exp(-5*(1-x)) def DPsiPoisson(x): return",
"PlPk: # r -= PlPk[k] # if r<0: # return k def PsiPowLaw(x):",
"PsiPoisson, DPsiPoisson, '^') #Bimodal Gsmall = get_G(Nsmall, bimodalPk) Gbig = get_G(Nbig, bimodalPk) process_degree_distribution(Gbig,",
"#Bimodal Gsmall = get_G(Nsmall, bimodalPk) Gbig = get_G(Nbig, bimodalPk) process_degree_distribution(Gbig, Gsmall, colors[1], PsiBimodal,",
"given. t, S, I, R = EoN.EBCM(N, lambda x: (1-rho)*Psi(x), lambda x: (1-rho)*DPsi(x),",
"poisson(): return scipy.random.poisson(5) def PsiPoisson(x): return scipy.exp(-5*(1-x)) def DPsiPoisson(x): return 5*scipy.exp(-5*(1-x)) bimodalPk =",
"colors[1], PsiBimodal, DPsiBimodal, 'o') #Homogeneous Gsmall = get_G(Nsmall, {5:1.}) Gbig = get_G(Nbig, {5:1.})",
"in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave += k*PlPk[k] normfact= sum(PlPk.values()) for k in PlPk: PlPk[k]",
"sum(ks)%2==0: break G = nx.configuration_model(ks) return G report_times = scipy.linspace(0,20,41) def process_degree_distribution(Gbig, Gsmall,",
"# if r<0: # return k def PsiPowLaw(x): #print PlPk rval = 0",
"{5:1.}) Gbig = get_G(Nbig, {5:1.}) process_degree_distribution(Gbig, Gsmall, colors[2], PsiHomogeneous, DPsiHomogeneous, 's') #Powerlaw Gsmall",
"= [] for ctr in range(N): r = random.random() for k in Pk:",
"[] for ctr in range(N): r = random.random() for k in Pk: if",
"0.01 Nbig=500000 Nsmall = 5000 tau =0.4 gamma = 1. def poisson(): return",
"'^') #Bimodal Gsmall = get_G(Nsmall, bimodalPk) Gbig = get_G(Nbig, bimodalPk) process_degree_distribution(Gbig, Gsmall, colors[1],",
"def PsiPowLaw(x): #print PlPk rval = 0 for k in PlPk: rval +=",
"G report_times = scipy.linspace(0,20,41) def process_degree_distribution(Gbig, Gsmall, color, Psi, DPsi, symbol): t, S,",
"x: (1-rho)*DPsi(x), tau, gamma, 1-rho) I = EoN.subsample(report_times, t, I) plt.plot(report_times, I/N, symbol,",
"=0.4 gamma = 1. def poisson(): return scipy.random.poisson(5) def PsiPoisson(x): return scipy.exp(-5*(1-x)) def",
"return rval def get_G(N, Pk): while True: ks = [] for ctr in",
"def DPsiHomogeneous(x): return 5*x**4 PlPk = {} exponent = 1.418184432 kave = 0",
"EoN.subsample(report_times, t, I) plt.plot(report_times, I/N, symbol, color = color, markeredgecolor='k') #<NAME> Gsmall =",
"tau, gamma, rho=rho) plt.plot(t, I*1./Gsmall.order(), ':', color = color) t, S, I, R",
"trunc_pow_law(): # r = random.random() # for k in PlPk: # r -=",
"gamma = 1. def poisson(): return scipy.random.poisson(5) def PsiPoisson(x): return scipy.exp(-5*(1-x)) def DPsiPoisson(x):",
"plt import scipy import random colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] rho = 0.01",
"is arbitrary, but included because our implementation of EBCM assumes N is given.",
"Pk): while True: ks = [] for ctr in range(N): r = random.random()",
"= 0 for k in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave += k*PlPk[k] normfact= sum(PlPk.values()) for",
"# r = random.random() # for k in PlPk: # r -= PlPk[k]",
"import networkx as nx import EoN from collections import defaultdict import matplotlib.pyplot as",
"PlPk[k] /= normfact #def trunc_pow_law(): # r = random.random() # for k in",
"#<NAME> Gsmall = nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig = nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall, colors[0], PsiPoisson,",
"implementation of EBCM assumes N is given. t, S, I, R = EoN.EBCM(N,",
"get_G(Nbig, bimodalPk) process_degree_distribution(Gbig, Gsmall, colors[1], PsiBimodal, DPsiBimodal, 'o') #Homogeneous Gsmall = get_G(Nsmall, {5:1.})",
"Gsmall = get_G(Nsmall, {5:1.}) Gbig = get_G(Nbig, {5:1.}) process_degree_distribution(Gbig, Gsmall, colors[2], PsiHomogeneous, DPsiHomogeneous,",
"def DPsiPowLaw(x): rval = 0 for k in PlPk: rval += k*PlPk[k]*x**(k-1) return",
"+= PlPk[k]*x**k return rval def DPsiPowLaw(x): rval = 0 for k in PlPk:",
"['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] rho = 0.01 Nbig=500000 Nsmall = 5000 tau =0.4 gamma",
"k in PlPk: rval += PlPk[k]*x**k return rval def DPsiPowLaw(x): rval = 0",
"random colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] rho = 0.01 Nbig=500000 Nsmall = 5000",
"Gbig = nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall, colors[0], PsiPoisson, DPsiPoisson, '^') #Bimodal Gsmall =",
"5*x**4 PlPk = {} exponent = 1.418184432 kave = 0 for k in",
"r<0: # return k def PsiPowLaw(x): #print PlPk rval = 0 for k",
"I = EoN.subsample(report_times, t, I) plt.plot(report_times, I/N, symbol, color = color, markeredgecolor='k') #<NAME>",
"our implementation of EBCM assumes N is given. t, S, I, R =",
"ks = [] for ctr in range(N): r = random.random() for k in",
"PsiBimodal(x): return (x**8 +x**2)/2. def DPsiBimodal(x): return(8*x**7 + 2*x)/2. def homogeneous(): return 5",
"scipy.linspace(0,20,41) def process_degree_distribution(Gbig, Gsmall, color, Psi, DPsi, symbol): t, S, I, R =",
"= random.random() for k in Pk: if r<Pk[k]: break else: r-= Pk[k] ks.append(k)",
"get_G(Nbig, PlPk) process_degree_distribution(Gbig, Gsmall, colors[3], PsiPowLaw, DPsiPowLaw, 'd') plt.axis(xmin=0, ymin=0, xmax = 20,",
"nx import EoN from collections import defaultdict import matplotlib.pyplot as plt import scipy",
"colors[2], PsiHomogeneous, DPsiHomogeneous, 's') #Powerlaw Gsmall = get_G(Nsmall, PlPk) Gbig = get_G(Nbig, PlPk)",
"range(N): r = random.random() for k in Pk: if r<Pk[k]: break else: r-=",
"r = random.random() # for k in PlPk: # r -= PlPk[k] #",
"x: (1-rho)*Psi(x), lambda x: (1-rho)*DPsi(x), tau, gamma, 1-rho) I = EoN.subsample(report_times, t, I)",
"R = EoN.fast_SIR(Gbig, tau, gamma, rho=rho) plt.plot(t, I*1./Gbig.order(), color = color) N= Gbig.order()#N",
"process_degree_distribution(Gbig, Gsmall, color, Psi, DPsi, symbol): t, S, I, R = EoN.fast_SIR(Gsmall, tau,",
"plt.plot(t, I*1./Gsmall.order(), ':', color = color) t, S, I, R = EoN.fast_SIR(Gbig, tau,",
"Psi, DPsi, symbol): t, S, I, R = EoN.fast_SIR(Gsmall, tau, gamma, rho=rho) plt.plot(t,",
"collections import defaultdict import matplotlib.pyplot as plt import scipy import random colors =",
"-= PlPk[k] # if r<0: # return k def PsiPowLaw(x): #print PlPk rval",
"Nbig=500000 Nsmall = 5000 tau =0.4 gamma = 1. def poisson(): return scipy.random.poisson(5)",
"def PsiBimodal(x): return (x**8 +x**2)/2. def DPsiBimodal(x): return(8*x**7 + 2*x)/2. def homogeneous(): return",
"+= k*PlPk[k] normfact= sum(PlPk.values()) for k in PlPk: PlPk[k] /= normfact #def trunc_pow_law():",
"color, markeredgecolor='k') #<NAME> Gsmall = nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig = nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall,",
"lambda x: (1-rho)*Psi(x), lambda x: (1-rho)*DPsi(x), tau, gamma, 1-rho) I = EoN.subsample(report_times, t,",
"because our implementation of EBCM assumes N is given. t, S, I, R",
"nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig = nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall, colors[0], PsiPoisson, DPsiPoisson, '^') #Bimodal",
"DPsiHomogeneous(x): return 5*x**4 PlPk = {} exponent = 1.418184432 kave = 0 for",
"k in PlPk: rval += k*PlPk[k]*x**(k-1) return rval def get_G(N, Pk): while True:",
"2*x)/2. def homogeneous(): return 5 def PsiHomogeneous(x): return x**5 def DPsiHomogeneous(x): return 5*x**4",
"Pk[k] ks.append(k) if sum(ks)%2==0: break G = nx.configuration_model(ks) return G report_times = scipy.linspace(0,20,41)",
"color = color, markeredgecolor='k') #<NAME> Gsmall = nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig = nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1))",
"for k in Pk: if r<Pk[k]: break else: r-= Pk[k] ks.append(k) if sum(ks)%2==0:",
"DPsiPoisson, '^') #Bimodal Gsmall = get_G(Nsmall, bimodalPk) Gbig = get_G(Nbig, bimodalPk) process_degree_distribution(Gbig, Gsmall,",
"return 5*x**4 PlPk = {} exponent = 1.418184432 kave = 0 for k",
"homogeneous(): return 5 def PsiHomogeneous(x): return x**5 def DPsiHomogeneous(x): return 5*x**4 PlPk =",
"0 for k in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave += k*PlPk[k] normfact= sum(PlPk.values()) for k",
"gamma, 1-rho) I = EoN.subsample(report_times, t, I) plt.plot(report_times, I/N, symbol, color = color,",
"I) plt.plot(report_times, I/N, symbol, color = color, markeredgecolor='k') #<NAME> Gsmall = nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1))",
"t, S, I, R = EoN.EBCM(N, lambda x: (1-rho)*Psi(x), lambda x: (1-rho)*DPsi(x), tau,",
"'#0073B3','#F0E442'] rho = 0.01 Nbig=500000 Nsmall = 5000 tau =0.4 gamma = 1.",
"process_degree_distribution(Gbig, Gsmall, colors[2], PsiHomogeneous, DPsiHomogeneous, 's') #Powerlaw Gsmall = get_G(Nsmall, PlPk) Gbig =",
"color) t, S, I, R = EoN.fast_SIR(Gbig, tau, gamma, rho=rho) plt.plot(t, I*1./Gbig.order(), color",
"for k in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave += k*PlPk[k] normfact= sum(PlPk.values()) for k in",
"in range(N): r = random.random() for k in Pk: if r<Pk[k]: break else:",
"5./(Nsmall-1)) Gbig = nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall, colors[0], PsiPoisson, DPsiPoisson, '^') #Bimodal Gsmall",
"exponent = 1.418184432 kave = 0 for k in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave +=",
"= random.random() # for k in PlPk: # r -= PlPk[k] # if",
"Gbig.order()#N is arbitrary, but included because our implementation of EBCM assumes N is",
"{5:1.}) process_degree_distribution(Gbig, Gsmall, colors[2], PsiHomogeneous, DPsiHomogeneous, 's') #Powerlaw Gsmall = get_G(Nsmall, PlPk) Gbig",
"'#CD9AB3', '#0073B3','#F0E442'] rho = 0.01 Nbig=500000 Nsmall = 5000 tau =0.4 gamma =",
"k*PlPk[k]*x**(k-1) return rval def get_G(N, Pk): while True: ks = [] for ctr",
"k in Pk: if r<Pk[k]: break else: r-= Pk[k] ks.append(k) if sum(ks)%2==0: break",
"colors[3], PsiPowLaw, DPsiPowLaw, 'd') plt.axis(xmin=0, ymin=0, xmax = 20, ymax = 0.2) plt.xlabel('$t$')",
"ks.append(k) if sum(ks)%2==0: break G = nx.configuration_model(ks) return G report_times = scipy.linspace(0,20,41) def",
"EBCM assumes N is given. t, S, I, R = EoN.EBCM(N, lambda x:",
"I/N, symbol, color = color, markeredgecolor='k') #<NAME> Gsmall = nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig =",
"Gsmall = get_G(Nsmall, PlPk) Gbig = get_G(Nbig, PlPk) process_degree_distribution(Gbig, Gsmall, colors[3], PsiPowLaw, DPsiPowLaw,",
"color) N= Gbig.order()#N is arbitrary, but included because our implementation of EBCM assumes",
"symbol, color = color, markeredgecolor='k') #<NAME> Gsmall = nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig = nx.fast_gnp_random_graph(Nbig,",
"5000 tau =0.4 gamma = 1. def poisson(): return scipy.random.poisson(5) def PsiPoisson(x): return",
"for k in PlPk: rval += PlPk[k]*x**k return rval def DPsiPowLaw(x): rval =",
"k in PlPk: PlPk[k] /= normfact #def trunc_pow_law(): # r = random.random() #",
"return scipy.random.poisson(5) def PsiPoisson(x): return scipy.exp(-5*(1-x)) def DPsiPoisson(x): return 5*scipy.exp(-5*(1-x)) bimodalPk = {8:0.5,",
"lambda x: (1-rho)*DPsi(x), tau, gamma, 1-rho) I = EoN.subsample(report_times, t, I) plt.plot(report_times, I/N,",
"rval = 0 for k in PlPk: rval += PlPk[k]*x**k return rval def",
"= 0.01 Nbig=500000 Nsmall = 5000 tau =0.4 gamma = 1. def poisson():",
"normfact #def trunc_pow_law(): # r = random.random() # for k in PlPk: #",
"= EoN.subsample(report_times, t, I) plt.plot(report_times, I/N, symbol, color = color, markeredgecolor='k') #<NAME> Gsmall",
"sum(PlPk.values()) for k in PlPk: PlPk[k] /= normfact #def trunc_pow_law(): # r =",
"DPsiBimodal(x): return(8*x**7 + 2*x)/2. def homogeneous(): return 5 def PsiHomogeneous(x): return x**5 def",
"= {} exponent = 1.418184432 kave = 0 for k in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40)",
"import EoN from collections import defaultdict import matplotlib.pyplot as plt import scipy import",
"as plt import scipy import random colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] rho =",
"EoN.fast_SIR(Gsmall, tau, gamma, rho=rho) plt.plot(t, I*1./Gsmall.order(), ':', color = color) t, S, I,",
"= color) t, S, I, R = EoN.fast_SIR(Gbig, tau, gamma, rho=rho) plt.plot(t, I*1./Gbig.order(),",
"+x**2)/2. def DPsiBimodal(x): return(8*x**7 + 2*x)/2. def homogeneous(): return 5 def PsiHomogeneous(x): return",
"rho=rho) plt.plot(t, I*1./Gbig.order(), color = color) N= Gbig.order()#N is arbitrary, but included because",
"import scipy import random colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] rho = 0.01 Nbig=500000",
"def DPsiPoisson(x): return 5*scipy.exp(-5*(1-x)) bimodalPk = {8:0.5, 2:0.5} def PsiBimodal(x): return (x**8 +x**2)/2.",
"rval = 0 for k in PlPk: rval += k*PlPk[k]*x**(k-1) return rval def",
"{8:0.5, 2:0.5} def PsiBimodal(x): return (x**8 +x**2)/2. def DPsiBimodal(x): return(8*x**7 + 2*x)/2. def",
"Gsmall, colors[3], PsiPowLaw, DPsiPowLaw, 'd') plt.axis(xmin=0, ymin=0, xmax = 20, ymax = 0.2)",
"PlPk: rval += PlPk[k]*x**k return rval def DPsiPowLaw(x): rval = 0 for k",
"= 0 for k in PlPk: rval += PlPk[k]*x**k return rval def DPsiPowLaw(x):",
"= 0 for k in PlPk: rval += k*PlPk[k]*x**(k-1) return rval def get_G(N,",
"PlPk rval = 0 for k in PlPk: rval += PlPk[k]*x**k return rval",
"PlPk) process_degree_distribution(Gbig, Gsmall, colors[3], PsiPowLaw, DPsiPowLaw, 'd') plt.axis(xmin=0, ymin=0, xmax = 20, ymax",
"rval += k*PlPk[k]*x**(k-1) return rval def get_G(N, Pk): while True: ks = []",
"for k in PlPk: # r -= PlPk[k] # if r<0: # return",
"return x**5 def DPsiHomogeneous(x): return 5*x**4 PlPk = {} exponent = 1.418184432 kave",
"random.random() # for k in PlPk: # r -= PlPk[k] # if r<0:",
"Gsmall = nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig = nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall, colors[0], PsiPoisson, DPsiPoisson,",
"I*1./Gbig.order(), color = color) N= Gbig.order()#N is arbitrary, but included because our implementation",
"matplotlib.pyplot as plt import scipy import random colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] rho",
"of EBCM assumes N is given. t, S, I, R = EoN.EBCM(N, lambda",
"PsiBimodal, DPsiBimodal, 'o') #Homogeneous Gsmall = get_G(Nsmall, {5:1.}) Gbig = get_G(Nbig, {5:1.}) process_degree_distribution(Gbig,",
"k*PlPk[k] normfact= sum(PlPk.values()) for k in PlPk: PlPk[k] /= normfact #def trunc_pow_law(): #",
"PlPk = {} exponent = 1.418184432 kave = 0 for k in range(1,81):",
"colors[0], PsiPoisson, DPsiPoisson, '^') #Bimodal Gsmall = get_G(Nsmall, bimodalPk) Gbig = get_G(Nbig, bimodalPk)",
"assumes N is given. t, S, I, R = EoN.EBCM(N, lambda x: (1-rho)*Psi(x),",
"k in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave += k*PlPk[k] normfact= sum(PlPk.values()) for k in PlPk:",
"#def trunc_pow_law(): # r = random.random() # for k in PlPk: # r",
"ctr in range(N): r = random.random() for k in Pk: if r<Pk[k]: break",
"else: r-= Pk[k] ks.append(k) if sum(ks)%2==0: break G = nx.configuration_model(ks) return G report_times",
"DPsiBimodal, 'o') #Homogeneous Gsmall = get_G(Nsmall, {5:1.}) Gbig = get_G(Nbig, {5:1.}) process_degree_distribution(Gbig, Gsmall,",
"def get_G(N, Pk): while True: ks = [] for ctr in range(N): r",
"= 5000 tau =0.4 gamma = 1. def poisson(): return scipy.random.poisson(5) def PsiPoisson(x):",
"PlPk: PlPk[k] /= normfact #def trunc_pow_law(): # r = random.random() # for k",
"in Pk: if r<Pk[k]: break else: r-= Pk[k] ks.append(k) if sum(ks)%2==0: break G",
"= color, markeredgecolor='k') #<NAME> Gsmall = nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig = nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig,",
"nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall, colors[0], PsiPoisson, DPsiPoisson, '^') #Bimodal Gsmall = get_G(Nsmall, bimodalPk)",
"rho = 0.01 Nbig=500000 Nsmall = 5000 tau =0.4 gamma = 1. def",
"is given. t, S, I, R = EoN.EBCM(N, lambda x: (1-rho)*Psi(x), lambda x:",
"#Homogeneous Gsmall = get_G(Nsmall, {5:1.}) Gbig = get_G(Nbig, {5:1.}) process_degree_distribution(Gbig, Gsmall, colors[2], PsiHomogeneous,",
"colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] rho = 0.01 Nbig=500000 Nsmall = 5000 tau",
"def PsiPoisson(x): return scipy.exp(-5*(1-x)) def DPsiPoisson(x): return 5*scipy.exp(-5*(1-x)) bimodalPk = {8:0.5, 2:0.5} def",
"= nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall, colors[0], PsiPoisson, DPsiPoisson, '^') #Bimodal Gsmall = get_G(Nsmall,",
"= nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig = nx.fast_gnp_random_graph(Nbig, 5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall, colors[0], PsiPoisson, DPsiPoisson, '^')",
"+ 2*x)/2. def homogeneous(): return 5 def PsiHomogeneous(x): return x**5 def DPsiHomogeneous(x): return",
"import random colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] rho = 0.01 Nbig=500000 Nsmall =",
"plt.plot(t, I*1./Gbig.order(), color = color) N= Gbig.order()#N is arbitrary, but included because our",
"5 def PsiHomogeneous(x): return x**5 def DPsiHomogeneous(x): return 5*x**4 PlPk = {} exponent",
"x**5 def DPsiHomogeneous(x): return 5*x**4 PlPk = {} exponent = 1.418184432 kave =",
"R = EoN.EBCM(N, lambda x: (1-rho)*Psi(x), lambda x: (1-rho)*DPsi(x), tau, gamma, 1-rho) I",
"def process_degree_distribution(Gbig, Gsmall, color, Psi, DPsi, symbol): t, S, I, R = EoN.fast_SIR(Gsmall,",
"break else: r-= Pk[k] ks.append(k) if sum(ks)%2==0: break G = nx.configuration_model(ks) return G",
"= get_G(Nbig, bimodalPk) process_degree_distribution(Gbig, Gsmall, colors[1], PsiBimodal, DPsiBimodal, 'o') #Homogeneous Gsmall = get_G(Nsmall,",
"while True: ks = [] for ctr in range(N): r = random.random() for",
"(1-rho)*DPsi(x), tau, gamma, 1-rho) I = EoN.subsample(report_times, t, I) plt.plot(report_times, I/N, symbol, color",
"= nx.configuration_model(ks) return G report_times = scipy.linspace(0,20,41) def process_degree_distribution(Gbig, Gsmall, color, Psi, DPsi,",
"for k in PlPk: PlPk[k] /= normfact #def trunc_pow_law(): # r = random.random()",
"I, R = EoN.EBCM(N, lambda x: (1-rho)*Psi(x), lambda x: (1-rho)*DPsi(x), tau, gamma, 1-rho)",
"color, Psi, DPsi, symbol): t, S, I, R = EoN.fast_SIR(Gsmall, tau, gamma, rho=rho)",
"0 for k in PlPk: rval += k*PlPk[k]*x**(k-1) return rval def get_G(N, Pk):",
"1-rho) I = EoN.subsample(report_times, t, I) plt.plot(report_times, I/N, symbol, color = color, markeredgecolor='k')",
"get_G(Nsmall, {5:1.}) Gbig = get_G(Nbig, {5:1.}) process_degree_distribution(Gbig, Gsmall, colors[2], PsiHomogeneous, DPsiHomogeneous, 's') #Powerlaw",
"from collections import defaultdict import matplotlib.pyplot as plt import scipy import random colors",
"PsiHomogeneous(x): return x**5 def DPsiHomogeneous(x): return 5*x**4 PlPk = {} exponent = 1.418184432",
"EoN.EBCM(N, lambda x: (1-rho)*Psi(x), lambda x: (1-rho)*DPsi(x), tau, gamma, 1-rho) I = EoN.subsample(report_times,",
"Gbig = get_G(Nbig, {5:1.}) process_degree_distribution(Gbig, Gsmall, colors[2], PsiHomogeneous, DPsiHomogeneous, 's') #Powerlaw Gsmall =",
"arbitrary, but included because our implementation of EBCM assumes N is given. t,",
"r = random.random() for k in Pk: if r<Pk[k]: break else: r-= Pk[k]",
"import defaultdict import matplotlib.pyplot as plt import scipy import random colors = ['#5AB3E6','#FF2000','#009A80','#E69A00',",
"scipy import random colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] rho = 0.01 Nbig=500000 Nsmall",
"PsiPowLaw, DPsiPowLaw, 'd') plt.axis(xmin=0, ymin=0, xmax = 20, ymax = 0.2) plt.xlabel('$t$') plt.ylabel('Proportion",
"Gsmall = get_G(Nsmall, bimodalPk) Gbig = get_G(Nbig, bimodalPk) process_degree_distribution(Gbig, Gsmall, colors[1], PsiBimodal, DPsiBimodal,",
"t, S, I, R = EoN.fast_SIR(Gbig, tau, gamma, rho=rho) plt.plot(t, I*1./Gbig.order(), color =",
"= get_G(Nbig, {5:1.}) process_degree_distribution(Gbig, Gsmall, colors[2], PsiHomogeneous, DPsiHomogeneous, 's') #Powerlaw Gsmall = get_G(Nsmall,",
"color = color) t, S, I, R = EoN.fast_SIR(Gbig, tau, gamma, rho=rho) plt.plot(t,",
"S, I, R = EoN.fast_SIR(Gsmall, tau, gamma, rho=rho) plt.plot(t, I*1./Gsmall.order(), ':', color =",
"get_G(N, Pk): while True: ks = [] for ctr in range(N): r =",
"PlPk: rval += k*PlPk[k]*x**(k-1) return rval def get_G(N, Pk): while True: ks =",
"return rval def DPsiPowLaw(x): rval = 0 for k in PlPk: rval +=",
"as nx import EoN from collections import defaultdict import matplotlib.pyplot as plt import",
"= get_G(Nsmall, PlPk) Gbig = get_G(Nbig, PlPk) process_degree_distribution(Gbig, Gsmall, colors[3], PsiPowLaw, DPsiPowLaw, 'd')",
"= EoN.fast_SIR(Gsmall, tau, gamma, rho=rho) plt.plot(t, I*1./Gsmall.order(), ':', color = color) t, S,",
"import matplotlib.pyplot as plt import scipy import random colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442']",
"Gsmall, colors[0], PsiPoisson, DPsiPoisson, '^') #Bimodal Gsmall = get_G(Nsmall, bimodalPk) Gbig = get_G(Nbig,",
"range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave += k*PlPk[k] normfact= sum(PlPk.values()) for k in PlPk: PlPk[k] /=",
"PsiHomogeneous, DPsiHomogeneous, 's') #Powerlaw Gsmall = get_G(Nsmall, PlPk) Gbig = get_G(Nbig, PlPk) process_degree_distribution(Gbig,",
"if r<Pk[k]: break else: r-= Pk[k] ks.append(k) if sum(ks)%2==0: break G = nx.configuration_model(ks)",
"kave = 0 for k in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave += k*PlPk[k] normfact= sum(PlPk.values())",
"DPsi, symbol): t, S, I, R = EoN.fast_SIR(Gsmall, tau, gamma, rho=rho) plt.plot(t, I*1./Gsmall.order(),",
"included because our implementation of EBCM assumes N is given. t, S, I,",
"return k def PsiPowLaw(x): #print PlPk rval = 0 for k in PlPk:",
"for k in PlPk: rval += k*PlPk[k]*x**(k-1) return rval def get_G(N, Pk): while",
"get_G(Nbig, {5:1.}) process_degree_distribution(Gbig, Gsmall, colors[2], PsiHomogeneous, DPsiHomogeneous, 's') #Powerlaw Gsmall = get_G(Nsmall, PlPk)",
"defaultdict import matplotlib.pyplot as plt import scipy import random colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3',",
"return(8*x**7 + 2*x)/2. def homogeneous(): return 5 def PsiHomogeneous(x): return x**5 def DPsiHomogeneous(x):",
"EoN.fast_SIR(Gbig, tau, gamma, rho=rho) plt.plot(t, I*1./Gbig.order(), color = color) N= Gbig.order()#N is arbitrary,",
"r-= Pk[k] ks.append(k) if sum(ks)%2==0: break G = nx.configuration_model(ks) return G report_times =",
"get_G(Nsmall, bimodalPk) Gbig = get_G(Nbig, bimodalPk) process_degree_distribution(Gbig, Gsmall, colors[1], PsiBimodal, DPsiBimodal, 'o') #Homogeneous",
"rval def get_G(N, Pk): while True: ks = [] for ctr in range(N):",
"= ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] rho = 0.01 Nbig=500000 Nsmall = 5000 tau =0.4",
"Gsmall, color, Psi, DPsi, symbol): t, S, I, R = EoN.fast_SIR(Gsmall, tau, gamma,",
"= get_G(Nsmall, bimodalPk) Gbig = get_G(Nbig, bimodalPk) process_degree_distribution(Gbig, Gsmall, colors[1], PsiBimodal, DPsiBimodal, 'o')",
"plt.plot(report_times, I/N, symbol, color = color, markeredgecolor='k') #<NAME> Gsmall = nx.fast_gnp_random_graph(Nsmall, 5./(Nsmall-1)) Gbig",
"in PlPk: PlPk[k] /= normfact #def trunc_pow_law(): # r = random.random() # for",
"kave += k*PlPk[k] normfact= sum(PlPk.values()) for k in PlPk: PlPk[k] /= normfact #def",
"rval += PlPk[k]*x**k return rval def DPsiPowLaw(x): rval = 0 for k in",
"'o') #Homogeneous Gsmall = get_G(Nsmall, {5:1.}) Gbig = get_G(Nbig, {5:1.}) process_degree_distribution(Gbig, Gsmall, colors[2],",
"r<Pk[k]: break else: r-= Pk[k] ks.append(k) if sum(ks)%2==0: break G = nx.configuration_model(ks) return",
"= get_G(Nbig, PlPk) process_degree_distribution(Gbig, Gsmall, colors[3], PsiPowLaw, DPsiPowLaw, 'd') plt.axis(xmin=0, ymin=0, xmax =",
"= EoN.EBCM(N, lambda x: (1-rho)*Psi(x), lambda x: (1-rho)*DPsi(x), tau, gamma, 1-rho) I =",
"def homogeneous(): return 5 def PsiHomogeneous(x): return x**5 def DPsiHomogeneous(x): return 5*x**4 PlPk",
"True: ks = [] for ctr in range(N): r = random.random() for k",
"color = color) N= Gbig.order()#N is arbitrary, but included because our implementation of",
"'d') plt.axis(xmin=0, ymin=0, xmax = 20, ymax = 0.2) plt.xlabel('$t$') plt.ylabel('Proportion Infected') plt.savefig('fig6p24.png')",
"G = nx.configuration_model(ks) return G report_times = scipy.linspace(0,20,41) def process_degree_distribution(Gbig, Gsmall, color, Psi,",
"= 1.418184432 kave = 0 for k in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave += k*PlPk[k]",
"S, I, R = EoN.EBCM(N, lambda x: (1-rho)*Psi(x), lambda x: (1-rho)*DPsi(x), tau, gamma,",
"def DPsiBimodal(x): return(8*x**7 + 2*x)/2. def homogeneous(): return 5 def PsiHomogeneous(x): return x**5",
"PlPk) Gbig = get_G(Nbig, PlPk) process_degree_distribution(Gbig, Gsmall, colors[3], PsiPowLaw, DPsiPowLaw, 'd') plt.axis(xmin=0, ymin=0,",
"PlPk[k] # if r<0: # return k def PsiPowLaw(x): #print PlPk rval =",
"rho=rho) plt.plot(t, I*1./Gsmall.order(), ':', color = color) t, S, I, R = EoN.fast_SIR(Gbig,",
"0 for k in PlPk: rval += PlPk[k]*x**k return rval def DPsiPowLaw(x): rval",
"report_times = scipy.linspace(0,20,41) def process_degree_distribution(Gbig, Gsmall, color, Psi, DPsi, symbol): t, S, I,",
"process_degree_distribution(Gbig, Gsmall, colors[0], PsiPoisson, DPsiPoisson, '^') #Bimodal Gsmall = get_G(Nsmall, bimodalPk) Gbig =",
"in PlPk: # r -= PlPk[k] # if r<0: # return k def",
"k def PsiPowLaw(x): #print PlPk rval = 0 for k in PlPk: rval",
"but included because our implementation of EBCM assumes N is given. t, S,",
"bimodalPk = {8:0.5, 2:0.5} def PsiBimodal(x): return (x**8 +x**2)/2. def DPsiBimodal(x): return(8*x**7 +",
"t, S, I, R = EoN.fast_SIR(Gsmall, tau, gamma, rho=rho) plt.plot(t, I*1./Gsmall.order(), ':', color",
"1.418184432 kave = 0 for k in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave += k*PlPk[k] normfact=",
"Gbig = get_G(Nbig, bimodalPk) process_degree_distribution(Gbig, Gsmall, colors[1], PsiBimodal, DPsiBimodal, 'o') #Homogeneous Gsmall =",
"DPsiHomogeneous, 's') #Powerlaw Gsmall = get_G(Nsmall, PlPk) Gbig = get_G(Nbig, PlPk) process_degree_distribution(Gbig, Gsmall,",
"return 5*scipy.exp(-5*(1-x)) bimodalPk = {8:0.5, 2:0.5} def PsiBimodal(x): return (x**8 +x**2)/2. def DPsiBimodal(x):",
"scipy.random.poisson(5) def PsiPoisson(x): return scipy.exp(-5*(1-x)) def DPsiPoisson(x): return 5*scipy.exp(-5*(1-x)) bimodalPk = {8:0.5, 2:0.5}",
"':', color = color) t, S, I, R = EoN.fast_SIR(Gbig, tau, gamma, rho=rho)",
"process_degree_distribution(Gbig, Gsmall, colors[3], PsiPowLaw, DPsiPowLaw, 'd') plt.axis(xmin=0, ymin=0, xmax = 20, ymax =",
"#print PlPk rval = 0 for k in PlPk: rval += PlPk[k]*x**k return",
"1. def poisson(): return scipy.random.poisson(5) def PsiPoisson(x): return scipy.exp(-5*(1-x)) def DPsiPoisson(x): return 5*scipy.exp(-5*(1-x))",
"DPsiPowLaw(x): rval = 0 for k in PlPk: rval += k*PlPk[k]*x**(k-1) return rval",
"S, I, R = EoN.fast_SIR(Gbig, tau, gamma, rho=rho) plt.plot(t, I*1./Gbig.order(), color = color)",
"#Powerlaw Gsmall = get_G(Nsmall, PlPk) Gbig = get_G(Nbig, PlPk) process_degree_distribution(Gbig, Gsmall, colors[3], PsiPowLaw,",
"EoN from collections import defaultdict import matplotlib.pyplot as plt import scipy import random",
"= EoN.fast_SIR(Gbig, tau, gamma, rho=rho) plt.plot(t, I*1./Gbig.order(), color = color) N= Gbig.order()#N is",
"gamma, rho=rho) plt.plot(t, I*1./Gsmall.order(), ':', color = color) t, S, I, R =",
"if sum(ks)%2==0: break G = nx.configuration_model(ks) return G report_times = scipy.linspace(0,20,41) def process_degree_distribution(Gbig,",
"if r<0: # return k def PsiPowLaw(x): #print PlPk rval = 0 for",
"bimodalPk) process_degree_distribution(Gbig, Gsmall, colors[1], PsiBimodal, DPsiBimodal, 'o') #Homogeneous Gsmall = get_G(Nsmall, {5:1.}) Gbig",
"{} exponent = 1.418184432 kave = 0 for k in range(1,81): PlPk[k]=k**(-exponent)*scipy.exp(-k*1./40) kave",
"DPsiPowLaw, 'd') plt.axis(xmin=0, ymin=0, xmax = 20, ymax = 0.2) plt.xlabel('$t$') plt.ylabel('Proportion Infected')",
"= color) N= Gbig.order()#N is arbitrary, but included because our implementation of EBCM",
"Gbig = get_G(Nbig, PlPk) process_degree_distribution(Gbig, Gsmall, colors[3], PsiPowLaw, DPsiPowLaw, 'd') plt.axis(xmin=0, ymin=0, xmax",
"process_degree_distribution(Gbig, Gsmall, colors[1], PsiBimodal, DPsiBimodal, 'o') #Homogeneous Gsmall = get_G(Nsmall, {5:1.}) Gbig =",
"PsiPoisson(x): return scipy.exp(-5*(1-x)) def DPsiPoisson(x): return 5*scipy.exp(-5*(1-x)) bimodalPk = {8:0.5, 2:0.5} def PsiBimodal(x):",
"tau, gamma, 1-rho) I = EoN.subsample(report_times, t, I) plt.plot(report_times, I/N, symbol, color =",
"5*scipy.exp(-5*(1-x)) bimodalPk = {8:0.5, 2:0.5} def PsiBimodal(x): return (x**8 +x**2)/2. def DPsiBimodal(x): return(8*x**7",
"(x**8 +x**2)/2. def DPsiBimodal(x): return(8*x**7 + 2*x)/2. def homogeneous(): return 5 def PsiHomogeneous(x):",
"N is given. t, S, I, R = EoN.EBCM(N, lambda x: (1-rho)*Psi(x), lambda",
"PsiPowLaw(x): #print PlPk rval = 0 for k in PlPk: rval += PlPk[k]*x**k",
"normfact= sum(PlPk.values()) for k in PlPk: PlPk[k] /= normfact #def trunc_pow_law(): # r",
"scipy.exp(-5*(1-x)) def DPsiPoisson(x): return 5*scipy.exp(-5*(1-x)) bimodalPk = {8:0.5, 2:0.5} def PsiBimodal(x): return (x**8",
"Gsmall, colors[1], PsiBimodal, DPsiBimodal, 'o') #Homogeneous Gsmall = get_G(Nsmall, {5:1.}) Gbig = get_G(Nbig,",
"r -= PlPk[k] # if r<0: # return k def PsiPowLaw(x): #print PlPk",
"# r -= PlPk[k] # if r<0: # return k def PsiPowLaw(x): #print",
"for ctr in range(N): r = random.random() for k in Pk: if r<Pk[k]:",
"random.random() for k in Pk: if r<Pk[k]: break else: r-= Pk[k] ks.append(k) if",
"return scipy.exp(-5*(1-x)) def DPsiPoisson(x): return 5*scipy.exp(-5*(1-x)) bimodalPk = {8:0.5, 2:0.5} def PsiBimodal(x): return",
"networkx as nx import EoN from collections import defaultdict import matplotlib.pyplot as plt",
"# for k in PlPk: # r -= PlPk[k] # if r<0: #",
"I, R = EoN.fast_SIR(Gsmall, tau, gamma, rho=rho) plt.plot(t, I*1./Gsmall.order(), ':', color = color)",
"/= normfact #def trunc_pow_law(): # r = random.random() # for k in PlPk:",
"return G report_times = scipy.linspace(0,20,41) def process_degree_distribution(Gbig, Gsmall, color, Psi, DPsi, symbol): t,",
"symbol): t, S, I, R = EoN.fast_SIR(Gsmall, tau, gamma, rho=rho) plt.plot(t, I*1./Gsmall.order(), ':',",
"R = EoN.fast_SIR(Gsmall, tau, gamma, rho=rho) plt.plot(t, I*1./Gsmall.order(), ':', color = color) t,",
"get_G(Nsmall, PlPk) Gbig = get_G(Nbig, PlPk) process_degree_distribution(Gbig, Gsmall, colors[3], PsiPowLaw, DPsiPowLaw, 'd') plt.axis(xmin=0,",
"bimodalPk) Gbig = get_G(Nbig, bimodalPk) process_degree_distribution(Gbig, Gsmall, colors[1], PsiBimodal, DPsiBimodal, 'o') #Homogeneous Gsmall",
"in PlPk: rval += PlPk[k]*x**k return rval def DPsiPowLaw(x): rval = 0 for",
"I, R = EoN.fast_SIR(Gbig, tau, gamma, rho=rho) plt.plot(t, I*1./Gbig.order(), color = color) N=",
"'s') #Powerlaw Gsmall = get_G(Nsmall, PlPk) Gbig = get_G(Nbig, PlPk) process_degree_distribution(Gbig, Gsmall, colors[3],",
"2:0.5} def PsiBimodal(x): return (x**8 +x**2)/2. def DPsiBimodal(x): return(8*x**7 + 2*x)/2. def homogeneous():",
"DPsiPoisson(x): return 5*scipy.exp(-5*(1-x)) bimodalPk = {8:0.5, 2:0.5} def PsiBimodal(x): return (x**8 +x**2)/2. def",
"def poisson(): return scipy.random.poisson(5) def PsiPoisson(x): return scipy.exp(-5*(1-x)) def DPsiPoisson(x): return 5*scipy.exp(-5*(1-x)) bimodalPk",
"Gsmall, colors[2], PsiHomogeneous, DPsiHomogeneous, 's') #Powerlaw Gsmall = get_G(Nsmall, PlPk) Gbig = get_G(Nbig,",
"return 5 def PsiHomogeneous(x): return x**5 def DPsiHomogeneous(x): return 5*x**4 PlPk = {}",
"5./(Nbig-1)) process_degree_distribution(Gbig, Gsmall, colors[0], PsiPoisson, DPsiPoisson, '^') #Bimodal Gsmall = get_G(Nsmall, bimodalPk) Gbig",
"t, I) plt.plot(report_times, I/N, symbol, color = color, markeredgecolor='k') #<NAME> Gsmall = nx.fast_gnp_random_graph(Nsmall,",
"tau =0.4 gamma = 1. def poisson(): return scipy.random.poisson(5) def PsiPoisson(x): return scipy.exp(-5*(1-x))",
"tau, gamma, rho=rho) plt.plot(t, I*1./Gbig.order(), color = color) N= Gbig.order()#N is arbitrary, but",
"in PlPk: rval += k*PlPk[k]*x**(k-1) return rval def get_G(N, Pk): while True: ks",
"PlPk[k]*x**k return rval def DPsiPowLaw(x): rval = 0 for k in PlPk: rval",
"= {8:0.5, 2:0.5} def PsiBimodal(x): return (x**8 +x**2)/2. def DPsiBimodal(x): return(8*x**7 + 2*x)/2."
] |
[] |
[
"max_y = None max_z = None min_x = None min_y = None min_z",
"None min_z = None use_limit_x = None use_limit_y = None use_limit_z = None",
"min_x = None min_y = None min_z = None use_limit_x = None use_limit_y",
"max_z = None min_x = None min_y = None min_z = None use_limit_x",
"= None use_limit_x = None use_limit_y = None use_limit_z = None use_transform_limit =",
"= None min_y = None min_z = None use_limit_x = None use_limit_y =",
"None use_limit_x = None use_limit_y = None use_limit_z = None use_transform_limit = None",
"= None max_z = None min_x = None min_y = None min_z =",
"= None min_x = None min_y = None min_z = None use_limit_x =",
"min_y = None min_z = None use_limit_x = None use_limit_y = None use_limit_z",
"class LimitRotationConstraint: max_x = None max_y = None max_z = None min_x =",
"LimitRotationConstraint: max_x = None max_y = None max_z = None min_x = None",
"max_x = None max_y = None max_z = None min_x = None min_y",
"None min_x = None min_y = None min_z = None use_limit_x = None",
"None max_y = None max_z = None min_x = None min_y = None",
"min_z = None use_limit_x = None use_limit_y = None use_limit_z = None use_transform_limit",
"= None min_z = None use_limit_x = None use_limit_y = None use_limit_z =",
"<reponame>cmbasnett/fake-bpy-module class LimitRotationConstraint: max_x = None max_y = None max_z = None min_x",
"None max_z = None min_x = None min_y = None min_z = None",
"= None max_y = None max_z = None min_x = None min_y =",
"None min_y = None min_z = None use_limit_x = None use_limit_y = None"
] |
[
"Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [",
"Django 1.10.6 on 2017-03-14 20:09 from __future__ import unicode_literals from django.db import migrations,",
"django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations",
"from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"migrations.CreateModel( name='Perfil', fields=[ ('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group')), ('descripcion', models.TextField(blank=True)), ],",
"= True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel( name='Perfil',",
"= [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel( name='Perfil', fields=[ ('group_ptr', models.OneToOneField(auto_created=True,",
"[ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel( name='Perfil', fields=[ ('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE,",
"-*- # Generated by Django 1.10.6 on 2017-03-14 20:09 from __future__ import unicode_literals",
"__future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial",
"class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations =",
"import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [",
"migrations.CreateModel( name='Usuario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)), ('perfil', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='laboratorio.Perfil')),",
"] operations = [ migrations.CreateModel( name='Perfil', fields=[ ('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False,",
"bases=('auth.group',), ), migrations.CreateModel( name='Usuario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)), ('perfil',",
"dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel( name='Perfil', fields=[ ('group_ptr',",
"fields=[ ('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group')), ('descripcion', models.TextField(blank=True)), ], options={ 'ordering':",
"'Perfiles', }, bases=('auth.group',), ), migrations.CreateModel( name='Usuario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre',",
"initial = True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel(",
"unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True",
"coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-14 20:09 from __future__",
"'ordering': ['name'], 'verbose_name_plural': 'Perfiles', }, bases=('auth.group',), ), migrations.CreateModel( name='Usuario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)), ('perfil', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='laboratorio.Perfil')), ], ), ]",
"1.10.6 on 2017-03-14 20:09 from __future__ import unicode_literals from django.db import migrations, models",
"Generated by Django 1.10.6 on 2017-03-14 20:09 from __future__ import unicode_literals from django.db",
"serialize=False, to='auth.Group')), ('descripcion', models.TextField(blank=True)), ], options={ 'ordering': ['name'], 'verbose_name_plural': 'Perfiles', }, bases=('auth.group',), ),",
"2017-03-14 20:09 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion",
"to='auth.Group')), ('descripcion', models.TextField(blank=True)), ], options={ 'ordering': ['name'], 'verbose_name_plural': 'Perfiles', }, bases=('auth.group',), ), migrations.CreateModel(",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =",
"[ migrations.CreateModel( name='Perfil', fields=[ ('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group')), ('descripcion', models.TextField(blank=True)),",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth',",
"import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ]",
"('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel( name='Perfil', fields=[ ('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True,",
"utf-8 -*- # Generated by Django 1.10.6 on 2017-03-14 20:09 from __future__ import",
"-*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-14 20:09 from",
"primary_key=True, serialize=False, to='auth.Group')), ('descripcion', models.TextField(blank=True)), ], options={ 'ordering': ['name'], 'verbose_name_plural': 'Perfiles', }, bases=('auth.group',),",
"['name'], 'verbose_name_plural': 'Perfiles', }, bases=('auth.group',), ), migrations.CreateModel( name='Usuario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)), ('perfil', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='laboratorio.Perfil')), ], ),",
"name='Perfil', fields=[ ('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group')), ('descripcion', models.TextField(blank=True)), ], options={",
"20:09 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class",
"'0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel( name='Perfil', fields=[ ('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True,",
"models.TextField(blank=True)), ], options={ 'ordering': ['name'], 'verbose_name_plural': 'Perfiles', }, bases=('auth.group',), ), migrations.CreateModel( name='Usuario', fields=[",
"on 2017-03-14 20:09 from __future__ import unicode_literals from django.db import migrations, models import",
"# Generated by Django 1.10.6 on 2017-03-14 20:09 from __future__ import unicode_literals from",
"('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group')), ('descripcion', models.TextField(blank=True)), ], options={ 'ordering': ['name'],",
"parent_link=True, primary_key=True, serialize=False, to='auth.Group')), ('descripcion', models.TextField(blank=True)), ], options={ 'ordering': ['name'], 'verbose_name_plural': 'Perfiles', },",
"('descripcion', models.TextField(blank=True)), ], options={ 'ordering': ['name'], 'verbose_name_plural': 'Perfiles', }, bases=('auth.group',), ), migrations.CreateModel( name='Usuario',",
"'verbose_name_plural': 'Perfiles', }, bases=('auth.group',), ), migrations.CreateModel( name='Usuario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"by Django 1.10.6 on 2017-03-14 20:09 from __future__ import unicode_literals from django.db import",
"# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-14 20:09",
"<reponame>alejandroquintero/proyecto_laboratorio # -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-14",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies",
"models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group')), ('descripcion', models.TextField(blank=True)), ], options={ 'ordering': ['name'], 'verbose_name_plural':",
"], options={ 'ordering': ['name'], 'verbose_name_plural': 'Perfiles', }, bases=('auth.group',), ), migrations.CreateModel( name='Usuario', fields=[ ('id',",
"name='Usuario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)), ('perfil', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='laboratorio.Perfil')), ],",
"= [ migrations.CreateModel( name='Perfil', fields=[ ('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group')), ('descripcion',",
"on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group')), ('descripcion', models.TextField(blank=True)), ], options={ 'ordering': ['name'], 'verbose_name_plural': 'Perfiles',",
"}, bases=('auth.group',), ), migrations.CreateModel( name='Usuario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)),",
"), migrations.CreateModel( name='Usuario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)), ('perfil', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE,",
"models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0008_alter_user_username_max_length'),",
"operations = [ migrations.CreateModel( name='Perfil', fields=[ ('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group')),",
"True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel( name='Perfil', fields=[",
"options={ 'ordering': ['name'], 'verbose_name_plural': 'Perfiles', }, bases=('auth.group',), ), migrations.CreateModel( name='Usuario', fields=[ ('id', models.AutoField(auto_created=True,"
] |
[
"x_chain = super(CScalerTestCases, self)._test_chain( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] - 1), x_chain.shape)",
"= super(CScalerTestCases, self)._test_chain( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] - 1), x_chain.shape) return",
"import CArray from secml.ml.tests import CModuleTestCases class CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface for Normalizers.\"\"\" def",
"CModuleTestCases class CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface for Normalizers.\"\"\" def _compare_scalers(self, scaler, scaler_sklearn, array, convert_to_dense=False):",
"scaler_sklearn, array, convert_to_dense=False): \"\"\"Compare wrapped scikit-learn scaler to the unwrapped scaler. Parameters ----------",
"\"\"\"Tests if gradient preprocess chain and gradient of manual chaining yield same result.\"\"\"",
"scaler_sklearn.fit(array_sk, None) transform_sklearn = CArray(scaler_sklearn.transform(array_sk)) # Our normalizer scaler._fit(array) transform = scaler.forward(array) self.logger.info(\"sklearn",
"array.tondarray() # Sklearn normalizer scaler_sklearn.fit(array_sk, None) transform_sklearn = CArray(scaler_sklearn.transform(array_sk)) # Our normalizer scaler._fit(array)",
"- 1), x_chain.shape) return x_chain def _test_chain_gradient(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if",
"is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform) return scaler, scaler_sklearn def _test_chain(self, x, class_type_list,",
"wrapped scikit-learn scaler to the unwrapped scaler. Parameters ---------- array : CArray scaler",
"\"\"\"Compare wrapped scikit-learn scaler to the unwrapped scaler. Parameters ---------- array : CArray",
"kwargs_list, y=None): \"\"\"Tests if gradient preprocess chain and gradient of manual chaining yield",
"convert_to_dense is False \\ else array.tondarray() # Sklearn normalizer scaler_sklearn.fit(array_sk, None) transform_sklearn =",
"CUnitTest from secml.array import CArray from secml.ml.tests import CModuleTestCases class CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface",
"scaler, scaler_sklearn def _test_chain(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if preprocess chain and",
"scaler to the unwrapped scaler. Parameters ---------- array : CArray scaler : A",
"of manual chaining yield same result.\"\"\" grad_chain = super(CScalerTestCases, self)._test_chain_gradient( x, class_type_list, kwargs_list,",
"Returns ------- scaler_sklearn Trained Scikit-learn normalizer (from `sklearn.preprocessing`). scaler : CScaler Trained normalizer.",
"gradient preprocess chain and gradient of manual chaining yield same result.\"\"\" grad_chain =",
"data used by the SkLearn scaler will be converted to dense. Returns -------",
"by the SkLearn scaler will be converted to dense. Returns ------- scaler_sklearn Trained",
"If True the data used by the SkLearn scaler will be converted to",
"# Our normalizer scaler._fit(array) transform = scaler.forward(array) self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result is:\\n{:}\".format(transform))",
"True the data used by the SkLearn scaler will be converted to dense.",
"else array.tondarray() # Sklearn normalizer scaler_sklearn.fit(array_sk, None) transform_sklearn = CArray(scaler_sklearn.transform(array_sk)) # Our normalizer",
"\"\"\"Tests if preprocess chain and manual chaining yield same result.\"\"\" x_chain = super(CScalerTestCases,",
"kwargs_list, y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] - 1), x_chain.shape) return x_chain def _test_chain_gradient(self, x, class_type_list,",
"Parameters ---------- array : CArray scaler : A wrapped CScaler scaler_sklearn Scikit-learn normalizer.",
"scaler.forward(array) self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform) return scaler, scaler_sklearn def",
"= array.get_data() if convert_to_dense is False \\ else array.tondarray() # Sklearn normalizer scaler_sklearn.fit(array_sk,",
"Trained normalizer. \"\"\" self.logger.info(\"Original array is:\\n{:}\".format(array)) array_sk = array.get_data() if convert_to_dense is False",
"x_chain.shape) return x_chain def _test_chain_gradient(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if gradient preprocess",
"class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] - 1), x_chain.shape) return x_chain def _test_chain_gradient(self, x,",
"---------- array : CArray scaler : A wrapped CScaler scaler_sklearn Scikit-learn normalizer. convert_to_dense",
"if convert_to_dense is False \\ else array.tondarray() # Sklearn normalizer scaler_sklearn.fit(array_sk, None) transform_sklearn",
"CArray(scaler_sklearn.transform(array_sk)) # Our normalizer scaler._fit(array) transform = scaler.forward(array) self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result",
"the data used by the SkLearn scaler will be converted to dense. Returns",
"\"\"\" self.logger.info(\"Original array is:\\n{:}\".format(array)) array_sk = array.get_data() if convert_to_dense is False \\ else",
": CArray scaler : A wrapped CScaler scaler_sklearn Scikit-learn normalizer. convert_to_dense : bool,",
"CScaler scaler_sklearn Scikit-learn normalizer. convert_to_dense : bool, optional If True the data used",
"_compare_scalers(self, scaler, scaler_sklearn, array, convert_to_dense=False): \"\"\"Compare wrapped scikit-learn scaler to the unwrapped scaler.",
"and gradient of manual chaining yield same result.\"\"\" grad_chain = super(CScalerTestCases, self)._test_chain_gradient( x,",
"def _compare_scalers(self, scaler, scaler_sklearn, array, convert_to_dense=False): \"\"\"Compare wrapped scikit-learn scaler to the unwrapped",
"used by the SkLearn scaler will be converted to dense. Returns ------- scaler_sklearn",
"y=None): \"\"\"Tests if preprocess chain and manual chaining yield same result.\"\"\" x_chain =",
"array is:\\n{:}\".format(array)) array_sk = array.get_data() if convert_to_dense is False \\ else array.tondarray() #",
"SkLearn scaler will be converted to dense. Returns ------- scaler_sklearn Trained Scikit-learn normalizer",
"_test_chain_gradient(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if gradient preprocess chain and gradient of",
"`sklearn.preprocessing`). scaler : CScaler Trained normalizer. \"\"\" self.logger.info(\"Original array is:\\n{:}\".format(array)) array_sk = array.get_data()",
": A wrapped CScaler scaler_sklearn Scikit-learn normalizer. convert_to_dense : bool, optional If True",
"self.assert_array_almost_equal(transform_sklearn, transform) return scaler, scaler_sklearn def _test_chain(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if",
"scaler : A wrapped CScaler scaler_sklearn Scikit-learn normalizer. convert_to_dense : bool, optional If",
"grad_chain = super(CScalerTestCases, self)._test_chain_gradient( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[1],), grad_chain.shape) return grad_chain if",
"Scikit-learn normalizer. convert_to_dense : bool, optional If True the data used by the",
"False \\ else array.tondarray() # Sklearn normalizer scaler_sklearn.fit(array_sk, None) transform_sklearn = CArray(scaler_sklearn.transform(array_sk)) #",
"1), x_chain.shape) return x_chain def _test_chain_gradient(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if gradient",
"is False \\ else array.tondarray() # Sklearn normalizer scaler_sklearn.fit(array_sk, None) transform_sklearn = CArray(scaler_sklearn.transform(array_sk))",
"\"\"\"Unittests interface for Normalizers.\"\"\" def _compare_scalers(self, scaler, scaler_sklearn, array, convert_to_dense=False): \"\"\"Compare wrapped scikit-learn",
"yield same result.\"\"\" grad_chain = super(CScalerTestCases, self)._test_chain_gradient( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[1],), grad_chain.shape)",
"converted to dense. Returns ------- scaler_sklearn Trained Scikit-learn normalizer (from `sklearn.preprocessing`). scaler :",
"if gradient preprocess chain and gradient of manual chaining yield same result.\"\"\" grad_chain",
"chaining yield same result.\"\"\" grad_chain = super(CScalerTestCases, self)._test_chain_gradient( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[1],),",
"the SkLearn scaler will be converted to dense. Returns ------- scaler_sklearn Trained Scikit-learn",
"convert_to_dense=False): \"\"\"Compare wrapped scikit-learn scaler to the unwrapped scaler. Parameters ---------- array :",
"from secml.ml.tests import CModuleTestCases class CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface for Normalizers.\"\"\" def _compare_scalers(self, scaler,",
"Scikit-learn normalizer (from `sklearn.preprocessing`). scaler : CScaler Trained normalizer. \"\"\" self.logger.info(\"Original array is:\\n{:}\".format(array))",
"transform_sklearn = CArray(scaler_sklearn.transform(array_sk)) # Our normalizer scaler._fit(array) transform = scaler.forward(array) self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn))",
"and manual chaining yield same result.\"\"\" x_chain = super(CScalerTestCases, self)._test_chain( x, class_type_list, kwargs_list,",
"x, class_type_list, kwargs_list, y=None): \"\"\"Tests if preprocess chain and manual chaining yield same",
"preprocess chain and manual chaining yield same result.\"\"\" x_chain = super(CScalerTestCases, self)._test_chain( x,",
"secml.array import CArray from secml.ml.tests import CModuleTestCases class CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface for Normalizers.\"\"\"",
"A wrapped CScaler scaler_sklearn Scikit-learn normalizer. convert_to_dense : bool, optional If True the",
"self)._test_chain( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] - 1), x_chain.shape) return x_chain def",
"transform) return scaler, scaler_sklearn def _test_chain(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if preprocess",
"array : CArray scaler : A wrapped CScaler scaler_sklearn Scikit-learn normalizer. convert_to_dense :",
"kwargs_list, y=None): \"\"\"Tests if preprocess chain and manual chaining yield same result.\"\"\" x_chain",
"if preprocess chain and manual chaining yield same result.\"\"\" x_chain = super(CScalerTestCases, self)._test_chain(",
"for Normalizers.\"\"\" def _compare_scalers(self, scaler, scaler_sklearn, array, convert_to_dense=False): \"\"\"Compare wrapped scikit-learn scaler to",
"convert_to_dense : bool, optional If True the data used by the SkLearn scaler",
"wrapped CScaler scaler_sklearn Scikit-learn normalizer. convert_to_dense : bool, optional If True the data",
"be converted to dense. Returns ------- scaler_sklearn Trained Scikit-learn normalizer (from `sklearn.preprocessing`). scaler",
"x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] - 1), x_chain.shape) return x_chain def _test_chain_gradient(self,",
"def _test_chain(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if preprocess chain and manual chaining",
"CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface for Normalizers.\"\"\" def _compare_scalers(self, scaler, scaler_sklearn, array, convert_to_dense=False): \"\"\"Compare wrapped",
"self)._test_chain_gradient( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[1],), grad_chain.shape) return grad_chain if __name__ == '__main__':",
"secml.testing import CUnitTest from secml.array import CArray from secml.ml.tests import CModuleTestCases class CScalerTestCases(CModuleTestCases):",
"Sklearn normalizer scaler_sklearn.fit(array_sk, None) transform_sklearn = CArray(scaler_sklearn.transform(array_sk)) # Our normalizer scaler._fit(array) transform =",
"scaler_sklearn def _test_chain(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if preprocess chain and manual",
"None) transform_sklearn = CArray(scaler_sklearn.transform(array_sk)) # Our normalizer scaler._fit(array) transform = scaler.forward(array) self.logger.info(\"sklearn result",
"super(CScalerTestCases, self)._test_chain( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] - 1), x_chain.shape) return x_chain",
"class_type_list, kwargs_list, y=None): \"\"\"Tests if preprocess chain and manual chaining yield same result.\"\"\"",
"= super(CScalerTestCases, self)._test_chain_gradient( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[1],), grad_chain.shape) return grad_chain if __name__",
"# Sklearn normalizer scaler_sklearn.fit(array_sk, None) transform_sklearn = CArray(scaler_sklearn.transform(array_sk)) # Our normalizer scaler._fit(array) transform",
"def _test_chain_gradient(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if gradient preprocess chain and gradient",
"------- scaler_sklearn Trained Scikit-learn normalizer (from `sklearn.preprocessing`). scaler : CScaler Trained normalizer. \"\"\"",
"to the unwrapped scaler. Parameters ---------- array : CArray scaler : A wrapped",
"x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[1],), grad_chain.shape) return grad_chain if __name__ == '__main__': CUnitTest.main()",
"same result.\"\"\" grad_chain = super(CScalerTestCases, self)._test_chain_gradient( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[1],), grad_chain.shape) return",
"(from `sklearn.preprocessing`). scaler : CScaler Trained normalizer. \"\"\" self.logger.info(\"Original array is:\\n{:}\".format(array)) array_sk =",
"y=None): \"\"\"Tests if gradient preprocess chain and gradient of manual chaining yield same",
"self.logger.info(\"Original array is:\\n{:}\".format(array)) array_sk = array.get_data() if convert_to_dense is False \\ else array.tondarray()",
"interface for Normalizers.\"\"\" def _compare_scalers(self, scaler, scaler_sklearn, array, convert_to_dense=False): \"\"\"Compare wrapped scikit-learn scaler",
"= scaler.forward(array) self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform) return scaler, scaler_sklearn",
"dense. Returns ------- scaler_sklearn Trained Scikit-learn normalizer (from `sklearn.preprocessing`). scaler : CScaler Trained",
"_test_chain(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if preprocess chain and manual chaining yield",
"CArray from secml.ml.tests import CModuleTestCases class CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface for Normalizers.\"\"\" def _compare_scalers(self,",
"scaler_sklearn Trained Scikit-learn normalizer (from `sklearn.preprocessing`). scaler : CScaler Trained normalizer. \"\"\" self.logger.info(\"Original",
"optional If True the data used by the SkLearn scaler will be converted",
"self.logger.info(\"Our result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform) return scaler, scaler_sklearn def _test_chain(self, x, class_type_list, kwargs_list,",
"array_sk = array.get_data() if convert_to_dense is False \\ else array.tondarray() # Sklearn normalizer",
"class_type_list, kwargs_list, y=None): \"\"\"Tests if gradient preprocess chain and gradient of manual chaining",
"= CArray(scaler_sklearn.transform(array_sk)) # Our normalizer scaler._fit(array) transform = scaler.forward(array) self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our",
"CScaler Trained normalizer. \"\"\" self.logger.info(\"Original array is:\\n{:}\".format(array)) array_sk = array.get_data() if convert_to_dense is",
"self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] - 1), x_chain.shape) return x_chain def _test_chain_gradient(self, x, class_type_list, kwargs_list, y=None):",
"unwrapped scaler. Parameters ---------- array : CArray scaler : A wrapped CScaler scaler_sklearn",
"x, class_type_list, kwargs_list, y=None): \"\"\"Tests if gradient preprocess chain and gradient of manual",
"to dense. Returns ------- scaler_sklearn Trained Scikit-learn normalizer (from `sklearn.preprocessing`). scaler : CScaler",
"from secml.array import CArray from secml.ml.tests import CModuleTestCases class CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface for",
"super(CScalerTestCases, self)._test_chain_gradient( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[1],), grad_chain.shape) return grad_chain if __name__ ==",
"yield same result.\"\"\" x_chain = super(CScalerTestCases, self)._test_chain( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1]",
"Normalizers.\"\"\" def _compare_scalers(self, scaler, scaler_sklearn, array, convert_to_dense=False): \"\"\"Compare wrapped scikit-learn scaler to the",
"scaler, scaler_sklearn, array, convert_to_dense=False): \"\"\"Compare wrapped scikit-learn scaler to the unwrapped scaler. Parameters",
"result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform) return scaler, scaler_sklearn def _test_chain(self, x,",
"normalizer (from `sklearn.preprocessing`). scaler : CScaler Trained normalizer. \"\"\" self.logger.info(\"Original array is:\\n{:}\".format(array)) array_sk",
"return scaler, scaler_sklearn def _test_chain(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if preprocess chain",
"array.get_data() if convert_to_dense is False \\ else array.tondarray() # Sklearn normalizer scaler_sklearn.fit(array_sk, None)",
"array, convert_to_dense=False): \"\"\"Compare wrapped scikit-learn scaler to the unwrapped scaler. Parameters ---------- array",
"result.\"\"\" grad_chain = super(CScalerTestCases, self)._test_chain_gradient( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[1],), grad_chain.shape) return grad_chain",
"scaler will be converted to dense. Returns ------- scaler_sklearn Trained Scikit-learn normalizer (from",
"same result.\"\"\" x_chain = super(CScalerTestCases, self)._test_chain( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] -",
"scikit-learn scaler to the unwrapped scaler. Parameters ---------- array : CArray scaler :",
"normalizer scaler_sklearn.fit(array_sk, None) transform_sklearn = CArray(scaler_sklearn.transform(array_sk)) # Our normalizer scaler._fit(array) transform = scaler.forward(array)",
"chain and manual chaining yield same result.\"\"\" x_chain = super(CScalerTestCases, self)._test_chain( x, class_type_list,",
": CScaler Trained normalizer. \"\"\" self.logger.info(\"Original array is:\\n{:}\".format(array)) array_sk = array.get_data() if convert_to_dense",
"result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform) return scaler, scaler_sklearn def _test_chain(self, x, class_type_list, kwargs_list, y=None):",
"the unwrapped scaler. Parameters ---------- array : CArray scaler : A wrapped CScaler",
"class CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface for Normalizers.\"\"\" def _compare_scalers(self, scaler, scaler_sklearn, array, convert_to_dense=False): \"\"\"Compare",
"Our normalizer scaler._fit(array) transform = scaler.forward(array) self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn,",
"scaler_sklearn Scikit-learn normalizer. convert_to_dense : bool, optional If True the data used by",
"normalizer. \"\"\" self.logger.info(\"Original array is:\\n{:}\".format(array)) array_sk = array.get_data() if convert_to_dense is False \\",
"is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform) return scaler, scaler_sklearn def _test_chain(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests",
"y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] - 1), x_chain.shape) return x_chain def _test_chain_gradient(self, x, class_type_list, kwargs_list,",
"preprocess chain and gradient of manual chaining yield same result.\"\"\" grad_chain = super(CScalerTestCases,",
"scaler. Parameters ---------- array : CArray scaler : A wrapped CScaler scaler_sklearn Scikit-learn",
"chaining yield same result.\"\"\" x_chain = super(CScalerTestCases, self)._test_chain( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[0],",
"x_chain def _test_chain_gradient(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if gradient preprocess chain and",
"chain and gradient of manual chaining yield same result.\"\"\" grad_chain = super(CScalerTestCases, self)._test_chain_gradient(",
"return x_chain def _test_chain_gradient(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests if gradient preprocess chain",
"scaler._fit(array) transform = scaler.forward(array) self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform) return",
"from secml.testing import CUnitTest from secml.array import CArray from secml.ml.tests import CModuleTestCases class",
"import CModuleTestCases class CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface for Normalizers.\"\"\" def _compare_scalers(self, scaler, scaler_sklearn, array,",
"CArray scaler : A wrapped CScaler scaler_sklearn Scikit-learn normalizer. convert_to_dense : bool, optional",
"\\ else array.tondarray() # Sklearn normalizer scaler_sklearn.fit(array_sk, None) transform_sklearn = CArray(scaler_sklearn.transform(array_sk)) # Our",
"is:\\n{:}\".format(array)) array_sk = array.get_data() if convert_to_dense is False \\ else array.tondarray() # Sklearn",
"self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform) return scaler, scaler_sklearn def _test_chain(self,",
"Trained Scikit-learn normalizer (from `sklearn.preprocessing`). scaler : CScaler Trained normalizer. \"\"\" self.logger.info(\"Original array",
"manual chaining yield same result.\"\"\" grad_chain = super(CScalerTestCases, self)._test_chain_gradient( x, class_type_list, kwargs_list, y)",
"scaler : CScaler Trained normalizer. \"\"\" self.logger.info(\"Original array is:\\n{:}\".format(array)) array_sk = array.get_data() if",
"import CUnitTest from secml.array import CArray from secml.ml.tests import CModuleTestCases class CScalerTestCases(CModuleTestCases): \"\"\"Unittests",
"will be converted to dense. Returns ------- scaler_sklearn Trained Scikit-learn normalizer (from `sklearn.preprocessing`).",
"normalizer. convert_to_dense : bool, optional If True the data used by the SkLearn",
"gradient of manual chaining yield same result.\"\"\" grad_chain = super(CScalerTestCases, self)._test_chain_gradient( x, class_type_list,",
"secml.ml.tests import CModuleTestCases class CScalerTestCases(CModuleTestCases): \"\"\"Unittests interface for Normalizers.\"\"\" def _compare_scalers(self, scaler, scaler_sklearn,",
"normalizer scaler._fit(array) transform = scaler.forward(array) self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform)",
"manual chaining yield same result.\"\"\" x_chain = super(CScalerTestCases, self)._test_chain( x, class_type_list, kwargs_list, y)",
"self.array_dense.shape[1] - 1), x_chain.shape) return x_chain def _test_chain_gradient(self, x, class_type_list, kwargs_list, y=None): \"\"\"Tests",
": bool, optional If True the data used by the SkLearn scaler will",
"result.\"\"\" x_chain = super(CScalerTestCases, self)._test_chain( x, class_type_list, kwargs_list, y) self.assertEqual((self.array_dense.shape[0], self.array_dense.shape[1] - 1),",
"transform = scaler.forward(array) self.logger.info(\"sklearn result is:\\n{:}\".format(transform_sklearn)) self.logger.info(\"Our result is:\\n{:}\".format(transform)) self.assert_array_almost_equal(transform_sklearn, transform) return scaler,",
"bool, optional If True the data used by the SkLearn scaler will be"
] |
[
"def setUp(self): self.app = ZapadorApp() def test_name(self): self.assertEqual(self.app.name, 'zapador') def tearDown(self): pass if",
"coding: utf-8 -*- import unittest from zapador.zapadorapp import ZapadorApp class TestZapadorApp(unittest.TestCase): \"\"\"TestCase for",
"zapador.zapadorapp import ZapadorApp class TestZapadorApp(unittest.TestCase): \"\"\"TestCase for ZapadorApp. \"\"\" def setUp(self): self.app =",
"python # -*- coding: utf-8 -*- import unittest from zapador.zapadorapp import ZapadorApp class",
"ZapadorApp. \"\"\" def setUp(self): self.app = ZapadorApp() def test_name(self): self.assertEqual(self.app.name, 'zapador') def tearDown(self):",
"-*- import unittest from zapador.zapadorapp import ZapadorApp class TestZapadorApp(unittest.TestCase): \"\"\"TestCase for ZapadorApp. \"\"\"",
"setUp(self): self.app = ZapadorApp() def test_name(self): self.assertEqual(self.app.name, 'zapador') def tearDown(self): pass if __name__",
"<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from zapador.zapadorapp import",
"# -*- coding: utf-8 -*- import unittest from zapador.zapadorapp import ZapadorApp class TestZapadorApp(unittest.TestCase):",
"utf-8 -*- import unittest from zapador.zapadorapp import ZapadorApp class TestZapadorApp(unittest.TestCase): \"\"\"TestCase for ZapadorApp.",
"self.app = ZapadorApp() def test_name(self): self.assertEqual(self.app.name, 'zapador') def tearDown(self): pass if __name__ ==",
"= ZapadorApp() def test_name(self): self.assertEqual(self.app.name, 'zapador') def tearDown(self): pass if __name__ == '__main__':",
"ZapadorApp() def test_name(self): self.assertEqual(self.app.name, 'zapador') def tearDown(self): pass if __name__ == '__main__': unittest.main()",
"import ZapadorApp class TestZapadorApp(unittest.TestCase): \"\"\"TestCase for ZapadorApp. \"\"\" def setUp(self): self.app = ZapadorApp()",
"\"\"\" def setUp(self): self.app = ZapadorApp() def test_name(self): self.assertEqual(self.app.name, 'zapador') def tearDown(self): pass",
"ZapadorApp class TestZapadorApp(unittest.TestCase): \"\"\"TestCase for ZapadorApp. \"\"\" def setUp(self): self.app = ZapadorApp() def",
"class TestZapadorApp(unittest.TestCase): \"\"\"TestCase for ZapadorApp. \"\"\" def setUp(self): self.app = ZapadorApp() def test_name(self):",
"for ZapadorApp. \"\"\" def setUp(self): self.app = ZapadorApp() def test_name(self): self.assertEqual(self.app.name, 'zapador') def",
"-*- coding: utf-8 -*- import unittest from zapador.zapadorapp import ZapadorApp class TestZapadorApp(unittest.TestCase): \"\"\"TestCase",
"\"\"\"TestCase for ZapadorApp. \"\"\" def setUp(self): self.app = ZapadorApp() def test_name(self): self.assertEqual(self.app.name, 'zapador')",
"import unittest from zapador.zapadorapp import ZapadorApp class TestZapadorApp(unittest.TestCase): \"\"\"TestCase for ZapadorApp. \"\"\" def",
"TestZapadorApp(unittest.TestCase): \"\"\"TestCase for ZapadorApp. \"\"\" def setUp(self): self.app = ZapadorApp() def test_name(self): self.assertEqual(self.app.name,",
"from zapador.zapadorapp import ZapadorApp class TestZapadorApp(unittest.TestCase): \"\"\"TestCase for ZapadorApp. \"\"\" def setUp(self): self.app",
"unittest from zapador.zapadorapp import ZapadorApp class TestZapadorApp(unittest.TestCase): \"\"\"TestCase for ZapadorApp. \"\"\" def setUp(self):",
"#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from zapador.zapadorapp import ZapadorApp"
] |
[
"See `types.ParamsOfBocCacheSet` :return: See `types.ResultOfBocCacheSet` \"\"\" return self.request(method='boc.cache_set', **params.dict) def cache_unpin(self, params: ParamsOfBocCacheUnpin):",
":param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse) def",
"See `types.ResultOfEncodeBoc` \"\"\" return self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt) def get_code_salt( self, params: ParamsOfGetCodeSalt) ->",
"image :param params: See `types.ParamsOfGetCodeFromTvc` :return: See `types.ResultOfGetCodeFromTvc` \"\"\" return self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet)",
"compatible with GraphQL API account object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse`",
"from tonclient.types import ParamsOfParse, ResultOfParse, \\ ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\",
"Returns the contract code's salt if it is present :param params: See `types.ParamsOfGetCodeSalt`",
"@result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc( self, params: ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc: \"\"\" Extracts code from TVC",
"get_compiler_version( self, params: ParamsOfGetCompilerVersion ) -> ResultOfGetCompilerVersion: \"\"\" Returns the compiler version used",
"\"\"\" return self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash) def get_boc_hash(self, params: ParamsOfGetBocHash) -> ResultOfGetBocHash: \"\"\" Calculates",
"block boc into a JSON. JSON structure is compatible with GraphQL API block",
"self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet) def cache_get(self, params: ParamsOfBocCacheGet) -> ResultOfBocCacheGet: \"\"\" Get BOC from",
"BOC of this method can be passed into Solidity and C++ contracts as",
"BOCs with specified pin. BOCs which don't have another pins will be removed",
"params: See `types.ParamsOfGetCodeFromTvc` :return: See `types.ResultOfGetCodeFromTvc` \"\"\" return self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet) def cache_get(self,",
"it is present :param params: See `types.ParamsOfGetCodeSalt` :return: See `types.ResultOfGetCodeSalt` \"\"\" return self.request(method='boc.get_code_salt',",
"ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt: \"\"\" Sets new salt to contract code. Returns the new",
"input params) :param params: See `types.ParamsOfEncodeTvc` :return: See `types.ResultOfEncodeTvc` \"\"\" return self.request(method='boc.encode_tvc', **params.dict)",
"the same functionality as Solidity TvmBuilder. Resulting BOC of this method can be",
"ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\ ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt,",
"`types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse) def parse_block(self, params: ParamsOfParse)",
"See `ParamsOfGetBocHash` :return: See `ResultOfGetBocHash` \"\"\" return self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config( self,",
":return: See `types.ResultOfBocCacheSet` \"\"\" return self.request(method='boc.cache_set', **params.dict) def cache_unpin(self, params: ParamsOfBocCacheUnpin): \"\"\" Unpin",
"params: See `types.ParamsOfEncodeTvc` :return: See `types.ResultOfEncodeTvc` \"\"\" return self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version(",
":return: See `ResultOfGetBlockchainConfig` \"\"\" return self.request( method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc( self, params:",
"\"\"\" return self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet) def cache_set(self, params: ParamsOfBocCacheSet) -> ResultOfBocCacheSet: \"\"\" Save",
"`types.ParamsOfBocCacheSet` :return: See `types.ResultOfBocCacheSet` \"\"\" return self.request(method='boc.cache_set', **params.dict) def cache_unpin(self, params: ParamsOfBocCacheUnpin): \"\"\"",
"a JSON. JSON structure is compatible with GraphQL API block object :param params:",
"\\ ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc, \\ ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion class TonBoc(TonModule): \"\"\"",
"structure is compatible with GraphQL API block object :param params: See `types.ParamsOfParse` :return:",
"`ResultOfParse` \"\"\" return self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash) def get_boc_hash(self, params: ParamsOfGetBocHash) -> ResultOfGetBocHash: \"\"\"",
"special options (see input params) :param params: See `types.ParamsOfEncodeTvc` :return: See `types.ResultOfEncodeTvc` \"\"\"",
"return self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet) def cache_get(self, params: ParamsOfBocCacheGet) -> ResultOfBocCacheGet: \"\"\" Get BOC",
"from tonclient.decorators import result_as from tonclient.module import TonModule from tonclient.types import ParamsOfParse, ResultOfParse,",
"from TVC contract image :param params: See `types.ParamsOfGetCodeFromTvc` :return: See `types.ResultOfGetCodeFromTvc` \"\"\" return",
"boc into a JSON. JSON structure is compatible with GraphQL API transaction object",
"\"\"\" Get BOC from cache :param params: See `types.ParamsOfBocCacheGet` :return: See `types.ResultOfBocCacheGet` \"\"\"",
"version used to compile the code :param params: See `types.ParamsOfGetCompilerVersion` :return: See `types.ResultOfGetCompilerVersion`",
"self, params: ParamsOfParseShardstate) -> ResultOfParse: \"\"\" Parses shardstate boc into a JSON. JSON",
"parse_account(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses account boc into a JSON. JSON",
"return self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash) def get_boc_hash(self, params: ParamsOfGetBocHash) -> ResultOfGetBocHash: \"\"\" Calculates BOC",
"contract code's salt if it is present :param params: See `types.ParamsOfGetCodeSalt` :return: See",
"def parse_message(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses message boc into a JSON.",
"params: ParamsOfBocCacheUnpin): \"\"\" Unpin BOCs with specified pin. BOCs which don't have another",
"-> ResultOfGetBlockchainConfig: \"\"\" Extract blockchain configuration from key block and also from zero",
":return: See `types.ResultOfDecodeTvc` \"\"\" return self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc) def encode_tvc(self, params: ParamsOfEncodeTvc) ->",
"-> ResultOfGetCompilerVersion: \"\"\" Returns the compiler version used to compile the code :param",
"ResultOfBocCacheGet: \"\"\" Get BOC from cache :param params: See `types.ParamsOfBocCacheGet` :return: See `types.ResultOfBocCacheGet`",
"method provides the same functionality as Solidity TvmBuilder. Resulting BOC of this method",
"\\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\ ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc, \\",
"ResultOfSetCodeSalt: \"\"\" Sets new salt to contract code. Returns the new contract code",
"JSON structure is compatible with GraphQL API shardstate object :param params: See `ParamsOfParseShardstate`",
"blockchain configuration from key block and also from zero state :param params: See",
"ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc, \\ ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion",
"zero state :param params: See `ParamsOfGetBlockchainConfig` :return: See `ResultOfGetBlockchainConfig` \"\"\" return self.request( method='boc.get_blockchain_config',",
"Solidity TvmBuilder. Resulting BOC of this method can be passed into Solidity and",
"options :param params: See `types.ParamsOfDecodeTvc` :return: See `types.ResultOfDecodeTvc` \"\"\" return self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc)",
"ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt,",
"Get BOC from cache :param params: See `types.ParamsOfBocCacheGet` :return: See `types.ResultOfBocCacheGet` \"\"\" return",
"**params.dict) @result_as(classname=ResultOfEncodeBoc) def encode_boc(self, params: ParamsOfEncodeBoc) -> ResultOfEncodeBoc: \"\"\" Encodes bag of cells",
"\"\"\" Encodes tvc from code, data, libraries ans special options (see input params)",
"be passed into Solidity and C++ contracts as TvmCell type :param params: See",
"SDK API implementation \"\"\" @result_as(classname=ResultOfParse) def parse_message(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses",
"API shardstate object :param params: See `ParamsOfParseShardstate` :return: See `ResultOfParse` \"\"\" return self.request(method='boc.parse_shardstate',",
"return self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse) def parse_block(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses block",
"transaction boc into a JSON. JSON structure is compatible with GraphQL API transaction",
"\"\"\" return self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet) def cache_get(self, params: ParamsOfBocCacheGet) -> ResultOfBocCacheGet: \"\"\" Get",
"\"\"\" return self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc) def encode_tvc(self, params: ParamsOfEncodeTvc) -> ResultOfEncodeTvc: \"\"\" Encodes",
"ParamsOfGetBlockchainConfig ) -> ResultOfGetBlockchainConfig: \"\"\" Extract blockchain configuration from key block and also",
"params: See `types.ParamsOfBocCacheSet` :return: See `types.ResultOfBocCacheSet` \"\"\" return self.request(method='boc.cache_set', **params.dict) def cache_unpin(self, params:",
"\\ ResultOfGetCompilerVersion class TonBoc(TonModule): \"\"\" Free TON boc SDK API implementation \"\"\" @result_as(classname=ResultOfParse)",
"a JSON. JSON structure is compatible with GraphQL API shardstate object :param params:",
"ResultOfParse: \"\"\" Parses block boc into a JSON. JSON structure is compatible with",
"self.request(method='boc.cache_set', **params.dict) def cache_unpin(self, params: ParamsOfBocCacheUnpin): \"\"\" Unpin BOCs with specified pin. BOCs",
"libraries ans special options (see input params) :param params: See `types.ParamsOfEncodeTvc` :return: See",
"\"\"\" Unpin BOCs with specified pin. BOCs which don't have another pins will",
"with salt :param params: See `types.ParamsOfSetCodeSalt` :return: See `types.ResultOfSetCodeSalt` \"\"\" return self.request(method='boc.set_code_salt', **params.dict)",
"ans special options (see input params) :param params: See `types.ParamsOfEncodeTvc` :return: See `types.ResultOfEncodeTvc`",
"TvmCell type :param params: See `types.ParamsOfEncodeBoc` :return: See `types.ResultOfEncodeBoc` \"\"\" return self.request(method='boc.encode_boc', **params.dict)",
"-> ResultOfDecodeTvc: \"\"\" Decodes tvc into code, data, libraries and special options :param",
"(see input params) :param params: See `types.ParamsOfEncodeTvc` :return: See `types.ResultOfEncodeTvc` \"\"\" return self.request(method='boc.encode_tvc',",
"@result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version( self, params: ParamsOfGetCompilerVersion ) -> ResultOfGetCompilerVersion: \"\"\" Returns the compiler",
"bag of cells (BOC) with builder operations. This method provides the same functionality",
"shardstate object :param params: See `ParamsOfParseShardstate` :return: See `ResultOfParse` \"\"\" return self.request(method='boc.parse_shardstate', **params.dict)",
"salt if it is present :param params: See `types.ParamsOfGetCodeSalt` :return: See `types.ResultOfGetCodeSalt` \"\"\"",
"See `types.ParamsOfBocCacheGet` :return: See `types.ResultOfBocCacheGet` \"\"\" return self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet) def cache_set(self, params:",
"builder operations. This method provides the same functionality as Solidity TvmBuilder. Resulting BOC",
"-> ResultOfParse: \"\"\" Parses shardstate boc into a JSON. JSON structure is compatible",
"API transaction object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_transaction',",
"`types.ParamsOfEncodeBoc` :return: See `types.ResultOfEncodeBoc` \"\"\" return self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt) def get_code_salt( self, params:",
"ParamsOfDecodeTvc) -> ResultOfDecodeTvc: \"\"\" Decodes tvc into code, data, libraries and special options",
"ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\ ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc,",
"@result_as(classname=ResultOfGetBocHash) def get_boc_hash(self, params: ParamsOfGetBocHash) -> ResultOfGetBocHash: \"\"\" Calculates BOC root hash :param",
"def parse_block(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses block boc into a JSON.",
"from tonclient.module import TonModule from tonclient.types import ParamsOfParse, ResultOfParse, \\ ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash,",
"\"\"\" Parses block boc into a JSON. JSON structure is compatible with GraphQL",
"code's salt if it is present :param params: See `types.ParamsOfGetCodeSalt` :return: See `types.ResultOfGetCodeSalt`",
":return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse) def parse_block(self, params: ParamsOfParse) ->",
"\"\"\" return self.request(method='boc.cache_set', **params.dict) def cache_unpin(self, params: ParamsOfBocCacheUnpin): \"\"\" Unpin BOCs with specified",
"See `types.ResultOfGetCodeFromTvc` \"\"\" return self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet) def cache_get(self, params: ParamsOfBocCacheGet) -> ResultOfBocCacheGet:",
"with specified pin. BOCs which don't have another pins will be removed from",
"GraphQL API block object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return",
"implementation \"\"\" @result_as(classname=ResultOfParse) def parse_message(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses message boc",
"See `ResultOfGetBlockchainConfig` \"\"\" return self.request( method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc( self, params: ParamsOfGetCodeFromTvc)",
"contracts as TvmCell type :param params: See `types.ParamsOfEncodeBoc` :return: See `types.ResultOfEncodeBoc` \"\"\" return",
"params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse) def parse_block(self,",
"is compatible with GraphQL API shardstate object :param params: See `ParamsOfParseShardstate` :return: See",
"have another pins will be removed from cache :param params: See `types.ParamsOfBocCacheUnpin` :return:",
"ResultOfGetCodeSalt: \"\"\" Returns the contract code's salt if it is present :param params:",
"ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc, \\ ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion class",
"`types.ResultOfEncodeBoc` \"\"\" return self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt) def get_code_salt( self, params: ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt:",
"See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse) def parse_transaction(self, params: ParamsOfParse) -> ResultOfParse:",
"with GraphQL API shardstate object :param params: See `ParamsOfParseShardstate` :return: See `ResultOfParse` \"\"\"",
"def parse_shardstate( self, params: ParamsOfParseShardstate) -> ResultOfParse: \"\"\" Parses shardstate boc into a",
"set_code_salt( self, params: ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt: \"\"\" Sets new salt to contract code.",
"compatible with GraphQL API transaction object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse`",
"tvc into code, data, libraries and special options :param params: See `types.ParamsOfDecodeTvc` :return:",
"new contract code with salt :param params: See `types.ParamsOfSetCodeSalt` :return: See `types.ResultOfSetCodeSalt` \"\"\"",
"API account object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_account',",
"object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse)",
"compatible with GraphQL API shardstate object :param params: See `ParamsOfParseShardstate` :return: See `ResultOfParse`",
"JSON structure is compatible with GraphQL API block object :param params: See `types.ParamsOfParse`",
"params: ParamsOfGetBlockchainConfig ) -> ResultOfGetBlockchainConfig: \"\"\" Extract blockchain configuration from key block and",
"ParamsOfBocCacheUnpin): \"\"\" Unpin BOCs with specified pin. BOCs which don't have another pins",
"get_code_salt( self, params: ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt: \"\"\" Returns the contract code's salt if",
":return: See `types.ResultOfGetCodeFromTvc` \"\"\" return self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet) def cache_get(self, params: ParamsOfBocCacheGet) ->",
"See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse) def parse_account(self, params:",
"code. Returns the new contract code with salt :param params: See `types.ParamsOfSetCodeSalt` :return:",
"ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\ ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet, \\",
"ParamsOfParse) -> ResultOfParse: \"\"\" Parses block boc into a JSON. JSON structure is",
"JSON. JSON structure is compatible with GraphQL API block object :param params: See",
"ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc, \\ ParamsOfEncodeTvc,",
"with GraphQL API message object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\"",
"params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse) def parse_transaction(self,",
"See `types.ResultOfGetCodeSalt` \"\"\" return self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt) def set_code_salt( self, params: ParamsOfSetCodeSalt) ->",
"self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse) def parse_account(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses account boc",
"@result_as(classname=ResultOfParse) def parse_transaction(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses transaction boc into a",
"@result_as(classname=ResultOfParse) def parse_block(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses block boc into a",
"`ResultOfGetBocHash` \"\"\" return self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config( self, params: ParamsOfGetBlockchainConfig ) ->",
"and also from zero state :param params: See `ParamsOfGetBlockchainConfig` :return: See `ResultOfGetBlockchainConfig` \"\"\"",
"def get_boc_hash(self, params: ParamsOfGetBocHash) -> ResultOfGetBocHash: \"\"\" Calculates BOC root hash :param params:",
"\\ ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\",
"\"\"\" return self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc) def decode_tvc(self, params: ParamsOfDecodeTvc) -> ResultOfDecodeTvc: \"\"\" Decodes",
"ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\ ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt,",
"get_boc_hash(self, params: ParamsOfGetBocHash) -> ResultOfGetBocHash: \"\"\" Calculates BOC root hash :param params: See",
"`types.ResultOfParse` \"\"\" return self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse) def parse_transaction(self, params: ParamsOfParse) -> ResultOfParse: \"\"\"",
"tvc from code, data, libraries ans special options (see input params) :param params:",
"`types.ResultOfSetCodeSalt` \"\"\" return self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc) def decode_tvc(self, params: ParamsOfDecodeTvc) -> ResultOfDecodeTvc: \"\"\"",
"This method provides the same functionality as Solidity TvmBuilder. Resulting BOC of this",
"`types.ResultOfGetCodeSalt` \"\"\" return self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt) def set_code_salt( self, params: ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt:",
"self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc) def encode_boc(self, params: ParamsOfEncodeBoc) -> ResultOfEncodeBoc: \"\"\" Encodes bag of",
"get_code_from_tvc( self, params: ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc: \"\"\" Extracts code from TVC contract image",
"specified pin. BOCs which don't have another pins will be removed from cache",
"**params.dict) @result_as(classname=ResultOfSetCodeSalt) def set_code_salt( self, params: ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt: \"\"\" Sets new salt",
"-> ResultOfGetCodeFromTvc: \"\"\" Extracts code from TVC contract image :param params: See `types.ParamsOfGetCodeFromTvc`",
":param params: See `ParamsOfGetBocHash` :return: See `ResultOfGetBocHash` \"\"\" return self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def",
"API block object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_block',",
"Free TON boc SDK API implementation \"\"\" @result_as(classname=ResultOfParse) def parse_message(self, params: ParamsOfParse) ->",
"-> ResultOfParse: \"\"\" Parses message boc into a JSON. JSON structure is compatible",
"\"\"\" Returns the compiler version used to compile the code :param params: See",
"structure is compatible with GraphQL API message object :param params: See `types.ParamsOfParse` :return:",
"GraphQL API shardstate object :param params: See `ParamsOfParseShardstate` :return: See `ResultOfParse` \"\"\" return",
"params: See `types.ParamsOfBocCacheUnpin` :return: \"\"\" return self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc) def encode_boc(self, params: ParamsOfEncodeBoc)",
"See `types.ResultOfDecodeTvc` \"\"\" return self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc) def encode_tvc(self, params: ParamsOfEncodeTvc) -> ResultOfEncodeTvc:",
":param params: See `types.ParamsOfSetCodeSalt` :return: See `types.ResultOfSetCodeSalt` \"\"\" return self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc) def",
"self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse) def parse_shardstate( self, params: ParamsOfParseShardstate) -> ResultOfParse: \"\"\" Parses shardstate",
"encode_boc(self, params: ParamsOfEncodeBoc) -> ResultOfEncodeBoc: \"\"\" Encodes bag of cells (BOC) with builder",
"@result_as(classname=ResultOfParse) def parse_account(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses account boc into a",
"C++ contracts as TvmCell type :param params: See `types.ParamsOfEncodeBoc` :return: See `types.ResultOfEncodeBoc` \"\"\"",
"\"\"\" return self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc) def encode_boc(self, params: ParamsOfEncodeBoc) -> ResultOfEncodeBoc: \"\"\" Encodes",
"ParamsOfGetBocHash, ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\ ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet,",
"def get_code_salt( self, params: ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt: \"\"\" Returns the contract code's salt",
"ParamsOfParse) -> ResultOfParse: \"\"\" Parses account boc into a JSON. JSON structure is",
"as TvmCell type :param params: See `types.ParamsOfEncodeBoc` :return: See `types.ResultOfEncodeBoc` \"\"\" return self.request(method='boc.encode_boc',",
"ParamsOfEncodeTvc) -> ResultOfEncodeTvc: \"\"\" Encodes tvc from code, data, libraries ans special options",
"ParamsOfEncodeBoc, ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc, \\ ParamsOfEncodeTvc, ResultOfEncodeTvc,",
"See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse) def parse_transaction(self, params:",
"object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse)",
"params: See `ParamsOfParseShardstate` :return: See `ResultOfParse` \"\"\" return self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash) def get_boc_hash(self,",
"JSON structure is compatible with GraphQL API message object :param params: See `types.ParamsOfParse`",
"See `types.ResultOfSetCodeSalt` \"\"\" return self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc) def decode_tvc(self, params: ParamsOfDecodeTvc) -> ResultOfDecodeTvc:",
"\\ ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion class TonBoc(TonModule): \"\"\" Free TON boc SDK",
"is compatible with GraphQL API message object :param params: See `types.ParamsOfParse` :return: See",
"ResultOfBocCacheSet: \"\"\" Save BOC into cache :param params: See `types.ParamsOfBocCacheSet` :return: See `types.ResultOfBocCacheSet`",
"params: ParamsOfDecodeTvc) -> ResultOfDecodeTvc: \"\"\" Decodes tvc into code, data, libraries and special",
"return self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt) def set_code_salt( self, params: ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt: \"\"\" Sets",
"@result_as(classname=ResultOfParse) def parse_message(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses message boc into a",
"def decode_tvc(self, params: ParamsOfDecodeTvc) -> ResultOfDecodeTvc: \"\"\" Decodes tvc into code, data, libraries",
"GraphQL API transaction object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return",
"(BOC) with builder operations. This method provides the same functionality as Solidity TvmBuilder.",
"the compiler version used to compile the code :param params: See `types.ParamsOfGetCompilerVersion` :return:",
"**params.dict) @result_as(classname=ResultOfParse) def parse_block(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses block boc into",
"removed from cache :param params: See `types.ParamsOfBocCacheUnpin` :return: \"\"\" return self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc)",
"params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses message boc into a JSON. JSON structure",
"ResultOfEncodeBoc: \"\"\" Encodes bag of cells (BOC) with builder operations. This method provides",
"self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt) def set_code_salt( self, params: ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt: \"\"\" Sets new",
":param params: See `ParamsOfParseShardstate` :return: See `ResultOfParse` \"\"\" return self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash) def",
"params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses account boc into a JSON. JSON structure",
"`types.ResultOfBocCacheSet` \"\"\" return self.request(method='boc.cache_set', **params.dict) def cache_unpin(self, params: ParamsOfBocCacheUnpin): \"\"\" Unpin BOCs with",
"See `ParamsOfParseShardstate` :return: See `ResultOfParse` \"\"\" return self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash) def get_boc_hash(self, params:",
"Parses message boc into a JSON. JSON structure is compatible with GraphQL API",
"TonBoc(TonModule): \"\"\" Free TON boc SDK API implementation \"\"\" @result_as(classname=ResultOfParse) def parse_message(self, params:",
"self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config( self, params: ParamsOfGetBlockchainConfig ) -> ResultOfGetBlockchainConfig: \"\"\" Extract",
"shardstate boc into a JSON. JSON structure is compatible with GraphQL API shardstate",
":return: See `types.ResultOfSetCodeSalt` \"\"\" return self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc) def decode_tvc(self, params: ParamsOfDecodeTvc) ->",
"state :param params: See `ParamsOfGetBlockchainConfig` :return: See `ResultOfGetBlockchainConfig` \"\"\" return self.request( method='boc.get_blockchain_config', **params.dict)",
"ParamsOfParse, ResultOfParse, \\ ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet,",
"the contract code's salt if it is present :param params: See `types.ParamsOfGetCodeSalt` :return:",
"parse_message(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses message boc into a JSON. JSON",
"into code, data, libraries and special options :param params: See `types.ParamsOfDecodeTvc` :return: See",
"`types.ResultOfEncodeTvc` \"\"\" return self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version( self, params: ParamsOfGetCompilerVersion ) ->",
"\\ ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\ ResultOfBocCacheGet,",
"Returns the compiler version used to compile the code :param params: See `types.ParamsOfGetCompilerVersion`",
"ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc: \"\"\" Extracts code from TVC contract image :param params: See",
"-> ResultOfSetCodeSalt: \"\"\" Sets new salt to contract code. Returns the new contract",
"params: See `types.ParamsOfEncodeBoc` :return: See `types.ResultOfEncodeBoc` \"\"\" return self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt) def get_code_salt(",
"`types.ParamsOfGetCodeFromTvc` :return: See `types.ResultOfGetCodeFromTvc` \"\"\" return self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet) def cache_get(self, params: ParamsOfBocCacheGet)",
"@result_as(classname=ResultOfParse) def parse_shardstate( self, params: ParamsOfParseShardstate) -> ResultOfParse: \"\"\" Parses shardstate boc into",
":return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse) def parse_account(self, params: ParamsOfParse) ->",
"`types.ResultOfDecodeTvc` \"\"\" return self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc) def encode_tvc(self, params: ParamsOfEncodeTvc) -> ResultOfEncodeTvc: \"\"\"",
"`ResultOfGetBlockchainConfig` \"\"\" return self.request( method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc( self, params: ParamsOfGetCodeFromTvc) ->",
"return self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt) def get_code_salt( self, params: ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt: \"\"\" Returns",
"\"\"\" Calculates BOC root hash :param params: See `ParamsOfGetBocHash` :return: See `ResultOfGetBocHash` \"\"\"",
"block and also from zero state :param params: See `ParamsOfGetBlockchainConfig` :return: See `ResultOfGetBlockchainConfig`",
"Extracts code from TVC contract image :param params: See `types.ParamsOfGetCodeFromTvc` :return: See `types.ResultOfGetCodeFromTvc`",
"is compatible with GraphQL API block object :param params: See `types.ParamsOfParse` :return: See",
"configuration from key block and also from zero state :param params: See `ParamsOfGetBlockchainConfig`",
"into cache :param params: See `types.ParamsOfBocCacheSet` :return: See `types.ResultOfBocCacheSet` \"\"\" return self.request(method='boc.cache_set', **params.dict)",
"ParamsOfGetBocHash) -> ResultOfGetBocHash: \"\"\" Calculates BOC root hash :param params: See `ParamsOfGetBocHash` :return:",
"params: See `ParamsOfGetBocHash` :return: See `ResultOfGetBocHash` \"\"\" return self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config(",
"params: ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt: \"\"\" Sets new salt to contract code. Returns the",
"\"\"\" Parses shardstate boc into a JSON. JSON structure is compatible with GraphQL",
"cache_unpin(self, params: ParamsOfBocCacheUnpin): \"\"\" Unpin BOCs with specified pin. BOCs which don't have",
"TVC contract image :param params: See `types.ParamsOfGetCodeFromTvc` :return: See `types.ResultOfGetCodeFromTvc` \"\"\" return self.request(method='boc.get_code_from_tvc',",
"ParamsOfBocCacheGet) -> ResultOfBocCacheGet: \"\"\" Get BOC from cache :param params: See `types.ParamsOfBocCacheGet` :return:",
"params: ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc: \"\"\" Extracts code from TVC contract image :param params:",
"be removed from cache :param params: See `types.ParamsOfBocCacheUnpin` :return: \"\"\" return self.request(method='boc.cache_unpin', **params.dict)",
"options (see input params) :param params: See `types.ParamsOfEncodeTvc` :return: See `types.ResultOfEncodeTvc` \"\"\" return",
"\"\"\" return self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse) def parse_block(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses",
"\"\"\" Encodes bag of cells (BOC) with builder operations. This method provides the",
"\"\"\" @result_as(classname=ResultOfParse) def parse_message(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses message boc into",
"See `ResultOfParse` \"\"\" return self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash) def get_boc_hash(self, params: ParamsOfGetBocHash) -> ResultOfGetBocHash:",
"`types.ResultOfParse` \"\"\" return self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse) def parse_block(self, params: ParamsOfParse) -> ResultOfParse: \"\"\"",
"\"\"\" return self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config( self, params: ParamsOfGetBlockchainConfig ) -> ResultOfGetBlockchainConfig:",
":return: See `types.ResultOfEncodeBoc` \"\"\" return self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt) def get_code_salt( self, params: ParamsOfGetCodeSalt)",
":return: See `ResultOfParse` \"\"\" return self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash) def get_boc_hash(self, params: ParamsOfGetBocHash) ->",
"params: ParamsOfBocCacheSet) -> ResultOfBocCacheSet: \"\"\" Save BOC into cache :param params: See `types.ParamsOfBocCacheSet`",
":param params: See `types.ParamsOfEncodeTvc` :return: See `types.ResultOfEncodeTvc` \"\"\" return self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion) def",
"**params.dict) @result_as(classname=ResultOfDecodeTvc) def decode_tvc(self, params: ParamsOfDecodeTvc) -> ResultOfDecodeTvc: \"\"\" Decodes tvc into code,",
"transaction object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_transaction', **params.dict)",
"return self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc) def decode_tvc(self, params: ParamsOfDecodeTvc) -> ResultOfDecodeTvc: \"\"\" Decodes tvc",
"return self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version( self, params: ParamsOfGetCompilerVersion ) -> ResultOfGetCompilerVersion: \"\"\"",
"\"\"\" Extracts code from TVC contract image :param params: See `types.ParamsOfGetCodeFromTvc` :return: See",
"ParamsOfParse) -> ResultOfParse: \"\"\" Parses transaction boc into a JSON. JSON structure is",
"params: See `types.ParamsOfGetCodeSalt` :return: See `types.ResultOfGetCodeSalt` \"\"\" return self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt) def set_code_salt(",
"which don't have another pins will be removed from cache :param params: See",
"Resulting BOC of this method can be passed into Solidity and C++ contracts",
"def parse_transaction(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses transaction boc into a JSON.",
":return: See `ResultOfGetBocHash` \"\"\" return self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config( self, params: ParamsOfGetBlockchainConfig",
"compile the code :param params: See `types.ParamsOfGetCompilerVersion` :return: See `types.ResultOfGetCompilerVersion` \"\"\" return self.request(method='boc.get_compiler_version',",
"@result_as(classname=ResultOfSetCodeSalt) def set_code_salt( self, params: ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt: \"\"\" Sets new salt to",
"\"\"\" return self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse) def parse_account(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses",
"@result_as(classname=ResultOfDecodeTvc) def decode_tvc(self, params: ParamsOfDecodeTvc) -> ResultOfDecodeTvc: \"\"\" Decodes tvc into code, data,",
"self, params: ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc: \"\"\" Extracts code from TVC contract image :param",
"import TonModule from tonclient.types import ParamsOfParse, ResultOfParse, \\ ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig,",
"GraphQL API account object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return",
"params: ParamsOfBocCacheGet) -> ResultOfBocCacheGet: \"\"\" Get BOC from cache :param params: See `types.ParamsOfBocCacheGet`",
":param params: See `types.ParamsOfBocCacheGet` :return: See `types.ResultOfBocCacheGet` \"\"\" return self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet) def",
"return self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse) def parse_account(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses account",
"`types.ResultOfParse` \"\"\" return self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse) def parse_account(self, params: ParamsOfParse) -> ResultOfParse: \"\"\"",
"ParamsOfParse) -> ResultOfParse: \"\"\" Parses message boc into a JSON. JSON structure is",
"See `types.ParamsOfDecodeTvc` :return: See `types.ResultOfDecodeTvc` \"\"\" return self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc) def encode_tvc(self, params:",
":return: See `types.ResultOfBocCacheGet` \"\"\" return self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet) def cache_set(self, params: ParamsOfBocCacheSet) ->",
"`ParamsOfGetBlockchainConfig` :return: See `ResultOfGetBlockchainConfig` \"\"\" return self.request( method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc( self,",
"with builder operations. This method provides the same functionality as Solidity TvmBuilder. Resulting",
"params: ParamsOfGetBocHash) -> ResultOfGetBocHash: \"\"\" Calculates BOC root hash :param params: See `ParamsOfGetBocHash`",
"params: ParamsOfEncodeBoc) -> ResultOfEncodeBoc: \"\"\" Encodes bag of cells (BOC) with builder operations.",
"self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash) def get_boc_hash(self, params: ParamsOfGetBocHash) -> ResultOfGetBocHash: \"\"\" Calculates BOC root",
"from key block and also from zero state :param params: See `ParamsOfGetBlockchainConfig` :return:",
"same functionality as Solidity TvmBuilder. Resulting BOC of this method can be passed",
"return self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse) def parse_shardstate( self, params: ParamsOfParseShardstate) -> ResultOfParse: \"\"\" Parses",
"params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse) def parse_account(self,",
"**params.dict) @result_as(classname=ResultOfBocCacheGet) def cache_get(self, params: ParamsOfBocCacheGet) -> ResultOfBocCacheGet: \"\"\" Get BOC from cache",
"ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc, \\ ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion class TonBoc(TonModule):",
"\"\"\" Decodes tvc into code, data, libraries and special options :param params: See",
"def get_compiler_version( self, params: ParamsOfGetCompilerVersion ) -> ResultOfGetCompilerVersion: \"\"\" Returns the compiler version",
"message object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_message', **params.dict)",
"ResultOfGetCodeFromTvc: \"\"\" Extracts code from TVC contract image :param params: See `types.ParamsOfGetCodeFromTvc` :return:",
":return: \"\"\" return self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc) def encode_boc(self, params: ParamsOfEncodeBoc) -> ResultOfEncodeBoc: \"\"\"",
"also from zero state :param params: See `ParamsOfGetBlockchainConfig` :return: See `ResultOfGetBlockchainConfig` \"\"\" return",
"-> ResultOfBocCacheSet: \"\"\" Save BOC into cache :param params: See `types.ParamsOfBocCacheSet` :return: See",
"of cells (BOC) with builder operations. This method provides the same functionality as",
"passed into Solidity and C++ contracts as TvmCell type :param params: See `types.ParamsOfEncodeBoc`",
"def set_code_salt( self, params: ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt: \"\"\" Sets new salt to contract",
"a JSON. JSON structure is compatible with GraphQL API transaction object :param params:",
"params: ParamsOfEncodeTvc) -> ResultOfEncodeTvc: \"\"\" Encodes tvc from code, data, libraries ans special",
"tonclient.module import TonModule from tonclient.types import ParamsOfParse, ResultOfParse, \\ ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash, \\",
"params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse) def parse_shardstate(",
"contract image :param params: See `types.ParamsOfGetCodeFromTvc` :return: See `types.ResultOfGetCodeFromTvc` \"\"\" return self.request(method='boc.get_code_from_tvc', **params.dict)",
"`types.ParamsOfBocCacheUnpin` :return: \"\"\" return self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc) def encode_boc(self, params: ParamsOfEncodeBoc) -> ResultOfEncodeBoc:",
"JSON. JSON structure is compatible with GraphQL API transaction object :param params: See",
"account boc into a JSON. JSON structure is compatible with GraphQL API account",
"decode_tvc(self, params: ParamsOfDecodeTvc) -> ResultOfDecodeTvc: \"\"\" Decodes tvc into code, data, libraries and",
"self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc) def encode_tvc(self, params: ParamsOfEncodeTvc) -> ResultOfEncodeTvc: \"\"\" Encodes tvc from",
"pin. BOCs which don't have another pins will be removed from cache :param",
"-> ResultOfEncodeTvc: \"\"\" Encodes tvc from code, data, libraries ans special options (see",
"result_as from tonclient.module import TonModule from tonclient.types import ParamsOfParse, ResultOfParse, \\ ParamsOfParseShardstate, ParamsOfGetBocHash,",
":return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse) def parse_transaction(self, params: ParamsOfParse) ->",
"return self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse) def parse_transaction(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses transaction",
"`types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse) def parse_shardstate( self, params:",
"structure is compatible with GraphQL API transaction object :param params: See `types.ParamsOfParse` :return:",
"\\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\ ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin,",
"ParamsOfBocCacheGet, \\ ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt,",
"TonModule from tonclient.types import ParamsOfParse, ResultOfParse, \\ ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig,",
"def cache_set(self, params: ParamsOfBocCacheSet) -> ResultOfBocCacheSet: \"\"\" Save BOC into cache :param params:",
"params: See `types.ParamsOfDecodeTvc` :return: See `types.ResultOfDecodeTvc` \"\"\" return self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc) def encode_tvc(self,",
"Save BOC into cache :param params: See `types.ParamsOfBocCacheSet` :return: See `types.ResultOfBocCacheSet` \"\"\" return",
"if it is present :param params: See `types.ParamsOfGetCodeSalt` :return: See `types.ResultOfGetCodeSalt` \"\"\" return",
"TON boc SDK API implementation \"\"\" @result_as(classname=ResultOfParse) def parse_message(self, params: ParamsOfParse) -> ResultOfParse:",
":param params: See `types.ParamsOfEncodeBoc` :return: See `types.ResultOfEncodeBoc` \"\"\" return self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt) def",
":param params: See `types.ParamsOfBocCacheUnpin` :return: \"\"\" return self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc) def encode_boc(self, params:",
"Parses shardstate boc into a JSON. JSON structure is compatible with GraphQL API",
"ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion class TonBoc(TonModule): \"\"\" Free TON boc SDK API implementation \"\"\"",
"functionality as Solidity TvmBuilder. Resulting BOC of this method can be passed into",
"self.request( method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc( self, params: ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc: \"\"\" Extracts",
"message boc into a JSON. JSON structure is compatible with GraphQL API message",
"into a JSON. JSON structure is compatible with GraphQL API block object :param",
"API message object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_message',",
"Parses account boc into a JSON. JSON structure is compatible with GraphQL API",
"this method can be passed into Solidity and C++ contracts as TvmCell type",
"special options :param params: See `types.ParamsOfDecodeTvc` :return: See `types.ResultOfDecodeTvc` \"\"\" return self.request(method='boc.decode_tvc', **params.dict)",
"def parse_account(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses account boc into a JSON.",
"ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc,",
"compatible with GraphQL API message object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse`",
"return self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet) def cache_set(self, params: ParamsOfBocCacheSet) -> ResultOfBocCacheSet: \"\"\" Save BOC",
"ResultOfDecodeTvc: \"\"\" Decodes tvc into code, data, libraries and special options :param params:",
"\"\"\" Parses account boc into a JSON. JSON structure is compatible with GraphQL",
":return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse) def parse_shardstate( self, params: ParamsOfParseShardstate)",
"from cache :param params: See `types.ParamsOfBocCacheUnpin` :return: \"\"\" return self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc) def",
"JSON. JSON structure is compatible with GraphQL API shardstate object :param params: See",
"-> ResultOfGetCodeSalt: \"\"\" Returns the contract code's salt if it is present :param",
") -> ResultOfGetBlockchainConfig: \"\"\" Extract blockchain configuration from key block and also from",
"JSON structure is compatible with GraphQL API transaction object :param params: See `types.ParamsOfParse`",
"don't have another pins will be removed from cache :param params: See `types.ParamsOfBocCacheUnpin`",
"JSON structure is compatible with GraphQL API account object :param params: See `types.ParamsOfParse`",
"structure is compatible with GraphQL API shardstate object :param params: See `ParamsOfParseShardstate` :return:",
"def get_blockchain_config( self, params: ParamsOfGetBlockchainConfig ) -> ResultOfGetBlockchainConfig: \"\"\" Extract blockchain configuration from",
"\"\"\" Extract blockchain configuration from key block and also from zero state :param",
"method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc( self, params: ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc: \"\"\" Extracts code",
"provides the same functionality as Solidity TvmBuilder. Resulting BOC of this method can",
"Returns the new contract code with salt :param params: See `types.ParamsOfSetCodeSalt` :return: See",
"encode_tvc(self, params: ParamsOfEncodeTvc) -> ResultOfEncodeTvc: \"\"\" Encodes tvc from code, data, libraries ans",
"ParamsOfGetCompilerVersion ) -> ResultOfGetCompilerVersion: \"\"\" Returns the compiler version used to compile the",
"self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet) def cache_set(self, params: ParamsOfBocCacheSet) -> ResultOfBocCacheSet: \"\"\" Save BOC into",
"compatible with GraphQL API block object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse`",
"params: See `ParamsOfGetBlockchainConfig` :return: See `ResultOfGetBlockchainConfig` \"\"\" return self.request( method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def",
"tonclient.types import ParamsOfParse, ResultOfParse, \\ ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc,",
"ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion class TonBoc(TonModule): \"\"\" Free TON boc SDK API",
"**params.dict) def cache_unpin(self, params: ParamsOfBocCacheUnpin): \"\"\" Unpin BOCs with specified pin. BOCs which",
"params: ParamsOfGetCompilerVersion ) -> ResultOfGetCompilerVersion: \"\"\" Returns the compiler version used to compile",
"self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version( self, params: ParamsOfGetCompilerVersion ) -> ResultOfGetCompilerVersion: \"\"\" Returns",
"boc into a JSON. JSON structure is compatible with GraphQL API block object",
"Calculates BOC root hash :param params: See `ParamsOfGetBocHash` :return: See `ResultOfGetBocHash` \"\"\" return",
"BOC root hash :param params: See `ParamsOfGetBocHash` :return: See `ResultOfGetBocHash` \"\"\" return self.request(method='boc.get_boc_hash',",
"See `types.ParamsOfEncodeBoc` :return: See `types.ResultOfEncodeBoc` \"\"\" return self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt) def get_code_salt( self,",
"def get_code_from_tvc( self, params: ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc: \"\"\" Extracts code from TVC contract",
"See `types.ResultOfEncodeTvc` \"\"\" return self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version( self, params: ParamsOfGetCompilerVersion )",
"-> ResultOfBocCacheGet: \"\"\" Get BOC from cache :param params: See `types.ParamsOfBocCacheGet` :return: See",
"\"\"\" Save BOC into cache :param params: See `types.ParamsOfBocCacheSet` :return: See `types.ResultOfBocCacheSet` \"\"\"",
":param params: See `types.ParamsOfGetCodeSalt` :return: See `types.ResultOfGetCodeSalt` \"\"\" return self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt) def",
"JSON. JSON structure is compatible with GraphQL API message object :param params: See",
"\\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc, \\",
"self, params: ParamsOfGetBlockchainConfig ) -> ResultOfGetBlockchainConfig: \"\"\" Extract blockchain configuration from key block",
"libraries and special options :param params: See `types.ParamsOfDecodeTvc` :return: See `types.ResultOfDecodeTvc` \"\"\" return",
"params) :param params: See `types.ParamsOfEncodeTvc` :return: See `types.ResultOfEncodeTvc` \"\"\" return self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion)",
"\"\"\" Sets new salt to contract code. Returns the new contract code with",
"boc SDK API implementation \"\"\" @result_as(classname=ResultOfParse) def parse_message(self, params: ParamsOfParse) -> ResultOfParse: \"\"\"",
"See `types.ParamsOfGetCodeFromTvc` :return: See `types.ResultOfGetCodeFromTvc` \"\"\" return self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet) def cache_get(self, params:",
"See `types.ParamsOfSetCodeSalt` :return: See `types.ResultOfSetCodeSalt` \"\"\" return self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc) def decode_tvc(self, params:",
"return self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc) def encode_tvc(self, params: ParamsOfEncodeTvc) -> ResultOfEncodeTvc: \"\"\" Encodes tvc",
"into a JSON. JSON structure is compatible with GraphQL API shardstate object :param",
") -> ResultOfGetCompilerVersion: \"\"\" Returns the compiler version used to compile the code",
"params: See `types.ParamsOfBocCacheGet` :return: See `types.ResultOfBocCacheGet` \"\"\" return self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet) def cache_set(self,",
"Decodes tvc into code, data, libraries and special options :param params: See `types.ParamsOfDecodeTvc`",
"TvmBuilder. Resulting BOC of this method can be passed into Solidity and C++",
"def encode_boc(self, params: ParamsOfEncodeBoc) -> ResultOfEncodeBoc: \"\"\" Encodes bag of cells (BOC) with",
"of this method can be passed into Solidity and C++ contracts as TvmCell",
"self, params: ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt: \"\"\" Sets new salt to contract code. Returns",
"code with salt :param params: See `types.ParamsOfSetCodeSalt` :return: See `types.ResultOfSetCodeSalt` \"\"\" return self.request(method='boc.set_code_salt',",
"@result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config( self, params: ParamsOfGetBlockchainConfig ) -> ResultOfGetBlockchainConfig: \"\"\" Extract blockchain configuration",
"**params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc( self, params: ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc: \"\"\" Extracts code from",
"ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion class TonBoc(TonModule): \"\"\" Free TON boc SDK API implementation",
"**params.dict) @result_as(classname=ResultOfGetCodeSalt) def get_code_salt( self, params: ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt: \"\"\" Returns the contract",
"code, data, libraries ans special options (see input params) :param params: See `types.ParamsOfEncodeTvc`",
"ResultOfParse: \"\"\" Parses account boc into a JSON. JSON structure is compatible with",
"**params.dict) @result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version( self, params: ParamsOfGetCompilerVersion ) -> ResultOfGetCompilerVersion: \"\"\" Returns the",
"\"\"\" return self.request( method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc( self, params: ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc:",
"Parses transaction boc into a JSON. JSON structure is compatible with GraphQL API",
"boc into a JSON. JSON structure is compatible with GraphQL API account object",
"and special options :param params: See `types.ParamsOfDecodeTvc` :return: See `types.ResultOfDecodeTvc` \"\"\" return self.request(method='boc.decode_tvc',",
"@result_as(classname=ResultOfEncodeTvc) def encode_tvc(self, params: ParamsOfEncodeTvc) -> ResultOfEncodeTvc: \"\"\" Encodes tvc from code, data,",
"**params.dict) @result_as(classname=ResultOfEncodeTvc) def encode_tvc(self, params: ParamsOfEncodeTvc) -> ResultOfEncodeTvc: \"\"\" Encodes tvc from code,",
"\"\"\" return self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt) def get_code_salt( self, params: ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt: \"\"\"",
"self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse) def parse_transaction(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses transaction boc",
"cache_get(self, params: ParamsOfBocCacheGet) -> ResultOfBocCacheGet: \"\"\" Get BOC from cache :param params: See",
"is compatible with GraphQL API transaction object :param params: See `types.ParamsOfParse` :return: See",
"new salt to contract code. Returns the new contract code with salt :param",
"\"\"\" Returns the contract code's salt if it is present :param params: See",
"See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse) def parse_account(self, params: ParamsOfParse) -> ResultOfParse:",
"can be passed into Solidity and C++ contracts as TvmCell type :param params:",
"`types.ParamsOfEncodeTvc` :return: See `types.ResultOfEncodeTvc` \"\"\" return self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version( self, params:",
"ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc, \\ ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion class TonBoc(TonModule): \"\"\" Free",
"Parses block boc into a JSON. JSON structure is compatible with GraphQL API",
"ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\ ResultOfBocCacheGet, ParamsOfBocCacheSet,",
"boc into a JSON. JSON structure is compatible with GraphQL API message object",
"parse_shardstate( self, params: ParamsOfParseShardstate) -> ResultOfParse: \"\"\" Parses shardstate boc into a JSON.",
"ResultOfEncodeTvc: \"\"\" Encodes tvc from code, data, libraries ans special options (see input",
"from code, data, libraries ans special options (see input params) :param params: See",
"into Solidity and C++ contracts as TvmCell type :param params: See `types.ParamsOfEncodeBoc` :return:",
"parse_transaction(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses transaction boc into a JSON. JSON",
"See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse) def parse_shardstate( self, params: ParamsOfParseShardstate) ->",
"See `types.ParamsOfGetCodeSalt` :return: See `types.ResultOfGetCodeSalt` \"\"\" return self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt) def set_code_salt( self,",
"operations. This method provides the same functionality as Solidity TvmBuilder. Resulting BOC of",
"code, data, libraries and special options :param params: See `types.ParamsOfDecodeTvc` :return: See `types.ResultOfDecodeTvc`",
"block object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_block', **params.dict)",
"salt :param params: See `types.ParamsOfSetCodeSalt` :return: See `types.ResultOfSetCodeSalt` \"\"\" return self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc)",
"-> ResultOfGetBocHash: \"\"\" Calculates BOC root hash :param params: See `ParamsOfGetBocHash` :return: See",
"params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses transaction boc into a JSON. JSON structure",
"type :param params: See `types.ParamsOfEncodeBoc` :return: See `types.ResultOfEncodeBoc` \"\"\" return self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt)",
":param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse) def",
"to compile the code :param params: See `types.ParamsOfGetCompilerVersion` :return: See `types.ResultOfGetCompilerVersion` \"\"\" return",
"@result_as(classname=ResultOfBocCacheGet) def cache_get(self, params: ParamsOfBocCacheGet) -> ResultOfBocCacheGet: \"\"\" Get BOC from cache :param",
":return: See `types.ResultOfGetCodeSalt` \"\"\" return self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt) def set_code_salt( self, params: ParamsOfSetCodeSalt)",
"\"\"\" return self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt) def set_code_salt( self, params: ParamsOfSetCodeSalt) -> ResultOfSetCodeSalt: \"\"\"",
":param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse) def",
"object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse)",
"`ParamsOfParseShardstate` :return: See `ResultOfParse` \"\"\" return self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash) def get_boc_hash(self, params: ParamsOfGetBocHash)",
"ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc, \\ ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion,",
"return self.request( method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc( self, params: ParamsOfGetCodeFromTvc) -> ResultOfGetCodeFromTvc: \"\"\"",
"def cache_get(self, params: ParamsOfBocCacheGet) -> ResultOfBocCacheGet: \"\"\" Get BOC from cache :param params:",
"the new contract code with salt :param params: See `types.ParamsOfSetCodeSalt` :return: See `types.ResultOfSetCodeSalt`",
"cache :param params: See `types.ParamsOfBocCacheUnpin` :return: \"\"\" return self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc) def encode_boc(self,",
"class TonBoc(TonModule): \"\"\" Free TON boc SDK API implementation \"\"\" @result_as(classname=ResultOfParse) def parse_message(self,",
"@result_as(classname=ResultOfGetCodeSalt) def get_code_salt( self, params: ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt: \"\"\" Returns the contract code's",
"`types.ResultOfParse` \"\"\" return self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse) def parse_shardstate( self, params: ParamsOfParseShardstate) -> ResultOfParse:",
":param params: See `types.ParamsOfGetCodeFromTvc` :return: See `types.ResultOfGetCodeFromTvc` \"\"\" return self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet) def",
"See `types.ResultOfBocCacheGet` \"\"\" return self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet) def cache_set(self, params: ParamsOfBocCacheSet) -> ResultOfBocCacheSet:",
"`types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse) def parse_transaction(self, params: ParamsOfParse)",
"present :param params: See `types.ParamsOfGetCodeSalt` :return: See `types.ResultOfGetCodeSalt` \"\"\" return self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt)",
"return self.request(method='boc.cache_set', **params.dict) def cache_unpin(self, params: ParamsOfBocCacheUnpin): \"\"\" Unpin BOCs with specified pin.",
"See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse) def parse_block(self, params: ParamsOfParse) -> ResultOfParse:",
"boc into a JSON. JSON structure is compatible with GraphQL API shardstate object",
"**params.dict) @result_as(classname=ResultOfParse) def parse_transaction(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses transaction boc into",
"ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\ ResultOfBocCacheGet, ParamsOfBocCacheSet, ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc,",
"`ParamsOfGetBocHash` :return: See `ResultOfGetBocHash` \"\"\" return self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config( self, params:",
"hash :param params: See `ParamsOfGetBocHash` :return: See `ResultOfGetBocHash` \"\"\" return self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig)",
"used to compile the code :param params: See `types.ParamsOfGetCompilerVersion` :return: See `types.ResultOfGetCompilerVersion` \"\"\"",
"a JSON. JSON structure is compatible with GraphQL API account object :param params:",
"params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses block boc into a JSON. JSON structure",
"from zero state :param params: See `ParamsOfGetBlockchainConfig` :return: See `ResultOfGetBlockchainConfig` \"\"\" return self.request(",
"method can be passed into Solidity and C++ contracts as TvmCell type :param",
"with GraphQL API block object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\"",
"self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse) def parse_block(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses block boc",
"`types.ParamsOfDecodeTvc` :return: See `types.ResultOfDecodeTvc` \"\"\" return self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc) def encode_tvc(self, params: ParamsOfEncodeTvc)",
"with GraphQL API account object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\"",
"object :param params: See `ParamsOfParseShardstate` :return: See `ResultOfParse` \"\"\" return self.request(method='boc.parse_shardstate', **params.dict) @result_as(classname=ResultOfGetBocHash)",
"@result_as(classname=ResultOfEncodeBoc) def encode_boc(self, params: ParamsOfEncodeBoc) -> ResultOfEncodeBoc: \"\"\" Encodes bag of cells (BOC)",
"See `types.ParamsOfEncodeTvc` :return: See `types.ResultOfEncodeTvc` \"\"\" return self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version( self,",
"ParamsOfEncodeBoc) -> ResultOfEncodeBoc: \"\"\" Encodes bag of cells (BOC) with builder operations. This",
"-> ResultOfEncodeBoc: \"\"\" Encodes bag of cells (BOC) with builder operations. This method",
"data, libraries and special options :param params: See `types.ParamsOfDecodeTvc` :return: See `types.ResultOfDecodeTvc` \"\"\"",
"ResultOfGetCompilerVersion: \"\"\" Returns the compiler version used to compile the code :param params:",
"See `types.ResultOfBocCacheSet` \"\"\" return self.request(method='boc.cache_set', **params.dict) def cache_unpin(self, params: ParamsOfBocCacheUnpin): \"\"\" Unpin BOCs",
"data, libraries ans special options (see input params) :param params: See `types.ParamsOfEncodeTvc` :return:",
"\"\"\" Free TON boc SDK API implementation \"\"\" @result_as(classname=ResultOfParse) def parse_message(self, params: ParamsOfParse)",
"another pins will be removed from cache :param params: See `types.ParamsOfBocCacheUnpin` :return: \"\"\"",
"ParamsOfDecodeTvc, ResultOfDecodeTvc, \\ ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion class TonBoc(TonModule): \"\"\" Free TON",
"Unpin BOCs with specified pin. BOCs which don't have another pins will be",
"-> ResultOfParse: \"\"\" Parses block boc into a JSON. JSON structure is compatible",
"a JSON. JSON structure is compatible with GraphQL API message object :param params:",
"**params.dict) @result_as(classname=ResultOfParse) def parse_account(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses account boc into",
"`types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_transaction', **params.dict) @result_as(classname=ResultOfParse) def parse_account(self, params: ParamsOfParse)",
"def cache_unpin(self, params: ParamsOfBocCacheUnpin): \"\"\" Unpin BOCs with specified pin. BOCs which don't",
"salt to contract code. Returns the new contract code with salt :param params:",
"code from TVC contract image :param params: See `types.ParamsOfGetCodeFromTvc` :return: See `types.ResultOfGetCodeFromTvc` \"\"\"",
"BOC from cache :param params: See `types.ParamsOfBocCacheGet` :return: See `types.ResultOfBocCacheGet` \"\"\" return self.request(method='boc.cache_get',",
"ParamsOfBocCacheSet, ResultOfBocCacheSet, \\ ParamsOfBocCacheUnpin, ParamsOfEncodeBoc, ResultOfEncodeBoc, \\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt, ParamsOfDecodeTvc,",
"contract code. Returns the new contract code with salt :param params: See `types.ParamsOfSetCodeSalt`",
"compiler version used to compile the code :param params: See `types.ParamsOfGetCompilerVersion` :return: See",
"ResultOfParse: \"\"\" Parses shardstate boc into a JSON. JSON structure is compatible with",
"Extract blockchain configuration from key block and also from zero state :param params:",
"from cache :param params: See `types.ParamsOfBocCacheGet` :return: See `types.ResultOfBocCacheGet` \"\"\" return self.request(method='boc.cache_get', **params.dict)",
"as Solidity TvmBuilder. Resulting BOC of this method can be passed into Solidity",
"the code :param params: See `types.ParamsOfGetCompilerVersion` :return: See `types.ResultOfGetCompilerVersion` \"\"\" return self.request(method='boc.get_compiler_version', **params.dict)",
"ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt: \"\"\" Returns the contract code's salt if it is present",
"to contract code. Returns the new contract code with salt :param params: See",
"-> ResultOfParse: \"\"\" Parses transaction boc into a JSON. JSON structure is compatible",
"root hash :param params: See `ParamsOfGetBocHash` :return: See `ResultOfGetBocHash` \"\"\" return self.request(method='boc.get_boc_hash', **params.dict)",
"ResultOfParse, \\ ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc, ParamsOfBocCacheGet, \\",
"BOC into cache :param params: See `types.ParamsOfBocCacheSet` :return: See `types.ResultOfBocCacheSet` \"\"\" return self.request(method='boc.cache_set',",
"See `types.ParamsOfBocCacheUnpin` :return: \"\"\" return self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc) def encode_boc(self, params: ParamsOfEncodeBoc) ->",
"into a JSON. JSON structure is compatible with GraphQL API message object :param",
"GraphQL API message object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return",
"`types.ResultOfBocCacheGet` \"\"\" return self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet) def cache_set(self, params: ParamsOfBocCacheSet) -> ResultOfBocCacheSet: \"\"\"",
"\"\"\" return self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version( self, params: ParamsOfGetCompilerVersion ) -> ResultOfGetCompilerVersion:",
"params: ParamsOfParseShardstate) -> ResultOfParse: \"\"\" Parses shardstate boc into a JSON. JSON structure",
"ResultOfGetCompilerVersion class TonBoc(TonModule): \"\"\" Free TON boc SDK API implementation \"\"\" @result_as(classname=ResultOfParse) def",
"**params.dict) @result_as(classname=ResultOfParse) def parse_shardstate( self, params: ParamsOfParseShardstate) -> ResultOfParse: \"\"\" Parses shardstate boc",
"`types.ParamsOfSetCodeSalt` :return: See `types.ResultOfSetCodeSalt` \"\"\" return self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc) def decode_tvc(self, params: ParamsOfDecodeTvc)",
"self, params: ParamsOfGetCompilerVersion ) -> ResultOfGetCompilerVersion: \"\"\" Returns the compiler version used to",
"\"\"\" Parses message boc into a JSON. JSON structure is compatible with GraphQL",
"def encode_tvc(self, params: ParamsOfEncodeTvc) -> ResultOfEncodeTvc: \"\"\" Encodes tvc from code, data, libraries",
"object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse)",
"will be removed from cache :param params: See `types.ParamsOfBocCacheUnpin` :return: \"\"\" return self.request(method='boc.cache_unpin',",
"self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc) def decode_tvc(self, params: ParamsOfDecodeTvc) -> ResultOfDecodeTvc: \"\"\" Decodes tvc into",
"`types.ParamsOfGetCodeSalt` :return: See `types.ResultOfGetCodeSalt` \"\"\" return self.request(method='boc.get_code_salt', **params.dict) @result_as(classname=ResultOfSetCodeSalt) def set_code_salt( self, params:",
"**params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config( self, params: ParamsOfGetBlockchainConfig ) -> ResultOfGetBlockchainConfig: \"\"\" Extract blockchain",
"**params.dict) @result_as(classname=ResultOfGetBocHash) def get_boc_hash(self, params: ParamsOfGetBocHash) -> ResultOfGetBocHash: \"\"\" Calculates BOC root hash",
"is compatible with GraphQL API account object :param params: See `types.ParamsOfParse` :return: See",
"Encodes bag of cells (BOC) with builder operations. This method provides the same",
"with GraphQL API transaction object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\"",
"See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse) def parse_shardstate( self,",
"ResultOfDecodeTvc, \\ ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\ ResultOfGetCompilerVersion class TonBoc(TonModule): \"\"\" Free TON boc",
"-> ResultOfParse: \"\"\" Parses account boc into a JSON. JSON structure is compatible",
"key block and also from zero state :param params: See `ParamsOfGetBlockchainConfig` :return: See",
"ParamsOfBocCacheSet) -> ResultOfBocCacheSet: \"\"\" Save BOC into cache :param params: See `types.ParamsOfBocCacheSet` :return:",
"Sets new salt to contract code. Returns the new contract code with salt",
"See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_account', **params.dict) @result_as(classname=ResultOfParse) def parse_block(self, params:",
"parse_block(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses block boc into a JSON. JSON",
"\"\"\" return self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse) def parse_shardstate( self, params: ParamsOfParseShardstate) -> ResultOfParse: \"\"\"",
"into a JSON. JSON structure is compatible with GraphQL API account object :param",
"self.request(method='boc.encode_boc', **params.dict) @result_as(classname=ResultOfGetCodeSalt) def get_code_salt( self, params: ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt: \"\"\" Returns the",
"Encodes tvc from code, data, libraries ans special options (see input params) :param",
"import result_as from tonclient.module import TonModule from tonclient.types import ParamsOfParse, ResultOfParse, \\ ParamsOfParseShardstate,",
"import ParamsOfParse, ResultOfParse, \\ ParamsOfParseShardstate, ParamsOfGetBocHash, ResultOfGetBocHash, \\ ParamsOfGetBlockchainConfig, ResultOfGetBlockchainConfig, \\ ParamsOfGetCodeFromTvc, ResultOfGetCodeFromTvc,",
"API implementation \"\"\" @result_as(classname=ResultOfParse) def parse_message(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses message",
"\"\"\" return self.request(method='boc.parse_message', **params.dict) @result_as(classname=ResultOfParse) def parse_transaction(self, params: ParamsOfParse) -> ResultOfParse: \"\"\" Parses",
":param params: See `types.ParamsOfDecodeTvc` :return: See `types.ResultOfDecodeTvc` \"\"\" return self.request(method='boc.decode_tvc', **params.dict) @result_as(classname=ResultOfEncodeTvc) def",
":param params: See `ParamsOfGetBlockchainConfig` :return: See `ResultOfGetBlockchainConfig` \"\"\" return self.request( method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc)",
":return: See `types.ResultOfEncodeTvc` \"\"\" return self.request(method='boc.encode_tvc', **params.dict) @result_as(classname=ResultOfGetCompilerVersion) def get_compiler_version( self, params: ParamsOfGetCompilerVersion",
"ResultOfGetBocHash: \"\"\" Calculates BOC root hash :param params: See `ParamsOfGetBocHash` :return: See `ResultOfGetBocHash`",
"account object :param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_account', **params.dict)",
"pins will be removed from cache :param params: See `types.ParamsOfBocCacheUnpin` :return: \"\"\" return",
"and C++ contracts as TvmCell type :param params: See `types.ParamsOfEncodeBoc` :return: See `types.ResultOfEncodeBoc`",
"JSON. JSON structure is compatible with GraphQL API account object :param params: See",
"return self.request(method='boc.cache_unpin', **params.dict) @result_as(classname=ResultOfEncodeBoc) def encode_boc(self, params: ParamsOfEncodeBoc) -> ResultOfEncodeBoc: \"\"\" Encodes bag",
"cache :param params: See `types.ParamsOfBocCacheGet` :return: See `types.ResultOfBocCacheGet` \"\"\" return self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet)",
"cells (BOC) with builder operations. This method provides the same functionality as Solidity",
":param params: See `types.ParamsOfParse` :return: See `types.ResultOfParse` \"\"\" return self.request(method='boc.parse_block', **params.dict) @result_as(classname=ResultOfParse) def",
"tonclient.decorators import result_as from tonclient.module import TonModule from tonclient.types import ParamsOfParse, ResultOfParse, \\",
"contract code with salt :param params: See `types.ParamsOfSetCodeSalt` :return: See `types.ResultOfSetCodeSalt` \"\"\" return",
"ResultOfParse: \"\"\" Parses transaction boc into a JSON. JSON structure is compatible with",
"params: See `types.ParamsOfSetCodeSalt` :return: See `types.ResultOfSetCodeSalt` \"\"\" return self.request(method='boc.set_code_salt', **params.dict) @result_as(classname=ResultOfDecodeTvc) def decode_tvc(self,",
"is present :param params: See `types.ParamsOfGetCodeSalt` :return: See `types.ResultOfGetCodeSalt` \"\"\" return self.request(method='boc.get_code_salt', **params.dict)",
"\\ ParamsOfGetCodeSalt, ResultOfGetCodeSalt, ParamsOfSetCodeSalt, \\ ResultOfSetCodeSalt, ParamsOfDecodeTvc, ResultOfDecodeTvc, \\ ParamsOfEncodeTvc, ResultOfEncodeTvc, ParamsOfGetCompilerVersion, \\",
"get_blockchain_config( self, params: ParamsOfGetBlockchainConfig ) -> ResultOfGetBlockchainConfig: \"\"\" Extract blockchain configuration from key",
"`types.ParamsOfBocCacheGet` :return: See `types.ResultOfBocCacheGet` \"\"\" return self.request(method='boc.cache_get', **params.dict) @result_as(classname=ResultOfBocCacheSet) def cache_set(self, params: ParamsOfBocCacheSet)",
"\"\"\" Parses transaction boc into a JSON. JSON structure is compatible with GraphQL",
"return self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config( self, params: ParamsOfGetBlockchainConfig ) -> ResultOfGetBlockchainConfig: \"\"\"",
"ResultOfParse: \"\"\" Parses message boc into a JSON. JSON structure is compatible with",
"cache :param params: See `types.ParamsOfBocCacheSet` :return: See `types.ResultOfBocCacheSet` \"\"\" return self.request(method='boc.cache_set', **params.dict) def",
"See `ResultOfGetBocHash` \"\"\" return self.request(method='boc.get_boc_hash', **params.dict) @result_as(classname=ResultOfGetBlockchainConfig) def get_blockchain_config( self, params: ParamsOfGetBlockchainConfig )",
"@result_as(classname=ResultOfBocCacheSet) def cache_set(self, params: ParamsOfBocCacheSet) -> ResultOfBocCacheSet: \"\"\" Save BOC into cache :param",
"self, params: ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt: \"\"\" Returns the contract code's salt if it",
"into a JSON. JSON structure is compatible with GraphQL API transaction object :param",
"See `ParamsOfGetBlockchainConfig` :return: See `ResultOfGetBlockchainConfig` \"\"\" return self.request( method='boc.get_blockchain_config', **params.dict) @result_as(classname=ResultOfGetCodeFromTvc) def get_code_from_tvc(",
"Solidity and C++ contracts as TvmCell type :param params: See `types.ParamsOfEncodeBoc` :return: See",
"cache_set(self, params: ParamsOfBocCacheSet) -> ResultOfBocCacheSet: \"\"\" Save BOC into cache :param params: See",
"<gh_stars>10-100 from tonclient.decorators import result_as from tonclient.module import TonModule from tonclient.types import ParamsOfParse,",
"ParamsOfParseShardstate) -> ResultOfParse: \"\"\" Parses shardstate boc into a JSON. JSON structure is",
"params: ParamsOfGetCodeSalt) -> ResultOfGetCodeSalt: \"\"\" Returns the contract code's salt if it is",
"`types.ResultOfGetCodeFromTvc` \"\"\" return self.request(method='boc.get_code_from_tvc', **params.dict) @result_as(classname=ResultOfBocCacheGet) def cache_get(self, params: ParamsOfBocCacheGet) -> ResultOfBocCacheGet: \"\"\"",
"BOCs which don't have another pins will be removed from cache :param params:",
"ResultOfGetBlockchainConfig: \"\"\" Extract blockchain configuration from key block and also from zero state",
"**params.dict) @result_as(classname=ResultOfBocCacheSet) def cache_set(self, params: ParamsOfBocCacheSet) -> ResultOfBocCacheSet: \"\"\" Save BOC into cache",
":param params: See `types.ParamsOfBocCacheSet` :return: See `types.ResultOfBocCacheSet` \"\"\" return self.request(method='boc.cache_set', **params.dict) def cache_unpin(self,",
"structure is compatible with GraphQL API account object :param params: See `types.ParamsOfParse` :return:"
] |
[
"should be', action='store_true') parser.add_argument( '--in_band', dest='in_band', help='The current temp is close to what",
"if need to get colder - PWM to 0% # out of band",
"action='store_true') # need target temp, current temp and last temp # in band:",
"__version__ = \"1.4.0\" __license__ = \"MIT\" import pigpio import logging import argparse import",
"import os import time import sys from Pyro5.api import Proxy from ..common.local_logging import",
"and options.cold): print(\"Cannot be too hot and too cold at the same time\")",
"logging.debug( \"Adjust down 20% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust up 5% to",
"# in band: # if need to get warmer and getting warmer -",
"time\") sys.exit(1) ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown): ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status()))",
"current temp is hotter than it should be', action='store_true') parser.add_argument( '--in_band', dest='in_band', help='The",
"does not throw an error, just returns the empty set if the file",
"help='Set log level, default: \\'' + loglevel + '\\'') parser.add_argument( '-d', '--log-destination', action='store',",
"MIT License See the LICENSE file \"\"\" __author__ = \"<NAME>\" __version__ = \"1.4.0\"",
"\"Stay at {:.2f}%\".format(ssrcObj.Status())) else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust down 20% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold):",
"in band # use previous value or pwm is set to 50% #",
"50% # need to save and restore PWM value for target temp parser.add_argument(",
"# if need to get colder - PWM to 0% # out of",
"need target temp, current temp and last temp # in band: # if",
"action='store_true') parser.add_argument( '--hot', dest='hot', help='The current temp is hotter than it should be',",
"need to get colder and getting colder - do nothing # if need",
"\"Exception while attempting to adjust SSRC - may be a temporary issue\") finally:",
"is set to 50% # need to save and restore PWM value for",
"attempting to adjust SSRC - may be a temporary issue\") finally: # Might",
"options.log_destination) if(0 < len(vars(options))): if(options.hot and options.cold): print(\"Cannot be too hot and too",
"except: logging.error( \"Exception while attempting to adjust SSRC - may be a temporary",
"just returns the empty set if the file doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel =",
"target temp parser.add_argument( '--exit', dest='shutdown', help='Tells the daemon to shutdown', action='store_true') parser.add_argument( '-l',",
"default=logfile, help='Set log destination (file), default: \\'' + logfile + '\\'') parser.add_argument( '--status',",
"len(vars(options))): if(options.hot and options.cold): print(\"Cannot be too hot and too cold at the",
"down 20% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust up 5% to {:.2f}%\".format(ssrcObj.Status())) else:",
"at {:.2f}%\".format(ssrcObj.Status())) else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust down 20% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD)",
"to get warmer and getting warmer - do nothing # if need to",
"amount (10%) # if need to get colder and staying the same -",
"or cold, ignoring\") # something else like logging pass except: logging.error( \"Exception while",
"Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown): ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM)",
"if need to get colder and getting warmer - down large amount (10%)",
"0.25% to {:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay at {:.2f}%\".format(ssrcObj.Status())) else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug(",
"up large amount (10%) # if need to get colder and getting warmer",
"__author__ = \"<NAME>\" __version__ = \"1.4.0\" __license__ = \"MIT\" import pigpio import logging",
"down 1% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust up 0.25% to {:.2f}%\".format(ssrcObj.Status())) else:",
"warmer - PWM to 100% # if need to get colder - PWM",
"pigpio import logging import argparse import configparser import os import time import sys",
"import sys from Pyro5.api import Proxy from ..common.local_logging import SetupLog from . import",
"to 50% # need to save and restore PWM value for target temp",
"config.get(\"Logging\", \"LogLevel\", fallback=\"Error\") logfile = config.get(\"Logging\", \"LogFile\", fallback=\"\") parser = argparse.ArgumentParser( description='Connects to",
"be', action='store_true') parser.add_argument( '--hot', dest='hot', help='The current temp is hotter than it should",
"like logging pass except: logging.error( \"Exception while attempting to adjust SSRC - may",
"# if need to get warmer and getting warmer - do nothing #",
"to get warmer and getting colder - up large amount (10%) # if",
"daemon for power control') parser.add_argument( '--cold', dest='cold', help='The current temp is colder than",
"close to what it should be', action='store_true') # need target temp, current temp",
"from ..common.constant import SSRC, CONFIG config = configparser.ConfigParser() # does not throw an",
"PWM value for target temp parser.add_argument( '--exit', dest='shutdown', help='Tells the daemon to shutdown',",
"= \"MIT\" import pigpio import logging import argparse import configparser import os import",
"shutdown', action='store_true') parser.add_argument( '-l', '--log-level', action='store', dest='log_level', default=loglevel, help='Set log level, default: \\''",
"the same and staying the same - do nothing # if need to",
"status', action='store_true') options = parser.parse_args() SetupLog(options.log_level, options.log_destination) if(0 < len(vars(options))): if(options.hot and options.cold):",
"# if need to stay the same and staying the same - do",
"small amount(1%) # if need to get warmer and getting colder - up",
"in band: # if need to get warmer and getting warmer - do",
"and getting colder - do nothing # if need to stay the same",
"restore PWM value for target temp parser.add_argument( '--exit', dest='shutdown', help='Tells the daemon to",
"\"1.4.0\" __license__ = \"MIT\" import pigpio import logging import argparse import configparser import",
"get colder and staying the same - down small amount (1%) # out",
"<NAME> <<EMAIL>> (https://git.kins.dev/igrill-smoker) License: MIT License See the LICENSE file \"\"\" __author__ =",
"import pigpio import logging import argparse import configparser import os import time import",
"= config.get(\"Logging\", \"LogLevel\", fallback=\"Error\") logfile = config.get(\"Logging\", \"LogFile\", fallback=\"\") parser = argparse.ArgumentParser( description='Connects",
"= parser.parse_args() SetupLog(options.log_level, options.log_destination) if(0 < len(vars(options))): if(options.hot and options.cold): print(\"Cannot be too",
"to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust up 0.25% to {:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug(",
"of band: # if need to get warmer - PWM to 100% #",
"(c) 2019: <NAME> <<EMAIL>> (https://git.kins.dev/igrill-smoker) License: MIT License See the LICENSE file \"\"\"",
"<<EMAIL>> (https://git.kins.dev/igrill-smoker) License: MIT License See the LICENSE file \"\"\" __author__ = \"<NAME>\"",
"if(0 < len(vars(options))): if(options.hot and options.cold): print(\"Cannot be too hot and too cold",
"logging import argparse import configparser import os import time import sys from Pyro5.api",
"Copyright (c) 2019: <NAME> <<EMAIL>> (https://git.kins.dev/igrill-smoker) License: MIT License See the LICENSE file",
"level, default: \\'' + loglevel + '\\'') parser.add_argument( '-d', '--log-destination', action='store', dest='log_destination', default=logfile,",
"ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust up 5% to {:.2f}%\".format(ssrcObj.Status())) else: logging.info( \"Odd, ssr_client called but",
"'--log-level', action='store', dest='log_level', default=loglevel, help='Set log level, default: \\'' + loglevel + '\\'')",
"need to get warmer and getting colder - up large amount (10%) #",
"the empty set if the file doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel = config.get(\"Logging\", \"LogLevel\",",
"if need to get warmer and getting warmer - do nothing # if",
"warmer and getting warmer - do nothing # if need to get colder",
"description='Connects to TP-Link Kasa daemon for power control') parser.add_argument( '--cold', dest='cold', help='The current",
"logging.debug( \"Adjust up 5% to {:.2f}%\".format(ssrcObj.Status())) else: logging.info( \"Odd, ssr_client called but not",
"print(\"Cannot be too hot and too cold at the same time\") sys.exit(1) ssrcObj",
"to 100% # if need to get colder - PWM to 0% #",
"if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust down 20% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust up",
"- PWM to 100% # if need to get colder - PWM to",
"parser.add_argument( '--exit', dest='shutdown', help='Tells the daemon to shutdown', action='store_true') parser.add_argument( '-l', '--log-level', action='store',",
"options = parser.parse_args() SetupLog(options.log_level, options.log_destination) if(0 < len(vars(options))): if(options.hot and options.cold): print(\"Cannot be",
"parser.add_argument( '-l', '--log-level', action='store', dest='log_level', default=loglevel, help='Set log level, default: \\'' + loglevel",
"file doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel = config.get(\"Logging\", \"LogLevel\", fallback=\"Error\") logfile = config.get(\"Logging\", \"LogFile\",",
"dest='cold', help='The current temp is colder than it should be', action='store_true') parser.add_argument( '--hot',",
"dest='shutdown', help='Tells the daemon to shutdown', action='store_true') parser.add_argument( '-l', '--log-level', action='store', dest='log_level', default=loglevel,",
"'--cold', dest='cold', help='The current temp is colder than it should be', action='store_true') parser.add_argument(",
"colder - do nothing # if need to stay the same and staying",
"it should be', action='store_true') # need target temp, current temp and last temp",
"'--log-destination', action='store', dest='log_destination', default=logfile, help='Set log destination (file), default: \\'' + logfile +",
"ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay at {:.2f}%\".format(ssrcObj.Status())) else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust down 20% to",
"nothing # if need to stay the same and staying the same -",
"dest='hot', help='The current temp is hotter than it should be', action='store_true') parser.add_argument( '--in_band',",
"- PWM to 0% # out of band to in band # use",
"out of band to in band # use previous value or pwm is",
"error, just returns the empty set if the file doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel",
"See the LICENSE file \"\"\" __author__ = \"<NAME>\" __version__ = \"1.4.0\" __license__ =",
"1% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust up 0.25% to {:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT)",
"same - do nothing # if need to get warmer and staying the",
"should be', action='store_true') # need target temp, current temp and last temp #",
"out of band: # if need to get warmer - PWM to 100%",
"do nothing # if need to get colder and getting colder - do",
"action='store', dest='log_level', default=loglevel, help='Set log level, default: \\'' + loglevel + '\\'') parser.add_argument(",
"action='store', dest='log_destination', default=logfile, help='Set log destination (file), default: \\'' + logfile + '\\'')",
"parser.parse_args() SetupLog(options.log_level, options.log_destination) if(0 < len(vars(options))): if(options.hot and options.cold): print(\"Cannot be too hot",
"log destination (file), default: \\'' + logfile + '\\'') parser.add_argument( '--status', dest='status', help='Gets",
"+ logfile + '\\'') parser.add_argument( '--status', dest='status', help='Gets the SSRC status', action='store_true') options",
"previous value or pwm is set to 50% # need to save and",
"finally: # Might get an exception from a communication error (new IP) sys.exit(0)",
"100% # if need to get colder - PWM to 0% # out",
"'\\'') parser.add_argument( '-d', '--log-destination', action='store', dest='log_destination', default=logfile, help='Set log destination (file), default: \\''",
"while attempting to adjust SSRC - may be a temporary issue\") finally: #",
"= argparse.ArgumentParser( description='Connects to TP-Link Kasa daemon for power control') parser.add_argument( '--cold', dest='cold',",
"elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust down 1% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold):",
"temp parser.add_argument( '--exit', dest='shutdown', help='Tells the daemon to shutdown', action='store_true') parser.add_argument( '-l', '--log-level',",
"if need to get warmer - PWM to 100% # if need to",
"= Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown): ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band): if(options.hot):",
"SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown): ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug(",
"logfile = config.get(\"Logging\", \"LogFile\", fallback=\"\") parser = argparse.ArgumentParser( description='Connects to TP-Link Kasa daemon",
"'--in_band', dest='in_band', help='The current temp is close to what it should be', action='store_true')",
"default=loglevel, help='Set log level, default: \\'' + loglevel + '\\'') parser.add_argument( '-d', '--log-destination',",
"logging.debug( \"Adjust up 0.25% to {:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay at {:.2f}%\".format(ssrcObj.Status())) else:",
"power control') parser.add_argument( '--cold', dest='cold', help='The current temp is colder than it should",
"temporary issue\") finally: # Might get an exception from a communication error (new",
"+ '\\'') parser.add_argument( '--status', dest='status', help='Gets the SSRC status', action='store_true') options = parser.parse_args()",
"\"LogFile\", fallback=\"\") parser = argparse.ArgumentParser( description='Connects to TP-Link Kasa daemon for power control')",
"logging.info( \"Odd, ssr_client called but not in band, hot or cold, ignoring\") #",
"to in band # use previous value or pwm is set to 50%",
"down small amount (1%) # out of band: # if need to get",
"help='Set log destination (file), default: \\'' + logfile + '\\'') parser.add_argument( '--status', dest='status',",
"if need to get warmer and getting colder - up large amount (10%)",
"if(options.hot and options.cold): print(\"Cannot be too hot and too cold at the same",
"band, hot or cold, ignoring\") # something else like logging pass except: logging.error(",
"\"Adjust up 5% to {:.2f}%\".format(ssrcObj.Status())) else: logging.info( \"Odd, ssr_client called but not in",
"\"Adjust down 1% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust up 0.25% to {:.2f}%\".format(ssrcObj.Status()))",
"- up large amount (10%) # if need to get colder and getting",
"file \"\"\" __author__ = \"<NAME>\" __version__ = \"1.4.0\" __license__ = \"MIT\" import pigpio",
"SetupLog from . import ssrc_daemon from ..common.constant import SSRC, CONFIG config = configparser.ConfigParser()",
"is hotter than it should be', action='store_true') parser.add_argument( '--in_band', dest='in_band', help='The current temp",
"pass except: logging.error( \"Exception while attempting to adjust SSRC - may be a",
"\"Adjust up 0.25% to {:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay at {:.2f}%\".format(ssrcObj.Status())) else: if(options.hot):",
"os import time import sys from Pyro5.api import Proxy from ..common.local_logging import SetupLog",
"import configparser import os import time import sys from Pyro5.api import Proxy from",
"action='store_true') parser.add_argument( '--in_band', dest='in_band', help='The current temp is close to what it should",
"it should be', action='store_true') parser.add_argument( '--hot', dest='hot', help='The current temp is hotter than",
"called but not in band, hot or cold, ignoring\") # something else like",
"warmer - down large amount (10%) # if need to get colder and",
"destination (file), default: \\'' + logfile + '\\'') parser.add_argument( '--status', dest='status', help='Gets the",
"be', action='store_true') # need target temp, current temp and last temp # in",
"cold at the same time\") sys.exit(1) ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try:",
"'--hot', dest='hot', help='The current temp is hotter than it should be', action='store_true') parser.add_argument(",
"down large amount (10%) # if need to get colder and staying the",
"- may be a temporary issue\") finally: # Might get an exception from",
"help='Gets the SSRC status', action='store_true') options = parser.parse_args() SetupLog(options.log_level, options.log_destination) if(0 < len(vars(options))):",
"need to stay the same and staying the same - do nothing #",
"is close to what it should be', action='store_true') # need target temp, current",
"- do nothing # if need to get warmer and staying the same",
"Proxy from ..common.local_logging import SetupLog from . import ssrc_daemon from ..common.constant import SSRC,",
"for target temp parser.add_argument( '--exit', dest='shutdown', help='Tells the daemon to shutdown', action='store_true') parser.add_argument(",
"# something else like logging pass except: logging.error( \"Exception while attempting to adjust",
"hotter than it should be', action='store_true') parser.add_argument( '--in_band', dest='in_band', help='The current temp is",
"in band, hot or cold, ignoring\") # something else like logging pass except:",
"doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel = config.get(\"Logging\", \"LogLevel\", fallback=\"Error\") logfile = config.get(\"Logging\", \"LogFile\", fallback=\"\")",
"SSRC status', action='store_true') options = parser.parse_args() SetupLog(options.log_level, options.log_destination) if(0 < len(vars(options))): if(options.hot and",
"import argparse import configparser import os import time import sys from Pyro5.api import",
"action='store_true') parser.add_argument( '-l', '--log-level', action='store', dest='log_level', default=loglevel, help='Set log level, default: \\'' +",
"amount (10%) # if need to get colder and getting warmer - down",
"and getting colder - up large amount (10%) # if need to get",
"fallback=\"Error\") logfile = config.get(\"Logging\", \"LogFile\", fallback=\"\") parser = argparse.ArgumentParser( description='Connects to TP-Link Kasa",
"staying the same - down small amount (1%) # out of band: #",
"default: \\'' + loglevel + '\\'') parser.add_argument( '-d', '--log-destination', action='store', dest='log_destination', default=logfile, help='Set",
"getting warmer - do nothing # if need to get colder and getting",
"logging pass except: logging.error( \"Exception while attempting to adjust SSRC - may be",
"to adjust SSRC - may be a temporary issue\") finally: # Might get",
"python3 \"\"\" Copyright (c) 2019: <NAME> <<EMAIL>> (https://git.kins.dev/igrill-smoker) License: MIT License See the",
"{:.2f}%\".format(ssrcObj.Status())) else: logging.info( \"Odd, ssr_client called but not in band, hot or cold,",
"< len(vars(options))): if(options.hot and options.cold): print(\"Cannot be too hot and too cold at",
"dest='in_band', help='The current temp is close to what it should be', action='store_true') #",
"logging.debug( \"Stay at {:.2f}%\".format(ssrcObj.Status())) else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust down 20% to {:.2f}%\".format(ssrcObj.Status()))",
"SSRC - may be a temporary issue\") finally: # Might get an exception",
"hot or cold, ignoring\") # something else like logging pass except: logging.error( \"Exception",
"to shutdown', action='store_true') parser.add_argument( '-l', '--log-level', action='store', dest='log_level', default=loglevel, help='Set log level, default:",
"small amount (1%) # out of band: # if need to get warmer",
"temp is hotter than it should be', action='store_true') parser.add_argument( '--in_band', dest='in_band', help='The current",
"get warmer and getting colder - up large amount (10%) # if need",
"colder than it should be', action='store_true') parser.add_argument( '--hot', dest='hot', help='The current temp is",
"= config.get(\"Logging\", \"LogFile\", fallback=\"\") parser = argparse.ArgumentParser( description='Connects to TP-Link Kasa daemon for",
"# if need to get warmer and getting colder - up large amount",
"CONFIG config = configparser.ConfigParser() # does not throw an error, just returns the",
"argparse.ArgumentParser( description='Connects to TP-Link Kasa daemon for power control') parser.add_argument( '--cold', dest='cold', help='The",
"# if need to get colder and getting warmer - down large amount",
"'--status', dest='status', help='Gets the SSRC status', action='store_true') options = parser.parse_args() SetupLog(options.log_level, options.log_destination) if(0",
"# out of band: # if need to get warmer - PWM to",
"License See the LICENSE file \"\"\" __author__ = \"<NAME>\" __version__ = \"1.4.0\" __license__",
"argparse import configparser import os import time import sys from Pyro5.api import Proxy",
"amount (1%) # out of band: # if need to get warmer -",
"current temp and last temp # in band: # if need to get",
"Kasa daemon for power control') parser.add_argument( '--cold', dest='cold', help='The current temp is colder",
"be a temporary issue\") finally: # Might get an exception from a communication",
"to stay the same and staying the same - do nothing # if",
"ssrc_daemon from ..common.constant import SSRC, CONFIG config = configparser.ConfigParser() # does not throw",
"__license__ = \"MIT\" import pigpio import logging import argparse import configparser import os",
"import SSRC, CONFIG config = configparser.ConfigParser() # does not throw an error, just",
"log level, default: \\'' + loglevel + '\\'') parser.add_argument( '-d', '--log-destination', action='store', dest='log_destination',",
"and last temp # in band: # if need to get warmer and",
"use previous value or pwm is set to 50% # need to save",
"need to get colder and getting warmer - down large amount (10%) #",
"to get warmer - PWM to 100% # if need to get colder",
"loglevel + '\\'') parser.add_argument( '-d', '--log-destination', action='store', dest='log_destination', default=logfile, help='Set log destination (file),",
"logging.debug( \"Adjust down 1% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust up 0.25% to",
"'-l', '--log-level', action='store', dest='log_level', default=loglevel, help='Set log level, default: \\'' + loglevel +",
"(1%) # out of band: # if need to get warmer - PWM",
"if(options.shutdown): ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust down 1% to",
"colder - PWM to 0% # out of band to in band #",
"daemon to shutdown', action='store_true') parser.add_argument( '-l', '--log-level', action='store', dest='log_level', default=loglevel, help='Set log level,",
"the same time\") sys.exit(1) ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown): ssrcObj.Exit()",
"set if the file doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel = config.get(\"Logging\", \"LogLevel\", fallback=\"Error\") logfile",
"# use previous value or pwm is set to 50% # need to",
"need to get warmer and staying the same - up small amount(1%) #",
"not in band, hot or cold, ignoring\") # something else like logging pass",
"an error, just returns the empty set if the file doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini')",
"\\'' + logfile + '\\'') parser.add_argument( '--status', dest='status', help='Gets the SSRC status', action='store_true')",
"ssr_client called but not in band, hot or cold, ignoring\") # something else",
"<gh_stars>1-10 #!/usr/bin/env python3 \"\"\" Copyright (c) 2019: <NAME> <<EMAIL>> (https://git.kins.dev/igrill-smoker) License: MIT License",
"\"\"\" __author__ = \"<NAME>\" __version__ = \"1.4.0\" __license__ = \"MIT\" import pigpio import",
"get colder and getting colder - do nothing # if need to stay",
"# if need to get colder and staying the same - down small",
"logging.error( \"Exception while attempting to adjust SSRC - may be a temporary issue\")",
"to TP-Link Kasa daemon for power control') parser.add_argument( '--cold', dest='cold', help='The current temp",
"warmer and staying the same - up small amount(1%) # if need to",
"loglevel = config.get(\"Logging\", \"LogLevel\", fallback=\"Error\") logfile = config.get(\"Logging\", \"LogFile\", fallback=\"\") parser = argparse.ArgumentParser(",
"may be a temporary issue\") finally: # Might get an exception from a",
"to 0% # out of band to in band # use previous value",
"need to save and restore PWM value for target temp parser.add_argument( '--exit', dest='shutdown',",
"hot and too cold at the same time\") sys.exit(1) ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID,",
"temp is close to what it should be', action='store_true') # need target temp,",
"if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust down 1% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust up",
"get warmer and staying the same - up small amount(1%) # if need",
"warmer - do nothing # if need to get colder and getting colder",
"parser.add_argument( '--hot', dest='hot', help='The current temp is hotter than it should be', action='store_true')",
"ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust down 1% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust up 0.25%",
"if need to stay the same and staying the same - do nothing",
"colder and getting warmer - down large amount (10%) # if need to",
"parser.add_argument( '--cold', dest='cold', help='The current temp is colder than it should be', action='store_true')",
"up 0.25% to {:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay at {:.2f}%\".format(ssrcObj.Status())) else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT)",
"= \"1.4.0\" __license__ = \"MIT\" import pigpio import logging import argparse import configparser",
"pwm is set to 50% # need to save and restore PWM value",
"= \"<NAME>\" __version__ = \"1.4.0\" __license__ = \"MIT\" import pigpio import logging import",
"parser.add_argument( '--in_band', dest='in_band', help='The current temp is close to what it should be',",
"and too cold at the same time\") sys.exit(1) ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST,",
"to {:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay at {:.2f}%\".format(ssrcObj.Status())) else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust",
"getting colder - do nothing # if need to stay the same and",
"time import sys from Pyro5.api import Proxy from ..common.local_logging import SetupLog from .",
"nothing # if need to get warmer and staying the same - up",
"config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel = config.get(\"Logging\", \"LogLevel\", fallback=\"Error\") logfile = config.get(\"Logging\", \"LogFile\", fallback=\"\") parser =",
"temp is colder than it should be', action='store_true') parser.add_argument( '--hot', dest='hot', help='The current",
"help='Tells the daemon to shutdown', action='store_true') parser.add_argument( '-l', '--log-level', action='store', dest='log_level', default=loglevel, help='Set",
"temp, current temp and last temp # in band: # if need to",
"value or pwm is set to 50% # need to save and restore",
"from ..common.local_logging import SetupLog from . import ssrc_daemon from ..common.constant import SSRC, CONFIG",
"to get colder - PWM to 0% # out of band to in",
"PWM to 0% # out of band to in band # use previous",
"value for target temp parser.add_argument( '--exit', dest='shutdown', help='Tells the daemon to shutdown', action='store_true')",
"a temporary issue\") finally: # Might get an exception from a communication error",
"2019: <NAME> <<EMAIL>> (https://git.kins.dev/igrill-smoker) License: MIT License See the LICENSE file \"\"\" __author__",
"band: # if need to get warmer - PWM to 100% # if",
"need to get colder and staying the same - down small amount (1%)",
"too hot and too cold at the same time\") sys.exit(1) ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format(",
"dest='log_level', default=loglevel, help='Set log level, default: \\'' + loglevel + '\\'') parser.add_argument( '-d',",
"the file doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel = config.get(\"Logging\", \"LogLevel\", fallback=\"Error\") logfile = config.get(\"Logging\",",
"default: \\'' + logfile + '\\'') parser.add_argument( '--status', dest='status', help='Gets the SSRC status',",
"else like logging pass except: logging.error( \"Exception while attempting to adjust SSRC -",
"configparser.ConfigParser() # does not throw an error, just returns the empty set if",
"..common.constant import SSRC, CONFIG config = configparser.ConfigParser() # does not throw an error,",
"fallback=\"\") parser = argparse.ArgumentParser( description='Connects to TP-Link Kasa daemon for power control') parser.add_argument(",
"up small amount(1%) # if need to get warmer and getting colder -",
"\"Odd, ssr_client called but not in band, hot or cold, ignoring\") # something",
"exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel = config.get(\"Logging\", \"LogLevel\", fallback=\"Error\") logfile = config.get(\"Logging\", \"LogFile\", fallback=\"\") parser",
"{:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay at {:.2f}%\".format(ssrcObj.Status())) else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust down",
"elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust up 5% to {:.2f}%\".format(ssrcObj.Status())) else: logging.info( \"Odd, ssr_client called",
"print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust down 1% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL)",
"- do nothing # if need to get colder and getting colder -",
"\"\"\" Copyright (c) 2019: <NAME> <<EMAIL>> (https://git.kins.dev/igrill-smoker) License: MIT License See the LICENSE",
"adjust SSRC - may be a temporary issue\") finally: # Might get an",
"throw an error, just returns the empty set if the file doesn't exist",
"the same - do nothing # if need to get warmer and staying",
"to get colder and getting colder - do nothing # if need to",
"be too hot and too cold at the same time\") sys.exit(1) ssrcObj =",
"to get colder and getting warmer - down large amount (10%) # if",
"issue\") finally: # Might get an exception from a communication error (new IP)",
"action='store_true') options = parser.parse_args() SetupLog(options.log_level, options.log_destination) if(0 < len(vars(options))): if(options.hot and options.cold): print(\"Cannot",
"..common.local_logging import SetupLog from . import ssrc_daemon from ..common.constant import SSRC, CONFIG config",
"colder - up large amount (10%) # if need to get colder and",
"License: MIT License See the LICENSE file \"\"\" __author__ = \"<NAME>\" __version__ =",
"the LICENSE file \"\"\" __author__ = \"<NAME>\" __version__ = \"1.4.0\" __license__ = \"MIT\"",
"current temp is close to what it should be', action='store_true') # need target",
"and staying the same - down small amount (1%) # out of band:",
"\\'' + loglevel + '\\'') parser.add_argument( '-d', '--log-destination', action='store', dest='log_destination', default=logfile, help='Set log",
"{:.2f}%\".format(ssrcObj.Status())) else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust down 20% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug(",
"warmer and getting colder - up large amount (10%) # if need to",
"ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown): ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band):",
"else: if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust down 1% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug(",
"help='The current temp is hotter than it should be', action='store_true') parser.add_argument( '--in_band', dest='in_band',",
"get warmer - PWM to 100% # if need to get colder -",
"not throw an error, just returns the empty set if the file doesn't",
"staying the same - up small amount(1%) # if need to get warmer",
"to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust up 5% to {:.2f}%\".format(ssrcObj.Status())) else: logging.info( \"Odd,",
"and getting warmer - down large amount (10%) # if need to get",
"0% # out of band to in band # use previous value or",
"set to 50% # need to save and restore PWM value for target",
"current temp is colder than it should be', action='store_true') parser.add_argument( '--hot', dest='hot', help='The",
"# need target temp, current temp and last temp # in band: #",
"help='The current temp is close to what it should be', action='store_true') # need",
"what it should be', action='store_true') # need target temp, current temp and last",
"the daemon to shutdown', action='store_true') parser.add_argument( '-l', '--log-level', action='store', dest='log_level', default=loglevel, help='Set log",
"5% to {:.2f}%\".format(ssrcObj.Status())) else: logging.info( \"Odd, ssr_client called but not in band, hot",
"- down large amount (10%) # if need to get colder and staying",
"import Proxy from ..common.local_logging import SetupLog from . import ssrc_daemon from ..common.constant import",
"else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay at {:.2f}%\".format(ssrcObj.Status())) else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust down 20%",
"same - down small amount (1%) # out of band: # if need",
"than it should be', action='store_true') parser.add_argument( '--in_band', dest='in_band', help='The current temp is close",
"parser = argparse.ArgumentParser( description='Connects to TP-Link Kasa daemon for power control') parser.add_argument( '--cold',",
"the same - up small amount(1%) # if need to get warmer and",
"same - up small amount(1%) # if need to get warmer and getting",
"ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust down 20% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust up 5%",
"and restore PWM value for target temp parser.add_argument( '--exit', dest='shutdown', help='Tells the daemon",
"same and staying the same - do nothing # if need to get",
"be', action='store_true') parser.add_argument( '--in_band', dest='in_band', help='The current temp is close to what it",
"sys.exit(1) ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown): ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else:",
"stay the same and staying the same - do nothing # if need",
"ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust down 1% to {:.2f}%\".format(ssrcObj.Status()))",
"it should be', action='store_true') parser.add_argument( '--in_band', dest='in_band', help='The current temp is close to",
"staying the same - do nothing # if need to get warmer and",
"something else like logging pass except: logging.error( \"Exception while attempting to adjust SSRC",
"'--exit', dest='shutdown', help='Tells the daemon to shutdown', action='store_true') parser.add_argument( '-l', '--log-level', action='store', dest='log_level',",
"band: # if need to get warmer and getting warmer - do nothing",
"config.get(\"Logging\", \"LogFile\", fallback=\"\") parser = argparse.ArgumentParser( description='Connects to TP-Link Kasa daemon for power",
"is colder than it should be', action='store_true') parser.add_argument( '--hot', dest='hot', help='The current temp",
"TP-Link Kasa daemon for power control') parser.add_argument( '--cold', dest='cold', help='The current temp is",
"from . import ssrc_daemon from ..common.constant import SSRC, CONFIG config = configparser.ConfigParser() #",
"for power control') parser.add_argument( '--cold', dest='cold', help='The current temp is colder than it",
"band # use previous value or pwm is set to 50% # need",
"need to get warmer - PWM to 100% # if need to get",
"SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown): ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust down",
"import ssrc_daemon from ..common.constant import SSRC, CONFIG config = configparser.ConfigParser() # does not",
"if need to get warmer and staying the same - up small amount(1%)",
"save and restore PWM value for target temp parser.add_argument( '--exit', dest='shutdown', help='Tells the",
"of band to in band # use previous value or pwm is set",
"get warmer and getting warmer - do nothing # if need to get",
"dest='status', help='Gets the SSRC status', action='store_true') options = parser.parse_args() SetupLog(options.log_level, options.log_destination) if(0 <",
"SSRC, CONFIG config = configparser.ConfigParser() # does not throw an error, just returns",
"the SSRC status', action='store_true') options = parser.parse_args() SetupLog(options.log_level, options.log_destination) if(0 < len(vars(options))): if(options.hot",
"too cold at the same time\") sys.exit(1) ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT))",
"PWM to 100% # if need to get colder - PWM to 0%",
"configparser import os import time import sys from Pyro5.api import Proxy from ..common.local_logging",
"{:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust up 0.25% to {:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay",
"- do nothing # if need to stay the same and staying the",
"# if need to get warmer and staying the same - up small",
"control') parser.add_argument( '--cold', dest='cold', help='The current temp is colder than it should be',",
"import logging import argparse import configparser import os import time import sys from",
"if need to get colder and staying the same - down small amount",
"ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust up 0.25% to {:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay at {:.2f}%\".format(ssrcObj.Status()))",
"last temp # in band: # if need to get warmer and getting",
"large amount (10%) # if need to get colder and getting warmer -",
"config = configparser.ConfigParser() # does not throw an error, just returns the empty",
"else: logging.info( \"Odd, ssr_client called but not in band, hot or cold, ignoring\")",
"# need to save and restore PWM value for target temp parser.add_argument( '--exit',",
"large amount (10%) # if need to get colder and staying the same",
"getting warmer - down large amount (10%) # if need to get colder",
"help='The current temp is colder than it should be', action='store_true') parser.add_argument( '--hot', dest='hot',",
"but not in band, hot or cold, ignoring\") # something else like logging",
"else: if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.HOT) logging.debug( \"Adjust down 20% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust",
"to what it should be', action='store_true') # need target temp, current temp and",
"= configparser.ConfigParser() # does not throw an error, just returns the empty set",
"do nothing # if need to stay the same and staying the same",
"(10%) # if need to get colder and getting warmer - down large",
"'\\'') parser.add_argument( '--status', dest='status', help='Gets the SSRC status', action='store_true') options = parser.parse_args() SetupLog(options.log_level,",
"options.cold): print(\"Cannot be too hot and too cold at the same time\") sys.exit(1)",
"need to get colder - PWM to 0% # out of band to",
"get colder - PWM to 0% # out of band to in band",
"up 5% to {:.2f}%\".format(ssrcObj.Status())) else: logging.info( \"Odd, ssr_client called but not in band,",
"and getting warmer - do nothing # if need to get colder and",
"LICENSE file \"\"\" __author__ = \"<NAME>\" __version__ = \"1.4.0\" __license__ = \"MIT\" import",
"same time\") sys.exit(1) ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown): ssrcObj.Exit() elif(options.status):",
"the same - down small amount (1%) # out of band: # if",
"elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust up 0.25% to {:.2f}%\".format(ssrcObj.Status())) else: ssrcObj.Adjust(SSRC.TemperatureState.PERFECT) logging.debug( \"Stay at",
"to get warmer and staying the same - up small amount(1%) # if",
"temp # in band: # if need to get warmer and getting warmer",
"returns the empty set if the file doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel = config.get(\"Logging\",",
"and staying the same - up small amount(1%) # if need to get",
"# does not throw an error, just returns the empty set if the",
"than it should be', action='store_true') parser.add_argument( '--hot', dest='hot', help='The current temp is hotter",
"\"Adjust down 20% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust up 5% to {:.2f}%\".format(ssrcObj.Status()))",
"or pwm is set to 50% # need to save and restore PWM",
"try: if(options.shutdown): ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust down 1%",
"parser.add_argument( '-d', '--log-destination', action='store', dest='log_destination', default=logfile, help='Set log destination (file), default: \\'' +",
"import SetupLog from . import ssrc_daemon from ..common.constant import SSRC, CONFIG config =",
"if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust down 1% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COOL) logging.debug( \"Adjust",
"to {:.2f}%\".format(ssrcObj.Status())) else: logging.info( \"Odd, ssr_client called but not in band, hot or",
"{:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust up 5% to {:.2f}%\".format(ssrcObj.Status())) else: logging.info( \"Odd, ssr_client",
"temp and last temp # in band: # if need to get warmer",
"colder and staying the same - down small amount (1%) # out of",
"(file), default: \\'' + logfile + '\\'') parser.add_argument( '--status', dest='status', help='Gets the SSRC",
"parser.add_argument( '--status', dest='status', help='Gets the SSRC status', action='store_true') options = parser.parse_args() SetupLog(options.log_level, options.log_destination)",
"\"MIT\" import pigpio import logging import argparse import configparser import os import time",
"import time import sys from Pyro5.api import Proxy from ..common.local_logging import SetupLog from",
"# out of band to in band # use previous value or pwm",
"sys from Pyro5.api import Proxy from ..common.local_logging import SetupLog from . import ssrc_daemon",
"should be', action='store_true') parser.add_argument( '--hot', dest='hot', help='The current temp is hotter than it",
"and staying the same - do nothing # if need to get warmer",
"# if need to get colder and getting colder - do nothing #",
"getting colder - up large amount (10%) # if need to get colder",
"+ loglevel + '\\'') parser.add_argument( '-d', '--log-destination', action='store', dest='log_destination', default=logfile, help='Set log destination",
"# if need to get warmer - PWM to 100% # if need",
"band to in band # use previous value or pwm is set to",
"amount(1%) # if need to get warmer and getting colder - up large",
"\"<NAME>\" __version__ = \"1.4.0\" __license__ = \"MIT\" import pigpio import logging import argparse",
"20% to {:.2f}%\".format(ssrcObj.Status())) elif(options.cold): ssrcObj.Adjust(SSRC.TemperatureState.COLD) logging.debug( \"Adjust up 5% to {:.2f}%\".format(ssrcObj.Status())) else: logging.info(",
"need to get warmer and getting warmer - do nothing # if need",
"- down small amount (1%) # out of band: # if need to",
"#!/usr/bin/env python3 \"\"\" Copyright (c) 2019: <NAME> <<EMAIL>> (https://git.kins.dev/igrill-smoker) License: MIT License See",
"nothing # if need to get colder and getting colder - do nothing",
"\"LogLevel\", fallback=\"Error\") logfile = config.get(\"Logging\", \"LogFile\", fallback=\"\") parser = argparse.ArgumentParser( description='Connects to TP-Link",
"to save and restore PWM value for target temp parser.add_argument( '--exit', dest='shutdown', help='Tells",
"SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown): ssrcObj.Exit() elif(options.status): print(\"{:.2f}\".format(ssrcObj.Status())) else: if(options.in_band): if(options.hot): ssrcObj.Adjust(SSRC.TemperatureState.WARM) logging.debug( \"Adjust",
"SetupLog(options.log_level, options.log_destination) if(0 < len(vars(options))): if(options.hot and options.cold): print(\"Cannot be too hot and",
"ignoring\") # something else like logging pass except: logging.error( \"Exception while attempting to",
"to get colder and staying the same - down small amount (1%) #",
"dest='log_destination', default=logfile, help='Set log destination (file), default: \\'' + logfile + '\\'') parser.add_argument(",
"empty set if the file doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel = config.get(\"Logging\", \"LogLevel\", fallback=\"Error\")",
"at the same time\") sys.exit(1) ssrcObj = Proxy((\"PYRO:{}@{}:{}\").format( SSRC.DAEMON.PYRO_OBJECT_ID, SSRC.DAEMON.PYRO_HOST, SSRC.DAEMON.PYRO_PORT)) try: if(options.shutdown):",
". import ssrc_daemon from ..common.constant import SSRC, CONFIG config = configparser.ConfigParser() # does",
"(10%) # if need to get colder and staying the same - down",
"from Pyro5.api import Proxy from ..common.local_logging import SetupLog from . import ssrc_daemon from",
"get colder and getting warmer - down large amount (10%) # if need",
"- up small amount(1%) # if need to get warmer and getting colder",
"colder and getting colder - do nothing # if need to stay the",
"cold, ignoring\") # something else like logging pass except: logging.error( \"Exception while attempting",
"'-d', '--log-destination', action='store', dest='log_destination', default=logfile, help='Set log destination (file), default: \\'' + logfile",
"if need to get colder and getting colder - do nothing # if",
"do nothing # if need to get warmer and staying the same -",
"Pyro5.api import Proxy from ..common.local_logging import SetupLog from . import ssrc_daemon from ..common.constant",
"(https://git.kins.dev/igrill-smoker) License: MIT License See the LICENSE file \"\"\" __author__ = \"<NAME>\" __version__",
"logfile + '\\'') parser.add_argument( '--status', dest='status', help='Gets the SSRC status', action='store_true') options =",
"target temp, current temp and last temp # in band: # if need",
"if the file doesn't exist config.read(CONFIG.BASEPATH+'/config/iGrill_config.ini') loglevel = config.get(\"Logging\", \"LogLevel\", fallback=\"Error\") logfile =",
"+ '\\'') parser.add_argument( '-d', '--log-destination', action='store', dest='log_destination', default=logfile, help='Set log destination (file), default:"
] |
[
"int(input()) a = int(input()) b = int(input()) c = int(input()) d = int(input())",
"sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) n = int(input()) a = int(input())",
"int(input()) d = int(input()) e = int(input()) print(((n + min(a,b,c,d,e) - 1) //",
"input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) n = int(input()) a = int(input()) b",
"= int(input()) c = int(input()) d = int(input()) e = int(input()) print(((n +",
"b = int(input()) c = int(input()) d = int(input()) e = int(input()) print(((n",
"sys.setrecursionlimit(10 ** 7) n = int(input()) a = int(input()) b = int(input()) c",
"a = int(input()) b = int(input()) c = int(input()) d = int(input()) e",
"= int(input()) d = int(input()) e = int(input()) print(((n + min(a,b,c,d,e) - 1)",
"** 7) n = int(input()) a = int(input()) b = int(input()) c =",
"sys.stdin.readline sys.setrecursionlimit(10 ** 7) n = int(input()) a = int(input()) b = int(input())",
"<reponame>FGtatsuro/myatcoder import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) n = int(input()) a",
"= int(input()) a = int(input()) b = int(input()) c = int(input()) d =",
"import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) n = int(input()) a =",
"d = int(input()) e = int(input()) print(((n + min(a,b,c,d,e) - 1) // min(a,b,c,d,e))",
"c = int(input()) d = int(input()) e = int(input()) print(((n + min(a,b,c,d,e) -",
"n = int(input()) a = int(input()) b = int(input()) c = int(input()) d",
"7) n = int(input()) a = int(input()) b = int(input()) c = int(input())",
"int(input()) c = int(input()) d = int(input()) e = int(input()) print(((n + min(a,b,c,d,e)",
"= int(input()) b = int(input()) c = int(input()) d = int(input()) e =",
"int(input()) e = int(input()) print(((n + min(a,b,c,d,e) - 1) // min(a,b,c,d,e)) + 4)",
"= sys.stdin.readline sys.setrecursionlimit(10 ** 7) n = int(input()) a = int(input()) b =",
"= int(input()) e = int(input()) print(((n + min(a,b,c,d,e) - 1) // min(a,b,c,d,e)) +",
"int(input()) b = int(input()) c = int(input()) d = int(input()) e = int(input())"
] |
[
"self.Entry_connect_port = tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190, y=60) self.user_name=tk.StringVar() self.Label_user_name = tk.Label(self, text='用户名',width=6).place(x=10, y=110) self.Entry_user_name",
"- height) // 2 # 获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height, sw, sh)) self.resizable(0, 0)",
"tk.Label(self, text='用户名',width=6).place(x=10, y=110) self.Entry_user_name = tk.Entry(self, textvariable=self.user_name, width=15).place(x=60, y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd = tk.Label(self,",
"height = 300 # 登录界面高度 sw = (self.winfo_screenwidth() - width) //2 # 获取x轴坐标",
"self.connect_port=tk.StringVar() self.Label_connect_addr = tk.Label(self, text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60, y=60) self.Entry_connect_port =",
"= 300 # 登录界面高度 sw = (self.winfo_screenwidth() - width) //2 # 获取x轴坐标 sh",
"addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{} -pw",
"textvariable=self.connect_addr, width=15).place(x=60, y=60) self.Entry_connect_port = tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190, y=60) self.user_name=tk.StringVar() self.Label_user_name = tk.Label(self,",
"= tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60, y=210) self.Button_save = tk.Button(self, text='保存', width=10).place(x=10, y=260) self.Button_connect =",
"sw = (self.winfo_screenwidth() - width) //2 # 获取x轴坐标 sh = (self.winfo_screenheight() - height)",
"y=210) self.Entry_connect_protocol = tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60, y=210) self.Button_save = tk.Button(self, text='保存', width=10).place(x=10, y=260)",
"sw, sh)) self.resizable(0, 0) # 固定窗口不能拉伸 self.setup_Ui() # 加载窗体 def setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name",
"y=10) self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr = tk.Label(self, text='地址',width=6).place(x=10, y=60)",
"connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{} -pw {} -P",
"= tk.Label(self, text='协议', width=6).place(x=10, y=210) self.Entry_connect_protocol = tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60, y=210) self.Button_save =",
"RemoteWindow_W(tk.Tk): \"\"\"remote module function\"\"\" def __init__(self): super(RemoteWindow_W, self).__init__() # 继承类 width = 500",
"width=6).place(x=190, y=60) self.user_name=tk.StringVar() self.Label_user_name = tk.Label(self, text='用户名',width=6).place(x=10, y=110) self.Entry_user_name = tk.Entry(self, textvariable=self.user_name, width=15).place(x=60,",
"super(RemoteWindow_W, self).__init__() # 继承类 width = 500 # 登录界面宽度 height = 300 #",
"继承类 width = 500 # 登录界面宽度 height = 300 # 登录界面高度 sw =",
"= 500 # 登录界面宽度 height = 300 # 登录界面高度 sw = (self.winfo_screenwidth() -",
"2 # 获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height, sw, sh)) self.resizable(0, 0) # 固定窗口不能拉伸 self.setup_Ui()",
"show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol = tk.Label(self, text='协议', width=6).place(x=10, y=210) self.Entry_connect_protocol = tk.Entry(self, textvariable=self.connect_protocol,",
"text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260) def connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def",
"tk.Button(self, text='保存', width=10).place(x=10, y=260) self.Button_connect = tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260) def connect_Remote_Var(self): passwd=self.user_passwd.get()",
"= tk.Label(self, text='用户名',width=6).place(x=10, y=110) self.Entry_user_name = tk.Entry(self, textvariable=self.user_name, width=15).place(x=60, y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd =",
"passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{}",
"300 # 登录界面高度 sw = (self.winfo_screenwidth() - width) //2 # 获取x轴坐标 sh =",
"width=15).place(x=60, y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr = tk.Label(self, text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60,",
"获取x轴坐标 sh = (self.winfo_screenheight() - height) // 2 # 获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height,",
"self.resizable(0, 0) # 固定窗口不能拉伸 self.setup_Ui() # 加载窗体 def setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10,",
"__init__(self): super(RemoteWindow_W, self).__init__() # 继承类 width = 500 # 登录界面宽度 height = 300",
"text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60, y=60) self.Entry_connect_port = tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190, y=60)",
"# 获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height, sw, sh)) self.resizable(0, 0) # 固定窗口不能拉伸 self.setup_Ui() #",
"self.Label_connect_protocol = tk.Label(self, text='协议', width=6).place(x=10, y=210) self.Entry_connect_protocol = tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60, y=210) self.Button_save",
"self.Entry_user_name = tk.Entry(self, textvariable=self.user_name, width=15).place(x=60, y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd = tk.Label(self, text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd",
"self.connect_name=tk.StringVar() self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr",
"# 继承类 width = 500 # 登录界面宽度 height = 300 # 登录界面高度 sw",
"//2 # 获取x轴坐标 sh = (self.winfo_screenheight() - height) // 2 # 获取y轴坐标 self.title(\"链接信息\")",
"(self.winfo_screenheight() - height) // 2 # 获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height, sw, sh)) self.resizable(0,",
"width=15).place(x=60, y=60) self.Entry_connect_port = tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190, y=60) self.user_name=tk.StringVar() self.Label_user_name = tk.Label(self, text='用户名',width=6).place(x=10,",
"width=10,command=self.connect_Remote_Var).place(x=160, y=260) def connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name):",
"self.geometry(\"{}x{}+{}+{}\".format(width, height, sw, sh)) self.resizable(0, 0) # 固定窗口不能拉伸 self.setup_Ui() # 加载窗体 def setup_Ui(self):",
"def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{} -pw {} -P {}\".format(os_path,protocol,name,addr,passwd,port)) class RemoteWindow_L(RemoteWindow_W):",
"= tk.Label(self, text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60, y=60) self.Entry_connect_port = tk.Entry(self, textvariable=self.connect_port,",
"# 登录界面高度 sw = (self.winfo_screenwidth() - width) //2 # 获取x轴坐标 sh = (self.winfo_screenheight()",
"# 获取x轴坐标 sh = (self.winfo_screenheight() - height) // 2 # 获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width,",
"tkinter as tk import os class RemoteWindow_W(tk.Tk): \"\"\"remote module function\"\"\" def __init__(self): super(RemoteWindow_W,",
"= (self.winfo_screenheight() - height) // 2 # 获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height, sw, sh))",
"tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr = tk.Label(self, text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr,",
"y=60) self.user_name=tk.StringVar() self.Label_user_name = tk.Label(self, text='用户名',width=6).place(x=10, y=110) self.Entry_user_name = tk.Entry(self, textvariable=self.user_name, width=15).place(x=60, y=110)",
"self.Label_connect_addr = tk.Label(self, text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60, y=60) self.Entry_connect_port = tk.Entry(self,",
"{}@{} -pw {} -P {}\".format(os_path,protocol,name,addr,passwd,port)) class RemoteWindow_L(RemoteWindow_W): def start_Connect(self,passwd,name,addr,port,protocol,connect_name): os.system(\"{} {}@{} -p {}\".format(protocol,name,addr,port))",
"y=260) self.Button_connect = tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260) def connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get()",
"class RemoteWindow_W(tk.Tk): \"\"\"remote module function\"\"\" def __init__(self): super(RemoteWindow_W, self).__init__() # 继承类 width =",
"- width) //2 # 获取x轴坐标 sh = (self.winfo_screenheight() - height) // 2 #",
"self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60, y=60) self.Entry_connect_port = tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190, y=60) self.user_name=tk.StringVar() self.Label_user_name",
"tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr = tk.Label(self, text='地址',width=6).place(x=10,",
"-{} {}@{} -pw {} -P {}\".format(os_path,protocol,name,addr,passwd,port)) class RemoteWindow_L(RemoteWindow_W): def start_Connect(self,passwd,name,addr,port,protocol,connect_name): os.system(\"{} {}@{} -p",
"获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height, sw, sh)) self.resizable(0, 0) # 固定窗口不能拉伸 self.setup_Ui() # 加载窗体",
"加载窗体 def setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10)",
"固定窗口不能拉伸 self.setup_Ui() # 加载窗体 def setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name =",
"= tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190, y=60) self.user_name=tk.StringVar() self.Label_user_name = tk.Label(self, text='用户名',width=6).place(x=10, y=110) self.Entry_user_name =",
"module function\"\"\" def __init__(self): super(RemoteWindow_W, self).__init__() # 继承类 width = 500 # 登录界面宽度",
"setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar()",
"self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr =",
"height) // 2 # 获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height, sw, sh)) self.resizable(0, 0) #",
"width = 500 # 登录界面宽度 height = 300 # 登录界面高度 sw = (self.winfo_screenwidth()",
"y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd = tk.Label(self, text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd = tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160)",
"width=6).place(x=10, y=210) self.Entry_connect_protocol = tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60, y=210) self.Button_save = tk.Button(self, text='保存', width=10).place(x=10,",
"y=160) self.Entry_user_passwd = tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol = tk.Label(self, text='协议', width=6).place(x=10,",
"self.connect_protocol=tk.StringVar() self.Label_connect_protocol = tk.Label(self, text='协议', width=6).place(x=10, y=210) self.Entry_connect_protocol = tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60, y=210)",
"500 # 登录界面宽度 height = 300 # 登录界面高度 sw = (self.winfo_screenwidth() - width)",
"self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{} -pw {} -P {}\".format(os_path,protocol,name,addr,passwd,port)) class",
"import tkinter as tk import os class RemoteWindow_W(tk.Tk): \"\"\"remote module function\"\"\" def __init__(self):",
"self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr = tk.Label(self, text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr=",
"textvariable=self.user_name, width=15).place(x=60, y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd = tk.Label(self, text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd = tk.Entry(self, textvariable=self.user_passwd,",
"// 2 # 获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height, sw, sh)) self.resizable(0, 0) # 固定窗口不能拉伸",
"self.user_name=tk.StringVar() self.Label_user_name = tk.Label(self, text='用户名',width=6).place(x=10, y=110) self.Entry_user_name = tk.Entry(self, textvariable=self.user_name, width=15).place(x=60, y=110) self.user_passwd=tk.StringVar()",
"y=60) self.Entry_connect_port = tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190, y=60) self.user_name=tk.StringVar() self.Label_user_name = tk.Label(self, text='用户名',width=6).place(x=10, y=110)",
"#!/usr/bin/env python import tkinter as tk import os class RemoteWindow_W(tk.Tk): \"\"\"remote module function\"\"\"",
"self).__init__() # 继承类 width = 500 # 登录界面宽度 height = 300 # 登录界面高度",
"self.Label_user_passwd = tk.Label(self, text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd = tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol",
"self.Button_save = tk.Button(self, text='保存', width=10).place(x=10, y=260) self.Button_connect = tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260) def",
"text='协议', width=6).place(x=10, y=210) self.Entry_connect_protocol = tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60, y=210) self.Button_save = tk.Button(self, text='保存',",
"登录界面宽度 height = 300 # 登录界面高度 sw = (self.winfo_screenwidth() - width) //2 #",
"# 固定窗口不能拉伸 self.setup_Ui() # 加载窗体 def setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name",
"tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60, y=60) self.Entry_connect_port = tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190, y=60) self.user_name=tk.StringVar() self.Label_user_name =",
"def connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start",
"y=260) def connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.')",
"tk.Label(self, text='协议', width=6).place(x=10, y=210) self.Entry_connect_protocol = tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60, y=210) self.Button_save = tk.Button(self,",
"y=210) self.Button_save = tk.Button(self, text='保存', width=10).place(x=10, y=260) self.Button_connect = tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260)",
"self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr = tk.Label(self, text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60, y=60) self.Entry_connect_port",
"width=15).place(x=60, y=210) self.Button_save = tk.Button(self, text='保存', width=10).place(x=10, y=260) self.Button_connect = tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160,",
"os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{} -pw {} -P {}\".format(os_path,protocol,name,addr,passwd,port)) class RemoteWindow_L(RemoteWindow_W): def start_Connect(self,passwd,name,addr,port,protocol,connect_name): os.system(\"{}",
"= tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260) def connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get()",
"text='用户名',width=6).place(x=10, y=110) self.Entry_user_name = tk.Entry(self, textvariable=self.user_name, width=15).place(x=60, y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd = tk.Label(self, text='密码',width=6).place(x=10,",
"self.user_passwd=tk.StringVar() self.Label_user_passwd = tk.Label(self, text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd = tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar()",
"= tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr = tk.Label(self, text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr= tk.Entry(self,",
"name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{}",
"= tk.Entry(self, textvariable=self.user_name, width=15).place(x=60, y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd = tk.Label(self, text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd =",
"function\"\"\" def __init__(self): super(RemoteWindow_W, self).__init__() # 继承类 width = 500 # 登录界面宽度 height",
"import os class RemoteWindow_W(tk.Tk): \"\"\"remote module function\"\"\" def __init__(self): super(RemoteWindow_W, self).__init__() # 继承类",
"protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{} -pw {} -P {}\".format(os_path,protocol,name,addr,passwd,port))",
"width) //2 # 获取x轴坐标 sh = (self.winfo_screenheight() - height) // 2 # 获取y轴坐标",
"tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190, y=60) self.user_name=tk.StringVar() self.Label_user_name = tk.Label(self, text='用户名',width=6).place(x=10, y=110) self.Entry_user_name = tk.Entry(self,",
"python import tkinter as tk import os class RemoteWindow_W(tk.Tk): \"\"\"remote module function\"\"\" def",
"width=15).place(x=60, y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd = tk.Label(self, text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd = tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60,",
"<filename>app/appmodule/remote.py #!/usr/bin/env python import tkinter as tk import os class RemoteWindow_W(tk.Tk): \"\"\"remote module",
"tk.Entry(self, textvariable=self.user_name, width=15).place(x=60, y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd = tk.Label(self, text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd = tk.Entry(self,",
"# 登录界面宽度 height = 300 # 登录界面高度 sw = (self.winfo_screenwidth() - width) //2",
"= (self.winfo_screenwidth() - width) //2 # 获取x轴坐标 sh = (self.winfo_screenheight() - height) //",
"text='保存', width=10).place(x=10, y=260) self.Button_connect = tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260) def connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get()",
"y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol = tk.Label(self, text='协议', width=6).place(x=10, y=210) self.Entry_connect_protocol = tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60,",
"os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{} -pw {} -P {}\".format(os_path,protocol,name,addr,passwd,port)) class RemoteWindow_L(RemoteWindow_W): def start_Connect(self,passwd,name,addr,port,protocol,connect_name):",
"sh)) self.resizable(0, 0) # 固定窗口不能拉伸 self.setup_Ui() # 加载窗体 def setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name =",
"= tk.Button(self, text='保存', width=10).place(x=10, y=260) self.Button_connect = tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260) def connect_Remote_Var(self):",
"textvariable=self.connect_protocol, width=15).place(x=60, y=210) self.Button_save = tk.Button(self, text='保存', width=10).place(x=10, y=260) self.Button_connect = tk.Button(self, text='启动链接',",
"= tk.Label(self, text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd = tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol =",
"textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol = tk.Label(self, text='协议', width=6).place(x=10, y=210) self.Entry_connect_protocol = tk.Entry(self,",
"self.Entry_connect_protocol = tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60, y=210) self.Button_save = tk.Button(self, text='保存', width=10).place(x=10, y=260) self.Button_connect",
"self.Button_connect = tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260) def connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get()",
"y=60) self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60, y=60) self.Entry_connect_port = tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190, y=60) self.user_name=tk.StringVar()",
"port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{} -pw {}",
"tk.Label(self, text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60, y=60) self.Entry_connect_port = tk.Entry(self, textvariable=self.connect_port, width=6).place(x=190,",
"self.Entry_user_passwd = tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol = tk.Label(self, text='协议', width=6).place(x=10, y=210)",
"start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{} -pw {} -P {}\".format(os_path,protocol,name,addr,passwd,port)) class RemoteWindow_L(RemoteWindow_W): def",
"tk.Entry(self, textvariable=self.connect_protocol, width=15).place(x=60, y=210) self.Button_save = tk.Button(self, text='保存', width=10).place(x=10, y=260) self.Button_connect = tk.Button(self,",
"as tk import os class RemoteWindow_W(tk.Tk): \"\"\"remote module function\"\"\" def __init__(self): super(RemoteWindow_W, self).__init__()",
"self.setup_Ui() # 加载窗体 def setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name,",
"y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr = tk.Label(self, text='地址',width=6).place(x=10, y=60) self.Entry_connect_addr= tk.Entry(self, textvariable=self.connect_addr, width=15).place(x=60, y=60)",
"def setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10) self.connect_addr=tk.StringVar()",
"(self.winfo_screenwidth() - width) //2 # 获取x轴坐标 sh = (self.winfo_screenheight() - height) // 2",
"{}\\\\app\\\\share\\\\sysfile\\\\putty.exe -{} {}@{} -pw {} -P {}\".format(os_path,protocol,name,addr,passwd,port)) class RemoteWindow_L(RemoteWindow_W): def start_Connect(self,passwd,name,addr,port,protocol,connect_name): os.system(\"{} {}@{}",
"tk import os class RemoteWindow_W(tk.Tk): \"\"\"remote module function\"\"\" def __init__(self): super(RemoteWindow_W, self).__init__() #",
"tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260) def connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name)",
"tk.Label(self, text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd = tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol = tk.Label(self,",
"\"\"\"remote module function\"\"\" def __init__(self): super(RemoteWindow_W, self).__init__() # 继承类 width = 500 #",
"= tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60, y=10) self.connect_addr=tk.StringVar() self.connect_port=tk.StringVar() self.Label_connect_addr = tk.Label(self,",
"def __init__(self): super(RemoteWindow_W, self).__init__() # 继承类 width = 500 # 登录界面宽度 height =",
"= tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol = tk.Label(self, text='协议', width=6).place(x=10, y=210) self.Entry_connect_protocol",
"tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol = tk.Label(self, text='协议', width=6).place(x=10, y=210) self.Entry_connect_protocol =",
"# 加载窗体 def setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10, y=10) self.Entry_connect_name = tk.Entry(self,textvariable=self.connect_name, width=15).place(x=60,",
"textvariable=self.connect_port, width=6).place(x=190, y=60) self.user_name=tk.StringVar() self.Label_user_name = tk.Label(self, text='用户名',width=6).place(x=10, y=110) self.Entry_user_name = tk.Entry(self, textvariable=self.user_name,",
"height, sw, sh)) self.resizable(0, 0) # 固定窗口不能拉伸 self.setup_Ui() # 加载窗体 def setup_Ui(self): self.connect_name=tk.StringVar()",
"sh = (self.winfo_screenheight() - height) // 2 # 获取y轴坐标 self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height, sw,",
"self.title(\"链接信息\") self.geometry(\"{}x{}+{}+{}\".format(width, height, sw, sh)) self.resizable(0, 0) # 固定窗口不能拉伸 self.setup_Ui() # 加载窗体 def",
"width=10).place(x=10, y=260) self.Button_connect = tk.Button(self, text='启动链接', width=10,command=self.connect_Remote_Var).place(x=160, y=260) def connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get()",
"登录界面高度 sw = (self.winfo_screenwidth() - width) //2 # 获取x轴坐标 sh = (self.winfo_screenheight() -",
"os class RemoteWindow_W(tk.Tk): \"\"\"remote module function\"\"\" def __init__(self): super(RemoteWindow_W, self).__init__() # 继承类 width",
"0) # 固定窗口不能拉伸 self.setup_Ui() # 加载窗体 def setup_Ui(self): self.connect_name=tk.StringVar() self.Label_connect_name = tk.Label(self,text='名称',width=6).place(x=10, y=10)",
"connect_Remote_Var(self): passwd=self.user_passwd.get() name=self.user_name.get() addr=self.connect_addr.get() port=self.connect_port.get() connect_name=self.connect_name.get() protocol=self.connect_protocol.get() self.start_Connect(protocol,name,addr,port,passwd,connect_name) def start_Connect(self,protocol,name,addr,port,passwd,connect_name): os_path=os.path.abspath('.') os.system(\"start {}\\\\app\\\\share\\\\sysfile\\\\putty.exe",
"y=110) self.Entry_user_name = tk.Entry(self, textvariable=self.user_name, width=15).place(x=60, y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd = tk.Label(self, text='密码',width=6).place(x=10, y=160)",
"text='密码',width=6).place(x=10, y=160) self.Entry_user_passwd = tk.Entry(self, textvariable=self.user_passwd, show=\"*\",width=15).place(x=60, y=160) self.connect_protocol=tk.StringVar() self.Label_connect_protocol = tk.Label(self, text='协议',",
"self.Label_user_name = tk.Label(self, text='用户名',width=6).place(x=10, y=110) self.Entry_user_name = tk.Entry(self, textvariable=self.user_name, width=15).place(x=60, y=110) self.user_passwd=tk.StringVar() self.Label_user_passwd"
] |
[
"h.add(_.StringCodetable('marsClass', 1, \"mars/class.table\")) h.add(_.StringCodetable('marsType', 1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType', 'marsType')",
"1, \"mars/class.table\")) h.add(_.StringCodetable('marsType', 1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType', 'marsType') h.alias('mars.class',",
"def load(h): h.add(_.StringCodetable('marsClass', 1, \"mars/class.table\")) h.add(_.StringCodetable('marsType', 1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4))",
"\"mars/class.table\")) h.add(_.StringCodetable('marsType', 1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType', 'marsType') h.alias('mars.class', 'marsClass')",
"\"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType', 'marsType') h.alias('mars.class', 'marsClass') h.alias('mars.type', 'marsType') h.alias('mars.stream',",
"_ def load(h): h.add(_.StringCodetable('marsClass', 1, \"mars/class.table\")) h.add(_.StringCodetable('marsType', 1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber',",
"load(h): h.add(_.StringCodetable('marsClass', 1, \"mars/class.table\")) h.add(_.StringCodetable('marsType', 1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType',",
"pyeccodes.accessors as _ def load(h): h.add(_.StringCodetable('marsClass', 1, \"mars/class.table\")) h.add(_.StringCodetable('marsType', 1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2,",
"h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType', 'marsType') h.alias('mars.class', 'marsClass') h.alias('mars.type', 'marsType') h.alias('mars.stream', 'marsStream')",
"<reponame>ecmwf/pyeccodes import pyeccodes.accessors as _ def load(h): h.add(_.StringCodetable('marsClass', 1, \"mars/class.table\")) h.add(_.StringCodetable('marsType', 1, \"mars/type.table\"))",
"h.add(_.StringCodetable('marsType', 1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType', 'marsType') h.alias('mars.class', 'marsClass') h.alias('mars.type',",
"\"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType', 'marsType') h.alias('mars.class', 'marsClass') h.alias('mars.type', 'marsType') h.alias('mars.stream', 'marsStream') h.alias('mars.expver', 'experimentVersionNumber')",
"4)) h.alias('ls.dataType', 'marsType') h.alias('mars.class', 'marsClass') h.alias('mars.type', 'marsType') h.alias('mars.stream', 'marsStream') h.alias('mars.expver', 'experimentVersionNumber') h.alias('mars.domain', 'globalDomain')",
"import pyeccodes.accessors as _ def load(h): h.add(_.StringCodetable('marsClass', 1, \"mars/class.table\")) h.add(_.StringCodetable('marsType', 1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream',",
"1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType', 'marsType') h.alias('mars.class', 'marsClass') h.alias('mars.type', 'marsType')",
"2, \"mars/stream.table\")) h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType', 'marsType') h.alias('mars.class', 'marsClass') h.alias('mars.type', 'marsType') h.alias('mars.stream', 'marsStream') h.alias('mars.expver',",
"h.add(_.Ksec1expver('experimentVersionNumber', 4)) h.alias('ls.dataType', 'marsType') h.alias('mars.class', 'marsClass') h.alias('mars.type', 'marsType') h.alias('mars.stream', 'marsStream') h.alias('mars.expver', 'experimentVersionNumber') h.alias('mars.domain',",
"as _ def load(h): h.add(_.StringCodetable('marsClass', 1, \"mars/class.table\")) h.add(_.StringCodetable('marsType', 1, \"mars/type.table\")) h.add(_.StringCodetable('marsStream', 2, \"mars/stream.table\"))"
] |
[
"of MIDI notes. \"\"\" from numpy import power, divide def midi_note_to_freq_basic(keynum): return 440.0",
"program to calculate note frequencies for a number of MIDI notes. \"\"\" from",
"python3 \"\"\" A program to calculate note frequencies for a number of MIDI",
"#!/usr/bin/env python3 \"\"\" A program to calculate note frequencies for a number of",
"\"\"\" A program to calculate note frequencies for a number of MIDI notes.",
"number of MIDI notes. \"\"\" from numpy import power, divide def midi_note_to_freq_basic(keynum): return",
"import power, divide def midi_note_to_freq_basic(keynum): return 440.0 * pow(2.0, (keynum - 69.0) /",
"(keynum - 69.0) / 12.0) f_basic = [midi_note_to_freq_basic(key) for key in range(128)] print(f_basic)",
"MIDI notes. \"\"\" from numpy import power, divide def midi_note_to_freq_basic(keynum): return 440.0 *",
"frequencies for a number of MIDI notes. \"\"\" from numpy import power, divide",
"440.0 * pow(2.0, (keynum - 69.0) / 12.0) f_basic = [midi_note_to_freq_basic(key) for key",
"* pow(2.0, (keynum - 69.0) / 12.0) f_basic = [midi_note_to_freq_basic(key) for key in",
"divide def midi_note_to_freq_basic(keynum): return 440.0 * pow(2.0, (keynum - 69.0) / 12.0) f_basic",
"for a number of MIDI notes. \"\"\" from numpy import power, divide def",
"return 440.0 * pow(2.0, (keynum - 69.0) / 12.0) f_basic = [midi_note_to_freq_basic(key) for",
"def midi_note_to_freq_basic(keynum): return 440.0 * pow(2.0, (keynum - 69.0) / 12.0) f_basic =",
"power, divide def midi_note_to_freq_basic(keynum): return 440.0 * pow(2.0, (keynum - 69.0) / 12.0)",
"\"\"\" from numpy import power, divide def midi_note_to_freq_basic(keynum): return 440.0 * pow(2.0, (keynum",
"to calculate note frequencies for a number of MIDI notes. \"\"\" from numpy",
"A program to calculate note frequencies for a number of MIDI notes. \"\"\"",
"midi_note_to_freq_basic(keynum): return 440.0 * pow(2.0, (keynum - 69.0) / 12.0) f_basic = [midi_note_to_freq_basic(key)",
"pow(2.0, (keynum - 69.0) / 12.0) f_basic = [midi_note_to_freq_basic(key) for key in range(128)]",
"calculate note frequencies for a number of MIDI notes. \"\"\" from numpy import",
"a number of MIDI notes. \"\"\" from numpy import power, divide def midi_note_to_freq_basic(keynum):",
"note frequencies for a number of MIDI notes. \"\"\" from numpy import power,",
"numpy import power, divide def midi_note_to_freq_basic(keynum): return 440.0 * pow(2.0, (keynum - 69.0)",
"notes. \"\"\" from numpy import power, divide def midi_note_to_freq_basic(keynum): return 440.0 * pow(2.0,",
"from numpy import power, divide def midi_note_to_freq_basic(keynum): return 440.0 * pow(2.0, (keynum -"
] |
[
"License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"action_cmd from highlanderclient.tests.unit import base ACTION_DICT = { 'name': 'a', 'is_system': True, 'input':",
"action', 'test', '1', '1')], result[1] ) @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self, mock, mock_open):",
"Unless required by applicable law or agreed to in writing, software # distributed",
"See the # License for the specific language governing permissions and limitations #",
"'1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self, mock): mock.return_value = ACTION result = self.call(action_cmd.Get,",
"mock from highlanderclient.api.v2 import actions from highlanderclient.commands.v2 import actions as action_cmd from highlanderclient.tests.unit",
"'1'), result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self, del_mock): self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self,",
"for the specific language governing permissions and limitations # under the License. #",
"result = self.call(action_cmd.Get, app_args=['name']) self.assertEqual( ('a', True, \"param1\", 'My cool action', 'test', '1',",
"'2.0' base: std.echo base-parameters: output: \"<% $.str1 %><% $.str2 %>\" output: \"<% $",
"\"License\"); you may # not use this file except in compliance with the",
"self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get')",
"self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list')",
"Apache License, Version 2.0 (the \"License\"); you may # not use this file",
"ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION = actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF = actions.Action(mock, ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open',",
"the License. You may obtain # a copy of the License at #",
"'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self,",
"test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete, app_args=['name1', 'name2']) self.assertEqual(2, del_mock.call_count) self.assertEqual( [mock.call('name1'), mock.call('name2')], del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.'",
"law or agreed to in writing, software # distributed under the License is",
"may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the Apache License, Version 2.0 (the \"License\"); you may # not use this",
"test_update(self, mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual( [('a', True,",
"import base ACTION_DICT = { 'name': 'a', 'is_system': True, 'input': \"param1\", 'description': 'My",
"Rights Reserved # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"express or implied. See the # License for the specific language governing permissions",
"@mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self, mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Update,",
") @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self, mock): mock.return_value = (ACTION,) result = self.call(action_cmd.List) self.assertEqual( [('a',",
"--- version: '2.0' base: std.echo base-parameters: output: \"<% $.str1 %><% $.str2 %>\" output:",
"self.call(action_cmd.Delete, app_args=['name1', 'name2']) self.assertEqual(2, del_mock.call_count) self.assertEqual( [mock.call('name1'), mock.call('name2')], del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.' 'ActionManager.get') def",
"permissions and limitations # under the License. # import mock from highlanderclient.api.v2 import",
"cool action', 'tags': ['test'], 'created_at': '1', 'updated_at': '1' } ACTION_DEF = \"\"\" ---",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"CONDITIONS OF ANY KIND, either express or implied. See the # License for",
"not use this file except in compliance with the License. You may obtain",
"def test_list(self, mock): mock.return_value = (ACTION,) result = self.call(action_cmd.List) self.assertEqual( [('a', True, \"param1\",",
"test_list(self, mock): mock.return_value = (ACTION,) result = self.call(action_cmd.List) self.assertEqual( [('a', True, \"param1\", 'My",
"(ACTION,) result = self.call(action_cmd.List) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1',",
"[('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('argparse.open', create=True)",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"with the License. You may obtain # a copy of the License at",
"'input': \"param1\", 'description': 'My cool action', 'tags': ['test'], 'created_at': '1', 'updated_at': '1' }",
"Copyright 2014 Mirantis, Inc. # All Rights Reserved # # Licensed under the",
"from highlanderclient.commands.v2 import actions as action_cmd from highlanderclient.tests.unit import base ACTION_DICT = {",
"create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self, mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Update, app_args=['my_action.yaml'])",
"action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self, mock): mock.return_value = (ACTION,)",
"# All Rights Reserved # # Licensed under the Apache License, Version 2.0",
"from highlanderclient.api.v2 import actions from highlanderclient.commands.v2 import actions as action_cmd from highlanderclient.tests.unit import",
"{ 'name': 'a', 'is_system': True, 'input': \"param1\", 'description': 'My cool action', 'tags': ['test'],",
"ACTION = actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF = actions.Action(mock, ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create')",
"cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self, mock): mock.return_value =",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not",
"\"param1\", 'description': 'My cool action', 'tags': ['test'], 'created_at': '1', 'updated_at': '1' } ACTION_DEF",
"'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self, mock): mock.return_value",
"True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self,",
"License for the specific language governing permissions and limitations # under the License.",
"= (ACTION,) result = self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual( [('a', True, \"param1\", 'My cool action',",
"\"<% $ %><% $ %>\" \"\"\" ACTION_WITH_DEF_DICT = ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION =",
"'1', '1')], result[1] ) @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self, mock, mock_open): mock.return_value =",
"'My cool action', 'tags': ['test'], 'created_at': '1', 'updated_at': '1' } ACTION_DEF = \"\"\"",
"import actions as action_cmd from highlanderclient.tests.unit import base ACTION_DICT = { 'name': 'a',",
"2.0 (the \"License\"); you may # not use this file except in compliance",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"@mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self, mock): mock.return_value = ACTION result = self.call(action_cmd.Get, app_args=['name']) self.assertEqual( ('a',",
"mock.return_value = ACTION result = self.call(action_cmd.Get, app_args=['name']) self.assertEqual( ('a', True, \"param1\", 'My cool",
"app_args=['my_action.yaml']) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] )",
"mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual( [('a', True, \"param1\", 'My",
"'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self, mock): mock.return_value",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self, mock, mock_open): mock.return_value = (ACTION,) result",
"def test_update(self, mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual( [('a',",
"use this file except in compliance with the License. You may obtain #",
"def test_create(self, mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual( [('a',",
"'My cool action', 'test', '1', '1'), result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self, del_mock): self.call(action_cmd.Delete,",
"# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"self.call(action_cmd.Get, app_args=['name']) self.assertEqual( ('a', True, \"param1\", 'My cool action', 'test', '1', '1'), result[1]",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #",
"compliance with the License. You may obtain # a copy of the License",
"'name': 'a', 'is_system': True, 'input': \"param1\", 'description': 'My cool action', 'tags': ['test'], 'created_at':",
"\"\"\" --- version: '2.0' base: std.echo base-parameters: output: \"<% $.str1 %><% $.str2 %>\"",
"self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1]",
"License, Version 2.0 (the \"License\"); you may # not use this file except",
"ACTION_DICT) ACTION_WITH_DEF = actions.Action(mock, ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self, mock,",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"and limitations # under the License. # import mock from highlanderclient.api.v2 import actions",
") @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self, mock): mock.return_value = ACTION result = self.call(action_cmd.Get, app_args=['name']) self.assertEqual(",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"self.call(action_cmd.List) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] )",
"%><% $.str2 %>\" output: \"<% $ %><% $ %>\" \"\"\" ACTION_WITH_DEF_DICT = ACTION_DICT.copy()",
"self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('argparse.open',",
"\"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self, mock):",
"ACTION_DEF = \"\"\" --- version: '2.0' base: std.echo base-parameters: output: \"<% $.str1 %><%",
"= ACTION result = self.call(action_cmd.Get, app_args=['name']) self.assertEqual( ('a', True, \"param1\", 'My cool action',",
"True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update')",
"'test', '1', '1')], result[1] ) @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self, mock, mock_open): mock.return_value",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"implied. See the # License for the specific language governing permissions and limitations",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"OF ANY KIND, either express or implied. See the # License for the",
"base ACTION_DICT = { 'name': 'a', 'is_system': True, 'input': \"param1\", 'description': 'My cool",
"@mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self, mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual(",
"$ %>\" \"\"\" ACTION_WITH_DEF_DICT = ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION = actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"'updated_at': '1' } ACTION_DEF = \"\"\" --- version: '2.0' base: std.echo base-parameters: output:",
"True, \"param1\", 'My cool action', 'test', '1', '1'), result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self,",
"del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.' 'ActionManager.get') def test_get_definition(self, mock): mock.return_value = ACTION_WITH_DEF self.call(action_cmd.GetDefinition, app_args=['name']) self.app.stdout.write.assert_called_with(ACTION_DEF)",
"del_mock): self.call(action_cmd.Delete, app_args=['name1', 'name2']) self.assertEqual(2, del_mock.call_count) self.assertEqual( [mock.call('name1'), mock.call('name2')], del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.' 'ActionManager.get')",
"the specific language governing permissions and limitations # under the License. # import",
"= actions.Action(mock, ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self, mock, mock_open): mock.return_value",
"True, 'input': \"param1\", 'description': 'My cool action', 'tags': ['test'], 'created_at': '1', 'updated_at': '1'",
") @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self, mock, mock_open): mock.return_value = (ACTION,) result =",
"cool action', 'test', '1', '1'), result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self, del_mock): self.call(action_cmd.Delete, app_args=['name'])",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"highlanderclient.api.v2 import actions from highlanderclient.commands.v2 import actions as action_cmd from highlanderclient.tests.unit import base",
"\"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def",
"mock): mock.return_value = (ACTION,) result = self.call(action_cmd.List) self.assertEqual( [('a', True, \"param1\", 'My cool",
"language governing permissions and limitations # under the License. # import mock from",
"you may # not use this file except in compliance with the License.",
"[('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def",
"<filename>highlanderclient/tests/unit/v1/test_cli_actions.py<gh_stars>0 # Copyright 2014 Mirantis, Inc. # All Rights Reserved # # Licensed",
"= (ACTION,) result = self.call(action_cmd.List) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test',",
"self.assertEqual(2, del_mock.call_count) self.assertEqual( [mock.call('name1'), mock.call('name2')], del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.' 'ActionManager.get') def test_get_definition(self, mock): mock.return_value",
"agreed to in writing, software # distributed under the License is distributed on",
"ACTION_DEF}) ACTION = actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF = actions.Action(mock, ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True)",
"License. # import mock from highlanderclient.api.v2 import actions from highlanderclient.commands.v2 import actions as",
"[('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def",
"(the \"License\"); you may # not use this file except in compliance with",
"'1', '1'), result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self, del_mock): self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def",
"specific language governing permissions and limitations # under the License. # import mock",
"may # not use this file except in compliance with the License. You",
"KIND, either express or implied. See the # License for the specific language",
"%><% $ %>\" \"\"\" ACTION_WITH_DEF_DICT = ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION = actions.Action(mock, ACTION_DICT)",
"test_get(self, mock): mock.return_value = ACTION result = self.call(action_cmd.Get, app_args=['name']) self.assertEqual( ('a', True, \"param1\",",
") @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self, del_mock): self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete,",
"# Copyright 2014 Mirantis, Inc. # All Rights Reserved # # Licensed under",
"either express or implied. See the # License for the specific language governing",
"\"\"\" ACTION_WITH_DEF_DICT = ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION = actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF = actions.Action(mock,",
"= self.call(action_cmd.List) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1]",
"True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self,",
"the License. # import mock from highlanderclient.api.v2 import actions from highlanderclient.commands.v2 import actions",
"# # Unless required by applicable law or agreed to in writing, software",
"%>\" output: \"<% $ %><% $ %>\" \"\"\" ACTION_WITH_DEF_DICT = ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF})",
"'created_at': '1', 'updated_at': '1' } ACTION_DEF = \"\"\" --- version: '2.0' base: std.echo",
"self.assertEqual( ('a', True, \"param1\", 'My cool action', 'test', '1', '1'), result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete')",
"file except in compliance with the License. You may obtain # a copy",
"def test_delete(self, del_mock): self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete, app_args=['name1', 'name2'])",
"= self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')],",
"this file except in compliance with the License. You may obtain # a",
"('a', True, \"param1\", 'My cool action', 'test', '1', '1'), result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def",
"'is_system': True, 'input': \"param1\", 'description': 'My cool action', 'tags': ['test'], 'created_at': '1', 'updated_at':",
"# Unless required by applicable law or agreed to in writing, software #",
"$.str1 %><% $.str2 %>\" output: \"<% $ %><% $ %>\" \"\"\" ACTION_WITH_DEF_DICT =",
"by applicable law or agreed to in writing, software # distributed under the",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self, mock): mock.return_value = (ACTION,) result = self.call(action_cmd.List) self.assertEqual(",
"= ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION = actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF = actions.Action(mock, ACTION_WITH_DEF_DICT) class",
"actions.Action(mock, ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self, mock, mock_open): mock.return_value =",
"mock): mock.return_value = ACTION result = self.call(action_cmd.Get, app_args=['name']) self.assertEqual( ('a', True, \"param1\", 'My",
"= { 'name': 'a', 'is_system': True, 'input': \"param1\", 'description': 'My cool action', 'tags':",
"} ACTION_DEF = \"\"\" --- version: '2.0' base: std.echo base-parameters: output: \"<% $.str1",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"or implied. See the # License for the specific language governing permissions and",
"governing permissions and limitations # under the License. # import mock from highlanderclient.api.v2",
"base-parameters: output: \"<% $.str1 %><% $.str2 %>\" output: \"<% $ %><% $ %>\"",
"action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self, mock): mock.return_value = ACTION",
"app_args=['name1', 'name2']) self.assertEqual(2, del_mock.call_count) self.assertEqual( [mock.call('name1'), mock.call('name2')], del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.' 'ActionManager.get') def test_get_definition(self,",
"def test_get(self, mock): mock.return_value = ACTION result = self.call(action_cmd.Get, app_args=['name']) self.assertEqual( ('a', True,",
"(ACTION,) result = self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test',",
"highlanderclient.tests.unit import base ACTION_DICT = { 'name': 'a', 'is_system': True, 'input': \"param1\", 'description':",
"'1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self, mock): mock.return_value = ACTION result =",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"$.str2 %>\" output: \"<% $ %><% $ %>\" \"\"\" ACTION_WITH_DEF_DICT = ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition':",
"ACTION_DICT = { 'name': 'a', 'is_system': True, 'input': \"param1\", 'description': 'My cool action',",
"@mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self, mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual(",
"mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual( [('a', True, \"param1\", 'My",
"'1')], result[1] ) @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self, mock, mock_open): mock.return_value = (ACTION,)",
"mock.return_value = (ACTION,) result = self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual( [('a', True, \"param1\", 'My cool",
"result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self, mock): mock.return_value = ACTION result = self.call(action_cmd.Get, app_args=['name'])",
"under the License. # import mock from highlanderclient.api.v2 import actions from highlanderclient.commands.v2 import",
"version: '2.0' base: std.echo base-parameters: output: \"<% $.str1 %><% $.str2 %>\" output: \"<%",
"'name2']) self.assertEqual(2, del_mock.call_count) self.assertEqual( [mock.call('name1'), mock.call('name2')], del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.' 'ActionManager.get') def test_get_definition(self, mock):",
"# import mock from highlanderclient.api.v2 import actions from highlanderclient.commands.v2 import actions as action_cmd",
"License. You may obtain # a copy of the License at # #",
"result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self, del_mock): self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self, del_mock):",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"'tags': ['test'], 'created_at': '1', 'updated_at': '1' } ACTION_DEF = \"\"\" --- version: '2.0'",
"'description': 'My cool action', 'tags': ['test'], 'created_at': '1', 'updated_at': '1' } ACTION_DEF =",
"%>\" \"\"\" ACTION_WITH_DEF_DICT = ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION = actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF =",
"2014 Mirantis, Inc. # All Rights Reserved # # Licensed under the Apache",
"@mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self, del_mock): self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete, app_args=['name1',",
"'a', 'is_system': True, 'input': \"param1\", 'description': 'My cool action', 'tags': ['test'], 'created_at': '1',",
"Reserved # # Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"action', 'tags': ['test'], 'created_at': '1', 'updated_at': '1' } ACTION_DEF = \"\"\" --- version:",
"std.echo base-parameters: output: \"<% $.str1 %><% $.str2 %>\" output: \"<% $ %><% $",
"limitations # under the License. # import mock from highlanderclient.api.v2 import actions from",
"(ACTION,) result = self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test',",
"= (ACTION,) result = self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual( [('a', True, \"param1\", 'My cool action',",
"TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self, mock, mock_open): mock.return_value = (ACTION,) result =",
"All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF = actions.Action(mock, ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self,",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"ACTION_WITH_DEF_DICT = ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION = actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF = actions.Action(mock, ACTION_WITH_DEF_DICT)",
"\"param1\", 'My cool action', 'test', '1', '1'), result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self, del_mock):",
"test_delete(self, del_mock): self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete, app_args=['name1', 'name2']) self.assertEqual(2,",
"'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self, mock): mock.return_value = (ACTION,) result",
"ANY KIND, either express or implied. See the # License for the specific",
"the # License for the specific language governing permissions and limitations # under",
"except in compliance with the License. You may obtain # a copy of",
"app_args=['name']) self.assertEqual( ('a', True, \"param1\", 'My cool action', 'test', '1', '1'), result[1] )",
"del_mock): self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete, app_args=['name1', 'name2']) self.assertEqual(2, del_mock.call_count)",
"actions from highlanderclient.commands.v2 import actions as action_cmd from highlanderclient.tests.unit import base ACTION_DICT =",
"= self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')],",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"\"param1\", 'My cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self, mock):",
"test_create(self, mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual( [('a', True,",
"@mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self, mock): mock.return_value = (ACTION,) result = self.call(action_cmd.List) self.assertEqual( [('a', True,",
"to in writing, software # distributed under the License is distributed on an",
"You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"del_mock.call_count) self.assertEqual( [mock.call('name1'), mock.call('name2')], del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.' 'ActionManager.get') def test_get_definition(self, mock): mock.return_value =",
"ACTION_WITH_DEF = actions.Action(mock, ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self, mock, mock_open):",
"result[1] ) @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self, mock, mock_open): mock.return_value = (ACTION,) result",
"$ %><% $ %>\" \"\"\" ACTION_WITH_DEF_DICT = ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION = actions.Action(mock,",
"app_args=['1.txt']) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1] )",
"'1' } ACTION_DEF = \"\"\" --- version: '2.0' base: std.echo base-parameters: output: \"<%",
"required by applicable law or agreed to in writing, software # distributed under",
"result = self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1',",
"cool action', 'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self, mock): mock.return_value =",
"'1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self, mock): mock.return_value = (ACTION,) result = self.call(action_cmd.List)",
"= \"\"\" --- version: '2.0' base: std.echo base-parameters: output: \"<% $.str1 %><% $.str2",
"applicable law or agreed to in writing, software # distributed under the License",
"actions as action_cmd from highlanderclient.tests.unit import base ACTION_DICT = { 'name': 'a', 'is_system':",
"= actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF = actions.Action(mock, ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual( [('a', True, \"param1\",",
"OR CONDITIONS OF ANY KIND, either express or implied. See the # License",
"ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest): @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self, mock, mock_open): mock.return_value = (ACTION,)",
"create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self, mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Create, app_args=['1.txt'])",
"obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"from highlanderclient.tests.unit import base ACTION_DICT = { 'name': 'a', 'is_system': True, 'input': \"param1\",",
"output: \"<% $.str1 %><% $.str2 %>\" output: \"<% $ %><% $ %>\" \"\"\"",
"self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')], result[1]",
"action', 'test', '1', '1'), result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self, del_mock): self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name')",
"self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete, app_args=['name1', 'name2']) self.assertEqual(2, del_mock.call_count) self.assertEqual(",
"'test', '1', '1'), result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete(self, del_mock): self.call(action_cmd.Delete, app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete')",
"'test', '1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.get') def test_get(self, mock): mock.return_value = ACTION result",
"highlanderclient.commands.v2 import actions as action_cmd from highlanderclient.tests.unit import base ACTION_DICT = { 'name':",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #",
"in compliance with the License. You may obtain # a copy of the",
"[mock.call('name1'), mock.call('name2')], del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.' 'ActionManager.get') def test_get_definition(self, mock): mock.return_value = ACTION_WITH_DEF self.call(action_cmd.GetDefinition,",
"# not use this file except in compliance with the License. You may",
"mock.call('name2')], del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.' 'ActionManager.get') def test_get_definition(self, mock): mock.return_value = ACTION_WITH_DEF self.call(action_cmd.GetDefinition, app_args=['name'])",
"= self.call(action_cmd.Get, app_args=['name']) self.assertEqual( ('a', True, \"param1\", 'My cool action', 'test', '1', '1'),",
"or agreed to in writing, software # distributed under the License is distributed",
"ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION = actions.Action(mock, ACTION_DICT) ACTION_WITH_DEF = actions.Action(mock, ACTION_WITH_DEF_DICT) class TestCLIActionsV2(base.BaseCommandTest):",
"result = self.call(action_cmd.List) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1', '1')],",
"def test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete, app_args=['name1', 'name2']) self.assertEqual(2, del_mock.call_count) self.assertEqual( [mock.call('name1'), mock.call('name2')], del_mock.call_args_list )",
"app_args=['name']) del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete, app_args=['name1', 'name2']) self.assertEqual(2, del_mock.call_count) self.assertEqual( [mock.call('name1'),",
"# License for the specific language governing permissions and limitations # under the",
"ACTION result = self.call(action_cmd.Get, app_args=['name']) self.assertEqual( ('a', True, \"param1\", 'My cool action', 'test',",
"cool action', 'test', '1', '1')], result[1] ) @mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.update') def test_update(self, mock,",
"mock.return_value = (ACTION,) result = self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual( [('a', True, \"param1\", 'My cool",
"import mock from highlanderclient.api.v2 import actions from highlanderclient.commands.v2 import actions as action_cmd from",
"'1', 'updated_at': '1' } ACTION_DEF = \"\"\" --- version: '2.0' base: std.echo base-parameters:",
"import actions from highlanderclient.commands.v2 import actions as action_cmd from highlanderclient.tests.unit import base ACTION_DICT",
"base: std.echo base-parameters: output: \"<% $.str1 %><% $.str2 %>\" output: \"<% $ %><%",
"Inc. # All Rights Reserved # # Licensed under the Apache License, Version",
"result = self.call(action_cmd.Create, app_args=['1.txt']) self.assertEqual( [('a', True, \"param1\", 'My cool action', 'test', '1',",
"del_mock.assert_called_once_with('name') @mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete, app_args=['name1', 'name2']) self.assertEqual(2, del_mock.call_count) self.assertEqual( [mock.call('name1'), mock.call('name2')],",
"as action_cmd from highlanderclient.tests.unit import base ACTION_DICT = { 'name': 'a', 'is_system': True,",
"under the Apache License, Version 2.0 (the \"License\"); you may # not use",
"Mirantis, Inc. # All Rights Reserved # # Licensed under the Apache License,",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"mock.return_value = (ACTION,) result = self.call(action_cmd.List) self.assertEqual( [('a', True, \"param1\", 'My cool action',",
"@mock.patch('argparse.open', create=True) @mock.patch('highlanderclient.api.v2.actions.ActionManager.create') def test_create(self, mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Create,",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"# under the License. # import mock from highlanderclient.api.v2 import actions from highlanderclient.commands.v2",
"'1', '1')], result[1] ) @mock.patch('highlanderclient.api.v2.actions.ActionManager.list') def test_list(self, mock): mock.return_value = (ACTION,) result =",
"\"<% $.str1 %><% $.str2 %>\" output: \"<% $ %><% $ %>\" \"\"\" ACTION_WITH_DEF_DICT",
"in writing, software # distributed under the License is distributed on an \"AS",
"self.assertEqual( [mock.call('name1'), mock.call('name2')], del_mock.call_args_list ) @mock.patch('highlanderclient.api.v2.actions.' 'ActionManager.get') def test_get_definition(self, mock): mock.return_value = ACTION_WITH_DEF",
"Version 2.0 (the \"License\"); you may # not use this file except in",
"@mock.patch('highlanderclient.api.v2.actions.ActionManager.delete') def test_delete_with_multi_names(self, del_mock): self.call(action_cmd.Delete, app_args=['name1', 'name2']) self.assertEqual(2, del_mock.call_count) self.assertEqual( [mock.call('name1'), mock.call('name2')], del_mock.call_args_list",
"['test'], 'created_at': '1', 'updated_at': '1' } ACTION_DEF = \"\"\" --- version: '2.0' base:",
"mock, mock_open): mock.return_value = (ACTION,) result = self.call(action_cmd.Update, app_args=['my_action.yaml']) self.assertEqual( [('a', True, \"param1\",",
"output: \"<% $ %><% $ %>\" \"\"\" ACTION_WITH_DEF_DICT = ACTION_DICT.copy() ACTION_WITH_DEF_DICT.update({'definition': ACTION_DEF}) ACTION"
] |